id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_bad_4689_0 | // SPDX-License-Identifier: GPL-2.0-only
/*
* linux/drivers/block/floppy.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright (C) 1993, 1994 Alain Knaff
* Copyright (C) 1998 Alan Cox
*/
/*
* 02.12.91 - Changed to static variables to indicate need for reset
* and recalibrate. This makes some things easier (output_byte reset
* checking etc), and means less interrupt jumping in case of errors,
* so the code is hopefully easier to understand.
*/
/*
* This file is certainly a mess. I've tried my best to get it working,
* but I don't like programming floppies, and I have only one anyway.
* Urgel. I should check for more errors, and do more graceful error
* recovery. Seems there are problems with several drives. I've tried to
* correct them. No promises.
*/
/*
* As with hd.c, all routines within this file can (and will) be called
* by interrupts, so extreme caution is needed. A hardware interrupt
* handler may not sleep, or a kernel panic will happen. Thus I cannot
* call "floppy-on" directly, but have to set a special timer interrupt
* etc.
*/
/*
* 28.02.92 - made track-buffering routines, based on the routines written
* by entropy@wintermute.wpi.edu (Lawrence Foard). Linus.
*/
/*
* Automatic floppy-detection and formatting written by Werner Almesberger
* (almesber@nessie.cs.id.ethz.ch), who also corrected some problems with
* the floppy-change signal detection.
*/
/*
* 1992/7/22 -- Hennus Bergman: Added better error reporting, fixed
* FDC data overrun bug, added some preliminary stuff for vertical
* recording support.
*
* 1992/9/17: Added DMA allocation & DMA functions. -- hhb.
*
* TODO: Errors are still not counted properly.
*/
/* 1992/9/20
* Modifications for ``Sector Shifting'' by Rob Hooft (hooft@chem.ruu.nl)
* modeled after the freeware MS-DOS program fdformat/88 V1.8 by
* Christoph H. Hochst\"atter.
* I have fixed the shift values to the ones I always use. Maybe a new
* ioctl() should be created to be able to modify them.
* There is a bug in the driver that makes it impossible to format a
* floppy as the first thing after bootup.
*/
/*
* 1993/4/29 -- Linus -- cleaned up the timer handling in the kernel, and
* this helped the floppy driver as well. Much cleaner, and still seems to
* work.
*/
/* 1994/6/24 --bbroad-- added the floppy table entries and made
* minor modifications to allow 2.88 floppies to be run.
*/
/* 1994/7/13 -- Paul Vojta -- modified the probing code to allow three or more
* disk types.
*/
/*
* 1994/8/8 -- Alain Knaff -- Switched to fdpatch driver: Support for bigger
* format bug fixes, but unfortunately some new bugs too...
*/
/* 1994/9/17 -- Koen Holtman -- added logging of physical floppy write
* errors to allow safe writing by specialized programs.
*/
/* 1995/4/24 -- Dan Fandrich -- added support for Commodore 1581 3.5" disks
* by defining bit 1 of the "stretch" parameter to mean put sectors on the
* opposite side of the disk, leaving the sector IDs alone (i.e. Commodore's
* drives are "upside-down").
*/
/*
* 1995/8/26 -- Andreas Busse -- added Mips support.
*/
/*
* 1995/10/18 -- Ralf Baechle -- Portability cleanup; move machine dependent
* features to asm/floppy.h.
*/
/*
* 1998/1/21 -- Richard Gooch <rgooch@atnf.csiro.au> -- devfs support
*/
/*
* 1998/05/07 -- Russell King -- More portability cleanups; moved definition of
* interrupt and dma channel to asm/floppy.h. Cleaned up some formatting &
* use of '0' for NULL.
*/
/*
* 1998/06/07 -- Alan Cox -- Merged the 2.0.34 fixes for resource allocation
* failures.
*/
/*
* 1998/09/20 -- David Weinehall -- Added slow-down code for buggy PS/2-drives.
*/
/*
* 1999/08/13 -- Paul Slootman -- floppy stopped working on Alpha after 24
* days, 6 hours, 32 minutes and 32 seconds (i.e. MAXINT jiffies; ints were
* being used to store jiffies, which are unsigned longs).
*/
/*
* 2000/08/28 -- Arnaldo Carvalho de Melo <acme@conectiva.com.br>
* - get rid of check_region
* - s/suser/capable/
*/
/*
* 2001/08/26 -- Paul Gortmaker - fix insmod oops on machines with no
* floppy controller (lingering task on list after module is gone... boom.)
*/
/*
* 2002/02/07 -- Anton Altaparmakov - Fix io ports reservation to correct range
* (0x3f2-0x3f5, 0x3f7). This fix is a bit of a hack but the proper fix
* requires many non-obvious changes in arch dependent code.
*/
/* 2003/07/28 -- Daniele Bellucci <bellucda@tiscali.it>.
* Better audit of register_blkdev.
*/
#undef FLOPPY_SILENT_DCL_CLEAR
#define REALLY_SLOW_IO
#define DEBUGT 2
#define DPRINT(format, args...) \
pr_info("floppy%d: " format, current_drive, ##args)
#define DCL_DEBUG /* debug disk change line */
#ifdef DCL_DEBUG
#define debug_dcl(test, fmt, args...) \
do { if ((test) & FD_DEBUG) DPRINT(fmt, ##args); } while (0)
#else
#define debug_dcl(test, fmt, args...) \
do { if (0) DPRINT(fmt, ##args); } while (0)
#endif
/* do print messages for unexpected interrupts */
static int print_unex = 1;
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/workqueue.h>
#define FDPATCHES
#include <linux/fdreg.h>
#include <linux/fd.h>
#include <linux/hdreg.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/bio.h>
#include <linux/string.h>
#include <linux/jiffies.h>
#include <linux/fcntl.h>
#include <linux/delay.h>
#include <linux/mc146818rtc.h> /* CMOS defines */
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/mod_devicetable.h>
#include <linux/mutex.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include <linux/async.h>
#include <linux/compat.h>
/*
* PS/2 floppies have much slower step rates than regular floppies.
* It's been recommended that take about 1/4 of the default speed
* in some more extreme cases.
*/
static DEFINE_MUTEX(floppy_mutex);
static int slow_floppy;
#include <asm/dma.h>
#include <asm/irq.h>
static int FLOPPY_IRQ = 6;
static int FLOPPY_DMA = 2;
static int can_use_virtual_dma = 2;
/* =======
* can use virtual DMA:
* 0 = use of virtual DMA disallowed by config
* 1 = use of virtual DMA prescribed by config
* 2 = no virtual DMA preference configured. By default try hard DMA,
* but fall back on virtual DMA when not enough memory available
*/
static int use_virtual_dma;
/* =======
* use virtual DMA
* 0 using hard DMA
* 1 using virtual DMA
* This variable is set to virtual when a DMA mem problem arises, and
* reset back in floppy_grab_irq_and_dma.
* It is not safe to reset it in other circumstances, because the floppy
* driver may have several buffers in use at once, and we do currently not
* record each buffers capabilities
*/
static DEFINE_SPINLOCK(floppy_lock);
static unsigned short virtual_dma_port = 0x3f0;
irqreturn_t floppy_interrupt(int irq, void *dev_id);
static int set_dor(int fdc, char mask, char data);
#define K_64 0x10000 /* 64KB */
/* the following is the mask of allowed drives. By default units 2 and
* 3 of both floppy controllers are disabled, because switching on the
* motor of these drives causes system hangs on some PCI computers. drive
* 0 is the low bit (0x1), and drive 7 is the high bit (0x80). Bits are on if
* a drive is allowed.
*
* NOTE: This must come before we include the arch floppy header because
* some ports reference this variable from there. -DaveM
*/
static int allowed_drive_mask = 0x33;
#include <asm/floppy.h>
static int irqdma_allocated;
#include <linux/blk-mq.h>
#include <linux/blkpg.h>
#include <linux/cdrom.h> /* for the compatibility eject ioctl */
#include <linux/completion.h>
static LIST_HEAD(floppy_reqs);
static struct request *current_req;
static int set_next_request(void);
#ifndef fd_get_dma_residue
#define fd_get_dma_residue() get_dma_residue(FLOPPY_DMA)
#endif
/* Dma Memory related stuff */
#ifndef fd_dma_mem_free
#define fd_dma_mem_free(addr, size) free_pages(addr, get_order(size))
#endif
#ifndef fd_dma_mem_alloc
#define fd_dma_mem_alloc(size) __get_dma_pages(GFP_KERNEL, get_order(size))
#endif
#ifndef fd_cacheflush
#define fd_cacheflush(addr, size) /* nothing... */
#endif
static inline void fallback_on_nodma_alloc(char **addr, size_t l)
{
#ifdef FLOPPY_CAN_FALLBACK_ON_NODMA
if (*addr)
return; /* we have the memory */
if (can_use_virtual_dma != 2)
return; /* no fallback allowed */
pr_info("DMA memory shortage. Temporarily falling back on virtual DMA\n");
*addr = (char *)nodma_mem_alloc(l);
#else
return;
#endif
}
/* End dma memory related stuff */
static unsigned long fake_change;
static bool initialized;
#define ITYPE(x) (((x) >> 2) & 0x1f)
#define TOMINOR(x) ((x & 3) | ((x & 4) << 5))
#define UNIT(x) ((x) & 0x03) /* drive on fdc */
#define FDC(x) (((x) & 0x04) >> 2) /* fdc of drive */
/* reverse mapping from unit and fdc to drive */
#define REVDRIVE(fdc, unit) ((unit) + ((fdc) << 2))
#define DP (&drive_params[current_drive])
#define DRS (&drive_state[current_drive])
#define DRWE (&write_errors[current_drive])
#define FDCS (&fdc_state[fdc])
#define UDP (&drive_params[drive])
#define UDRS (&drive_state[drive])
#define UDRWE (&write_errors[drive])
#define UFDCS (&fdc_state[FDC(drive)])
#define PH_HEAD(floppy, head) (((((floppy)->stretch & 2) >> 1) ^ head) << 2)
#define STRETCH(floppy) ((floppy)->stretch & FD_STRETCH)
/* read/write */
#define COMMAND (raw_cmd->cmd[0])
#define DR_SELECT (raw_cmd->cmd[1])
#define TRACK (raw_cmd->cmd[2])
#define HEAD (raw_cmd->cmd[3])
#define SECTOR (raw_cmd->cmd[4])
#define SIZECODE (raw_cmd->cmd[5])
#define SECT_PER_TRACK (raw_cmd->cmd[6])
#define GAP (raw_cmd->cmd[7])
#define SIZECODE2 (raw_cmd->cmd[8])
#define NR_RW 9
/* format */
#define F_SIZECODE (raw_cmd->cmd[2])
#define F_SECT_PER_TRACK (raw_cmd->cmd[3])
#define F_GAP (raw_cmd->cmd[4])
#define F_FILL (raw_cmd->cmd[5])
#define NR_F 6
/*
* Maximum disk size (in kilobytes).
* This default is used whenever the current disk size is unknown.
* [Now it is rather a minimum]
*/
#define MAX_DISK_SIZE 4 /* 3984 */
/*
* globals used by 'result()'
*/
#define MAX_REPLIES 16
static unsigned char reply_buffer[MAX_REPLIES];
static int inr; /* size of reply buffer, when called from interrupt */
#define ST0 (reply_buffer[0])
#define ST1 (reply_buffer[1])
#define ST2 (reply_buffer[2])
#define ST3 (reply_buffer[0]) /* result of GETSTATUS */
#define R_TRACK (reply_buffer[3])
#define R_HEAD (reply_buffer[4])
#define R_SECTOR (reply_buffer[5])
#define R_SIZECODE (reply_buffer[6])
#define SEL_DLY (2 * HZ / 100)
/*
* this struct defines the different floppy drive types.
*/
static struct {
struct floppy_drive_params params;
const char *name; /* name printed while booting */
} default_drive_params[] = {
/* NOTE: the time values in jiffies should be in msec!
CMOS drive type
| Maximum data rate supported by drive type
| | Head load time, msec
| | | Head unload time, msec (not used)
| | | | Step rate interval, usec
| | | | | Time needed for spinup time (jiffies)
| | | | | | Timeout for spinning down (jiffies)
| | | | | | | Spindown offset (where disk stops)
| | | | | | | | Select delay
| | | | | | | | | RPS
| | | | | | | | | | Max number of tracks
| | | | | | | | | | | Interrupt timeout
| | | | | | | | | | | | Max nonintlv. sectors
| | | | | | | | | | | | | -Max Errors- flags */
{{0, 500, 16, 16, 8000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 80, 3*HZ, 20, {3,1,2,0,2}, 0,
0, { 7, 4, 8, 2, 1, 5, 3,10}, 3*HZ/2, 0 }, "unknown" },
{{1, 300, 16, 16, 8000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 40, 3*HZ, 17, {3,1,2,0,2}, 0,
0, { 1, 0, 0, 0, 0, 0, 0, 0}, 3*HZ/2, 1 }, "360K PC" }, /*5 1/4 360 KB PC*/
{{2, 500, 16, 16, 6000, 4*HZ/10, 3*HZ, 14, SEL_DLY, 6, 83, 3*HZ, 17, {3,1,2,0,2}, 0,
0, { 2, 5, 6,23,10,20,12, 0}, 3*HZ/2, 2 }, "1.2M" }, /*5 1/4 HD AT*/
{{3, 250, 16, 16, 3000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 83, 3*HZ, 20, {3,1,2,0,2}, 0,
0, { 4,22,21,30, 3, 0, 0, 0}, 3*HZ/2, 4 }, "720k" }, /*3 1/2 DD*/
{{4, 500, 16, 16, 4000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 20, {3,1,2,0,2}, 0,
0, { 7, 4,25,22,31,21,29,11}, 3*HZ/2, 7 }, "1.44M" }, /*3 1/2 HD*/
{{5, 1000, 15, 8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 40, {3,1,2,0,2}, 0,
0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, "2.88M AMI BIOS" }, /*3 1/2 ED*/
{{6, 1000, 15, 8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 40, {3,1,2,0,2}, 0,
0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, "2.88M" } /*3 1/2 ED*/
/* | --autodetected formats--- | | |
* read_track | | Name printed when booting
* | Native format
* Frequency of disk change checks */
};
static struct floppy_drive_params drive_params[N_DRIVE];
static struct floppy_drive_struct drive_state[N_DRIVE];
static struct floppy_write_errors write_errors[N_DRIVE];
static struct timer_list motor_off_timer[N_DRIVE];
static struct gendisk *disks[N_DRIVE];
static struct blk_mq_tag_set tag_sets[N_DRIVE];
static struct block_device *opened_bdev[N_DRIVE];
static DEFINE_MUTEX(open_lock);
static struct floppy_raw_cmd *raw_cmd, default_raw_cmd;
/*
* This struct defines the different floppy types.
*
* Bit 0 of 'stretch' tells if the tracks need to be doubled for some
* types (e.g. 360kB diskette in 1.2MB drive, etc.). Bit 1 of 'stretch'
* tells if the disk is in Commodore 1581 format, which means side 0 sectors
* are located on side 1 of the disk but with a side 0 ID, and vice-versa.
* This is the same as the Sharp MZ-80 5.25" CP/M disk format, except that the
* 1581's logical side 0 is on physical side 1, whereas the Sharp's logical
* side 0 is on physical side 0 (but with the misnamed sector IDs).
* 'stretch' should probably be renamed to something more general, like
* 'options'.
*
* Bits 2 through 9 of 'stretch' tell the number of the first sector.
* The LSB (bit 2) is flipped. For most disks, the first sector
* is 1 (represented by 0x00<<2). For some CP/M and music sampler
* disks (such as Ensoniq EPS 16plus) it is 0 (represented as 0x01<<2).
* For Amstrad CPC disks it is 0xC1 (represented as 0xC0<<2).
*
* Other parameters should be self-explanatory (see also setfdprm(8)).
*/
/*
Size
| Sectors per track
| | Head
| | | Tracks
| | | | Stretch
| | | | | Gap 1 size
| | | | | | Data rate, | 0x40 for perp
| | | | | | | Spec1 (stepping rate, head unload
| | | | | | | | /fmt gap (gap2) */
static struct floppy_struct floppy_type[32] = {
{ 0, 0,0, 0,0,0x00,0x00,0x00,0x00,NULL }, /* 0 no testing */
{ 720, 9,2,40,0,0x2A,0x02,0xDF,0x50,"d360" }, /* 1 360KB PC */
{ 2400,15,2,80,0,0x1B,0x00,0xDF,0x54,"h1200" }, /* 2 1.2MB AT */
{ 720, 9,1,80,0,0x2A,0x02,0xDF,0x50,"D360" }, /* 3 360KB SS 3.5" */
{ 1440, 9,2,80,0,0x2A,0x02,0xDF,0x50,"D720" }, /* 4 720KB 3.5" */
{ 720, 9,2,40,1,0x23,0x01,0xDF,0x50,"h360" }, /* 5 360KB AT */
{ 1440, 9,2,80,0,0x23,0x01,0xDF,0x50,"h720" }, /* 6 720KB AT */
{ 2880,18,2,80,0,0x1B,0x00,0xCF,0x6C,"H1440" }, /* 7 1.44MB 3.5" */
{ 5760,36,2,80,0,0x1B,0x43,0xAF,0x54,"E2880" }, /* 8 2.88MB 3.5" */
{ 6240,39,2,80,0,0x1B,0x43,0xAF,0x28,"E3120" }, /* 9 3.12MB 3.5" */
{ 2880,18,2,80,0,0x25,0x00,0xDF,0x02,"h1440" }, /* 10 1.44MB 5.25" */
{ 3360,21,2,80,0,0x1C,0x00,0xCF,0x0C,"H1680" }, /* 11 1.68MB 3.5" */
{ 820,10,2,41,1,0x25,0x01,0xDF,0x2E,"h410" }, /* 12 410KB 5.25" */
{ 1640,10,2,82,0,0x25,0x02,0xDF,0x2E,"H820" }, /* 13 820KB 3.5" */
{ 2952,18,2,82,0,0x25,0x00,0xDF,0x02,"h1476" }, /* 14 1.48MB 5.25" */
{ 3444,21,2,82,0,0x25,0x00,0xDF,0x0C,"H1722" }, /* 15 1.72MB 3.5" */
{ 840,10,2,42,1,0x25,0x01,0xDF,0x2E,"h420" }, /* 16 420KB 5.25" */
{ 1660,10,2,83,0,0x25,0x02,0xDF,0x2E,"H830" }, /* 17 830KB 3.5" */
{ 2988,18,2,83,0,0x25,0x00,0xDF,0x02,"h1494" }, /* 18 1.49MB 5.25" */
{ 3486,21,2,83,0,0x25,0x00,0xDF,0x0C,"H1743" }, /* 19 1.74 MB 3.5" */
{ 1760,11,2,80,0,0x1C,0x09,0xCF,0x00,"h880" }, /* 20 880KB 5.25" */
{ 2080,13,2,80,0,0x1C,0x01,0xCF,0x00,"D1040" }, /* 21 1.04MB 3.5" */
{ 2240,14,2,80,0,0x1C,0x19,0xCF,0x00,"D1120" }, /* 22 1.12MB 3.5" */
{ 3200,20,2,80,0,0x1C,0x20,0xCF,0x2C,"h1600" }, /* 23 1.6MB 5.25" */
{ 3520,22,2,80,0,0x1C,0x08,0xCF,0x2e,"H1760" }, /* 24 1.76MB 3.5" */
{ 3840,24,2,80,0,0x1C,0x20,0xCF,0x00,"H1920" }, /* 25 1.92MB 3.5" */
{ 6400,40,2,80,0,0x25,0x5B,0xCF,0x00,"E3200" }, /* 26 3.20MB 3.5" */
{ 7040,44,2,80,0,0x25,0x5B,0xCF,0x00,"E3520" }, /* 27 3.52MB 3.5" */
{ 7680,48,2,80,0,0x25,0x63,0xCF,0x00,"E3840" }, /* 28 3.84MB 3.5" */
{ 3680,23,2,80,0,0x1C,0x10,0xCF,0x00,"H1840" }, /* 29 1.84MB 3.5" */
{ 1600,10,2,80,0,0x25,0x02,0xDF,0x2E,"D800" }, /* 30 800KB 3.5" */
{ 3200,20,2,80,0,0x1C,0x00,0xCF,0x2C,"H1600" }, /* 31 1.6MB 3.5" */
};
#define SECTSIZE (_FD_SECTSIZE(*floppy))
/* Auto-detection: Disk type used until the next media change occurs. */
static struct floppy_struct *current_type[N_DRIVE];
/*
* User-provided type information. current_type points to
* the respective entry of this array.
*/
static struct floppy_struct user_params[N_DRIVE];
static sector_t floppy_sizes[256];
static char floppy_device_name[] = "floppy";
/*
* The driver is trying to determine the correct media format
* while probing is set. rw_interrupt() clears it after a
* successful access.
*/
static int probing;
/* Synchronization of FDC access. */
#define FD_COMMAND_NONE -1
#define FD_COMMAND_ERROR 2
#define FD_COMMAND_OKAY 3
static volatile int command_status = FD_COMMAND_NONE;
static unsigned long fdc_busy;
static DECLARE_WAIT_QUEUE_HEAD(fdc_wait);
static DECLARE_WAIT_QUEUE_HEAD(command_done);
/* Errors during formatting are counted here. */
static int format_errors;
/* Format request descriptor. */
static struct format_descr format_req;
/*
* Rate is 0 for 500kb/s, 1 for 300kbps, 2 for 250kbps
* Spec1 is 0xSH, where S is stepping rate (F=1ms, E=2ms, D=3ms etc),
* H is head unload time (1=16ms, 2=32ms, etc)
*/
/*
* Track buffer
* Because these are written to by the DMA controller, they must
* not contain a 64k byte boundary crossing, or data will be
* corrupted/lost.
*/
static char *floppy_track_buffer;
static int max_buffer_sectors;
static int *errors;
typedef void (*done_f)(int);
static const struct cont_t {
void (*interrupt)(void);
/* this is called after the interrupt of the
* main command */
void (*redo)(void); /* this is called to retry the operation */
void (*error)(void); /* this is called to tally an error */
done_f done; /* this is called to say if the operation has
* succeeded/failed */
} *cont;
static void floppy_ready(void);
static void floppy_start(void);
static void process_fd_request(void);
static void recalibrate_floppy(void);
static void floppy_shutdown(struct work_struct *);
static int floppy_request_regions(int);
static void floppy_release_regions(int);
static int floppy_grab_irq_and_dma(void);
static void floppy_release_irq_and_dma(void);
/*
* The "reset" variable should be tested whenever an interrupt is scheduled,
* after the commands have been sent. This is to ensure that the driver doesn't
* get wedged when the interrupt doesn't come because of a failed command.
* reset doesn't need to be tested before sending commands, because
* output_byte is automatically disabled when reset is set.
*/
static void reset_fdc(void);
/*
* These are global variables, as that's the easiest way to give
* information to interrupts. They are the data used for the current
* request.
*/
#define NO_TRACK -1
#define NEED_1_RECAL -2
#define NEED_2_RECAL -3
static atomic_t usage_count = ATOMIC_INIT(0);
/* buffer related variables */
static int buffer_track = -1;
static int buffer_drive = -1;
static int buffer_min = -1;
static int buffer_max = -1;
/* fdc related variables, should end up in a struct */
static struct floppy_fdc_state fdc_state[N_FDC];
static int fdc; /* current fdc */
static struct workqueue_struct *floppy_wq;
static struct floppy_struct *_floppy = floppy_type;
static unsigned char current_drive;
static long current_count_sectors;
static unsigned char fsector_t; /* sector in track */
static unsigned char in_sector_offset; /* offset within physical sector,
* expressed in units of 512 bytes */
static inline bool drive_no_geom(int drive)
{
return !current_type[drive] && !ITYPE(UDRS->fd_device);
}
#ifndef fd_eject
static inline int fd_eject(int drive)
{
return -EINVAL;
}
#endif
/*
* Debugging
* =========
*/
#ifdef DEBUGT
static long unsigned debugtimer;
static inline void set_debugt(void)
{
debugtimer = jiffies;
}
static inline void debugt(const char *func, const char *msg)
{
if (DP->flags & DEBUGT)
pr_info("%s:%s dtime=%lu\n", func, msg, jiffies - debugtimer);
}
#else
static inline void set_debugt(void) { }
static inline void debugt(const char *func, const char *msg) { }
#endif /* DEBUGT */
static DECLARE_DELAYED_WORK(fd_timeout, floppy_shutdown);
static const char *timeout_message;
static void is_alive(const char *func, const char *message)
{
/* this routine checks whether the floppy driver is "alive" */
if (test_bit(0, &fdc_busy) && command_status < 2 &&
!delayed_work_pending(&fd_timeout)) {
DPRINT("%s: timeout handler died. %s\n", func, message);
}
}
static void (*do_floppy)(void) = NULL;
#define OLOGSIZE 20
static void (*lasthandler)(void);
static unsigned long interruptjiffies;
static unsigned long resultjiffies;
static int resultsize;
static unsigned long lastredo;
static struct output_log {
unsigned char data;
unsigned char status;
unsigned long jiffies;
} output_log[OLOGSIZE];
static int output_log_pos;
#define current_reqD -1
#define MAXTIMEOUT -2
static void __reschedule_timeout(int drive, const char *message)
{
unsigned long delay;
if (drive == current_reqD)
drive = current_drive;
if (drive < 0 || drive >= N_DRIVE) {
delay = 20UL * HZ;
drive = 0;
} else
delay = UDP->timeout;
mod_delayed_work(floppy_wq, &fd_timeout, delay);
if (UDP->flags & FD_DEBUG)
DPRINT("reschedule timeout %s\n", message);
timeout_message = message;
}
static void reschedule_timeout(int drive, const char *message)
{
unsigned long flags;
spin_lock_irqsave(&floppy_lock, flags);
__reschedule_timeout(drive, message);
spin_unlock_irqrestore(&floppy_lock, flags);
}
#define INFBOUND(a, b) (a) = max_t(int, a, b)
#define SUPBOUND(a, b) (a) = min_t(int, a, b)
/*
* Bottom half floppy driver.
* ==========================
*
* This part of the file contains the code talking directly to the hardware,
* and also the main service loop (seek-configure-spinup-command)
*/
/*
* disk change.
* This routine is responsible for maintaining the FD_DISK_CHANGE flag,
* and the last_checked date.
*
* last_checked is the date of the last check which showed 'no disk change'
* FD_DISK_CHANGE is set under two conditions:
* 1. The floppy has been changed after some i/o to that floppy already
* took place.
* 2. No floppy disk is in the drive. This is done in order to ensure that
* requests are quickly flushed in case there is no disk in the drive. It
* follows that FD_DISK_CHANGE can only be cleared if there is a disk in
* the drive.
*
* For 1., maxblock is observed. Maxblock is 0 if no i/o has taken place yet.
* For 2., FD_DISK_NEWCHANGE is watched. FD_DISK_NEWCHANGE is cleared on
* each seek. If a disk is present, the disk change line should also be
* cleared on each seek. Thus, if FD_DISK_NEWCHANGE is clear, but the disk
* change line is set, this means either that no disk is in the drive, or
* that it has been removed since the last seek.
*
* This means that we really have a third possibility too:
* The floppy has been changed after the last seek.
*/
static int disk_change(int drive)
{
int fdc = FDC(drive);
if (time_before(jiffies, UDRS->select_date + UDP->select_delay))
DPRINT("WARNING disk change called early\n");
if (!(FDCS->dor & (0x10 << UNIT(drive))) ||
(FDCS->dor & 3) != UNIT(drive) || fdc != FDC(drive)) {
DPRINT("probing disk change on unselected drive\n");
DPRINT("drive=%d fdc=%d dor=%x\n", drive, FDC(drive),
(unsigned int)FDCS->dor);
}
debug_dcl(UDP->flags,
"checking disk change line for drive %d\n", drive);
debug_dcl(UDP->flags, "jiffies=%lu\n", jiffies);
debug_dcl(UDP->flags, "disk change line=%x\n", fd_inb(FD_DIR) & 0x80);
debug_dcl(UDP->flags, "flags=%lx\n", UDRS->flags);
if (UDP->flags & FD_BROKEN_DCL)
return test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
if ((fd_inb(FD_DIR) ^ UDP->flags) & 0x80) {
set_bit(FD_VERIFY_BIT, &UDRS->flags);
/* verify write protection */
if (UDRS->maxblock) /* mark it changed */
set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
/* invalidate its geometry */
if (UDRS->keep_data >= 0) {
if ((UDP->flags & FTD_MSG) &&
current_type[drive] != NULL)
DPRINT("Disk type is undefined after disk change\n");
current_type[drive] = NULL;
floppy_sizes[TOMINOR(drive)] = MAX_DISK_SIZE << 1;
}
return 1;
} else {
UDRS->last_checked = jiffies;
clear_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags);
}
return 0;
}
static inline int is_selected(int dor, int unit)
{
return ((dor & (0x10 << unit)) && (dor & 3) == unit);
}
static bool is_ready_state(int status)
{
int state = status & (STATUS_READY | STATUS_DIR | STATUS_DMA);
return state == STATUS_READY;
}
static int set_dor(int fdc, char mask, char data)
{
unsigned char unit;
unsigned char drive;
unsigned char newdor;
unsigned char olddor;
if (FDCS->address == -1)
return -1;
olddor = FDCS->dor;
newdor = (olddor & mask) | data;
if (newdor != olddor) {
unit = olddor & 0x3;
if (is_selected(olddor, unit) && !is_selected(newdor, unit)) {
drive = REVDRIVE(fdc, unit);
debug_dcl(UDP->flags,
"calling disk change from set_dor\n");
disk_change(drive);
}
FDCS->dor = newdor;
fd_outb(newdor, FD_DOR);
unit = newdor & 0x3;
if (!is_selected(olddor, unit) && is_selected(newdor, unit)) {
drive = REVDRIVE(fdc, unit);
UDRS->select_date = jiffies;
}
}
return olddor;
}
static void twaddle(void)
{
if (DP->select_delay)
return;
fd_outb(FDCS->dor & ~(0x10 << UNIT(current_drive)), FD_DOR);
fd_outb(FDCS->dor, FD_DOR);
DRS->select_date = jiffies;
}
/*
* Reset all driver information about the current fdc.
* This is needed after a reset, and after a raw command.
*/
static void reset_fdc_info(int mode)
{
int drive;
FDCS->spec1 = FDCS->spec2 = -1;
FDCS->need_configure = 1;
FDCS->perp_mode = 1;
FDCS->rawcmd = 0;
for (drive = 0; drive < N_DRIVE; drive++)
if (FDC(drive) == fdc && (mode || UDRS->track != NEED_1_RECAL))
UDRS->track = NEED_2_RECAL;
}
/* selects the fdc and drive, and enables the fdc's input/dma. */
static void set_fdc(int drive)
{
if (drive >= 0 && drive < N_DRIVE) {
fdc = FDC(drive);
current_drive = drive;
}
if (fdc != 1 && fdc != 0) {
pr_info("bad fdc value\n");
return;
}
set_dor(fdc, ~0, 8);
#if N_FDC > 1
set_dor(1 - fdc, ~8, 0);
#endif
if (FDCS->rawcmd == 2)
reset_fdc_info(1);
if (fd_inb(FD_STATUS) != STATUS_READY)
FDCS->reset = 1;
}
/* locks the driver */
static int lock_fdc(int drive)
{
if (WARN(atomic_read(&usage_count) == 0,
"Trying to lock fdc while usage count=0\n"))
return -1;
if (wait_event_interruptible(fdc_wait, !test_and_set_bit(0, &fdc_busy)))
return -EINTR;
command_status = FD_COMMAND_NONE;
reschedule_timeout(drive, "lock fdc");
set_fdc(drive);
return 0;
}
/* unlocks the driver */
static void unlock_fdc(void)
{
if (!test_bit(0, &fdc_busy))
DPRINT("FDC access conflict!\n");
raw_cmd = NULL;
command_status = FD_COMMAND_NONE;
cancel_delayed_work(&fd_timeout);
do_floppy = NULL;
cont = NULL;
clear_bit(0, &fdc_busy);
wake_up(&fdc_wait);
}
/* switches the motor off after a given timeout */
static void motor_off_callback(struct timer_list *t)
{
unsigned long nr = t - motor_off_timer;
unsigned char mask = ~(0x10 << UNIT(nr));
if (WARN_ON_ONCE(nr >= N_DRIVE))
return;
set_dor(FDC(nr), mask, 0);
}
/* schedules motor off */
static void floppy_off(unsigned int drive)
{
unsigned long volatile delta;
int fdc = FDC(drive);
if (!(FDCS->dor & (0x10 << UNIT(drive))))
return;
del_timer(motor_off_timer + drive);
/* make spindle stop in a position which minimizes spinup time
* next time */
if (UDP->rps) {
delta = jiffies - UDRS->first_read_date + HZ -
UDP->spindown_offset;
delta = ((delta * UDP->rps) % HZ) / UDP->rps;
motor_off_timer[drive].expires =
jiffies + UDP->spindown - delta;
}
add_timer(motor_off_timer + drive);
}
/*
* cycle through all N_DRIVE floppy drives, for disk change testing.
* stopping at current drive. This is done before any long operation, to
* be sure to have up to date disk change information.
*/
static void scandrives(void)
{
int i;
int drive;
int saved_drive;
if (DP->select_delay)
return;
saved_drive = current_drive;
for (i = 0; i < N_DRIVE; i++) {
drive = (saved_drive + i + 1) % N_DRIVE;
if (UDRS->fd_ref == 0 || UDP->select_delay != 0)
continue; /* skip closed drives */
set_fdc(drive);
if (!(set_dor(fdc, ~3, UNIT(drive) | (0x10 << UNIT(drive))) &
(0x10 << UNIT(drive))))
/* switch the motor off again, if it was off to
* begin with */
set_dor(fdc, ~(0x10 << UNIT(drive)), 0);
}
set_fdc(saved_drive);
}
static void empty(void)
{
}
static void (*floppy_work_fn)(void);
static void floppy_work_workfn(struct work_struct *work)
{
floppy_work_fn();
}
static DECLARE_WORK(floppy_work, floppy_work_workfn);
static void schedule_bh(void (*handler)(void))
{
WARN_ON(work_pending(&floppy_work));
floppy_work_fn = handler;
queue_work(floppy_wq, &floppy_work);
}
static void (*fd_timer_fn)(void) = NULL;
static void fd_timer_workfn(struct work_struct *work)
{
fd_timer_fn();
}
static DECLARE_DELAYED_WORK(fd_timer, fd_timer_workfn);
static void cancel_activity(void)
{
do_floppy = NULL;
cancel_delayed_work_sync(&fd_timer);
cancel_work_sync(&floppy_work);
}
/* this function makes sure that the disk stays in the drive during the
* transfer */
static void fd_watchdog(void)
{
debug_dcl(DP->flags, "calling disk change from watchdog\n");
if (disk_change(current_drive)) {
DPRINT("disk removed during i/o\n");
cancel_activity();
cont->done(0);
reset_fdc();
} else {
cancel_delayed_work(&fd_timer);
fd_timer_fn = fd_watchdog;
queue_delayed_work(floppy_wq, &fd_timer, HZ / 10);
}
}
static void main_command_interrupt(void)
{
cancel_delayed_work(&fd_timer);
cont->interrupt();
}
/* waits for a delay (spinup or select) to pass */
static int fd_wait_for_completion(unsigned long expires,
void (*function)(void))
{
if (FDCS->reset) {
reset_fdc(); /* do the reset during sleep to win time
* if we don't need to sleep, it's a good
* occasion anyways */
return 1;
}
if (time_before(jiffies, expires)) {
cancel_delayed_work(&fd_timer);
fd_timer_fn = function;
queue_delayed_work(floppy_wq, &fd_timer, expires - jiffies);
return 1;
}
return 0;
}
static void setup_DMA(void)
{
unsigned long f;
if (raw_cmd->length == 0) {
int i;
pr_info("zero dma transfer size:");
for (i = 0; i < raw_cmd->cmd_count; i++)
pr_cont("%x,", raw_cmd->cmd[i]);
pr_cont("\n");
cont->done(0);
FDCS->reset = 1;
return;
}
if (((unsigned long)raw_cmd->kernel_data) % 512) {
pr_info("non aligned address: %p\n", raw_cmd->kernel_data);
cont->done(0);
FDCS->reset = 1;
return;
}
f = claim_dma_lock();
fd_disable_dma();
#ifdef fd_dma_setup
if (fd_dma_setup(raw_cmd->kernel_data, raw_cmd->length,
(raw_cmd->flags & FD_RAW_READ) ?
DMA_MODE_READ : DMA_MODE_WRITE, FDCS->address) < 0) {
release_dma_lock(f);
cont->done(0);
FDCS->reset = 1;
return;
}
release_dma_lock(f);
#else
fd_clear_dma_ff();
fd_cacheflush(raw_cmd->kernel_data, raw_cmd->length);
fd_set_dma_mode((raw_cmd->flags & FD_RAW_READ) ?
DMA_MODE_READ : DMA_MODE_WRITE);
fd_set_dma_addr(raw_cmd->kernel_data);
fd_set_dma_count(raw_cmd->length);
virtual_dma_port = FDCS->address;
fd_enable_dma();
release_dma_lock(f);
#endif
}
static void show_floppy(void);
/* waits until the fdc becomes ready */
static int wait_til_ready(void)
{
int status;
int counter;
if (FDCS->reset)
return -1;
for (counter = 0; counter < 10000; counter++) {
status = fd_inb(FD_STATUS);
if (status & STATUS_READY)
return status;
}
if (initialized) {
DPRINT("Getstatus times out (%x) on fdc %d\n", status, fdc);
show_floppy();
}
FDCS->reset = 1;
return -1;
}
/* sends a command byte to the fdc */
static int output_byte(char byte)
{
int status = wait_til_ready();
if (status < 0)
return -1;
if (is_ready_state(status)) {
fd_outb(byte, FD_DATA);
output_log[output_log_pos].data = byte;
output_log[output_log_pos].status = status;
output_log[output_log_pos].jiffies = jiffies;
output_log_pos = (output_log_pos + 1) % OLOGSIZE;
return 0;
}
FDCS->reset = 1;
if (initialized) {
DPRINT("Unable to send byte %x to FDC. Fdc=%x Status=%x\n",
byte, fdc, status);
show_floppy();
}
return -1;
}
/* gets the response from the fdc */
static int result(void)
{
int i;
int status = 0;
for (i = 0; i < MAX_REPLIES; i++) {
status = wait_til_ready();
if (status < 0)
break;
status &= STATUS_DIR | STATUS_READY | STATUS_BUSY | STATUS_DMA;
if ((status & ~STATUS_BUSY) == STATUS_READY) {
resultjiffies = jiffies;
resultsize = i;
return i;
}
if (status == (STATUS_DIR | STATUS_READY | STATUS_BUSY))
reply_buffer[i] = fd_inb(FD_DATA);
else
break;
}
if (initialized) {
DPRINT("get result error. Fdc=%d Last status=%x Read bytes=%d\n",
fdc, status, i);
show_floppy();
}
FDCS->reset = 1;
return -1;
}
#define MORE_OUTPUT -2
/* does the fdc need more output? */
static int need_more_output(void)
{
int status = wait_til_ready();
if (status < 0)
return -1;
if (is_ready_state(status))
return MORE_OUTPUT;
return result();
}
/* Set perpendicular mode as required, based on data rate, if supported.
* 82077 Now tested. 1Mbps data rate only possible with 82077-1.
*/
static void perpendicular_mode(void)
{
unsigned char perp_mode;
if (raw_cmd->rate & 0x40) {
switch (raw_cmd->rate & 3) {
case 0:
perp_mode = 2;
break;
case 3:
perp_mode = 3;
break;
default:
DPRINT("Invalid data rate for perpendicular mode!\n");
cont->done(0);
FDCS->reset = 1;
/*
* convenient way to return to
* redo without too much hassle
* (deep stack et al.)
*/
return;
}
} else
perp_mode = 0;
if (FDCS->perp_mode == perp_mode)
return;
if (FDCS->version >= FDC_82077_ORIG) {
output_byte(FD_PERPENDICULAR);
output_byte(perp_mode);
FDCS->perp_mode = perp_mode;
} else if (perp_mode) {
DPRINT("perpendicular mode not supported by this FDC.\n");
}
} /* perpendicular_mode */
static int fifo_depth = 0xa;
static int no_fifo;
static int fdc_configure(void)
{
/* Turn on FIFO */
output_byte(FD_CONFIGURE);
if (need_more_output() != MORE_OUTPUT)
return 0;
output_byte(0);
output_byte(0x10 | (no_fifo & 0x20) | (fifo_depth & 0xf));
output_byte(0); /* pre-compensation from track
0 upwards */
return 1;
}
#define NOMINAL_DTR 500
/* Issue a "SPECIFY" command to set the step rate time, head unload time,
* head load time, and DMA disable flag to values needed by floppy.
*
* The value "dtr" is the data transfer rate in Kbps. It is needed
* to account for the data rate-based scaling done by the 82072 and 82077
* FDC types. This parameter is ignored for other types of FDCs (i.e.
* 8272a).
*
* Note that changing the data transfer rate has a (probably deleterious)
* effect on the parameters subject to scaling for 82072/82077 FDCs, so
* fdc_specify is called again after each data transfer rate
* change.
*
* srt: 1000 to 16000 in microseconds
* hut: 16 to 240 milliseconds
* hlt: 2 to 254 milliseconds
*
* These values are rounded up to the next highest available delay time.
*/
static void fdc_specify(void)
{
unsigned char spec1;
unsigned char spec2;
unsigned long srt;
unsigned long hlt;
unsigned long hut;
unsigned long dtr = NOMINAL_DTR;
unsigned long scale_dtr = NOMINAL_DTR;
int hlt_max_code = 0x7f;
int hut_max_code = 0xf;
if (FDCS->need_configure && FDCS->version >= FDC_82072A) {
fdc_configure();
FDCS->need_configure = 0;
}
switch (raw_cmd->rate & 0x03) {
case 3:
dtr = 1000;
break;
case 1:
dtr = 300;
if (FDCS->version >= FDC_82078) {
/* chose the default rate table, not the one
* where 1 = 2 Mbps */
output_byte(FD_DRIVESPEC);
if (need_more_output() == MORE_OUTPUT) {
output_byte(UNIT(current_drive));
output_byte(0xc0);
}
}
break;
case 2:
dtr = 250;
break;
}
if (FDCS->version >= FDC_82072) {
scale_dtr = dtr;
hlt_max_code = 0x00; /* 0==256msec*dtr0/dtr (not linear!) */
hut_max_code = 0x0; /* 0==256msec*dtr0/dtr (not linear!) */
}
/* Convert step rate from microseconds to milliseconds and 4 bits */
srt = 16 - DIV_ROUND_UP(DP->srt * scale_dtr / 1000, NOMINAL_DTR);
if (slow_floppy)
srt = srt / 4;
SUPBOUND(srt, 0xf);
INFBOUND(srt, 0);
hlt = DIV_ROUND_UP(DP->hlt * scale_dtr / 2, NOMINAL_DTR);
if (hlt < 0x01)
hlt = 0x01;
else if (hlt > 0x7f)
hlt = hlt_max_code;
hut = DIV_ROUND_UP(DP->hut * scale_dtr / 16, NOMINAL_DTR);
if (hut < 0x1)
hut = 0x1;
else if (hut > 0xf)
hut = hut_max_code;
spec1 = (srt << 4) | hut;
spec2 = (hlt << 1) | (use_virtual_dma & 1);
/* If these parameters did not change, just return with success */
if (FDCS->spec1 != spec1 || FDCS->spec2 != spec2) {
/* Go ahead and set spec1 and spec2 */
output_byte(FD_SPECIFY);
output_byte(FDCS->spec1 = spec1);
output_byte(FDCS->spec2 = spec2);
}
} /* fdc_specify */
/* Set the FDC's data transfer rate on behalf of the specified drive.
* NOTE: with 82072/82077 FDCs, changing the data rate requires a reissue
* of the specify command (i.e. using the fdc_specify function).
*/
static int fdc_dtr(void)
{
/* If data rate not already set to desired value, set it. */
if ((raw_cmd->rate & 3) == FDCS->dtr)
return 0;
/* Set dtr */
fd_outb(raw_cmd->rate & 3, FD_DCR);
/* TODO: some FDC/drive combinations (C&T 82C711 with TEAC 1.2MB)
* need a stabilization period of several milliseconds to be
* enforced after data rate changes before R/W operations.
* Pause 5 msec to avoid trouble. (Needs to be 2 jiffies)
*/
FDCS->dtr = raw_cmd->rate & 3;
return fd_wait_for_completion(jiffies + 2UL * HZ / 100, floppy_ready);
} /* fdc_dtr */
static void tell_sector(void)
{
pr_cont(": track %d, head %d, sector %d, size %d",
R_TRACK, R_HEAD, R_SECTOR, R_SIZECODE);
} /* tell_sector */
static void print_errors(void)
{
DPRINT("");
if (ST0 & ST0_ECE) {
pr_cont("Recalibrate failed!");
} else if (ST2 & ST2_CRC) {
pr_cont("data CRC error");
tell_sector();
} else if (ST1 & ST1_CRC) {
pr_cont("CRC error");
tell_sector();
} else if ((ST1 & (ST1_MAM | ST1_ND)) ||
(ST2 & ST2_MAM)) {
if (!probing) {
pr_cont("sector not found");
tell_sector();
} else
pr_cont("probe failed...");
} else if (ST2 & ST2_WC) { /* seek error */
pr_cont("wrong cylinder");
} else if (ST2 & ST2_BC) { /* cylinder marked as bad */
pr_cont("bad cylinder");
} else {
pr_cont("unknown error. ST[0..2] are: 0x%x 0x%x 0x%x",
ST0, ST1, ST2);
tell_sector();
}
pr_cont("\n");
}
/*
* OK, this error interpreting routine is called after a
* DMA read/write has succeeded
* or failed, so we check the results, and copy any buffers.
* hhb: Added better error reporting.
* ak: Made this into a separate routine.
*/
static int interpret_errors(void)
{
char bad;
if (inr != 7) {
DPRINT("-- FDC reply error\n");
FDCS->reset = 1;
return 1;
}
/* check IC to find cause of interrupt */
switch (ST0 & ST0_INTR) {
case 0x40: /* error occurred during command execution */
if (ST1 & ST1_EOC)
return 0; /* occurs with pseudo-DMA */
bad = 1;
if (ST1 & ST1_WP) {
DPRINT("Drive is write protected\n");
clear_bit(FD_DISK_WRITABLE_BIT, &DRS->flags);
cont->done(0);
bad = 2;
} else if (ST1 & ST1_ND) {
set_bit(FD_NEED_TWADDLE_BIT, &DRS->flags);
} else if (ST1 & ST1_OR) {
if (DP->flags & FTD_MSG)
DPRINT("Over/Underrun - retrying\n");
bad = 0;
} else if (*errors >= DP->max_errors.reporting) {
print_errors();
}
if (ST2 & ST2_WC || ST2 & ST2_BC)
/* wrong cylinder => recal */
DRS->track = NEED_2_RECAL;
return bad;
case 0x80: /* invalid command given */
DPRINT("Invalid FDC command given!\n");
cont->done(0);
return 2;
case 0xc0:
DPRINT("Abnormal termination caused by polling\n");
cont->error();
return 2;
default: /* (0) Normal command termination */
return 0;
}
}
/*
* This routine is called when everything should be correctly set up
* for the transfer (i.e. floppy motor is on, the correct floppy is
* selected, and the head is sitting on the right track).
*/
static void setup_rw_floppy(void)
{
int i;
int r;
int flags;
unsigned long ready_date;
void (*function)(void);
flags = raw_cmd->flags;
if (flags & (FD_RAW_READ | FD_RAW_WRITE))
flags |= FD_RAW_INTR;
if ((flags & FD_RAW_SPIN) && !(flags & FD_RAW_NO_MOTOR)) {
ready_date = DRS->spinup_date + DP->spinup;
/* If spinup will take a long time, rerun scandrives
* again just before spinup completion. Beware that
* after scandrives, we must again wait for selection.
*/
if (time_after(ready_date, jiffies + DP->select_delay)) {
ready_date -= DP->select_delay;
function = floppy_start;
} else
function = setup_rw_floppy;
/* wait until the floppy is spinning fast enough */
if (fd_wait_for_completion(ready_date, function))
return;
}
if ((flags & FD_RAW_READ) || (flags & FD_RAW_WRITE))
setup_DMA();
if (flags & FD_RAW_INTR)
do_floppy = main_command_interrupt;
r = 0;
for (i = 0; i < raw_cmd->cmd_count; i++)
r |= output_byte(raw_cmd->cmd[i]);
debugt(__func__, "rw_command");
if (r) {
cont->error();
reset_fdc();
return;
}
if (!(flags & FD_RAW_INTR)) {
inr = result();
cont->interrupt();
} else if (flags & FD_RAW_NEED_DISK)
fd_watchdog();
}
static int blind_seek;
/*
* This is the routine called after every seek (or recalibrate) interrupt
* from the floppy controller.
*/
static void seek_interrupt(void)
{
debugt(__func__, "");
if (inr != 2 || (ST0 & 0xF8) != 0x20) {
DPRINT("seek failed\n");
DRS->track = NEED_2_RECAL;
cont->error();
cont->redo();
return;
}
if (DRS->track >= 0 && DRS->track != ST1 && !blind_seek) {
debug_dcl(DP->flags,
"clearing NEWCHANGE flag because of effective seek\n");
debug_dcl(DP->flags, "jiffies=%lu\n", jiffies);
clear_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);
/* effective seek */
DRS->select_date = jiffies;
}
DRS->track = ST1;
floppy_ready();
}
static void check_wp(void)
{
if (test_bit(FD_VERIFY_BIT, &DRS->flags)) {
/* check write protection */
output_byte(FD_GETSTATUS);
output_byte(UNIT(current_drive));
if (result() != 1) {
FDCS->reset = 1;
return;
}
clear_bit(FD_VERIFY_BIT, &DRS->flags);
clear_bit(FD_NEED_TWADDLE_BIT, &DRS->flags);
debug_dcl(DP->flags,
"checking whether disk is write protected\n");
debug_dcl(DP->flags, "wp=%x\n", ST3 & 0x40);
if (!(ST3 & 0x40))
set_bit(FD_DISK_WRITABLE_BIT, &DRS->flags);
else
clear_bit(FD_DISK_WRITABLE_BIT, &DRS->flags);
}
}
static void seek_floppy(void)
{
int track;
blind_seek = 0;
debug_dcl(DP->flags, "calling disk change from %s\n", __func__);
if (!test_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags) &&
disk_change(current_drive) && (raw_cmd->flags & FD_RAW_NEED_DISK)) {
/* the media changed flag should be cleared after the seek.
* If it isn't, this means that there is really no disk in
* the drive.
*/
set_bit(FD_DISK_CHANGED_BIT, &DRS->flags);
cont->done(0);
cont->redo();
return;
}
if (DRS->track <= NEED_1_RECAL) {
recalibrate_floppy();
return;
} else if (test_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags) &&
(raw_cmd->flags & FD_RAW_NEED_DISK) &&
(DRS->track <= NO_TRACK || DRS->track == raw_cmd->track)) {
/* we seek to clear the media-changed condition. Does anybody
* know a more elegant way, which works on all drives? */
if (raw_cmd->track)
track = raw_cmd->track - 1;
else {
if (DP->flags & FD_SILENT_DCL_CLEAR) {
set_dor(fdc, ~(0x10 << UNIT(current_drive)), 0);
blind_seek = 1;
raw_cmd->flags |= FD_RAW_NEED_SEEK;
}
track = 1;
}
} else {
check_wp();
if (raw_cmd->track != DRS->track &&
(raw_cmd->flags & FD_RAW_NEED_SEEK))
track = raw_cmd->track;
else {
setup_rw_floppy();
return;
}
}
do_floppy = seek_interrupt;
output_byte(FD_SEEK);
output_byte(UNIT(current_drive));
if (output_byte(track) < 0) {
reset_fdc();
return;
}
debugt(__func__, "");
}
static void recal_interrupt(void)
{
debugt(__func__, "");
if (inr != 2)
FDCS->reset = 1;
else if (ST0 & ST0_ECE) {
switch (DRS->track) {
case NEED_1_RECAL:
debugt(__func__, "need 1 recal");
/* after a second recalibrate, we still haven't
* reached track 0. Probably no drive. Raise an
* error, as failing immediately might upset
* computers possessed by the Devil :-) */
cont->error();
cont->redo();
return;
case NEED_2_RECAL:
debugt(__func__, "need 2 recal");
/* If we already did a recalibrate,
* and we are not at track 0, this
* means we have moved. (The only way
* not to move at recalibration is to
* be already at track 0.) Clear the
* new change flag */
debug_dcl(DP->flags,
"clearing NEWCHANGE flag because of second recalibrate\n");
clear_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);
DRS->select_date = jiffies;
/* fall through */
default:
debugt(__func__, "default");
/* Recalibrate moves the head by at
* most 80 steps. If after one
* recalibrate we don't have reached
* track 0, this might mean that we
* started beyond track 80. Try
* again. */
DRS->track = NEED_1_RECAL;
break;
}
} else
DRS->track = ST1;
floppy_ready();
}
static void print_result(char *message, int inr)
{
int i;
DPRINT("%s ", message);
if (inr >= 0)
for (i = 0; i < inr; i++)
pr_cont("repl[%d]=%x ", i, reply_buffer[i]);
pr_cont("\n");
}
/* interrupt handler. Note that this can be called externally on the Sparc */
irqreturn_t floppy_interrupt(int irq, void *dev_id)
{
int do_print;
unsigned long f;
void (*handler)(void) = do_floppy;
lasthandler = handler;
interruptjiffies = jiffies;
f = claim_dma_lock();
fd_disable_dma();
release_dma_lock(f);
do_floppy = NULL;
if (fdc >= N_FDC || FDCS->address == -1) {
/* we don't even know which FDC is the culprit */
pr_info("DOR0=%x\n", fdc_state[0].dor);
pr_info("floppy interrupt on bizarre fdc %d\n", fdc);
pr_info("handler=%ps\n", handler);
is_alive(__func__, "bizarre fdc");
return IRQ_NONE;
}
FDCS->reset = 0;
/* We have to clear the reset flag here, because apparently on boxes
* with level triggered interrupts (PS/2, Sparc, ...), it is needed to
* emit SENSEI's to clear the interrupt line. And FDCS->reset blocks the
* emission of the SENSEI's.
* It is OK to emit floppy commands because we are in an interrupt
* handler here, and thus we have to fear no interference of other
* activity.
*/
do_print = !handler && print_unex && initialized;
inr = result();
if (do_print)
print_result("unexpected interrupt", inr);
if (inr == 0) {
int max_sensei = 4;
do {
output_byte(FD_SENSEI);
inr = result();
if (do_print)
print_result("sensei", inr);
max_sensei--;
} while ((ST0 & 0x83) != UNIT(current_drive) &&
inr == 2 && max_sensei);
}
if (!handler) {
FDCS->reset = 1;
return IRQ_NONE;
}
schedule_bh(handler);
is_alive(__func__, "normal interrupt end");
/* FIXME! Was it really for us? */
return IRQ_HANDLED;
}
static void recalibrate_floppy(void)
{
debugt(__func__, "");
do_floppy = recal_interrupt;
output_byte(FD_RECALIBRATE);
if (output_byte(UNIT(current_drive)) < 0)
reset_fdc();
}
/*
* Must do 4 FD_SENSEIs after reset because of ``drive polling''.
*/
static void reset_interrupt(void)
{
debugt(__func__, "");
result(); /* get the status ready for set_fdc */
if (FDCS->reset) {
pr_info("reset set in interrupt, calling %ps\n", cont->error);
cont->error(); /* a reset just after a reset. BAD! */
}
cont->redo();
}
/*
* reset is done by pulling bit 2 of DOR low for a while (old FDCs),
* or by setting the self clearing bit 7 of STATUS (newer FDCs)
*/
static void reset_fdc(void)
{
unsigned long flags;
do_floppy = reset_interrupt;
FDCS->reset = 0;
reset_fdc_info(0);
/* Pseudo-DMA may intercept 'reset finished' interrupt. */
/* Irrelevant for systems with true DMA (i386). */
flags = claim_dma_lock();
fd_disable_dma();
release_dma_lock(flags);
if (FDCS->version >= FDC_82072A)
fd_outb(0x80 | (FDCS->dtr & 3), FD_STATUS);
else {
fd_outb(FDCS->dor & ~0x04, FD_DOR);
udelay(FD_RESET_DELAY);
fd_outb(FDCS->dor, FD_DOR);
}
}
static void show_floppy(void)
{
int i;
pr_info("\n");
pr_info("floppy driver state\n");
pr_info("-------------------\n");
pr_info("now=%lu last interrupt=%lu diff=%lu last called handler=%ps\n",
jiffies, interruptjiffies, jiffies - interruptjiffies,
lasthandler);
pr_info("timeout_message=%s\n", timeout_message);
pr_info("last output bytes:\n");
for (i = 0; i < OLOGSIZE; i++)
pr_info("%2x %2x %lu\n",
output_log[(i + output_log_pos) % OLOGSIZE].data,
output_log[(i + output_log_pos) % OLOGSIZE].status,
output_log[(i + output_log_pos) % OLOGSIZE].jiffies);
pr_info("last result at %lu\n", resultjiffies);
pr_info("last redo_fd_request at %lu\n", lastredo);
print_hex_dump(KERN_INFO, "", DUMP_PREFIX_NONE, 16, 1,
reply_buffer, resultsize, true);
pr_info("status=%x\n", fd_inb(FD_STATUS));
pr_info("fdc_busy=%lu\n", fdc_busy);
if (do_floppy)
pr_info("do_floppy=%ps\n", do_floppy);
if (work_pending(&floppy_work))
pr_info("floppy_work.func=%ps\n", floppy_work.func);
if (delayed_work_pending(&fd_timer))
pr_info("delayed work.function=%p expires=%ld\n",
fd_timer.work.func,
fd_timer.timer.expires - jiffies);
if (delayed_work_pending(&fd_timeout))
pr_info("timer_function=%p expires=%ld\n",
fd_timeout.work.func,
fd_timeout.timer.expires - jiffies);
pr_info("cont=%p\n", cont);
pr_info("current_req=%p\n", current_req);
pr_info("command_status=%d\n", command_status);
pr_info("\n");
}
static void floppy_shutdown(struct work_struct *arg)
{
unsigned long flags;
if (initialized)
show_floppy();
cancel_activity();
flags = claim_dma_lock();
fd_disable_dma();
release_dma_lock(flags);
/* avoid dma going to a random drive after shutdown */
if (initialized)
DPRINT("floppy timeout called\n");
FDCS->reset = 1;
if (cont) {
cont->done(0);
cont->redo(); /* this will recall reset when needed */
} else {
pr_info("no cont in shutdown!\n");
process_fd_request();
}
is_alive(__func__, "");
}
/* start motor, check media-changed condition and write protection */
static int start_motor(void (*function)(void))
{
int mask;
int data;
mask = 0xfc;
data = UNIT(current_drive);
if (!(raw_cmd->flags & FD_RAW_NO_MOTOR)) {
if (!(FDCS->dor & (0x10 << UNIT(current_drive)))) {
set_debugt();
/* no read since this drive is running */
DRS->first_read_date = 0;
/* note motor start time if motor is not yet running */
DRS->spinup_date = jiffies;
data |= (0x10 << UNIT(current_drive));
}
} else if (FDCS->dor & (0x10 << UNIT(current_drive)))
mask &= ~(0x10 << UNIT(current_drive));
/* starts motor and selects floppy */
del_timer(motor_off_timer + current_drive);
set_dor(fdc, mask, data);
/* wait_for_completion also schedules reset if needed. */
return fd_wait_for_completion(DRS->select_date + DP->select_delay,
function);
}
static void floppy_ready(void)
{
if (FDCS->reset) {
reset_fdc();
return;
}
if (start_motor(floppy_ready))
return;
if (fdc_dtr())
return;
debug_dcl(DP->flags, "calling disk change from floppy_ready\n");
if (!(raw_cmd->flags & FD_RAW_NO_MOTOR) &&
disk_change(current_drive) && !DP->select_delay)
twaddle(); /* this clears the dcl on certain
* drive/controller combinations */
#ifdef fd_chose_dma_mode
if ((raw_cmd->flags & FD_RAW_READ) || (raw_cmd->flags & FD_RAW_WRITE)) {
unsigned long flags = claim_dma_lock();
fd_chose_dma_mode(raw_cmd->kernel_data, raw_cmd->length);
release_dma_lock(flags);
}
#endif
if (raw_cmd->flags & (FD_RAW_NEED_SEEK | FD_RAW_NEED_DISK)) {
perpendicular_mode();
fdc_specify(); /* must be done here because of hut, hlt ... */
seek_floppy();
} else {
if ((raw_cmd->flags & FD_RAW_READ) ||
(raw_cmd->flags & FD_RAW_WRITE))
fdc_specify();
setup_rw_floppy();
}
}
static void floppy_start(void)
{
reschedule_timeout(current_reqD, "floppy start");
scandrives();
debug_dcl(DP->flags, "setting NEWCHANGE in floppy_start\n");
set_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);
floppy_ready();
}
/*
* ========================================================================
* here ends the bottom half. Exported routines are:
* floppy_start, floppy_off, floppy_ready, lock_fdc, unlock_fdc, set_fdc,
* start_motor, reset_fdc, reset_fdc_info, interpret_errors.
* Initialization also uses output_byte, result, set_dor, floppy_interrupt
* and set_dor.
* ========================================================================
*/
/*
* General purpose continuations.
* ==============================
*/
static void do_wakeup(void)
{
reschedule_timeout(MAXTIMEOUT, "do wakeup");
cont = NULL;
command_status += 2;
wake_up(&command_done);
}
static const struct cont_t wakeup_cont = {
.interrupt = empty,
.redo = do_wakeup,
.error = empty,
.done = (done_f)empty
};
static const struct cont_t intr_cont = {
.interrupt = empty,
.redo = process_fd_request,
.error = empty,
.done = (done_f)empty
};
static int wait_til_done(void (*handler)(void), bool interruptible)
{
int ret;
schedule_bh(handler);
if (interruptible)
wait_event_interruptible(command_done, command_status >= 2);
else
wait_event(command_done, command_status >= 2);
if (command_status < 2) {
cancel_activity();
cont = &intr_cont;
reset_fdc();
return -EINTR;
}
if (FDCS->reset)
command_status = FD_COMMAND_ERROR;
if (command_status == FD_COMMAND_OKAY)
ret = 0;
else
ret = -EIO;
command_status = FD_COMMAND_NONE;
return ret;
}
static void generic_done(int result)
{
command_status = result;
cont = &wakeup_cont;
}
static void generic_success(void)
{
cont->done(1);
}
static void generic_failure(void)
{
cont->done(0);
}
static void success_and_wakeup(void)
{
generic_success();
cont->redo();
}
/*
* formatting and rw support.
* ==========================
*/
static int next_valid_format(void)
{
int probed_format;
probed_format = DRS->probed_format;
while (1) {
if (probed_format >= 8 || !DP->autodetect[probed_format]) {
DRS->probed_format = 0;
return 1;
}
if (floppy_type[DP->autodetect[probed_format]].sect) {
DRS->probed_format = probed_format;
return 0;
}
probed_format++;
}
}
static void bad_flp_intr(void)
{
int err_count;
if (probing) {
DRS->probed_format++;
if (!next_valid_format())
return;
}
err_count = ++(*errors);
INFBOUND(DRWE->badness, err_count);
if (err_count > DP->max_errors.abort)
cont->done(0);
if (err_count > DP->max_errors.reset)
FDCS->reset = 1;
else if (err_count > DP->max_errors.recal)
DRS->track = NEED_2_RECAL;
}
static void set_floppy(int drive)
{
int type = ITYPE(UDRS->fd_device);
if (type)
_floppy = floppy_type + type;
else
_floppy = current_type[drive];
}
/*
* formatting support.
* ===================
*/
static void format_interrupt(void)
{
switch (interpret_errors()) {
case 1:
cont->error();
case 2:
break;
case 0:
cont->done(1);
}
cont->redo();
}
#define FM_MODE(x, y) ((y) & ~(((x)->rate & 0x80) >> 1))
#define CT(x) ((x) | 0xc0)
static void setup_format_params(int track)
{
int n;
int il;
int count;
int head_shift;
int track_shift;
struct fparm {
unsigned char track, head, sect, size;
} *here = (struct fparm *)floppy_track_buffer;
raw_cmd = &default_raw_cmd;
raw_cmd->track = track;
raw_cmd->flags = (FD_RAW_WRITE | FD_RAW_INTR | FD_RAW_SPIN |
FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK);
raw_cmd->rate = _floppy->rate & 0x43;
raw_cmd->cmd_count = NR_F;
COMMAND = FM_MODE(_floppy, FD_FORMAT);
DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, format_req.head);
F_SIZECODE = FD_SIZECODE(_floppy);
F_SECT_PER_TRACK = _floppy->sect << 2 >> F_SIZECODE;
F_GAP = _floppy->fmt_gap;
F_FILL = FD_FILL_BYTE;
raw_cmd->kernel_data = floppy_track_buffer;
raw_cmd->length = 4 * F_SECT_PER_TRACK;
if (!F_SECT_PER_TRACK)
return;
/* allow for about 30ms for data transport per track */
head_shift = (F_SECT_PER_TRACK + 5) / 6;
/* a ``cylinder'' is two tracks plus a little stepping time */
track_shift = 2 * head_shift + 3;
/* position of logical sector 1 on this track */
n = (track_shift * format_req.track + head_shift * format_req.head)
% F_SECT_PER_TRACK;
/* determine interleave */
il = 1;
if (_floppy->fmt_gap < 0x22)
il++;
/* initialize field */
for (count = 0; count < F_SECT_PER_TRACK; ++count) {
here[count].track = format_req.track;
here[count].head = format_req.head;
here[count].sect = 0;
here[count].size = F_SIZECODE;
}
/* place logical sectors */
for (count = 1; count <= F_SECT_PER_TRACK; ++count) {
here[n].sect = count;
n = (n + il) % F_SECT_PER_TRACK;
if (here[n].sect) { /* sector busy, find next free sector */
++n;
if (n >= F_SECT_PER_TRACK) {
n -= F_SECT_PER_TRACK;
while (here[n].sect)
++n;
}
}
}
if (_floppy->stretch & FD_SECTBASEMASK) {
for (count = 0; count < F_SECT_PER_TRACK; count++)
here[count].sect += FD_SECTBASE(_floppy) - 1;
}
}
static void redo_format(void)
{
buffer_track = -1;
setup_format_params(format_req.track << STRETCH(_floppy));
floppy_start();
debugt(__func__, "queue format request");
}
static const struct cont_t format_cont = {
.interrupt = format_interrupt,
.redo = redo_format,
.error = bad_flp_intr,
.done = generic_done
};
static int do_format(int drive, struct format_descr *tmp_format_req)
{
int ret;
if (lock_fdc(drive))
return -EINTR;
set_floppy(drive);
if (!_floppy ||
_floppy->track > DP->tracks ||
tmp_format_req->track >= _floppy->track ||
tmp_format_req->head >= _floppy->head ||
(_floppy->sect << 2) % (1 << FD_SIZECODE(_floppy)) ||
!_floppy->fmt_gap) {
process_fd_request();
return -EINVAL;
}
format_req = *tmp_format_req;
format_errors = 0;
cont = &format_cont;
errors = &format_errors;
ret = wait_til_done(redo_format, true);
if (ret == -EINTR)
return -EINTR;
process_fd_request();
return ret;
}
/*
* Buffer read/write and support
* =============================
*/
static void floppy_end_request(struct request *req, blk_status_t error)
{
unsigned int nr_sectors = current_count_sectors;
unsigned int drive = (unsigned long)req->rq_disk->private_data;
/* current_count_sectors can be zero if transfer failed */
if (error)
nr_sectors = blk_rq_cur_sectors(req);
if (blk_update_request(req, error, nr_sectors << 9))
return;
__blk_mq_end_request(req, error);
/* We're done with the request */
floppy_off(drive);
current_req = NULL;
}
/* new request_done. Can handle physical sectors which are smaller than a
* logical buffer */
static void request_done(int uptodate)
{
struct request *req = current_req;
int block;
char msg[sizeof("request done ") + sizeof(int) * 3];
probing = 0;
snprintf(msg, sizeof(msg), "request done %d", uptodate);
reschedule_timeout(MAXTIMEOUT, msg);
if (!req) {
pr_info("floppy.c: no request in request_done\n");
return;
}
if (uptodate) {
/* maintain values for invalidation on geometry
* change */
block = current_count_sectors + blk_rq_pos(req);
INFBOUND(DRS->maxblock, block);
if (block > _floppy->sect)
DRS->maxtrack = 1;
floppy_end_request(req, 0);
} else {
if (rq_data_dir(req) == WRITE) {
/* record write error information */
DRWE->write_errors++;
if (DRWE->write_errors == 1) {
DRWE->first_error_sector = blk_rq_pos(req);
DRWE->first_error_generation = DRS->generation;
}
DRWE->last_error_sector = blk_rq_pos(req);
DRWE->last_error_generation = DRS->generation;
}
floppy_end_request(req, BLK_STS_IOERR);
}
}
/* Interrupt handler evaluating the result of the r/w operation */
static void rw_interrupt(void)
{
int eoc;
int ssize;
int heads;
int nr_sectors;
if (R_HEAD >= 2) {
/* some Toshiba floppy controllers occasionnally seem to
* return bogus interrupts after read/write operations, which
* can be recognized by a bad head number (>= 2) */
return;
}
if (!DRS->first_read_date)
DRS->first_read_date = jiffies;
nr_sectors = 0;
ssize = DIV_ROUND_UP(1 << SIZECODE, 4);
if (ST1 & ST1_EOC)
eoc = 1;
else
eoc = 0;
if (COMMAND & 0x80)
heads = 2;
else
heads = 1;
nr_sectors = (((R_TRACK - TRACK) * heads +
R_HEAD - HEAD) * SECT_PER_TRACK +
R_SECTOR - SECTOR + eoc) << SIZECODE >> 2;
if (nr_sectors / ssize >
DIV_ROUND_UP(in_sector_offset + current_count_sectors, ssize)) {
DPRINT("long rw: %x instead of %lx\n",
nr_sectors, current_count_sectors);
pr_info("rs=%d s=%d\n", R_SECTOR, SECTOR);
pr_info("rh=%d h=%d\n", R_HEAD, HEAD);
pr_info("rt=%d t=%d\n", R_TRACK, TRACK);
pr_info("heads=%d eoc=%d\n", heads, eoc);
pr_info("spt=%d st=%d ss=%d\n",
SECT_PER_TRACK, fsector_t, ssize);
pr_info("in_sector_offset=%d\n", in_sector_offset);
}
nr_sectors -= in_sector_offset;
INFBOUND(nr_sectors, 0);
SUPBOUND(current_count_sectors, nr_sectors);
switch (interpret_errors()) {
case 2:
cont->redo();
return;
case 1:
if (!current_count_sectors) {
cont->error();
cont->redo();
return;
}
break;
case 0:
if (!current_count_sectors) {
cont->redo();
return;
}
current_type[current_drive] = _floppy;
floppy_sizes[TOMINOR(current_drive)] = _floppy->size;
break;
}
if (probing) {
if (DP->flags & FTD_MSG)
DPRINT("Auto-detected floppy type %s in fd%d\n",
_floppy->name, current_drive);
current_type[current_drive] = _floppy;
floppy_sizes[TOMINOR(current_drive)] = _floppy->size;
probing = 0;
}
if (CT(COMMAND) != FD_READ ||
raw_cmd->kernel_data == bio_data(current_req->bio)) {
/* transfer directly from buffer */
cont->done(1);
} else if (CT(COMMAND) == FD_READ) {
buffer_track = raw_cmd->track;
buffer_drive = current_drive;
INFBOUND(buffer_max, nr_sectors + fsector_t);
}
cont->redo();
}
/* Compute maximal contiguous buffer size. */
static int buffer_chain_size(void)
{
struct bio_vec bv;
int size;
struct req_iterator iter;
char *base;
base = bio_data(current_req->bio);
size = 0;
rq_for_each_segment(bv, current_req, iter) {
if (page_address(bv.bv_page) + bv.bv_offset != base + size)
break;
size += bv.bv_len;
}
return size >> 9;
}
/* Compute the maximal transfer size */
static int transfer_size(int ssize, int max_sector, int max_size)
{
SUPBOUND(max_sector, fsector_t + max_size);
/* alignment */
max_sector -= (max_sector % _floppy->sect) % ssize;
/* transfer size, beginning not aligned */
current_count_sectors = max_sector - fsector_t;
return max_sector;
}
/*
* Move data from/to the track buffer to/from the buffer cache.
*/
static void copy_buffer(int ssize, int max_sector, int max_sector_2)
{
int remaining; /* number of transferred 512-byte sectors */
struct bio_vec bv;
char *buffer;
char *dma_buffer;
int size;
struct req_iterator iter;
max_sector = transfer_size(ssize,
min(max_sector, max_sector_2),
blk_rq_sectors(current_req));
if (current_count_sectors <= 0 && CT(COMMAND) == FD_WRITE &&
buffer_max > fsector_t + blk_rq_sectors(current_req))
current_count_sectors = min_t(int, buffer_max - fsector_t,
blk_rq_sectors(current_req));
remaining = current_count_sectors << 9;
if (remaining > blk_rq_bytes(current_req) && CT(COMMAND) == FD_WRITE) {
DPRINT("in copy buffer\n");
pr_info("current_count_sectors=%ld\n", current_count_sectors);
pr_info("remaining=%d\n", remaining >> 9);
pr_info("current_req->nr_sectors=%u\n",
blk_rq_sectors(current_req));
pr_info("current_req->current_nr_sectors=%u\n",
blk_rq_cur_sectors(current_req));
pr_info("max_sector=%d\n", max_sector);
pr_info("ssize=%d\n", ssize);
}
buffer_max = max(max_sector, buffer_max);
dma_buffer = floppy_track_buffer + ((fsector_t - buffer_min) << 9);
size = blk_rq_cur_bytes(current_req);
rq_for_each_segment(bv, current_req, iter) {
if (!remaining)
break;
size = bv.bv_len;
SUPBOUND(size, remaining);
buffer = page_address(bv.bv_page) + bv.bv_offset;
if (dma_buffer + size >
floppy_track_buffer + (max_buffer_sectors << 10) ||
dma_buffer < floppy_track_buffer) {
DPRINT("buffer overrun in copy buffer %d\n",
(int)((floppy_track_buffer - dma_buffer) >> 9));
pr_info("fsector_t=%d buffer_min=%d\n",
fsector_t, buffer_min);
pr_info("current_count_sectors=%ld\n",
current_count_sectors);
if (CT(COMMAND) == FD_READ)
pr_info("read\n");
if (CT(COMMAND) == FD_WRITE)
pr_info("write\n");
break;
}
if (((unsigned long)buffer) % 512)
DPRINT("%p buffer not aligned\n", buffer);
if (CT(COMMAND) == FD_READ)
memcpy(buffer, dma_buffer, size);
else
memcpy(dma_buffer, buffer, size);
remaining -= size;
dma_buffer += size;
}
if (remaining) {
if (remaining > 0)
max_sector -= remaining >> 9;
DPRINT("weirdness: remaining %d\n", remaining >> 9);
}
}
/* work around a bug in pseudo DMA
* (on some FDCs) pseudo DMA does not stop when the CPU stops
* sending data. Hence we need a different way to signal the
* transfer length: We use SECT_PER_TRACK. Unfortunately, this
* does not work with MT, hence we can only transfer one head at
* a time
*/
static void virtualdmabug_workaround(void)
{
int hard_sectors;
int end_sector;
if (CT(COMMAND) == FD_WRITE) {
COMMAND &= ~0x80; /* switch off multiple track mode */
hard_sectors = raw_cmd->length >> (7 + SIZECODE);
end_sector = SECTOR + hard_sectors - 1;
if (end_sector > SECT_PER_TRACK) {
pr_info("too many sectors %d > %d\n",
end_sector, SECT_PER_TRACK);
return;
}
SECT_PER_TRACK = end_sector;
/* make sure SECT_PER_TRACK
* points to end of transfer */
}
}
/*
* Formulate a read/write request.
* this routine decides where to load the data (directly to buffer, or to
* tmp floppy area), how much data to load (the size of the buffer, the whole
* track, or a single sector)
* All floppy_track_buffer handling goes in here. If we ever add track buffer
* allocation on the fly, it should be done here. No other part should need
* modification.
*/
static int make_raw_rw_request(void)
{
int aligned_sector_t;
int max_sector;
int max_size;
int tracksize;
int ssize;
if (WARN(max_buffer_sectors == 0, "VFS: Block I/O scheduled on unopened device\n"))
return 0;
set_fdc((long)current_req->rq_disk->private_data);
raw_cmd = &default_raw_cmd;
raw_cmd->flags = FD_RAW_SPIN | FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK;
raw_cmd->cmd_count = NR_RW;
if (rq_data_dir(current_req) == READ) {
raw_cmd->flags |= FD_RAW_READ;
COMMAND = FM_MODE(_floppy, FD_READ);
} else if (rq_data_dir(current_req) == WRITE) {
raw_cmd->flags |= FD_RAW_WRITE;
COMMAND = FM_MODE(_floppy, FD_WRITE);
} else {
DPRINT("%s: unknown command\n", __func__);
return 0;
}
max_sector = _floppy->sect * _floppy->head;
TRACK = (int)blk_rq_pos(current_req) / max_sector;
fsector_t = (int)blk_rq_pos(current_req) % max_sector;
if (_floppy->track && TRACK >= _floppy->track) {
if (blk_rq_cur_sectors(current_req) & 1) {
current_count_sectors = 1;
return 1;
} else
return 0;
}
HEAD = fsector_t / _floppy->sect;
if (((_floppy->stretch & (FD_SWAPSIDES | FD_SECTBASEMASK)) ||
test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags)) &&
fsector_t < _floppy->sect)
max_sector = _floppy->sect;
/* 2M disks have phantom sectors on the first track */
if ((_floppy->rate & FD_2M) && (!TRACK) && (!HEAD)) {
max_sector = 2 * _floppy->sect / 3;
if (fsector_t >= max_sector) {
current_count_sectors =
min_t(int, _floppy->sect - fsector_t,
blk_rq_sectors(current_req));
return 1;
}
SIZECODE = 2;
} else
SIZECODE = FD_SIZECODE(_floppy);
raw_cmd->rate = _floppy->rate & 0x43;
if ((_floppy->rate & FD_2M) && (TRACK || HEAD) && raw_cmd->rate == 2)
raw_cmd->rate = 1;
if (SIZECODE)
SIZECODE2 = 0xff;
else
SIZECODE2 = 0x80;
raw_cmd->track = TRACK << STRETCH(_floppy);
DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, HEAD);
GAP = _floppy->gap;
ssize = DIV_ROUND_UP(1 << SIZECODE, 4);
SECT_PER_TRACK = _floppy->sect << 2 >> SIZECODE;
SECTOR = ((fsector_t % _floppy->sect) << 2 >> SIZECODE) +
FD_SECTBASE(_floppy);
/* tracksize describes the size which can be filled up with sectors
* of size ssize.
*/
tracksize = _floppy->sect - _floppy->sect % ssize;
if (tracksize < _floppy->sect) {
SECT_PER_TRACK++;
if (tracksize <= fsector_t % _floppy->sect)
SECTOR--;
/* if we are beyond tracksize, fill up using smaller sectors */
while (tracksize <= fsector_t % _floppy->sect) {
while (tracksize + ssize > _floppy->sect) {
SIZECODE--;
ssize >>= 1;
}
SECTOR++;
SECT_PER_TRACK++;
tracksize += ssize;
}
max_sector = HEAD * _floppy->sect + tracksize;
} else if (!TRACK && !HEAD && !(_floppy->rate & FD_2M) && probing) {
max_sector = _floppy->sect;
} else if (!HEAD && CT(COMMAND) == FD_WRITE) {
/* for virtual DMA bug workaround */
max_sector = _floppy->sect;
}
in_sector_offset = (fsector_t % _floppy->sect) % ssize;
aligned_sector_t = fsector_t - in_sector_offset;
max_size = blk_rq_sectors(current_req);
if ((raw_cmd->track == buffer_track) &&
(current_drive == buffer_drive) &&
(fsector_t >= buffer_min) && (fsector_t < buffer_max)) {
/* data already in track buffer */
if (CT(COMMAND) == FD_READ) {
copy_buffer(1, max_sector, buffer_max);
return 1;
}
} else if (in_sector_offset || blk_rq_sectors(current_req) < ssize) {
if (CT(COMMAND) == FD_WRITE) {
unsigned int sectors;
sectors = fsector_t + blk_rq_sectors(current_req);
if (sectors > ssize && sectors < ssize + ssize)
max_size = ssize + ssize;
else
max_size = ssize;
}
raw_cmd->flags &= ~FD_RAW_WRITE;
raw_cmd->flags |= FD_RAW_READ;
COMMAND = FM_MODE(_floppy, FD_READ);
} else if ((unsigned long)bio_data(current_req->bio) < MAX_DMA_ADDRESS) {
unsigned long dma_limit;
int direct, indirect;
indirect =
transfer_size(ssize, max_sector,
max_buffer_sectors * 2) - fsector_t;
/*
* Do NOT use minimum() here---MAX_DMA_ADDRESS is 64 bits wide
* on a 64 bit machine!
*/
max_size = buffer_chain_size();
dma_limit = (MAX_DMA_ADDRESS -
((unsigned long)bio_data(current_req->bio))) >> 9;
if ((unsigned long)max_size > dma_limit)
max_size = dma_limit;
/* 64 kb boundaries */
if (CROSS_64KB(bio_data(current_req->bio), max_size << 9))
max_size = (K_64 -
((unsigned long)bio_data(current_req->bio)) %
K_64) >> 9;
direct = transfer_size(ssize, max_sector, max_size) - fsector_t;
/*
* We try to read tracks, but if we get too many errors, we
* go back to reading just one sector at a time.
*
* This means we should be able to read a sector even if there
* are other bad sectors on this track.
*/
if (!direct ||
(indirect * 2 > direct * 3 &&
*errors < DP->max_errors.read_track &&
((!probing ||
(DP->read_track & (1 << DRS->probed_format)))))) {
max_size = blk_rq_sectors(current_req);
} else {
raw_cmd->kernel_data = bio_data(current_req->bio);
raw_cmd->length = current_count_sectors << 9;
if (raw_cmd->length == 0) {
DPRINT("%s: zero dma transfer attempted\n", __func__);
DPRINT("indirect=%d direct=%d fsector_t=%d\n",
indirect, direct, fsector_t);
return 0;
}
virtualdmabug_workaround();
return 2;
}
}
if (CT(COMMAND) == FD_READ)
max_size = max_sector; /* unbounded */
/* claim buffer track if needed */
if (buffer_track != raw_cmd->track || /* bad track */
buffer_drive != current_drive || /* bad drive */
fsector_t > buffer_max ||
fsector_t < buffer_min ||
((CT(COMMAND) == FD_READ ||
(!in_sector_offset && blk_rq_sectors(current_req) >= ssize)) &&
max_sector > 2 * max_buffer_sectors + buffer_min &&
max_size + fsector_t > 2 * max_buffer_sectors + buffer_min)) {
/* not enough space */
buffer_track = -1;
buffer_drive = current_drive;
buffer_max = buffer_min = aligned_sector_t;
}
raw_cmd->kernel_data = floppy_track_buffer +
((aligned_sector_t - buffer_min) << 9);
if (CT(COMMAND) == FD_WRITE) {
/* copy write buffer to track buffer.
* if we get here, we know that the write
* is either aligned or the data already in the buffer
* (buffer will be overwritten) */
if (in_sector_offset && buffer_track == -1)
DPRINT("internal error offset !=0 on write\n");
buffer_track = raw_cmd->track;
buffer_drive = current_drive;
copy_buffer(ssize, max_sector,
2 * max_buffer_sectors + buffer_min);
} else
transfer_size(ssize, max_sector,
2 * max_buffer_sectors + buffer_min -
aligned_sector_t);
/* round up current_count_sectors to get dma xfer size */
raw_cmd->length = in_sector_offset + current_count_sectors;
raw_cmd->length = ((raw_cmd->length - 1) | (ssize - 1)) + 1;
raw_cmd->length <<= 9;
if ((raw_cmd->length < current_count_sectors << 9) ||
(raw_cmd->kernel_data != bio_data(current_req->bio) &&
CT(COMMAND) == FD_WRITE &&
(aligned_sector_t + (raw_cmd->length >> 9) > buffer_max ||
aligned_sector_t < buffer_min)) ||
raw_cmd->length % (128 << SIZECODE) ||
raw_cmd->length <= 0 || current_count_sectors <= 0) {
DPRINT("fractionary current count b=%lx s=%lx\n",
raw_cmd->length, current_count_sectors);
if (raw_cmd->kernel_data != bio_data(current_req->bio))
pr_info("addr=%d, length=%ld\n",
(int)((raw_cmd->kernel_data -
floppy_track_buffer) >> 9),
current_count_sectors);
pr_info("st=%d ast=%d mse=%d msi=%d\n",
fsector_t, aligned_sector_t, max_sector, max_size);
pr_info("ssize=%x SIZECODE=%d\n", ssize, SIZECODE);
pr_info("command=%x SECTOR=%d HEAD=%d, TRACK=%d\n",
COMMAND, SECTOR, HEAD, TRACK);
pr_info("buffer drive=%d\n", buffer_drive);
pr_info("buffer track=%d\n", buffer_track);
pr_info("buffer_min=%d\n", buffer_min);
pr_info("buffer_max=%d\n", buffer_max);
return 0;
}
if (raw_cmd->kernel_data != bio_data(current_req->bio)) {
if (raw_cmd->kernel_data < floppy_track_buffer ||
current_count_sectors < 0 ||
raw_cmd->length < 0 ||
raw_cmd->kernel_data + raw_cmd->length >
floppy_track_buffer + (max_buffer_sectors << 10)) {
DPRINT("buffer overrun in schedule dma\n");
pr_info("fsector_t=%d buffer_min=%d current_count=%ld\n",
fsector_t, buffer_min, raw_cmd->length >> 9);
pr_info("current_count_sectors=%ld\n",
current_count_sectors);
if (CT(COMMAND) == FD_READ)
pr_info("read\n");
if (CT(COMMAND) == FD_WRITE)
pr_info("write\n");
return 0;
}
} else if (raw_cmd->length > blk_rq_bytes(current_req) ||
current_count_sectors > blk_rq_sectors(current_req)) {
DPRINT("buffer overrun in direct transfer\n");
return 0;
} else if (raw_cmd->length < current_count_sectors << 9) {
DPRINT("more sectors than bytes\n");
pr_info("bytes=%ld\n", raw_cmd->length >> 9);
pr_info("sectors=%ld\n", current_count_sectors);
}
if (raw_cmd->length == 0) {
DPRINT("zero dma transfer attempted from make_raw_request\n");
return 0;
}
virtualdmabug_workaround();
return 2;
}
static int set_next_request(void)
{
current_req = list_first_entry_or_null(&floppy_reqs, struct request,
queuelist);
if (current_req) {
current_req->error_count = 0;
list_del_init(¤t_req->queuelist);
}
return current_req != NULL;
}
static void redo_fd_request(void)
{
int drive;
int tmp;
lastredo = jiffies;
if (current_drive < N_DRIVE)
floppy_off(current_drive);
do_request:
if (!current_req) {
int pending;
spin_lock_irq(&floppy_lock);
pending = set_next_request();
spin_unlock_irq(&floppy_lock);
if (!pending) {
do_floppy = NULL;
unlock_fdc();
return;
}
}
drive = (long)current_req->rq_disk->private_data;
set_fdc(drive);
reschedule_timeout(current_reqD, "redo fd request");
set_floppy(drive);
raw_cmd = &default_raw_cmd;
raw_cmd->flags = 0;
if (start_motor(redo_fd_request))
return;
disk_change(current_drive);
if (test_bit(current_drive, &fake_change) ||
test_bit(FD_DISK_CHANGED_BIT, &DRS->flags)) {
DPRINT("disk absent or changed during operation\n");
request_done(0);
goto do_request;
}
if (!_floppy) { /* Autodetection */
if (!probing) {
DRS->probed_format = 0;
if (next_valid_format()) {
DPRINT("no autodetectable formats\n");
_floppy = NULL;
request_done(0);
goto do_request;
}
}
probing = 1;
_floppy = floppy_type + DP->autodetect[DRS->probed_format];
} else
probing = 0;
errors = &(current_req->error_count);
tmp = make_raw_rw_request();
if (tmp < 2) {
request_done(tmp);
goto do_request;
}
if (test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags))
twaddle();
schedule_bh(floppy_start);
debugt(__func__, "queue fd request");
return;
}
static const struct cont_t rw_cont = {
.interrupt = rw_interrupt,
.redo = redo_fd_request,
.error = bad_flp_intr,
.done = request_done
};
static void process_fd_request(void)
{
cont = &rw_cont;
schedule_bh(redo_fd_request);
}
static blk_status_t floppy_queue_rq(struct blk_mq_hw_ctx *hctx,
const struct blk_mq_queue_data *bd)
{
blk_mq_start_request(bd->rq);
if (WARN(max_buffer_sectors == 0,
"VFS: %s called on non-open device\n", __func__))
return BLK_STS_IOERR;
if (WARN(atomic_read(&usage_count) == 0,
"warning: usage count=0, current_req=%p sect=%ld flags=%llx\n",
current_req, (long)blk_rq_pos(current_req),
(unsigned long long) current_req->cmd_flags))
return BLK_STS_IOERR;
spin_lock_irq(&floppy_lock);
list_add_tail(&bd->rq->queuelist, &floppy_reqs);
spin_unlock_irq(&floppy_lock);
if (test_and_set_bit(0, &fdc_busy)) {
/* fdc busy, this new request will be treated when the
current one is done */
is_alive(__func__, "old request running");
return BLK_STS_OK;
}
command_status = FD_COMMAND_NONE;
__reschedule_timeout(MAXTIMEOUT, "fd_request");
set_fdc(0);
process_fd_request();
is_alive(__func__, "");
return BLK_STS_OK;
}
static const struct cont_t poll_cont = {
.interrupt = success_and_wakeup,
.redo = floppy_ready,
.error = generic_failure,
.done = generic_done
};
static int poll_drive(bool interruptible, int flag)
{
/* no auto-sense, just clear dcl */
raw_cmd = &default_raw_cmd;
raw_cmd->flags = flag;
raw_cmd->track = 0;
raw_cmd->cmd_count = 0;
cont = &poll_cont;
debug_dcl(DP->flags, "setting NEWCHANGE in poll_drive\n");
set_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);
return wait_til_done(floppy_ready, interruptible);
}
/*
* User triggered reset
* ====================
*/
static void reset_intr(void)
{
pr_info("weird, reset interrupt called\n");
}
static const struct cont_t reset_cont = {
.interrupt = reset_intr,
.redo = success_and_wakeup,
.error = generic_failure,
.done = generic_done
};
static int user_reset_fdc(int drive, int arg, bool interruptible)
{
int ret;
if (lock_fdc(drive))
return -EINTR;
if (arg == FD_RESET_ALWAYS)
FDCS->reset = 1;
if (FDCS->reset) {
cont = &reset_cont;
ret = wait_til_done(reset_fdc, interruptible);
if (ret == -EINTR)
return -EINTR;
}
process_fd_request();
return 0;
}
/*
* Misc Ioctl's and support
* ========================
*/
static inline int fd_copyout(void __user *param, const void *address,
unsigned long size)
{
return copy_to_user(param, address, size) ? -EFAULT : 0;
}
static inline int fd_copyin(void __user *param, void *address,
unsigned long size)
{
return copy_from_user(address, param, size) ? -EFAULT : 0;
}
static const char *drive_name(int type, int drive)
{
struct floppy_struct *floppy;
if (type)
floppy = floppy_type + type;
else {
if (UDP->native_format)
floppy = floppy_type + UDP->native_format;
else
return "(null)";
}
if (floppy->name)
return floppy->name;
else
return "(null)";
}
/* raw commands */
static void raw_cmd_done(int flag)
{
int i;
if (!flag) {
raw_cmd->flags |= FD_RAW_FAILURE;
raw_cmd->flags |= FD_RAW_HARDFAILURE;
} else {
raw_cmd->reply_count = inr;
if (raw_cmd->reply_count > MAX_REPLIES)
raw_cmd->reply_count = 0;
for (i = 0; i < raw_cmd->reply_count; i++)
raw_cmd->reply[i] = reply_buffer[i];
if (raw_cmd->flags & (FD_RAW_READ | FD_RAW_WRITE)) {
unsigned long flags;
flags = claim_dma_lock();
raw_cmd->length = fd_get_dma_residue();
release_dma_lock(flags);
}
if ((raw_cmd->flags & FD_RAW_SOFTFAILURE) &&
(!raw_cmd->reply_count || (raw_cmd->reply[0] & 0xc0)))
raw_cmd->flags |= FD_RAW_FAILURE;
if (disk_change(current_drive))
raw_cmd->flags |= FD_RAW_DISK_CHANGE;
else
raw_cmd->flags &= ~FD_RAW_DISK_CHANGE;
if (raw_cmd->flags & FD_RAW_NO_MOTOR_AFTER)
motor_off_callback(&motor_off_timer[current_drive]);
if (raw_cmd->next &&
(!(raw_cmd->flags & FD_RAW_FAILURE) ||
!(raw_cmd->flags & FD_RAW_STOP_IF_FAILURE)) &&
((raw_cmd->flags & FD_RAW_FAILURE) ||
!(raw_cmd->flags & FD_RAW_STOP_IF_SUCCESS))) {
raw_cmd = raw_cmd->next;
return;
}
}
generic_done(flag);
}
static const struct cont_t raw_cmd_cont = {
.interrupt = success_and_wakeup,
.redo = floppy_start,
.error = generic_failure,
.done = raw_cmd_done
};
static int raw_cmd_copyout(int cmd, void __user *param,
struct floppy_raw_cmd *ptr)
{
int ret;
while (ptr) {
struct floppy_raw_cmd cmd = *ptr;
cmd.next = NULL;
cmd.kernel_data = NULL;
ret = copy_to_user(param, &cmd, sizeof(cmd));
if (ret)
return -EFAULT;
param += sizeof(struct floppy_raw_cmd);
if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) {
if (ptr->length >= 0 &&
ptr->length <= ptr->buffer_length) {
long length = ptr->buffer_length - ptr->length;
ret = fd_copyout(ptr->data, ptr->kernel_data,
length);
if (ret)
return ret;
}
}
ptr = ptr->next;
}
return 0;
}
static void raw_cmd_free(struct floppy_raw_cmd **ptr)
{
struct floppy_raw_cmd *next;
struct floppy_raw_cmd *this;
this = *ptr;
*ptr = NULL;
while (this) {
if (this->buffer_length) {
fd_dma_mem_free((unsigned long)this->kernel_data,
this->buffer_length);
this->buffer_length = 0;
}
next = this->next;
kfree(this);
this = next;
}
}
static int raw_cmd_copyin(int cmd, void __user *param,
struct floppy_raw_cmd **rcmd)
{
struct floppy_raw_cmd *ptr;
int ret;
int i;
*rcmd = NULL;
loop:
ptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_KERNEL);
if (!ptr)
return -ENOMEM;
*rcmd = ptr;
ret = copy_from_user(ptr, param, sizeof(*ptr));
ptr->next = NULL;
ptr->buffer_length = 0;
ptr->kernel_data = NULL;
if (ret)
return -EFAULT;
param += sizeof(struct floppy_raw_cmd);
if (ptr->cmd_count > 33)
/* the command may now also take up the space
* initially intended for the reply & the
* reply count. Needed for long 82078 commands
* such as RESTORE, which takes ... 17 command
* bytes. Murphy's law #137: When you reserve
* 16 bytes for a structure, you'll one day
* discover that you really need 17...
*/
return -EINVAL;
for (i = 0; i < 16; i++)
ptr->reply[i] = 0;
ptr->resultcode = 0;
if (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) {
if (ptr->length <= 0)
return -EINVAL;
ptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length);
fallback_on_nodma_alloc(&ptr->kernel_data, ptr->length);
if (!ptr->kernel_data)
return -ENOMEM;
ptr->buffer_length = ptr->length;
}
if (ptr->flags & FD_RAW_WRITE) {
ret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length);
if (ret)
return ret;
}
if (ptr->flags & FD_RAW_MORE) {
rcmd = &(ptr->next);
ptr->rate &= 0x43;
goto loop;
}
return 0;
}
static int raw_cmd_ioctl(int cmd, void __user *param)
{
struct floppy_raw_cmd *my_raw_cmd;
int drive;
int ret2;
int ret;
if (FDCS->rawcmd <= 1)
FDCS->rawcmd = 1;
for (drive = 0; drive < N_DRIVE; drive++) {
if (FDC(drive) != fdc)
continue;
if (drive == current_drive) {
if (UDRS->fd_ref > 1) {
FDCS->rawcmd = 2;
break;
}
} else if (UDRS->fd_ref) {
FDCS->rawcmd = 2;
break;
}
}
if (FDCS->reset)
return -EIO;
ret = raw_cmd_copyin(cmd, param, &my_raw_cmd);
if (ret) {
raw_cmd_free(&my_raw_cmd);
return ret;
}
raw_cmd = my_raw_cmd;
cont = &raw_cmd_cont;
ret = wait_til_done(floppy_start, true);
debug_dcl(DP->flags, "calling disk change from raw_cmd ioctl\n");
if (ret != -EINTR && FDCS->reset)
ret = -EIO;
DRS->track = NO_TRACK;
ret2 = raw_cmd_copyout(cmd, param, my_raw_cmd);
if (!ret)
ret = ret2;
raw_cmd_free(&my_raw_cmd);
return ret;
}
static int invalidate_drive(struct block_device *bdev)
{
/* invalidate the buffer track to force a reread */
set_bit((long)bdev->bd_disk->private_data, &fake_change);
process_fd_request();
check_disk_change(bdev);
return 0;
}
static int set_geometry(unsigned int cmd, struct floppy_struct *g,
int drive, int type, struct block_device *bdev)
{
int cnt;
/* sanity checking for parameters. */
if ((int)g->sect <= 0 ||
(int)g->head <= 0 ||
/* check for overflow in max_sector */
(int)(g->sect * g->head) <= 0 ||
/* check for zero in F_SECT_PER_TRACK */
(unsigned char)((g->sect << 2) >> FD_SIZECODE(g)) == 0 ||
g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||
/* check if reserved bits are set */
(g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)
return -EINVAL;
if (type) {
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
mutex_lock(&open_lock);
if (lock_fdc(drive)) {
mutex_unlock(&open_lock);
return -EINTR;
}
floppy_type[type] = *g;
floppy_type[type].name = "user format";
for (cnt = type << 2; cnt < (type << 2) + 4; cnt++)
floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =
floppy_type[type].size + 1;
process_fd_request();
for (cnt = 0; cnt < N_DRIVE; cnt++) {
struct block_device *bdev = opened_bdev[cnt];
if (!bdev || ITYPE(drive_state[cnt].fd_device) != type)
continue;
__invalidate_device(bdev, true);
}
mutex_unlock(&open_lock);
} else {
int oldStretch;
if (lock_fdc(drive))
return -EINTR;
if (cmd != FDDEFPRM) {
/* notice a disk change immediately, else
* we lose our settings immediately*/
if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
return -EINTR;
}
oldStretch = g->stretch;
user_params[drive] = *g;
if (buffer_drive == drive)
SUPBOUND(buffer_max, user_params[drive].sect);
current_type[drive] = &user_params[drive];
floppy_sizes[drive] = user_params[drive].size;
if (cmd == FDDEFPRM)
DRS->keep_data = -1;
else
DRS->keep_data = 1;
/* invalidation. Invalidate only when needed, i.e.
* when there are already sectors in the buffer cache
* whose number will change. This is useful, because
* mtools often changes the geometry of the disk after
* looking at the boot block */
if (DRS->maxblock > user_params[drive].sect ||
DRS->maxtrack ||
((user_params[drive].sect ^ oldStretch) &
(FD_SWAPSIDES | FD_SECTBASEMASK)))
invalidate_drive(bdev);
else
process_fd_request();
}
return 0;
}
/* handle obsolete ioctl's */
static unsigned int ioctl_table[] = {
FDCLRPRM,
FDSETPRM,
FDDEFPRM,
FDGETPRM,
FDMSGON,
FDMSGOFF,
FDFMTBEG,
FDFMTTRK,
FDFMTEND,
FDSETEMSGTRESH,
FDFLUSH,
FDSETMAXERRS,
FDGETMAXERRS,
FDGETDRVTYP,
FDSETDRVPRM,
FDGETDRVPRM,
FDGETDRVSTAT,
FDPOLLDRVSTAT,
FDRESET,
FDGETFDCSTAT,
FDWERRORCLR,
FDWERRORGET,
FDRAWCMD,
FDEJECT,
FDTWADDLE
};
static int normalize_ioctl(unsigned int *cmd, int *size)
{
int i;
for (i = 0; i < ARRAY_SIZE(ioctl_table); i++) {
if ((*cmd & 0xffff) == (ioctl_table[i] & 0xffff)) {
*size = _IOC_SIZE(*cmd);
*cmd = ioctl_table[i];
if (*size > _IOC_SIZE(*cmd)) {
pr_info("ioctl not yet supported\n");
return -EFAULT;
}
return 0;
}
}
return -EINVAL;
}
static int get_floppy_geometry(int drive, int type, struct floppy_struct **g)
{
if (type)
*g = &floppy_type[type];
else {
if (lock_fdc(drive))
return -EINTR;
if (poll_drive(false, 0) == -EINTR)
return -EINTR;
process_fd_request();
*g = current_type[drive];
}
if (!*g)
return -ENODEV;
return 0;
}
static int fd_getgeo(struct block_device *bdev, struct hd_geometry *geo)
{
int drive = (long)bdev->bd_disk->private_data;
int type = ITYPE(drive_state[drive].fd_device);
struct floppy_struct *g;
int ret;
ret = get_floppy_geometry(drive, type, &g);
if (ret)
return ret;
geo->heads = g->head;
geo->sectors = g->sect;
geo->cylinders = g->track;
return 0;
}
static bool valid_floppy_drive_params(const short autodetect[8],
int native_format)
{
size_t floppy_type_size = ARRAY_SIZE(floppy_type);
size_t i = 0;
for (i = 0; i < 8; ++i) {
if (autodetect[i] < 0 ||
autodetect[i] >= floppy_type_size)
return false;
}
if (native_format < 0 || native_format >= floppy_type_size)
return false;
return true;
}
static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,
unsigned long param)
{
int drive = (long)bdev->bd_disk->private_data;
int type = ITYPE(UDRS->fd_device);
int i;
int ret;
int size;
union inparam {
struct floppy_struct g; /* geometry */
struct format_descr f;
struct floppy_max_errors max_errors;
struct floppy_drive_params dp;
} inparam; /* parameters coming from user space */
const void *outparam; /* parameters passed back to user space */
/* convert compatibility eject ioctls into floppy eject ioctl.
* We do this in order to provide a means to eject floppy disks before
* installing the new fdutils package */
if (cmd == CDROMEJECT || /* CD-ROM eject */
cmd == 0x6470) { /* SunOS floppy eject */
DPRINT("obsolete eject ioctl\n");
DPRINT("please use floppycontrol --eject\n");
cmd = FDEJECT;
}
if (!((cmd & 0xff00) == 0x0200))
return -EINVAL;
/* convert the old style command into a new style command */
ret = normalize_ioctl(&cmd, &size);
if (ret)
return ret;
/* permission checks */
if (((cmd & 0x40) && !(mode & (FMODE_WRITE | FMODE_WRITE_IOCTL))) ||
((cmd & 0x80) && !capable(CAP_SYS_ADMIN)))
return -EPERM;
if (WARN_ON(size < 0 || size > sizeof(inparam)))
return -EINVAL;
/* copyin */
memset(&inparam, 0, sizeof(inparam));
if (_IOC_DIR(cmd) & _IOC_WRITE) {
ret = fd_copyin((void __user *)param, &inparam, size);
if (ret)
return ret;
}
switch (cmd) {
case FDEJECT:
if (UDRS->fd_ref != 1)
/* somebody else has this drive open */
return -EBUSY;
if (lock_fdc(drive))
return -EINTR;
/* do the actual eject. Fails on
* non-Sparc architectures */
ret = fd_eject(UNIT(drive));
set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
set_bit(FD_VERIFY_BIT, &UDRS->flags);
process_fd_request();
return ret;
case FDCLRPRM:
if (lock_fdc(drive))
return -EINTR;
current_type[drive] = NULL;
floppy_sizes[drive] = MAX_DISK_SIZE << 1;
UDRS->keep_data = 0;
return invalidate_drive(bdev);
case FDSETPRM:
case FDDEFPRM:
return set_geometry(cmd, &inparam.g, drive, type, bdev);
case FDGETPRM:
ret = get_floppy_geometry(drive, type,
(struct floppy_struct **)&outparam);
if (ret)
return ret;
memcpy(&inparam.g, outparam,
offsetof(struct floppy_struct, name));
outparam = &inparam.g;
break;
case FDMSGON:
UDP->flags |= FTD_MSG;
return 0;
case FDMSGOFF:
UDP->flags &= ~FTD_MSG;
return 0;
case FDFMTBEG:
if (lock_fdc(drive))
return -EINTR;
if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
return -EINTR;
ret = UDRS->flags;
process_fd_request();
if (ret & FD_VERIFY)
return -ENODEV;
if (!(ret & FD_DISK_WRITABLE))
return -EROFS;
return 0;
case FDFMTTRK:
if (UDRS->fd_ref != 1)
return -EBUSY;
return do_format(drive, &inparam.f);
case FDFMTEND:
case FDFLUSH:
if (lock_fdc(drive))
return -EINTR;
return invalidate_drive(bdev);
case FDSETEMSGTRESH:
UDP->max_errors.reporting = (unsigned short)(param & 0x0f);
return 0;
case FDGETMAXERRS:
outparam = &UDP->max_errors;
break;
case FDSETMAXERRS:
UDP->max_errors = inparam.max_errors;
break;
case FDGETDRVTYP:
outparam = drive_name(type, drive);
SUPBOUND(size, strlen((const char *)outparam) + 1);
break;
case FDSETDRVPRM:
if (!valid_floppy_drive_params(inparam.dp.autodetect,
inparam.dp.native_format))
return -EINVAL;
*UDP = inparam.dp;
break;
case FDGETDRVPRM:
outparam = UDP;
break;
case FDPOLLDRVSTAT:
if (lock_fdc(drive))
return -EINTR;
if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
return -EINTR;
process_fd_request();
/* fall through */
case FDGETDRVSTAT:
outparam = UDRS;
break;
case FDRESET:
return user_reset_fdc(drive, (int)param, true);
case FDGETFDCSTAT:
outparam = UFDCS;
break;
case FDWERRORCLR:
memset(UDRWE, 0, sizeof(*UDRWE));
return 0;
case FDWERRORGET:
outparam = UDRWE;
break;
case FDRAWCMD:
if (type)
return -EINVAL;
if (lock_fdc(drive))
return -EINTR;
set_floppy(drive);
i = raw_cmd_ioctl(cmd, (void __user *)param);
if (i == -EINTR)
return -EINTR;
process_fd_request();
return i;
case FDTWADDLE:
if (lock_fdc(drive))
return -EINTR;
twaddle();
process_fd_request();
return 0;
default:
return -EINVAL;
}
if (_IOC_DIR(cmd) & _IOC_READ)
return fd_copyout((void __user *)param, outparam, size);
return 0;
}
static int fd_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long param)
{
int ret;
mutex_lock(&floppy_mutex);
ret = fd_locked_ioctl(bdev, mode, cmd, param);
mutex_unlock(&floppy_mutex);
return ret;
}
#ifdef CONFIG_COMPAT
struct compat_floppy_drive_params {
char cmos;
compat_ulong_t max_dtr;
compat_ulong_t hlt;
compat_ulong_t hut;
compat_ulong_t srt;
compat_ulong_t spinup;
compat_ulong_t spindown;
unsigned char spindown_offset;
unsigned char select_delay;
unsigned char rps;
unsigned char tracks;
compat_ulong_t timeout;
unsigned char interleave_sect;
struct floppy_max_errors max_errors;
char flags;
char read_track;
short autodetect[8];
compat_int_t checkfreq;
compat_int_t native_format;
};
struct compat_floppy_drive_struct {
signed char flags;
compat_ulong_t spinup_date;
compat_ulong_t select_date;
compat_ulong_t first_read_date;
short probed_format;
short track;
short maxblock;
short maxtrack;
compat_int_t generation;
compat_int_t keep_data;
compat_int_t fd_ref;
compat_int_t fd_device;
compat_int_t last_checked;
compat_caddr_t dmabuf;
compat_int_t bufblocks;
};
struct compat_floppy_fdc_state {
compat_int_t spec1;
compat_int_t spec2;
compat_int_t dtr;
unsigned char version;
unsigned char dor;
compat_ulong_t address;
unsigned int rawcmd:2;
unsigned int reset:1;
unsigned int need_configure:1;
unsigned int perp_mode:2;
unsigned int has_fifo:1;
unsigned int driver_version;
unsigned char track[4];
};
struct compat_floppy_write_errors {
unsigned int write_errors;
compat_ulong_t first_error_sector;
compat_int_t first_error_generation;
compat_ulong_t last_error_sector;
compat_int_t last_error_generation;
compat_uint_t badness;
};
#define FDSETPRM32 _IOW(2, 0x42, struct compat_floppy_struct)
#define FDDEFPRM32 _IOW(2, 0x43, struct compat_floppy_struct)
#define FDSETDRVPRM32 _IOW(2, 0x90, struct compat_floppy_drive_params)
#define FDGETDRVPRM32 _IOR(2, 0x11, struct compat_floppy_drive_params)
#define FDGETDRVSTAT32 _IOR(2, 0x12, struct compat_floppy_drive_struct)
#define FDPOLLDRVSTAT32 _IOR(2, 0x13, struct compat_floppy_drive_struct)
#define FDGETFDCSTAT32 _IOR(2, 0x15, struct compat_floppy_fdc_state)
#define FDWERRORGET32 _IOR(2, 0x17, struct compat_floppy_write_errors)
static int compat_set_geometry(struct block_device *bdev, fmode_t mode, unsigned int cmd,
struct compat_floppy_struct __user *arg)
{
struct floppy_struct v;
int drive, type;
int err;
BUILD_BUG_ON(offsetof(struct floppy_struct, name) !=
offsetof(struct compat_floppy_struct, name));
if (!(mode & (FMODE_WRITE | FMODE_WRITE_IOCTL)))
return -EPERM;
memset(&v, 0, sizeof(struct floppy_struct));
if (copy_from_user(&v, arg, offsetof(struct floppy_struct, name)))
return -EFAULT;
mutex_lock(&floppy_mutex);
drive = (long)bdev->bd_disk->private_data;
type = ITYPE(UDRS->fd_device);
err = set_geometry(cmd == FDSETPRM32 ? FDSETPRM : FDDEFPRM,
&v, drive, type, bdev);
mutex_unlock(&floppy_mutex);
return err;
}
static int compat_get_prm(int drive,
struct compat_floppy_struct __user *arg)
{
struct compat_floppy_struct v;
struct floppy_struct *p;
int err;
memset(&v, 0, sizeof(v));
mutex_lock(&floppy_mutex);
err = get_floppy_geometry(drive, ITYPE(UDRS->fd_device), &p);
if (err) {
mutex_unlock(&floppy_mutex);
return err;
}
memcpy(&v, p, offsetof(struct floppy_struct, name));
mutex_unlock(&floppy_mutex);
if (copy_to_user(arg, &v, sizeof(struct compat_floppy_struct)))
return -EFAULT;
return 0;
}
static int compat_setdrvprm(int drive,
struct compat_floppy_drive_params __user *arg)
{
struct compat_floppy_drive_params v;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
if (copy_from_user(&v, arg, sizeof(struct compat_floppy_drive_params)))
return -EFAULT;
if (!valid_floppy_drive_params(v.autodetect, v.native_format))
return -EINVAL;
mutex_lock(&floppy_mutex);
UDP->cmos = v.cmos;
UDP->max_dtr = v.max_dtr;
UDP->hlt = v.hlt;
UDP->hut = v.hut;
UDP->srt = v.srt;
UDP->spinup = v.spinup;
UDP->spindown = v.spindown;
UDP->spindown_offset = v.spindown_offset;
UDP->select_delay = v.select_delay;
UDP->rps = v.rps;
UDP->tracks = v.tracks;
UDP->timeout = v.timeout;
UDP->interleave_sect = v.interleave_sect;
UDP->max_errors = v.max_errors;
UDP->flags = v.flags;
UDP->read_track = v.read_track;
memcpy(UDP->autodetect, v.autodetect, sizeof(v.autodetect));
UDP->checkfreq = v.checkfreq;
UDP->native_format = v.native_format;
mutex_unlock(&floppy_mutex);
return 0;
}
static int compat_getdrvprm(int drive,
struct compat_floppy_drive_params __user *arg)
{
struct compat_floppy_drive_params v;
memset(&v, 0, sizeof(struct compat_floppy_drive_params));
mutex_lock(&floppy_mutex);
v.cmos = UDP->cmos;
v.max_dtr = UDP->max_dtr;
v.hlt = UDP->hlt;
v.hut = UDP->hut;
v.srt = UDP->srt;
v.spinup = UDP->spinup;
v.spindown = UDP->spindown;
v.spindown_offset = UDP->spindown_offset;
v.select_delay = UDP->select_delay;
v.rps = UDP->rps;
v.tracks = UDP->tracks;
v.timeout = UDP->timeout;
v.interleave_sect = UDP->interleave_sect;
v.max_errors = UDP->max_errors;
v.flags = UDP->flags;
v.read_track = UDP->read_track;
memcpy(v.autodetect, UDP->autodetect, sizeof(v.autodetect));
v.checkfreq = UDP->checkfreq;
v.native_format = UDP->native_format;
mutex_unlock(&floppy_mutex);
if (copy_to_user(arg, &v, sizeof(struct compat_floppy_drive_params)))
return -EFAULT;
return 0;
}
static int compat_getdrvstat(int drive, bool poll,
struct compat_floppy_drive_struct __user *arg)
{
struct compat_floppy_drive_struct v;
memset(&v, 0, sizeof(struct compat_floppy_drive_struct));
mutex_lock(&floppy_mutex);
if (poll) {
if (lock_fdc(drive))
goto Eintr;
if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
goto Eintr;
process_fd_request();
}
v.spinup_date = UDRS->spinup_date;
v.select_date = UDRS->select_date;
v.first_read_date = UDRS->first_read_date;
v.probed_format = UDRS->probed_format;
v.track = UDRS->track;
v.maxblock = UDRS->maxblock;
v.maxtrack = UDRS->maxtrack;
v.generation = UDRS->generation;
v.keep_data = UDRS->keep_data;
v.fd_ref = UDRS->fd_ref;
v.fd_device = UDRS->fd_device;
v.last_checked = UDRS->last_checked;
v.dmabuf = (uintptr_t)UDRS->dmabuf;
v.bufblocks = UDRS->bufblocks;
mutex_unlock(&floppy_mutex);
if (copy_to_user(arg, &v, sizeof(struct compat_floppy_drive_struct)))
return -EFAULT;
return 0;
Eintr:
mutex_unlock(&floppy_mutex);
return -EINTR;
}
static int compat_getfdcstat(int drive,
struct compat_floppy_fdc_state __user *arg)
{
struct compat_floppy_fdc_state v32;
struct floppy_fdc_state v;
mutex_lock(&floppy_mutex);
v = *UFDCS;
mutex_unlock(&floppy_mutex);
memset(&v32, 0, sizeof(struct compat_floppy_fdc_state));
v32.spec1 = v.spec1;
v32.spec2 = v.spec2;
v32.dtr = v.dtr;
v32.version = v.version;
v32.dor = v.dor;
v32.address = v.address;
v32.rawcmd = v.rawcmd;
v32.reset = v.reset;
v32.need_configure = v.need_configure;
v32.perp_mode = v.perp_mode;
v32.has_fifo = v.has_fifo;
v32.driver_version = v.driver_version;
memcpy(v32.track, v.track, 4);
if (copy_to_user(arg, &v32, sizeof(struct compat_floppy_fdc_state)))
return -EFAULT;
return 0;
}
static int compat_werrorget(int drive,
struct compat_floppy_write_errors __user *arg)
{
struct compat_floppy_write_errors v32;
struct floppy_write_errors v;
memset(&v32, 0, sizeof(struct compat_floppy_write_errors));
mutex_lock(&floppy_mutex);
v = *UDRWE;
mutex_unlock(&floppy_mutex);
v32.write_errors = v.write_errors;
v32.first_error_sector = v.first_error_sector;
v32.first_error_generation = v.first_error_generation;
v32.last_error_sector = v.last_error_sector;
v32.last_error_generation = v.last_error_generation;
v32.badness = v.badness;
if (copy_to_user(arg, &v32, sizeof(struct compat_floppy_write_errors)))
return -EFAULT;
return 0;
}
static int fd_compat_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,
unsigned long param)
{
int drive = (long)bdev->bd_disk->private_data;
switch (cmd) {
case CDROMEJECT: /* CD-ROM eject */
case 0x6470: /* SunOS floppy eject */
case FDMSGON:
case FDMSGOFF:
case FDSETEMSGTRESH:
case FDFLUSH:
case FDWERRORCLR:
case FDEJECT:
case FDCLRPRM:
case FDFMTBEG:
case FDRESET:
case FDTWADDLE:
return fd_ioctl(bdev, mode, cmd, param);
case FDSETMAXERRS:
case FDGETMAXERRS:
case FDGETDRVTYP:
case FDFMTEND:
case FDFMTTRK:
case FDRAWCMD:
return fd_ioctl(bdev, mode, cmd,
(unsigned long)compat_ptr(param));
case FDSETPRM32:
case FDDEFPRM32:
return compat_set_geometry(bdev, mode, cmd, compat_ptr(param));
case FDGETPRM32:
return compat_get_prm(drive, compat_ptr(param));
case FDSETDRVPRM32:
return compat_setdrvprm(drive, compat_ptr(param));
case FDGETDRVPRM32:
return compat_getdrvprm(drive, compat_ptr(param));
case FDPOLLDRVSTAT32:
return compat_getdrvstat(drive, true, compat_ptr(param));
case FDGETDRVSTAT32:
return compat_getdrvstat(drive, false, compat_ptr(param));
case FDGETFDCSTAT32:
return compat_getfdcstat(drive, compat_ptr(param));
case FDWERRORGET32:
return compat_werrorget(drive, compat_ptr(param));
}
return -EINVAL;
}
#endif
static void __init config_types(void)
{
bool has_drive = false;
int drive;
/* read drive info out of physical CMOS */
drive = 0;
if (!UDP->cmos)
UDP->cmos = FLOPPY0_TYPE;
drive = 1;
if (!UDP->cmos)
UDP->cmos = FLOPPY1_TYPE;
/* FIXME: additional physical CMOS drive detection should go here */
for (drive = 0; drive < N_DRIVE; drive++) {
unsigned int type = UDP->cmos;
struct floppy_drive_params *params;
const char *name = NULL;
char temparea[32];
if (type < ARRAY_SIZE(default_drive_params)) {
params = &default_drive_params[type].params;
if (type) {
name = default_drive_params[type].name;
allowed_drive_mask |= 1 << drive;
} else
allowed_drive_mask &= ~(1 << drive);
} else {
params = &default_drive_params[0].params;
snprintf(temparea, sizeof(temparea),
"unknown type %d (usb?)", type);
name = temparea;
}
if (name) {
const char *prepend;
if (!has_drive) {
prepend = "";
has_drive = true;
pr_info("Floppy drive(s):");
} else {
prepend = ",";
}
pr_cont("%s fd%d is %s", prepend, drive, name);
}
*UDP = *params;
}
if (has_drive)
pr_cont("\n");
}
static void floppy_release(struct gendisk *disk, fmode_t mode)
{
int drive = (long)disk->private_data;
mutex_lock(&floppy_mutex);
mutex_lock(&open_lock);
if (!UDRS->fd_ref--) {
DPRINT("floppy_release with fd_ref == 0");
UDRS->fd_ref = 0;
}
if (!UDRS->fd_ref)
opened_bdev[drive] = NULL;
mutex_unlock(&open_lock);
mutex_unlock(&floppy_mutex);
}
/*
* floppy_open check for aliasing (/dev/fd0 can be the same as
* /dev/PS0 etc), and disallows simultaneous access to the same
* drive with different device numbers.
*/
static int floppy_open(struct block_device *bdev, fmode_t mode)
{
int drive = (long)bdev->bd_disk->private_data;
int old_dev, new_dev;
int try;
int res = -EBUSY;
char *tmp;
mutex_lock(&floppy_mutex);
mutex_lock(&open_lock);
old_dev = UDRS->fd_device;
if (opened_bdev[drive] && opened_bdev[drive] != bdev)
goto out2;
if (!UDRS->fd_ref && (UDP->flags & FD_BROKEN_DCL)) {
set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
set_bit(FD_VERIFY_BIT, &UDRS->flags);
}
UDRS->fd_ref++;
opened_bdev[drive] = bdev;
res = -ENXIO;
if (!floppy_track_buffer) {
/* if opening an ED drive, reserve a big buffer,
* else reserve a small one */
if ((UDP->cmos == 6) || (UDP->cmos == 5))
try = 64; /* Only 48 actually useful */
else
try = 32; /* Only 24 actually useful */
tmp = (char *)fd_dma_mem_alloc(1024 * try);
if (!tmp && !floppy_track_buffer) {
try >>= 1; /* buffer only one side */
INFBOUND(try, 16);
tmp = (char *)fd_dma_mem_alloc(1024 * try);
}
if (!tmp && !floppy_track_buffer)
fallback_on_nodma_alloc(&tmp, 2048 * try);
if (!tmp && !floppy_track_buffer) {
DPRINT("Unable to allocate DMA memory\n");
goto out;
}
if (floppy_track_buffer) {
if (tmp)
fd_dma_mem_free((unsigned long)tmp, try * 1024);
} else {
buffer_min = buffer_max = -1;
floppy_track_buffer = tmp;
max_buffer_sectors = try;
}
}
new_dev = MINOR(bdev->bd_dev);
UDRS->fd_device = new_dev;
set_capacity(disks[drive], floppy_sizes[new_dev]);
if (old_dev != -1 && old_dev != new_dev) {
if (buffer_drive == drive)
buffer_track = -1;
}
if (UFDCS->rawcmd == 1)
UFDCS->rawcmd = 2;
if (!(mode & FMODE_NDELAY)) {
if (mode & (FMODE_READ|FMODE_WRITE)) {
UDRS->last_checked = 0;
clear_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags);
check_disk_change(bdev);
if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags))
goto out;
if (test_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags))
goto out;
}
res = -EROFS;
if ((mode & FMODE_WRITE) &&
!test_bit(FD_DISK_WRITABLE_BIT, &UDRS->flags))
goto out;
}
mutex_unlock(&open_lock);
mutex_unlock(&floppy_mutex);
return 0;
out:
UDRS->fd_ref--;
if (!UDRS->fd_ref)
opened_bdev[drive] = NULL;
out2:
mutex_unlock(&open_lock);
mutex_unlock(&floppy_mutex);
return res;
}
/*
* Check if the disk has been changed or if a change has been faked.
*/
static unsigned int floppy_check_events(struct gendisk *disk,
unsigned int clearing)
{
int drive = (long)disk->private_data;
if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||
test_bit(FD_VERIFY_BIT, &UDRS->flags))
return DISK_EVENT_MEDIA_CHANGE;
if (time_after(jiffies, UDRS->last_checked + UDP->checkfreq)) {
if (lock_fdc(drive))
return 0;
poll_drive(false, 0);
process_fd_request();
}
if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||
test_bit(FD_VERIFY_BIT, &UDRS->flags) ||
test_bit(drive, &fake_change) ||
drive_no_geom(drive))
return DISK_EVENT_MEDIA_CHANGE;
return 0;
}
/*
* This implements "read block 0" for floppy_revalidate().
* Needed for format autodetection, checking whether there is
* a disk in the drive, and whether that disk is writable.
*/
struct rb0_cbdata {
int drive;
struct completion complete;
};
static void floppy_rb0_cb(struct bio *bio)
{
struct rb0_cbdata *cbdata = (struct rb0_cbdata *)bio->bi_private;
int drive = cbdata->drive;
if (bio->bi_status) {
pr_info("floppy: error %d while reading block 0\n",
bio->bi_status);
set_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags);
}
complete(&cbdata->complete);
}
static int __floppy_read_block_0(struct block_device *bdev, int drive)
{
struct bio bio;
struct bio_vec bio_vec;
struct page *page;
struct rb0_cbdata cbdata;
size_t size;
page = alloc_page(GFP_NOIO);
if (!page) {
process_fd_request();
return -ENOMEM;
}
size = bdev->bd_block_size;
if (!size)
size = 1024;
cbdata.drive = drive;
bio_init(&bio, &bio_vec, 1);
bio_set_dev(&bio, bdev);
bio_add_page(&bio, page, size, 0);
bio.bi_iter.bi_sector = 0;
bio.bi_flags |= (1 << BIO_QUIET);
bio.bi_private = &cbdata;
bio.bi_end_io = floppy_rb0_cb;
bio_set_op_attrs(&bio, REQ_OP_READ, 0);
init_completion(&cbdata.complete);
submit_bio(&bio);
process_fd_request();
wait_for_completion(&cbdata.complete);
__free_page(page);
return 0;
}
/* revalidate the floppy disk, i.e. trigger format autodetection by reading
* the bootblock (block 0). "Autodetection" is also needed to check whether
* there is a disk in the drive at all... Thus we also do it for fixed
* geometry formats */
static int floppy_revalidate(struct gendisk *disk)
{
int drive = (long)disk->private_data;
int cf;
int res = 0;
if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||
test_bit(FD_VERIFY_BIT, &UDRS->flags) ||
test_bit(drive, &fake_change) ||
drive_no_geom(drive)) {
if (WARN(atomic_read(&usage_count) == 0,
"VFS: revalidate called on non-open device.\n"))
return -EFAULT;
res = lock_fdc(drive);
if (res)
return res;
cf = (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||
test_bit(FD_VERIFY_BIT, &UDRS->flags));
if (!(cf || test_bit(drive, &fake_change) || drive_no_geom(drive))) {
process_fd_request(); /*already done by another thread */
return 0;
}
UDRS->maxblock = 0;
UDRS->maxtrack = 0;
if (buffer_drive == drive)
buffer_track = -1;
clear_bit(drive, &fake_change);
clear_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
if (cf)
UDRS->generation++;
if (drive_no_geom(drive)) {
/* auto-sensing */
res = __floppy_read_block_0(opened_bdev[drive], drive);
} else {
if (cf)
poll_drive(false, FD_RAW_NEED_DISK);
process_fd_request();
}
}
set_capacity(disk, floppy_sizes[UDRS->fd_device]);
return res;
}
static const struct block_device_operations floppy_fops = {
.owner = THIS_MODULE,
.open = floppy_open,
.release = floppy_release,
.ioctl = fd_ioctl,
.getgeo = fd_getgeo,
.check_events = floppy_check_events,
.revalidate_disk = floppy_revalidate,
#ifdef CONFIG_COMPAT
.compat_ioctl = fd_compat_ioctl,
#endif
};
/*
* Floppy Driver initialization
* =============================
*/
/* Determine the floppy disk controller type */
/* This routine was written by David C. Niemi */
static char __init get_fdc_version(void)
{
int r;
output_byte(FD_DUMPREGS); /* 82072 and better know DUMPREGS */
if (FDCS->reset)
return FDC_NONE;
r = result();
if (r <= 0x00)
return FDC_NONE; /* No FDC present ??? */
if ((r == 1) && (reply_buffer[0] == 0x80)) {
pr_info("FDC %d is an 8272A\n", fdc);
return FDC_8272A; /* 8272a/765 don't know DUMPREGS */
}
if (r != 10) {
pr_info("FDC %d init: DUMPREGS: unexpected return of %d bytes.\n",
fdc, r);
return FDC_UNKNOWN;
}
if (!fdc_configure()) {
pr_info("FDC %d is an 82072\n", fdc);
return FDC_82072; /* 82072 doesn't know CONFIGURE */
}
output_byte(FD_PERPENDICULAR);
if (need_more_output() == MORE_OUTPUT) {
output_byte(0);
} else {
pr_info("FDC %d is an 82072A\n", fdc);
return FDC_82072A; /* 82072A as found on Sparcs. */
}
output_byte(FD_UNLOCK);
r = result();
if ((r == 1) && (reply_buffer[0] == 0x80)) {
pr_info("FDC %d is a pre-1991 82077\n", fdc);
return FDC_82077_ORIG; /* Pre-1991 82077, doesn't know
* LOCK/UNLOCK */
}
if ((r != 1) || (reply_buffer[0] != 0x00)) {
pr_info("FDC %d init: UNLOCK: unexpected return of %d bytes.\n",
fdc, r);
return FDC_UNKNOWN;
}
output_byte(FD_PARTID);
r = result();
if (r != 1) {
pr_info("FDC %d init: PARTID: unexpected return of %d bytes.\n",
fdc, r);
return FDC_UNKNOWN;
}
if (reply_buffer[0] == 0x80) {
pr_info("FDC %d is a post-1991 82077\n", fdc);
return FDC_82077; /* Revised 82077AA passes all the tests */
}
switch (reply_buffer[0] >> 5) {
case 0x0:
/* Either a 82078-1 or a 82078SL running at 5Volt */
pr_info("FDC %d is an 82078.\n", fdc);
return FDC_82078;
case 0x1:
pr_info("FDC %d is a 44pin 82078\n", fdc);
return FDC_82078;
case 0x2:
pr_info("FDC %d is a S82078B\n", fdc);
return FDC_S82078B;
case 0x3:
pr_info("FDC %d is a National Semiconductor PC87306\n", fdc);
return FDC_87306;
default:
pr_info("FDC %d init: 82078 variant with unknown PARTID=%d.\n",
fdc, reply_buffer[0] >> 5);
return FDC_82078_UNKN;
}
} /* get_fdc_version */
/* lilo configuration */
static void __init floppy_set_flags(int *ints, int param, int param2)
{
int i;
for (i = 0; i < ARRAY_SIZE(default_drive_params); i++) {
if (param)
default_drive_params[i].params.flags |= param2;
else
default_drive_params[i].params.flags &= ~param2;
}
DPRINT("%s flag 0x%x\n", param2 ? "Setting" : "Clearing", param);
}
static void __init daring(int *ints, int param, int param2)
{
int i;
for (i = 0; i < ARRAY_SIZE(default_drive_params); i++) {
if (param) {
default_drive_params[i].params.select_delay = 0;
default_drive_params[i].params.flags |=
FD_SILENT_DCL_CLEAR;
} else {
default_drive_params[i].params.select_delay =
2 * HZ / 100;
default_drive_params[i].params.flags &=
~FD_SILENT_DCL_CLEAR;
}
}
DPRINT("Assuming %s floppy hardware\n", param ? "standard" : "broken");
}
static void __init set_cmos(int *ints, int dummy, int dummy2)
{
int current_drive = 0;
if (ints[0] != 2) {
DPRINT("wrong number of parameters for CMOS\n");
return;
}
current_drive = ints[1];
if (current_drive < 0 || current_drive >= 8) {
DPRINT("bad drive for set_cmos\n");
return;
}
#if N_FDC > 1
if (current_drive >= 4 && !FDC2)
FDC2 = 0x370;
#endif
DP->cmos = ints[2];
DPRINT("setting CMOS code to %d\n", ints[2]);
}
static struct param_table {
const char *name;
void (*fn) (int *ints, int param, int param2);
int *var;
int def_param;
int param2;
} config_params[] __initdata = {
{"allowed_drive_mask", NULL, &allowed_drive_mask, 0xff, 0}, /* obsolete */
{"all_drives", NULL, &allowed_drive_mask, 0xff, 0}, /* obsolete */
{"asus_pci", NULL, &allowed_drive_mask, 0x33, 0},
{"irq", NULL, &FLOPPY_IRQ, 6, 0},
{"dma", NULL, &FLOPPY_DMA, 2, 0},
{"daring", daring, NULL, 1, 0},
#if N_FDC > 1
{"two_fdc", NULL, &FDC2, 0x370, 0},
{"one_fdc", NULL, &FDC2, 0, 0},
#endif
{"thinkpad", floppy_set_flags, NULL, 1, FD_INVERTED_DCL},
{"broken_dcl", floppy_set_flags, NULL, 1, FD_BROKEN_DCL},
{"messages", floppy_set_flags, NULL, 1, FTD_MSG},
{"silent_dcl_clear", floppy_set_flags, NULL, 1, FD_SILENT_DCL_CLEAR},
{"debug", floppy_set_flags, NULL, 1, FD_DEBUG},
{"nodma", NULL, &can_use_virtual_dma, 1, 0},
{"omnibook", NULL, &can_use_virtual_dma, 1, 0},
{"yesdma", NULL, &can_use_virtual_dma, 0, 0},
{"fifo_depth", NULL, &fifo_depth, 0xa, 0},
{"nofifo", NULL, &no_fifo, 0x20, 0},
{"usefifo", NULL, &no_fifo, 0, 0},
{"cmos", set_cmos, NULL, 0, 0},
{"slow", NULL, &slow_floppy, 1, 0},
{"unexpected_interrupts", NULL, &print_unex, 1, 0},
{"no_unexpected_interrupts", NULL, &print_unex, 0, 0},
{"L40SX", NULL, &print_unex, 0, 0}
EXTRA_FLOPPY_PARAMS
};
static int __init floppy_setup(char *str)
{
int i;
int param;
int ints[11];
str = get_options(str, ARRAY_SIZE(ints), ints);
if (str) {
for (i = 0; i < ARRAY_SIZE(config_params); i++) {
if (strcmp(str, config_params[i].name) == 0) {
if (ints[0])
param = ints[1];
else
param = config_params[i].def_param;
if (config_params[i].fn)
config_params[i].fn(ints, param,
config_params[i].
param2);
if (config_params[i].var) {
DPRINT("%s=%d\n", str, param);
*config_params[i].var = param;
}
return 1;
}
}
}
if (str) {
DPRINT("unknown floppy option [%s]\n", str);
DPRINT("allowed options are:");
for (i = 0; i < ARRAY_SIZE(config_params); i++)
pr_cont(" %s", config_params[i].name);
pr_cont("\n");
} else
DPRINT("botched floppy option\n");
DPRINT("Read Documentation/admin-guide/blockdev/floppy.rst\n");
return 0;
}
static int have_no_fdc = -ENODEV;
static ssize_t floppy_cmos_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *p = to_platform_device(dev);
int drive;
drive = p->id;
return sprintf(buf, "%X\n", UDP->cmos);
}
static DEVICE_ATTR(cmos, 0444, floppy_cmos_show, NULL);
static struct attribute *floppy_dev_attrs[] = {
&dev_attr_cmos.attr,
NULL
};
ATTRIBUTE_GROUPS(floppy_dev);
static void floppy_device_release(struct device *dev)
{
}
static int floppy_resume(struct device *dev)
{
int fdc;
for (fdc = 0; fdc < N_FDC; fdc++)
if (FDCS->address != -1)
user_reset_fdc(-1, FD_RESET_ALWAYS, false);
return 0;
}
static const struct dev_pm_ops floppy_pm_ops = {
.resume = floppy_resume,
.restore = floppy_resume,
};
static struct platform_driver floppy_driver = {
.driver = {
.name = "floppy",
.pm = &floppy_pm_ops,
},
};
static const struct blk_mq_ops floppy_mq_ops = {
.queue_rq = floppy_queue_rq,
};
static struct platform_device floppy_device[N_DRIVE];
static bool floppy_available(int drive)
{
if (!(allowed_drive_mask & (1 << drive)))
return false;
if (fdc_state[FDC(drive)].version == FDC_NONE)
return false;
return true;
}
static struct kobject *floppy_find(dev_t dev, int *part, void *data)
{
int drive = (*part & 3) | ((*part & 0x80) >> 5);
if (drive >= N_DRIVE || !floppy_available(drive))
return NULL;
if (((*part >> 2) & 0x1f) >= ARRAY_SIZE(floppy_type))
return NULL;
*part = 0;
return get_disk_and_module(disks[drive]);
}
static int __init do_floppy_init(void)
{
int i, unit, drive, err;
set_debugt();
interruptjiffies = resultjiffies = jiffies;
#if defined(CONFIG_PPC)
if (check_legacy_ioport(FDC1))
return -ENODEV;
#endif
raw_cmd = NULL;
floppy_wq = alloc_ordered_workqueue("floppy", 0);
if (!floppy_wq)
return -ENOMEM;
for (drive = 0; drive < N_DRIVE; drive++) {
disks[drive] = alloc_disk(1);
if (!disks[drive]) {
err = -ENOMEM;
goto out_put_disk;
}
disks[drive]->queue = blk_mq_init_sq_queue(&tag_sets[drive],
&floppy_mq_ops, 2,
BLK_MQ_F_SHOULD_MERGE);
if (IS_ERR(disks[drive]->queue)) {
err = PTR_ERR(disks[drive]->queue);
disks[drive]->queue = NULL;
goto out_put_disk;
}
blk_queue_bounce_limit(disks[drive]->queue, BLK_BOUNCE_HIGH);
blk_queue_max_hw_sectors(disks[drive]->queue, 64);
disks[drive]->major = FLOPPY_MAJOR;
disks[drive]->first_minor = TOMINOR(drive);
disks[drive]->fops = &floppy_fops;
disks[drive]->events = DISK_EVENT_MEDIA_CHANGE;
sprintf(disks[drive]->disk_name, "fd%d", drive);
timer_setup(&motor_off_timer[drive], motor_off_callback, 0);
}
err = register_blkdev(FLOPPY_MAJOR, "fd");
if (err)
goto out_put_disk;
err = platform_driver_register(&floppy_driver);
if (err)
goto out_unreg_blkdev;
blk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE,
floppy_find, NULL, NULL);
for (i = 0; i < 256; i++)
if (ITYPE(i))
floppy_sizes[i] = floppy_type[ITYPE(i)].size;
else
floppy_sizes[i] = MAX_DISK_SIZE << 1;
reschedule_timeout(MAXTIMEOUT, "floppy init");
config_types();
for (i = 0; i < N_FDC; i++) {
fdc = i;
memset(FDCS, 0, sizeof(*FDCS));
FDCS->dtr = -1;
FDCS->dor = 0x4;
#if defined(__sparc__) || defined(__mc68000__)
/*sparcs/sun3x don't have a DOR reset which we can fall back on to */
#ifdef __mc68000__
if (MACH_IS_SUN3X)
#endif
FDCS->version = FDC_82072A;
#endif
}
use_virtual_dma = can_use_virtual_dma & 1;
fdc_state[0].address = FDC1;
if (fdc_state[0].address == -1) {
cancel_delayed_work(&fd_timeout);
err = -ENODEV;
goto out_unreg_region;
}
#if N_FDC > 1
fdc_state[1].address = FDC2;
#endif
fdc = 0; /* reset fdc in case of unexpected interrupt */
err = floppy_grab_irq_and_dma();
if (err) {
cancel_delayed_work(&fd_timeout);
err = -EBUSY;
goto out_unreg_region;
}
/* initialise drive state */
for (drive = 0; drive < N_DRIVE; drive++) {
memset(UDRS, 0, sizeof(*UDRS));
memset(UDRWE, 0, sizeof(*UDRWE));
set_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags);
set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
set_bit(FD_VERIFY_BIT, &UDRS->flags);
UDRS->fd_device = -1;
floppy_track_buffer = NULL;
max_buffer_sectors = 0;
}
/*
* Small 10 msec delay to let through any interrupt that
* initialization might have triggered, to not
* confuse detection:
*/
msleep(10);
for (i = 0; i < N_FDC; i++) {
fdc = i;
FDCS->driver_version = FD_DRIVER_VERSION;
for (unit = 0; unit < 4; unit++)
FDCS->track[unit] = 0;
if (FDCS->address == -1)
continue;
FDCS->rawcmd = 2;
if (user_reset_fdc(-1, FD_RESET_ALWAYS, false)) {
/* free ioports reserved by floppy_grab_irq_and_dma() */
floppy_release_regions(fdc);
FDCS->address = -1;
FDCS->version = FDC_NONE;
continue;
}
/* Try to determine the floppy controller type */
FDCS->version = get_fdc_version();
if (FDCS->version == FDC_NONE) {
/* free ioports reserved by floppy_grab_irq_and_dma() */
floppy_release_regions(fdc);
FDCS->address = -1;
continue;
}
if (can_use_virtual_dma == 2 && FDCS->version < FDC_82072A)
can_use_virtual_dma = 0;
have_no_fdc = 0;
/* Not all FDCs seem to be able to handle the version command
* properly, so force a reset for the standard FDC clones,
* to avoid interrupt garbage.
*/
user_reset_fdc(-1, FD_RESET_ALWAYS, false);
}
fdc = 0;
cancel_delayed_work(&fd_timeout);
current_drive = 0;
initialized = true;
if (have_no_fdc) {
DPRINT("no floppy controllers found\n");
err = have_no_fdc;
goto out_release_dma;
}
for (drive = 0; drive < N_DRIVE; drive++) {
if (!floppy_available(drive))
continue;
floppy_device[drive].name = floppy_device_name;
floppy_device[drive].id = drive;
floppy_device[drive].dev.release = floppy_device_release;
floppy_device[drive].dev.groups = floppy_dev_groups;
err = platform_device_register(&floppy_device[drive]);
if (err)
goto out_remove_drives;
/* to be cleaned up... */
disks[drive]->private_data = (void *)(long)drive;
disks[drive]->flags |= GENHD_FL_REMOVABLE;
device_add_disk(&floppy_device[drive].dev, disks[drive], NULL);
}
return 0;
out_remove_drives:
while (drive--) {
if (floppy_available(drive)) {
del_gendisk(disks[drive]);
platform_device_unregister(&floppy_device[drive]);
}
}
out_release_dma:
if (atomic_read(&usage_count))
floppy_release_irq_and_dma();
out_unreg_region:
blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);
platform_driver_unregister(&floppy_driver);
out_unreg_blkdev:
unregister_blkdev(FLOPPY_MAJOR, "fd");
out_put_disk:
destroy_workqueue(floppy_wq);
for (drive = 0; drive < N_DRIVE; drive++) {
if (!disks[drive])
break;
if (disks[drive]->queue) {
del_timer_sync(&motor_off_timer[drive]);
blk_cleanup_queue(disks[drive]->queue);
disks[drive]->queue = NULL;
blk_mq_free_tag_set(&tag_sets[drive]);
}
put_disk(disks[drive]);
}
return err;
}
#ifndef MODULE
static __init void floppy_async_init(void *data, async_cookie_t cookie)
{
do_floppy_init();
}
#endif
static int __init floppy_init(void)
{
#ifdef MODULE
return do_floppy_init();
#else
/* Don't hold up the bootup by the floppy initialization */
async_schedule(floppy_async_init, NULL);
return 0;
#endif
}
static const struct io_region {
int offset;
int size;
} io_regions[] = {
{ 2, 1 },
/* address + 3 is sometimes reserved by pnp bios for motherboard */
{ 4, 2 },
/* address + 6 is reserved, and may be taken by IDE.
* Unfortunately, Adaptec doesn't know this :-(, */
{ 7, 1 },
};
static void floppy_release_allocated_regions(int fdc, const struct io_region *p)
{
while (p != io_regions) {
p--;
release_region(FDCS->address + p->offset, p->size);
}
}
#define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)]))
static int floppy_request_regions(int fdc)
{
const struct io_region *p;
for (p = io_regions; p < ARRAY_END(io_regions); p++) {
if (!request_region(FDCS->address + p->offset,
p->size, "floppy")) {
DPRINT("Floppy io-port 0x%04lx in use\n",
FDCS->address + p->offset);
floppy_release_allocated_regions(fdc, p);
return -EBUSY;
}
}
return 0;
}
static void floppy_release_regions(int fdc)
{
floppy_release_allocated_regions(fdc, ARRAY_END(io_regions));
}
static int floppy_grab_irq_and_dma(void)
{
if (atomic_inc_return(&usage_count) > 1)
return 0;
/*
* We might have scheduled a free_irq(), wait it to
* drain first:
*/
flush_workqueue(floppy_wq);
if (fd_request_irq()) {
DPRINT("Unable to grab IRQ%d for the floppy driver\n",
FLOPPY_IRQ);
atomic_dec(&usage_count);
return -1;
}
if (fd_request_dma()) {
DPRINT("Unable to grab DMA%d for the floppy driver\n",
FLOPPY_DMA);
if (can_use_virtual_dma & 2)
use_virtual_dma = can_use_virtual_dma = 1;
if (!(can_use_virtual_dma & 1)) {
fd_free_irq();
atomic_dec(&usage_count);
return -1;
}
}
for (fdc = 0; fdc < N_FDC; fdc++) {
if (FDCS->address != -1) {
if (floppy_request_regions(fdc))
goto cleanup;
}
}
for (fdc = 0; fdc < N_FDC; fdc++) {
if (FDCS->address != -1) {
reset_fdc_info(1);
fd_outb(FDCS->dor, FD_DOR);
}
}
fdc = 0;
set_dor(0, ~0, 8); /* avoid immediate interrupt */
for (fdc = 0; fdc < N_FDC; fdc++)
if (FDCS->address != -1)
fd_outb(FDCS->dor, FD_DOR);
/*
* The driver will try and free resources and relies on us
* to know if they were allocated or not.
*/
fdc = 0;
irqdma_allocated = 1;
return 0;
cleanup:
fd_free_irq();
fd_free_dma();
while (--fdc >= 0)
floppy_release_regions(fdc);
atomic_dec(&usage_count);
return -1;
}
static void floppy_release_irq_and_dma(void)
{
int old_fdc;
#ifndef __sparc__
int drive;
#endif
long tmpsize;
unsigned long tmpaddr;
if (!atomic_dec_and_test(&usage_count))
return;
if (irqdma_allocated) {
fd_disable_dma();
fd_free_dma();
fd_free_irq();
irqdma_allocated = 0;
}
set_dor(0, ~0, 8);
#if N_FDC > 1
set_dor(1, ~8, 0);
#endif
if (floppy_track_buffer && max_buffer_sectors) {
tmpsize = max_buffer_sectors * 1024;
tmpaddr = (unsigned long)floppy_track_buffer;
floppy_track_buffer = NULL;
max_buffer_sectors = 0;
buffer_min = buffer_max = -1;
fd_dma_mem_free(tmpaddr, tmpsize);
}
#ifndef __sparc__
for (drive = 0; drive < N_FDC * 4; drive++)
if (timer_pending(motor_off_timer + drive))
pr_info("motor off timer %d still active\n", drive);
#endif
if (delayed_work_pending(&fd_timeout))
pr_info("floppy timer still active:%s\n", timeout_message);
if (delayed_work_pending(&fd_timer))
pr_info("auxiliary floppy timer still active\n");
if (work_pending(&floppy_work))
pr_info("work still pending\n");
old_fdc = fdc;
for (fdc = 0; fdc < N_FDC; fdc++)
if (FDCS->address != -1)
floppy_release_regions(fdc);
fdc = old_fdc;
}
#ifdef MODULE
static char *floppy;
static void __init parse_floppy_cfg_string(char *cfg)
{
char *ptr;
while (*cfg) {
ptr = cfg;
while (*cfg && *cfg != ' ' && *cfg != '\t')
cfg++;
if (*cfg) {
*cfg = '\0';
cfg++;
}
if (*ptr)
floppy_setup(ptr);
}
}
static int __init floppy_module_init(void)
{
if (floppy)
parse_floppy_cfg_string(floppy);
return floppy_init();
}
module_init(floppy_module_init);
static void __exit floppy_module_exit(void)
{
int drive;
blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);
unregister_blkdev(FLOPPY_MAJOR, "fd");
platform_driver_unregister(&floppy_driver);
destroy_workqueue(floppy_wq);
for (drive = 0; drive < N_DRIVE; drive++) {
del_timer_sync(&motor_off_timer[drive]);
if (floppy_available(drive)) {
del_gendisk(disks[drive]);
platform_device_unregister(&floppy_device[drive]);
}
blk_cleanup_queue(disks[drive]->queue);
blk_mq_free_tag_set(&tag_sets[drive]);
/*
* These disks have not called add_disk(). Don't put down
* queue reference in put_disk().
*/
if (!(allowed_drive_mask & (1 << drive)) ||
fdc_state[FDC(drive)].version == FDC_NONE)
disks[drive]->queue = NULL;
put_disk(disks[drive]);
}
cancel_delayed_work_sync(&fd_timeout);
cancel_delayed_work_sync(&fd_timer);
if (atomic_read(&usage_count))
floppy_release_irq_and_dma();
/* eject disk, if any */
fd_eject(0);
}
module_exit(floppy_module_exit);
module_param(floppy, charp, 0);
module_param(FLOPPY_IRQ, int, 0);
module_param(FLOPPY_DMA, int, 0);
MODULE_AUTHOR("Alain L. Knaff");
MODULE_SUPPORTED_DEVICE("fd");
MODULE_LICENSE("GPL");
/* This doesn't actually get used other than for module information */
static const struct pnp_device_id floppy_pnpids[] = {
{"PNP0700", 0},
{}
};
MODULE_DEVICE_TABLE(pnp, floppy_pnpids);
#else
__setup("floppy=", floppy_setup);
module_init(floppy_init)
#endif
MODULE_ALIAS_BLOCKDEV_MAJOR(FLOPPY_MAJOR);
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4689_0 |
crossvul-cpp_data_bad_417_0 | /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
* Copyright (c) 2016 Facebook
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/bpf.h>
#include <linux/bpf_verifier.h>
#include <linux/filter.h>
#include <net/netlink.h>
#include <linux/file.h>
#include <linux/vmalloc.h>
#include <linux/stringify.h>
#include <linux/bsearch.h>
#include <linux/sort.h>
#include <linux/perf_event.h>
#include "disasm.h"
static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
#define BPF_PROG_TYPE(_id, _name) \
[_id] = & _name ## _verifier_ops,
#define BPF_MAP_TYPE(_id, _ops)
#include <linux/bpf_types.h>
#undef BPF_PROG_TYPE
#undef BPF_MAP_TYPE
};
/* bpf_check() is a static code analyzer that walks eBPF program
* instruction by instruction and updates register/stack state.
* All paths of conditional branches are analyzed until 'bpf_exit' insn.
*
* The first pass is depth-first-search to check that the program is a DAG.
* It rejects the following programs:
* - larger than BPF_MAXINSNS insns
* - if loop is present (detected via back-edge)
* - unreachable insns exist (shouldn't be a forest. program = one function)
* - out of bounds or malformed jumps
* The second pass is all possible path descent from the 1st insn.
* Since it's analyzing all pathes through the program, the length of the
* analysis is limited to 64k insn, which may be hit even if total number of
* insn is less then 4K, but there are too many branches that change stack/regs.
* Number of 'branches to be analyzed' is limited to 1k
*
* On entry to each instruction, each register has a type, and the instruction
* changes the types of the registers depending on instruction semantics.
* If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
* copied to R1.
*
* All registers are 64-bit.
* R0 - return register
* R1-R5 argument passing registers
* R6-R9 callee saved registers
* R10 - frame pointer read-only
*
* At the start of BPF program the register R1 contains a pointer to bpf_context
* and has type PTR_TO_CTX.
*
* Verifier tracks arithmetic operations on pointers in case:
* BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
* BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
* 1st insn copies R10 (which has FRAME_PTR) type into R1
* and 2nd arithmetic instruction is pattern matched to recognize
* that it wants to construct a pointer to some element within stack.
* So after 2nd insn, the register R1 has type PTR_TO_STACK
* (and -20 constant is saved for further stack bounds checking).
* Meaning that this reg is a pointer to stack plus known immediate constant.
*
* Most of the time the registers have SCALAR_VALUE type, which
* means the register has some value, but it's not a valid pointer.
* (like pointer plus pointer becomes SCALAR_VALUE type)
*
* When verifier sees load or store instructions the type of base register
* can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
* types recognized by check_mem_access() function.
*
* PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
* and the range of [ptr, ptr + map's value_size) is accessible.
*
* registers used to pass values to function calls are checked against
* function argument constraints.
*
* ARG_PTR_TO_MAP_KEY is one of such argument constraints.
* It means that the register type passed to this function must be
* PTR_TO_STACK and it will be used inside the function as
* 'pointer to map element key'
*
* For example the argument constraints for bpf_map_lookup_elem():
* .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
* .arg1_type = ARG_CONST_MAP_PTR,
* .arg2_type = ARG_PTR_TO_MAP_KEY,
*
* ret_type says that this function returns 'pointer to map elem value or null'
* function expects 1st argument to be a const pointer to 'struct bpf_map' and
* 2nd argument should be a pointer to stack, which will be used inside
* the helper function as a pointer to map element key.
*
* On the kernel side the helper function looks like:
* u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
* {
* struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
* void *key = (void *) (unsigned long) r2;
* void *value;
*
* here kernel can access 'key' and 'map' pointers safely, knowing that
* [key, key + map->key_size) bytes are valid and were initialized on
* the stack of eBPF program.
* }
*
* Corresponding eBPF program may look like:
* BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
* BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
* BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
* BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
* here verifier looks at prototype of map_lookup_elem() and sees:
* .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
* Now verifier knows that this map has key of R1->map_ptr->key_size bytes
*
* Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
* Now verifier checks that [R2, R2 + map's key_size) are within stack limits
* and were initialized prior to this call.
* If it's ok, then verifier allows this BPF_CALL insn and looks at
* .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
* R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
* returns ether pointer to map value or NULL.
*
* When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
* insn, the register holding that pointer in the true branch changes state to
* PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
* branch. See check_cond_jmp_op().
*
* After the call R0 is set to return type of the function and registers R1-R5
* are set to NOT_INIT to indicate that they are no longer readable.
*/
/* verifier_state + insn_idx are pushed to stack when branch is encountered */
struct bpf_verifier_stack_elem {
/* verifer state is 'st'
* before processing instruction 'insn_idx'
* and after processing instruction 'prev_insn_idx'
*/
struct bpf_verifier_state st;
int insn_idx;
int prev_insn_idx;
struct bpf_verifier_stack_elem *next;
};
#define BPF_COMPLEXITY_LIMIT_INSNS 131072
#define BPF_COMPLEXITY_LIMIT_STACK 1024
#define BPF_MAP_PTR_UNPRIV 1UL
#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
POISON_POINTER_DELTA))
#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
{
return BPF_MAP_PTR(aux->map_state) == BPF_MAP_PTR_POISON;
}
static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
{
return aux->map_state & BPF_MAP_PTR_UNPRIV;
}
static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
const struct bpf_map *map, bool unpriv)
{
BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
unpriv |= bpf_map_ptr_unpriv(aux);
aux->map_state = (unsigned long)map |
(unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
}
struct bpf_call_arg_meta {
struct bpf_map *map_ptr;
bool raw_mode;
bool pkt_access;
int regno;
int access_size;
s64 msize_smax_value;
u64 msize_umax_value;
};
static DEFINE_MUTEX(bpf_verifier_lock);
void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
va_list args)
{
unsigned int n;
n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
"verifier log line truncated - local buffer too short\n");
n = min(log->len_total - log->len_used - 1, n);
log->kbuf[n] = '\0';
if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
log->len_used += n;
else
log->ubuf = NULL;
}
/* log_level controls verbosity level of eBPF verifier.
* bpf_verifier_log_write() is used to dump the verification trace to the log,
* so the user can figure out what's wrong with the program
*/
__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
const char *fmt, ...)
{
va_list args;
if (!bpf_verifier_log_needed(&env->log))
return;
va_start(args, fmt);
bpf_verifier_vlog(&env->log, fmt, args);
va_end(args);
}
EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
{
struct bpf_verifier_env *env = private_data;
va_list args;
if (!bpf_verifier_log_needed(&env->log))
return;
va_start(args, fmt);
bpf_verifier_vlog(&env->log, fmt, args);
va_end(args);
}
static bool type_is_pkt_pointer(enum bpf_reg_type type)
{
return type == PTR_TO_PACKET ||
type == PTR_TO_PACKET_META;
}
/* string representation of 'enum bpf_reg_type' */
static const char * const reg_type_str[] = {
[NOT_INIT] = "?",
[SCALAR_VALUE] = "inv",
[PTR_TO_CTX] = "ctx",
[CONST_PTR_TO_MAP] = "map_ptr",
[PTR_TO_MAP_VALUE] = "map_value",
[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
[PTR_TO_STACK] = "fp",
[PTR_TO_PACKET] = "pkt",
[PTR_TO_PACKET_META] = "pkt_meta",
[PTR_TO_PACKET_END] = "pkt_end",
};
static void print_liveness(struct bpf_verifier_env *env,
enum bpf_reg_liveness live)
{
if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN))
verbose(env, "_");
if (live & REG_LIVE_READ)
verbose(env, "r");
if (live & REG_LIVE_WRITTEN)
verbose(env, "w");
}
static struct bpf_func_state *func(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg)
{
struct bpf_verifier_state *cur = env->cur_state;
return cur->frame[reg->frameno];
}
static void print_verifier_state(struct bpf_verifier_env *env,
const struct bpf_func_state *state)
{
const struct bpf_reg_state *reg;
enum bpf_reg_type t;
int i;
if (state->frameno)
verbose(env, " frame%d:", state->frameno);
for (i = 0; i < MAX_BPF_REG; i++) {
reg = &state->regs[i];
t = reg->type;
if (t == NOT_INIT)
continue;
verbose(env, " R%d", i);
print_liveness(env, reg->live);
verbose(env, "=%s", reg_type_str[t]);
if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
tnum_is_const(reg->var_off)) {
/* reg->off should be 0 for SCALAR_VALUE */
verbose(env, "%lld", reg->var_off.value + reg->off);
if (t == PTR_TO_STACK)
verbose(env, ",call_%d", func(env, reg)->callsite);
} else {
verbose(env, "(id=%d", reg->id);
if (t != SCALAR_VALUE)
verbose(env, ",off=%d", reg->off);
if (type_is_pkt_pointer(t))
verbose(env, ",r=%d", reg->range);
else if (t == CONST_PTR_TO_MAP ||
t == PTR_TO_MAP_VALUE ||
t == PTR_TO_MAP_VALUE_OR_NULL)
verbose(env, ",ks=%d,vs=%d",
reg->map_ptr->key_size,
reg->map_ptr->value_size);
if (tnum_is_const(reg->var_off)) {
/* Typically an immediate SCALAR_VALUE, but
* could be a pointer whose offset is too big
* for reg->off
*/
verbose(env, ",imm=%llx", reg->var_off.value);
} else {
if (reg->smin_value != reg->umin_value &&
reg->smin_value != S64_MIN)
verbose(env, ",smin_value=%lld",
(long long)reg->smin_value);
if (reg->smax_value != reg->umax_value &&
reg->smax_value != S64_MAX)
verbose(env, ",smax_value=%lld",
(long long)reg->smax_value);
if (reg->umin_value != 0)
verbose(env, ",umin_value=%llu",
(unsigned long long)reg->umin_value);
if (reg->umax_value != U64_MAX)
verbose(env, ",umax_value=%llu",
(unsigned long long)reg->umax_value);
if (!tnum_is_unknown(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, ",var_off=%s", tn_buf);
}
}
verbose(env, ")");
}
}
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] == STACK_SPILL) {
verbose(env, " fp%d",
(-i - 1) * BPF_REG_SIZE);
print_liveness(env, state->stack[i].spilled_ptr.live);
verbose(env, "=%s",
reg_type_str[state->stack[i].spilled_ptr.type]);
}
if (state->stack[i].slot_type[0] == STACK_ZERO)
verbose(env, " fp%d=0", (-i - 1) * BPF_REG_SIZE);
}
verbose(env, "\n");
}
static int copy_stack_state(struct bpf_func_state *dst,
const struct bpf_func_state *src)
{
if (!src->stack)
return 0;
if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
/* internal bug, make state invalid to reject the program */
memset(dst, 0, sizeof(*dst));
return -EFAULT;
}
memcpy(dst->stack, src->stack,
sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
return 0;
}
/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
* make it consume minimal amount of memory. check_stack_write() access from
* the program calls into realloc_func_state() to grow the stack size.
* Note there is a non-zero 'parent' pointer inside bpf_verifier_state
* which this function copies over. It points to previous bpf_verifier_state
* which is never reallocated
*/
static int realloc_func_state(struct bpf_func_state *state, int size,
bool copy_old)
{
u32 old_size = state->allocated_stack;
struct bpf_stack_state *new_stack;
int slot = size / BPF_REG_SIZE;
if (size <= old_size || !size) {
if (copy_old)
return 0;
state->allocated_stack = slot * BPF_REG_SIZE;
if (!size && old_size) {
kfree(state->stack);
state->stack = NULL;
}
return 0;
}
new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
GFP_KERNEL);
if (!new_stack)
return -ENOMEM;
if (copy_old) {
if (state->stack)
memcpy(new_stack, state->stack,
sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
memset(new_stack + old_size / BPF_REG_SIZE, 0,
sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
}
state->allocated_stack = slot * BPF_REG_SIZE;
kfree(state->stack);
state->stack = new_stack;
return 0;
}
static void free_func_state(struct bpf_func_state *state)
{
if (!state)
return;
kfree(state->stack);
kfree(state);
}
static void free_verifier_state(struct bpf_verifier_state *state,
bool free_self)
{
int i;
for (i = 0; i <= state->curframe; i++) {
free_func_state(state->frame[i]);
state->frame[i] = NULL;
}
if (free_self)
kfree(state);
}
/* copy verifier state from src to dst growing dst stack space
* when necessary to accommodate larger src stack
*/
static int copy_func_state(struct bpf_func_state *dst,
const struct bpf_func_state *src)
{
int err;
err = realloc_func_state(dst, src->allocated_stack, false);
if (err)
return err;
memcpy(dst, src, offsetof(struct bpf_func_state, allocated_stack));
return copy_stack_state(dst, src);
}
static int copy_verifier_state(struct bpf_verifier_state *dst_state,
const struct bpf_verifier_state *src)
{
struct bpf_func_state *dst;
int i, err;
/* if dst has more stack frames then src frame, free them */
for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
free_func_state(dst_state->frame[i]);
dst_state->frame[i] = NULL;
}
dst_state->curframe = src->curframe;
dst_state->parent = src->parent;
for (i = 0; i <= src->curframe; i++) {
dst = dst_state->frame[i];
if (!dst) {
dst = kzalloc(sizeof(*dst), GFP_KERNEL);
if (!dst)
return -ENOMEM;
dst_state->frame[i] = dst;
}
err = copy_func_state(dst, src->frame[i]);
if (err)
return err;
}
return 0;
}
static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
int *insn_idx)
{
struct bpf_verifier_state *cur = env->cur_state;
struct bpf_verifier_stack_elem *elem, *head = env->head;
int err;
if (env->head == NULL)
return -ENOENT;
if (cur) {
err = copy_verifier_state(cur, &head->st);
if (err)
return err;
}
if (insn_idx)
*insn_idx = head->insn_idx;
if (prev_insn_idx)
*prev_insn_idx = head->prev_insn_idx;
elem = head->next;
free_verifier_state(&head->st, false);
kfree(head);
env->head = elem;
env->stack_size--;
return 0;
}
static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
int insn_idx, int prev_insn_idx)
{
struct bpf_verifier_state *cur = env->cur_state;
struct bpf_verifier_stack_elem *elem;
int err;
elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
if (!elem)
goto err;
elem->insn_idx = insn_idx;
elem->prev_insn_idx = prev_insn_idx;
elem->next = env->head;
env->head = elem;
env->stack_size++;
err = copy_verifier_state(&elem->st, cur);
if (err)
goto err;
if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
verbose(env, "BPF program is too complex\n");
goto err;
}
return &elem->st;
err:
free_verifier_state(env->cur_state, true);
env->cur_state = NULL;
/* pop all elements and return */
while (!pop_stack(env, NULL, NULL));
return NULL;
}
#define CALLER_SAVED_REGS 6
static const int caller_saved[CALLER_SAVED_REGS] = {
BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
};
static void __mark_reg_not_init(struct bpf_reg_state *reg);
/* Mark the unknown part of a register (variable offset or scalar value) as
* known to have the value @imm.
*/
static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
{
reg->id = 0;
reg->var_off = tnum_const(imm);
reg->smin_value = (s64)imm;
reg->smax_value = (s64)imm;
reg->umin_value = imm;
reg->umax_value = imm;
}
/* Mark the 'variable offset' part of a register as zero. This should be
* used only on registers holding a pointer type.
*/
static void __mark_reg_known_zero(struct bpf_reg_state *reg)
{
__mark_reg_known(reg, 0);
}
static void __mark_reg_const_zero(struct bpf_reg_state *reg)
{
__mark_reg_known(reg, 0);
reg->off = 0;
reg->type = SCALAR_VALUE;
}
static void mark_reg_known_zero(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs */
for (regno = 0; regno < MAX_BPF_REG; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_known_zero(regs + regno);
}
static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
{
return type_is_pkt_pointer(reg->type);
}
static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
{
return reg_is_pkt_pointer(reg) ||
reg->type == PTR_TO_PACKET_END;
}
/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
enum bpf_reg_type which)
{
/* The register can already have a range from prior markings.
* This is fine as long as it hasn't been advanced from its
* origin.
*/
return reg->type == which &&
reg->id == 0 &&
reg->off == 0 &&
tnum_equals_const(reg->var_off, 0);
}
/* Attempts to improve min/max values based on var_off information */
static void __update_reg_bounds(struct bpf_reg_state *reg)
{
/* min signed is max(sign bit) | min(other bits) */
reg->smin_value = max_t(s64, reg->smin_value,
reg->var_off.value | (reg->var_off.mask & S64_MIN));
/* max signed is min(sign bit) | max(other bits) */
reg->smax_value = min_t(s64, reg->smax_value,
reg->var_off.value | (reg->var_off.mask & S64_MAX));
reg->umin_value = max(reg->umin_value, reg->var_off.value);
reg->umax_value = min(reg->umax_value,
reg->var_off.value | reg->var_off.mask);
}
/* Uses signed min/max values to inform unsigned, and vice-versa */
static void __reg_deduce_bounds(struct bpf_reg_state *reg)
{
/* Learn sign from signed bounds.
* If we cannot cross the sign boundary, then signed and unsigned bounds
* are the same, so combine. This works even in the negative case, e.g.
* -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
*/
if (reg->smin_value >= 0 || reg->smax_value < 0) {
reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
reg->umin_value);
reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
reg->umax_value);
return;
}
/* Learn sign from unsigned bounds. Signed bounds cross the sign
* boundary, so we must be careful.
*/
if ((s64)reg->umax_value >= 0) {
/* Positive. We can't learn anything from the smin, but smax
* is positive, hence safe.
*/
reg->smin_value = reg->umin_value;
reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
reg->umax_value);
} else if ((s64)reg->umin_value < 0) {
/* Negative. We can't learn anything from the smax, but smin
* is negative, hence safe.
*/
reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
reg->umin_value);
reg->smax_value = reg->umax_value;
}
}
/* Attempts to improve var_off based on unsigned min/max information */
static void __reg_bound_offset(struct bpf_reg_state *reg)
{
reg->var_off = tnum_intersect(reg->var_off,
tnum_range(reg->umin_value,
reg->umax_value));
}
/* Reset the min/max bounds of a register */
static void __mark_reg_unbounded(struct bpf_reg_state *reg)
{
reg->smin_value = S64_MIN;
reg->smax_value = S64_MAX;
reg->umin_value = 0;
reg->umax_value = U64_MAX;
}
/* Mark a register as having a completely unknown (scalar) value. */
static void __mark_reg_unknown(struct bpf_reg_state *reg)
{
reg->type = SCALAR_VALUE;
reg->id = 0;
reg->off = 0;
reg->var_off = tnum_unknown;
reg->frameno = 0;
__mark_reg_unbounded(reg);
}
static void mark_reg_unknown(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs except FP */
for (regno = 0; regno < BPF_REG_FP; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_unknown(regs + regno);
}
static void __mark_reg_not_init(struct bpf_reg_state *reg)
{
__mark_reg_unknown(reg);
reg->type = NOT_INIT;
}
static void mark_reg_not_init(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs except FP */
for (regno = 0; regno < BPF_REG_FP; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_not_init(regs + regno);
}
static void init_reg_state(struct bpf_verifier_env *env,
struct bpf_func_state *state)
{
struct bpf_reg_state *regs = state->regs;
int i;
for (i = 0; i < MAX_BPF_REG; i++) {
mark_reg_not_init(env, regs, i);
regs[i].live = REG_LIVE_NONE;
}
/* frame pointer */
regs[BPF_REG_FP].type = PTR_TO_STACK;
mark_reg_known_zero(env, regs, BPF_REG_FP);
regs[BPF_REG_FP].frameno = state->frameno;
/* 1st arg to a function */
regs[BPF_REG_1].type = PTR_TO_CTX;
mark_reg_known_zero(env, regs, BPF_REG_1);
}
#define BPF_MAIN_FUNC (-1)
static void init_func_state(struct bpf_verifier_env *env,
struct bpf_func_state *state,
int callsite, int frameno, int subprogno)
{
state->callsite = callsite;
state->frameno = frameno;
state->subprogno = subprogno;
init_reg_state(env, state);
}
enum reg_arg_type {
SRC_OP, /* register is used as source operand */
DST_OP, /* register is used as destination operand */
DST_OP_NO_MARK /* same as above, check only, don't mark */
};
static int cmp_subprogs(const void *a, const void *b)
{
return ((struct bpf_subprog_info *)a)->start -
((struct bpf_subprog_info *)b)->start;
}
static int find_subprog(struct bpf_verifier_env *env, int off)
{
struct bpf_subprog_info *p;
p = bsearch(&off, env->subprog_info, env->subprog_cnt,
sizeof(env->subprog_info[0]), cmp_subprogs);
if (!p)
return -ENOENT;
return p - env->subprog_info;
}
static int add_subprog(struct bpf_verifier_env *env, int off)
{
int insn_cnt = env->prog->len;
int ret;
if (off >= insn_cnt || off < 0) {
verbose(env, "call to invalid destination\n");
return -EINVAL;
}
ret = find_subprog(env, off);
if (ret >= 0)
return 0;
if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
verbose(env, "too many subprograms\n");
return -E2BIG;
}
env->subprog_info[env->subprog_cnt++].start = off;
sort(env->subprog_info, env->subprog_cnt,
sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
return 0;
}
static int check_subprogs(struct bpf_verifier_env *env)
{
int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
struct bpf_subprog_info *subprog = env->subprog_info;
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
/* Add entry function. */
ret = add_subprog(env, 0);
if (ret < 0)
return ret;
/* determine subprog starts. The end is one before the next starts */
for (i = 0; i < insn_cnt; i++) {
if (insn[i].code != (BPF_JMP | BPF_CALL))
continue;
if (insn[i].src_reg != BPF_PSEUDO_CALL)
continue;
if (!env->allow_ptr_leaks) {
verbose(env, "function calls to other bpf functions are allowed for root only\n");
return -EPERM;
}
if (bpf_prog_is_dev_bound(env->prog->aux)) {
verbose(env, "function calls in offloaded programs are not supported yet\n");
return -EINVAL;
}
ret = add_subprog(env, i + insn[i].imm + 1);
if (ret < 0)
return ret;
}
/* Add a fake 'exit' subprog which could simplify subprog iteration
* logic. 'subprog_cnt' should not be increased.
*/
subprog[env->subprog_cnt].start = insn_cnt;
if (env->log.level > 1)
for (i = 0; i < env->subprog_cnt; i++)
verbose(env, "func#%d @%d\n", i, subprog[i].start);
/* now check that all jumps are within the same subprog */
subprog_start = subprog[cur_subprog].start;
subprog_end = subprog[cur_subprog + 1].start;
for (i = 0; i < insn_cnt; i++) {
u8 code = insn[i].code;
if (BPF_CLASS(code) != BPF_JMP)
goto next;
if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
goto next;
off = i + insn[i].off + 1;
if (off < subprog_start || off >= subprog_end) {
verbose(env, "jump out of range from insn %d to %d\n", i, off);
return -EINVAL;
}
next:
if (i == subprog_end - 1) {
/* to avoid fall-through from one subprog into another
* the last insn of the subprog should be either exit
* or unconditional jump back
*/
if (code != (BPF_JMP | BPF_EXIT) &&
code != (BPF_JMP | BPF_JA)) {
verbose(env, "last insn is not an exit or jmp\n");
return -EINVAL;
}
subprog_start = subprog_end;
cur_subprog++;
if (cur_subprog < env->subprog_cnt)
subprog_end = subprog[cur_subprog + 1].start;
}
}
return 0;
}
static
struct bpf_verifier_state *skip_callee(struct bpf_verifier_env *env,
const struct bpf_verifier_state *state,
struct bpf_verifier_state *parent,
u32 regno)
{
struct bpf_verifier_state *tmp = NULL;
/* 'parent' could be a state of caller and
* 'state' could be a state of callee. In such case
* parent->curframe < state->curframe
* and it's ok for r1 - r5 registers
*
* 'parent' could be a callee's state after it bpf_exit-ed.
* In such case parent->curframe > state->curframe
* and it's ok for r0 only
*/
if (parent->curframe == state->curframe ||
(parent->curframe < state->curframe &&
regno >= BPF_REG_1 && regno <= BPF_REG_5) ||
(parent->curframe > state->curframe &&
regno == BPF_REG_0))
return parent;
if (parent->curframe > state->curframe &&
regno >= BPF_REG_6) {
/* for callee saved regs we have to skip the whole chain
* of states that belong to callee and mark as LIVE_READ
* the registers before the call
*/
tmp = parent;
while (tmp && tmp->curframe != state->curframe) {
tmp = tmp->parent;
}
if (!tmp)
goto bug;
parent = tmp;
} else {
goto bug;
}
return parent;
bug:
verbose(env, "verifier bug regno %d tmp %p\n", regno, tmp);
verbose(env, "regno %d parent frame %d current frame %d\n",
regno, parent->curframe, state->curframe);
return NULL;
}
static int mark_reg_read(struct bpf_verifier_env *env,
const struct bpf_verifier_state *state,
struct bpf_verifier_state *parent,
u32 regno)
{
bool writes = parent == state->parent; /* Observe write marks */
if (regno == BPF_REG_FP)
/* We don't need to worry about FP liveness because it's read-only */
return 0;
while (parent) {
/* if read wasn't screened by an earlier write ... */
if (writes && state->frame[state->curframe]->regs[regno].live & REG_LIVE_WRITTEN)
break;
parent = skip_callee(env, state, parent, regno);
if (!parent)
return -EFAULT;
/* ... then we depend on parent's value */
parent->frame[parent->curframe]->regs[regno].live |= REG_LIVE_READ;
state = parent;
parent = state->parent;
writes = true;
}
return 0;
}
static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
enum reg_arg_type t)
{
struct bpf_verifier_state *vstate = env->cur_state;
struct bpf_func_state *state = vstate->frame[vstate->curframe];
struct bpf_reg_state *regs = state->regs;
if (regno >= MAX_BPF_REG) {
verbose(env, "R%d is invalid\n", regno);
return -EINVAL;
}
if (t == SRC_OP) {
/* check whether register used as source operand can be read */
if (regs[regno].type == NOT_INIT) {
verbose(env, "R%d !read_ok\n", regno);
return -EACCES;
}
return mark_reg_read(env, vstate, vstate->parent, regno);
} else {
/* check whether register used as dest operand can be written to */
if (regno == BPF_REG_FP) {
verbose(env, "frame pointer is read only\n");
return -EACCES;
}
regs[regno].live |= REG_LIVE_WRITTEN;
if (t == DST_OP)
mark_reg_unknown(env, regs, regno);
}
return 0;
}
static bool is_spillable_regtype(enum bpf_reg_type type)
{
switch (type) {
case PTR_TO_MAP_VALUE:
case PTR_TO_MAP_VALUE_OR_NULL:
case PTR_TO_STACK:
case PTR_TO_CTX:
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
case PTR_TO_PACKET_END:
case CONST_PTR_TO_MAP:
return true;
default:
return false;
}
}
/* Does this register contain a constant zero? */
static bool register_is_null(struct bpf_reg_state *reg)
{
return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
}
/* check_stack_read/write functions track spill/fill of registers,
* stack boundary and alignment are checked in check_mem_access()
*/
static int check_stack_write(struct bpf_verifier_env *env,
struct bpf_func_state *state, /* func where register points to */
int off, int size, int value_regno, int insn_idx)
{
struct bpf_func_state *cur; /* state of the current function */
int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
enum bpf_reg_type type;
err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
true);
if (err)
return err;
/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
* so it's aligned access and [off, off + size) are within stack limits
*/
if (!env->allow_ptr_leaks &&
state->stack[spi].slot_type[0] == STACK_SPILL &&
size != BPF_REG_SIZE) {
verbose(env, "attempt to corrupt spilled pointer on stack\n");
return -EACCES;
}
cur = env->cur_state->frame[env->cur_state->curframe];
if (value_regno >= 0 &&
is_spillable_regtype((type = cur->regs[value_regno].type))) {
/* register containing pointer is being spilled into stack */
if (size != BPF_REG_SIZE) {
verbose(env, "invalid size of register spill\n");
return -EACCES;
}
if (state != cur && type == PTR_TO_STACK) {
verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
return -EINVAL;
}
/* save register state */
state->stack[spi].spilled_ptr = cur->regs[value_regno];
state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
for (i = 0; i < BPF_REG_SIZE; i++) {
if (state->stack[spi].slot_type[i] == STACK_MISC &&
!env->allow_ptr_leaks) {
int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
int soff = (-spi - 1) * BPF_REG_SIZE;
/* detected reuse of integer stack slot with a pointer
* which means either llvm is reusing stack slot or
* an attacker is trying to exploit CVE-2018-3639
* (speculative store bypass)
* Have to sanitize that slot with preemptive
* store of zero.
*/
if (*poff && *poff != soff) {
/* disallow programs where single insn stores
* into two different stack slots, since verifier
* cannot sanitize them
*/
verbose(env,
"insn %d cannot access two stack slots fp%d and fp%d",
insn_idx, *poff, soff);
return -EINVAL;
}
*poff = soff;
}
state->stack[spi].slot_type[i] = STACK_SPILL;
}
} else {
u8 type = STACK_MISC;
/* regular write of data into stack */
state->stack[spi].spilled_ptr = (struct bpf_reg_state) {};
/* only mark the slot as written if all 8 bytes were written
* otherwise read propagation may incorrectly stop too soon
* when stack slots are partially written.
* This heuristic means that read propagation will be
* conservative, since it will add reg_live_read marks
* to stack slots all the way to first state when programs
* writes+reads less than 8 bytes
*/
if (size == BPF_REG_SIZE)
state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
/* when we zero initialize stack slots mark them as such */
if (value_regno >= 0 &&
register_is_null(&cur->regs[value_regno]))
type = STACK_ZERO;
for (i = 0; i < size; i++)
state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
type;
}
return 0;
}
/* registers of every function are unique and mark_reg_read() propagates
* the liveness in the following cases:
* - from callee into caller for R1 - R5 that were used as arguments
* - from caller into callee for R0 that used as result of the call
* - from caller to the same caller skipping states of the callee for R6 - R9,
* since R6 - R9 are callee saved by implicit function prologue and
* caller's R6 != callee's R6, so when we propagate liveness up to
* parent states we need to skip callee states for R6 - R9.
*
* stack slot marking is different, since stacks of caller and callee are
* accessible in both (since caller can pass a pointer to caller's stack to
* callee which can pass it to another function), hence mark_stack_slot_read()
* has to propagate the stack liveness to all parent states at given frame number.
* Consider code:
* f1() {
* ptr = fp - 8;
* *ptr = ctx;
* call f2 {
* .. = *ptr;
* }
* .. = *ptr;
* }
* First *ptr is reading from f1's stack and mark_stack_slot_read() has
* to mark liveness at the f1's frame and not f2's frame.
* Second *ptr is also reading from f1's stack and mark_stack_slot_read() has
* to propagate liveness to f2 states at f1's frame level and further into
* f1 states at f1's frame level until write into that stack slot
*/
static void mark_stack_slot_read(struct bpf_verifier_env *env,
const struct bpf_verifier_state *state,
struct bpf_verifier_state *parent,
int slot, int frameno)
{
bool writes = parent == state->parent; /* Observe write marks */
while (parent) {
if (parent->frame[frameno]->allocated_stack <= slot * BPF_REG_SIZE)
/* since LIVE_WRITTEN mark is only done for full 8-byte
* write the read marks are conservative and parent
* state may not even have the stack allocated. In such case
* end the propagation, since the loop reached beginning
* of the function
*/
break;
/* if read wasn't screened by an earlier write ... */
if (writes && state->frame[frameno]->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN)
break;
/* ... then we depend on parent's value */
parent->frame[frameno]->stack[slot].spilled_ptr.live |= REG_LIVE_READ;
state = parent;
parent = state->parent;
writes = true;
}
}
static int check_stack_read(struct bpf_verifier_env *env,
struct bpf_func_state *reg_state /* func where register points to */,
int off, int size, int value_regno)
{
struct bpf_verifier_state *vstate = env->cur_state;
struct bpf_func_state *state = vstate->frame[vstate->curframe];
int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
u8 *stype;
if (reg_state->allocated_stack <= slot) {
verbose(env, "invalid read from stack off %d+0 size %d\n",
off, size);
return -EACCES;
}
stype = reg_state->stack[spi].slot_type;
if (stype[0] == STACK_SPILL) {
if (size != BPF_REG_SIZE) {
verbose(env, "invalid size of register spill\n");
return -EACCES;
}
for (i = 1; i < BPF_REG_SIZE; i++) {
if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
verbose(env, "corrupted spill memory\n");
return -EACCES;
}
}
if (value_regno >= 0) {
/* restore register state from stack */
state->regs[value_regno] = reg_state->stack[spi].spilled_ptr;
/* mark reg as written since spilled pointer state likely
* has its liveness marks cleared by is_state_visited()
* which resets stack/reg liveness for state transitions
*/
state->regs[value_regno].live |= REG_LIVE_WRITTEN;
}
mark_stack_slot_read(env, vstate, vstate->parent, spi,
reg_state->frameno);
return 0;
} else {
int zeros = 0;
for (i = 0; i < size; i++) {
if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
continue;
if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
zeros++;
continue;
}
verbose(env, "invalid read from stack off %d+%d size %d\n",
off, i, size);
return -EACCES;
}
mark_stack_slot_read(env, vstate, vstate->parent, spi,
reg_state->frameno);
if (value_regno >= 0) {
if (zeros == size) {
/* any size read into register is zero extended,
* so the whole register == const_zero
*/
__mark_reg_const_zero(&state->regs[value_regno]);
} else {
/* have read misc data from the stack */
mark_reg_unknown(env, state->regs, value_regno);
}
state->regs[value_regno].live |= REG_LIVE_WRITTEN;
}
return 0;
}
}
/* check read/write into map element returned by bpf_map_lookup_elem() */
static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_map *map = regs[regno].map_ptr;
if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
off + size > map->value_size) {
verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
map->value_size, off, size);
return -EACCES;
}
return 0;
}
/* check read/write into a map element with possible variable offset */
static int check_map_access(struct bpf_verifier_env *env, u32 regno,
int off, int size, bool zero_size_allowed)
{
struct bpf_verifier_state *vstate = env->cur_state;
struct bpf_func_state *state = vstate->frame[vstate->curframe];
struct bpf_reg_state *reg = &state->regs[regno];
int err;
/* We may have adjusted the register to this map value, so we
* need to try adding each of min_value and max_value to off
* to make sure our theoretical access will be safe.
*/
if (env->log.level)
print_verifier_state(env, state);
/* The minimum value is only important with signed
* comparisons where we can't assume the floor of a
* value is 0. If we are using signed variables for our
* index'es we need to make sure that whatever we use
* will have a set floor within our range.
*/
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
regno);
return -EACCES;
}
err = __check_map_access(env, regno, reg->smin_value + off, size,
zero_size_allowed);
if (err) {
verbose(env, "R%d min value is outside of the array range\n",
regno);
return err;
}
/* If we haven't set a max value then we need to bail since we can't be
* sure we won't do bad things.
* If reg->umax_value + off could overflow, treat that as unbounded too.
*/
if (reg->umax_value >= BPF_MAX_VAR_OFF) {
verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
regno);
return -EACCES;
}
err = __check_map_access(env, regno, reg->umax_value + off, size,
zero_size_allowed);
if (err)
verbose(env, "R%d max value is outside of the array range\n",
regno);
return err;
}
#define MAX_PACKET_OFF 0xffff
static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
const struct bpf_call_arg_meta *meta,
enum bpf_access_type t)
{
switch (env->prog->type) {
case BPF_PROG_TYPE_LWT_IN:
case BPF_PROG_TYPE_LWT_OUT:
case BPF_PROG_TYPE_LWT_SEG6LOCAL:
case BPF_PROG_TYPE_SK_REUSEPORT:
/* dst_input() and dst_output() can't write for now */
if (t == BPF_WRITE)
return false;
/* fallthrough */
case BPF_PROG_TYPE_SCHED_CLS:
case BPF_PROG_TYPE_SCHED_ACT:
case BPF_PROG_TYPE_XDP:
case BPF_PROG_TYPE_LWT_XMIT:
case BPF_PROG_TYPE_SK_SKB:
case BPF_PROG_TYPE_SK_MSG:
if (meta)
return meta->pkt_access;
env->seen_direct_write = true;
return true;
default:
return false;
}
}
static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
int off, int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = ®s[regno];
if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
(u64)off + size > reg->range) {
verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
off, size, regno, reg->id, reg->off, reg->range);
return -EACCES;
}
return 0;
}
static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = ®s[regno];
int err;
/* We may have added a variable offset to the packet pointer; but any
* reg->range we have comes after that. We are only checking the fixed
* offset.
*/
/* We don't allow negative numbers, because we aren't tracking enough
* detail to prove they're safe.
*/
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
regno);
return -EACCES;
}
err = __check_packet_access(env, regno, off, size, zero_size_allowed);
if (err) {
verbose(env, "R%d offset is outside of the packet\n", regno);
return err;
}
return err;
}
/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
enum bpf_access_type t, enum bpf_reg_type *reg_type)
{
struct bpf_insn_access_aux info = {
.reg_type = *reg_type,
};
if (env->ops->is_valid_access &&
env->ops->is_valid_access(off, size, t, env->prog, &info)) {
/* A non zero info.ctx_field_size indicates that this field is a
* candidate for later verifier transformation to load the whole
* field and then apply a mask when accessed with a narrower
* access than actual ctx access size. A zero info.ctx_field_size
* will only allow for whole field access and rejects any other
* type of narrower access.
*/
*reg_type = info.reg_type;
env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
/* remember the offset of last byte accessed in ctx */
if (env->prog->aux->max_ctx_offset < off + size)
env->prog->aux->max_ctx_offset = off + size;
return 0;
}
verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
return -EACCES;
}
static bool __is_pointer_value(bool allow_ptr_leaks,
const struct bpf_reg_state *reg)
{
if (allow_ptr_leaks)
return false;
return reg->type != SCALAR_VALUE;
}
static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
{
return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
}
static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
{
const struct bpf_reg_state *reg = cur_regs(env) + regno;
return reg->type == PTR_TO_CTX;
}
static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
{
const struct bpf_reg_state *reg = cur_regs(env) + regno;
return type_is_pkt_pointer(reg->type);
}
static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
int off, int size, bool strict)
{
struct tnum reg_off;
int ip_align;
/* Byte size accesses are always allowed. */
if (!strict || size == 1)
return 0;
/* For platforms that do not have a Kconfig enabling
* CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
* NET_IP_ALIGN is universally set to '2'. And on platforms
* that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
* to this code only in strict mode where we want to emulate
* the NET_IP_ALIGN==2 checking. Therefore use an
* unconditional IP align value of '2'.
*/
ip_align = 2;
reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
if (!tnum_is_aligned(reg_off, size)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env,
"misaligned packet access off %d+%s+%d+%d size %d\n",
ip_align, tn_buf, reg->off, off, size);
return -EACCES;
}
return 0;
}
static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
const char *pointer_desc,
int off, int size, bool strict)
{
struct tnum reg_off;
/* Byte size accesses are always allowed. */
if (!strict || size == 1)
return 0;
reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
if (!tnum_is_aligned(reg_off, size)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
pointer_desc, tn_buf, reg->off, off, size);
return -EACCES;
}
return 0;
}
static int check_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg, int off,
int size, bool strict_alignment_once)
{
bool strict = env->strict_alignment || strict_alignment_once;
const char *pointer_desc = "";
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
/* Special case, because of NET_IP_ALIGN. Given metadata sits
* right in front, treat it the very same way.
*/
return check_pkt_ptr_alignment(env, reg, off, size, strict);
case PTR_TO_MAP_VALUE:
pointer_desc = "value ";
break;
case PTR_TO_CTX:
pointer_desc = "context ";
break;
case PTR_TO_STACK:
pointer_desc = "stack ";
/* The stack spill tracking logic in check_stack_write()
* and check_stack_read() relies on stack accesses being
* aligned.
*/
strict = true;
break;
default:
break;
}
return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
strict);
}
static int update_stack_depth(struct bpf_verifier_env *env,
const struct bpf_func_state *func,
int off)
{
u16 stack = env->subprog_info[func->subprogno].stack_depth;
if (stack >= -off)
return 0;
/* update known max for given subprogram */
env->subprog_info[func->subprogno].stack_depth = -off;
return 0;
}
/* starting from main bpf function walk all instructions of the function
* and recursively walk all callees that given function can call.
* Ignore jump and exit insns.
* Since recursion is prevented by check_cfg() this algorithm
* only needs a local stack of MAX_CALL_FRAMES to remember callsites
*/
static int check_max_stack_depth(struct bpf_verifier_env *env)
{
int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
struct bpf_subprog_info *subprog = env->subprog_info;
struct bpf_insn *insn = env->prog->insnsi;
int ret_insn[MAX_CALL_FRAMES];
int ret_prog[MAX_CALL_FRAMES];
process_func:
/* round up to 32-bytes, since this is granularity
* of interpreter stack size
*/
depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
if (depth > MAX_BPF_STACK) {
verbose(env, "combined stack size of %d calls is %d. Too large\n",
frame + 1, depth);
return -EACCES;
}
continue_func:
subprog_end = subprog[idx + 1].start;
for (; i < subprog_end; i++) {
if (insn[i].code != (BPF_JMP | BPF_CALL))
continue;
if (insn[i].src_reg != BPF_PSEUDO_CALL)
continue;
/* remember insn and function to return to */
ret_insn[frame] = i + 1;
ret_prog[frame] = idx;
/* find the callee */
i = i + insn[i].imm + 1;
idx = find_subprog(env, i);
if (idx < 0) {
WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
i);
return -EFAULT;
}
frame++;
if (frame >= MAX_CALL_FRAMES) {
WARN_ONCE(1, "verifier bug. Call stack is too deep\n");
return -EFAULT;
}
goto process_func;
}
/* end of for() loop means the last insn of the 'subprog'
* was reached. Doesn't matter whether it was JA or EXIT
*/
if (frame == 0)
return 0;
depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
frame--;
i = ret_insn[frame];
idx = ret_prog[frame];
goto continue_func;
}
#ifndef CONFIG_BPF_JIT_ALWAYS_ON
static int get_callee_stack_depth(struct bpf_verifier_env *env,
const struct bpf_insn *insn, int idx)
{
int start = idx + insn->imm + 1, subprog;
subprog = find_subprog(env, start);
if (subprog < 0) {
WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
start);
return -EFAULT;
}
return env->subprog_info[subprog].stack_depth;
}
#endif
static int check_ctx_reg(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg, int regno)
{
/* Access to ctx or passing it to a helper is only allowed in
* its original, unmodified form.
*/
if (reg->off) {
verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
regno, reg->off);
return -EACCES;
}
if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
return -EACCES;
}
return 0;
}
/* truncate register to smaller size (in bytes)
* must be called with size < BPF_REG_SIZE
*/
static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
{
u64 mask;
/* clear high bits in bit representation */
reg->var_off = tnum_cast(reg->var_off, size);
/* fix arithmetic bounds */
mask = ((u64)1 << (size * 8)) - 1;
if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
reg->umin_value &= mask;
reg->umax_value &= mask;
} else {
reg->umin_value = 0;
reg->umax_value = mask;
}
reg->smin_value = reg->umin_value;
reg->smax_value = reg->umax_value;
}
/* check whether memory at (regno + off) is accessible for t = (read | write)
* if t==write, value_regno is a register which value is stored into memory
* if t==read, value_regno is a register which will receive the value from memory
* if t==write && value_regno==-1, some unknown value is stored into memory
* if t==read && value_regno==-1, don't care what we read from memory
*/
static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
int off, int bpf_size, enum bpf_access_type t,
int value_regno, bool strict_alignment_once)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = regs + regno;
struct bpf_func_state *state;
int size, err = 0;
size = bpf_size_to_bytes(bpf_size);
if (size < 0)
return size;
/* alignment checks will add in reg->off themselves */
err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
if (err)
return err;
/* for access checks, reg->off is just part of off */
off += reg->off;
if (reg->type == PTR_TO_MAP_VALUE) {
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into map\n", value_regno);
return -EACCES;
}
err = check_map_access(env, regno, off, size, false);
if (!err && t == BPF_READ && value_regno >= 0)
mark_reg_unknown(env, regs, value_regno);
} else if (reg->type == PTR_TO_CTX) {
enum bpf_reg_type reg_type = SCALAR_VALUE;
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into ctx\n", value_regno);
return -EACCES;
}
err = check_ctx_reg(env, reg, regno);
if (err < 0)
return err;
err = check_ctx_access(env, insn_idx, off, size, t, ®_type);
if (!err && t == BPF_READ && value_regno >= 0) {
/* ctx access returns either a scalar, or a
* PTR_TO_PACKET[_META,_END]. In the latter
* case, we know the offset is zero.
*/
if (reg_type == SCALAR_VALUE)
mark_reg_unknown(env, regs, value_regno);
else
mark_reg_known_zero(env, regs,
value_regno);
regs[value_regno].id = 0;
regs[value_regno].off = 0;
regs[value_regno].range = 0;
regs[value_regno].type = reg_type;
}
} else if (reg->type == PTR_TO_STACK) {
/* stack accesses must be at a fixed offset, so that we can
* determine what type of data were returned.
* See check_stack_read().
*/
if (!tnum_is_const(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "variable stack access var_off=%s off=%d size=%d",
tn_buf, off, size);
return -EACCES;
}
off += reg->var_off.value;
if (off >= 0 || off < -MAX_BPF_STACK) {
verbose(env, "invalid stack off=%d size=%d\n", off,
size);
return -EACCES;
}
state = func(env, reg);
err = update_stack_depth(env, state, off);
if (err)
return err;
if (t == BPF_WRITE)
err = check_stack_write(env, state, off, size,
value_regno, insn_idx);
else
err = check_stack_read(env, state, off, size,
value_regno);
} else if (reg_is_pkt_pointer(reg)) {
if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
verbose(env, "cannot write into packet\n");
return -EACCES;
}
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into packet\n",
value_regno);
return -EACCES;
}
err = check_packet_access(env, regno, off, size, false);
if (!err && t == BPF_READ && value_regno >= 0)
mark_reg_unknown(env, regs, value_regno);
} else {
verbose(env, "R%d invalid mem access '%s'\n", regno,
reg_type_str[reg->type]);
return -EACCES;
}
if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
regs[value_regno].type == SCALAR_VALUE) {
/* b/h/w load zero-extends, mark upper bits as known 0 */
coerce_reg_to_size(®s[value_regno], size);
}
return err;
}
static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
{
int err;
if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
insn->imm != 0) {
verbose(env, "BPF_XADD uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->src_reg)) {
verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
return -EACCES;
}
if (is_ctx_reg(env, insn->dst_reg) ||
is_pkt_reg(env, insn->dst_reg)) {
verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
insn->dst_reg, is_ctx_reg(env, insn->dst_reg) ?
"context" : "packet");
return -EACCES;
}
/* check whether atomic_add can read the memory */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_READ, -1, true);
if (err)
return err;
/* check whether atomic_add can write into the same memory */
return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE, -1, true);
}
/* when register 'regno' is passed into function that will read 'access_size'
* bytes from that pointer, make sure that it's within stack boundary
* and all elements of stack are initialized.
* Unlike most pointer bounds-checking functions, this one doesn't take an
* 'off' argument, so it has to add in reg->off itself.
*/
static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
int access_size, bool zero_size_allowed,
struct bpf_call_arg_meta *meta)
{
struct bpf_reg_state *reg = cur_regs(env) + regno;
struct bpf_func_state *state = func(env, reg);
int off, i, slot, spi;
if (reg->type != PTR_TO_STACK) {
/* Allow zero-byte read from NULL, regardless of pointer type */
if (zero_size_allowed && access_size == 0 &&
register_is_null(reg))
return 0;
verbose(env, "R%d type=%s expected=%s\n", regno,
reg_type_str[reg->type],
reg_type_str[PTR_TO_STACK]);
return -EACCES;
}
/* Only allow fixed-offset stack reads */
if (!tnum_is_const(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "invalid variable stack read R%d var_off=%s\n",
regno, tn_buf);
return -EACCES;
}
off = reg->off + reg->var_off.value;
if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
regno, off, access_size);
return -EACCES;
}
if (meta && meta->raw_mode) {
meta->access_size = access_size;
meta->regno = regno;
return 0;
}
for (i = 0; i < access_size; i++) {
u8 *stype;
slot = -(off + i) - 1;
spi = slot / BPF_REG_SIZE;
if (state->allocated_stack <= slot)
goto err;
stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
if (*stype == STACK_MISC)
goto mark;
if (*stype == STACK_ZERO) {
/* helper can write anything into the stack */
*stype = STACK_MISC;
goto mark;
}
err:
verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
off, i, access_size);
return -EACCES;
mark:
/* reading any byte out of 8-byte 'spill_slot' will cause
* the whole slot to be marked as 'read'
*/
mark_stack_slot_read(env, env->cur_state, env->cur_state->parent,
spi, state->frameno);
}
return update_stack_depth(env, state, off);
}
static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
int access_size, bool zero_size_allowed,
struct bpf_call_arg_meta *meta)
{
struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
return check_packet_access(env, regno, reg->off, access_size,
zero_size_allowed);
case PTR_TO_MAP_VALUE:
return check_map_access(env, regno, reg->off, access_size,
zero_size_allowed);
default: /* scalar_value|ptr_to_stack or invalid ptr */
return check_stack_boundary(env, regno, access_size,
zero_size_allowed, meta);
}
}
static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
{
return type == ARG_PTR_TO_MEM ||
type == ARG_PTR_TO_MEM_OR_NULL ||
type == ARG_PTR_TO_UNINIT_MEM;
}
static bool arg_type_is_mem_size(enum bpf_arg_type type)
{
return type == ARG_CONST_SIZE ||
type == ARG_CONST_SIZE_OR_ZERO;
}
static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
enum bpf_arg_type arg_type,
struct bpf_call_arg_meta *meta)
{
struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
enum bpf_reg_type expected_type, type = reg->type;
int err = 0;
if (arg_type == ARG_DONTCARE)
return 0;
err = check_reg_arg(env, regno, SRC_OP);
if (err)
return err;
if (arg_type == ARG_ANYTHING) {
if (is_pointer_value(env, regno)) {
verbose(env, "R%d leaks addr into helper function\n",
regno);
return -EACCES;
}
return 0;
}
if (type_is_pkt_pointer(type) &&
!may_access_direct_pkt_data(env, meta, BPF_READ)) {
verbose(env, "helper access to the packet is not allowed\n");
return -EACCES;
}
if (arg_type == ARG_PTR_TO_MAP_KEY ||
arg_type == ARG_PTR_TO_MAP_VALUE) {
expected_type = PTR_TO_STACK;
if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE &&
type != expected_type)
goto err_type;
} else if (arg_type == ARG_CONST_SIZE ||
arg_type == ARG_CONST_SIZE_OR_ZERO) {
expected_type = SCALAR_VALUE;
if (type != expected_type)
goto err_type;
} else if (arg_type == ARG_CONST_MAP_PTR) {
expected_type = CONST_PTR_TO_MAP;
if (type != expected_type)
goto err_type;
} else if (arg_type == ARG_PTR_TO_CTX) {
expected_type = PTR_TO_CTX;
if (type != expected_type)
goto err_type;
err = check_ctx_reg(env, reg, regno);
if (err < 0)
return err;
} else if (arg_type_is_mem_ptr(arg_type)) {
expected_type = PTR_TO_STACK;
/* One exception here. In case function allows for NULL to be
* passed in as argument, it's a SCALAR_VALUE type. Final test
* happens during stack boundary checking.
*/
if (register_is_null(reg) &&
arg_type == ARG_PTR_TO_MEM_OR_NULL)
/* final test in check_stack_boundary() */;
else if (!type_is_pkt_pointer(type) &&
type != PTR_TO_MAP_VALUE &&
type != expected_type)
goto err_type;
meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
} else {
verbose(env, "unsupported arg_type %d\n", arg_type);
return -EFAULT;
}
if (arg_type == ARG_CONST_MAP_PTR) {
/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
meta->map_ptr = reg->map_ptr;
} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
/* bpf_map_xxx(..., map_ptr, ..., key) call:
* check that [key, key + map->key_size) are within
* stack limits and initialized
*/
if (!meta->map_ptr) {
/* in function declaration map_ptr must come before
* map_key, so that it's verified and known before
* we have to check map_key here. Otherwise it means
* that kernel subsystem misconfigured verifier
*/
verbose(env, "invalid map_ptr to access map->key\n");
return -EACCES;
}
err = check_helper_mem_access(env, regno,
meta->map_ptr->key_size, false,
NULL);
} else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
/* bpf_map_xxx(..., map_ptr, ..., value) call:
* check [value, value + map->value_size) validity
*/
if (!meta->map_ptr) {
/* kernel subsystem misconfigured verifier */
verbose(env, "invalid map_ptr to access map->value\n");
return -EACCES;
}
err = check_helper_mem_access(env, regno,
meta->map_ptr->value_size, false,
NULL);
} else if (arg_type_is_mem_size(arg_type)) {
bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
/* remember the mem_size which may be used later
* to refine return values.
*/
meta->msize_smax_value = reg->smax_value;
meta->msize_umax_value = reg->umax_value;
/* The register is SCALAR_VALUE; the access check
* happens using its boundaries.
*/
if (!tnum_is_const(reg->var_off))
/* For unprivileged variable accesses, disable raw
* mode so that the program is required to
* initialize all the memory that the helper could
* just partially fill up.
*/
meta = NULL;
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
regno);
return -EACCES;
}
if (reg->umin_value == 0) {
err = check_helper_mem_access(env, regno - 1, 0,
zero_size_allowed,
meta);
if (err)
return err;
}
if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
regno);
return -EACCES;
}
err = check_helper_mem_access(env, regno - 1,
reg->umax_value,
zero_size_allowed, meta);
}
return err;
err_type:
verbose(env, "R%d type=%s expected=%s\n", regno,
reg_type_str[type], reg_type_str[expected_type]);
return -EACCES;
}
static int check_map_func_compatibility(struct bpf_verifier_env *env,
struct bpf_map *map, int func_id)
{
if (!map)
return 0;
/* We need a two way check, first is from map perspective ... */
switch (map->map_type) {
case BPF_MAP_TYPE_PROG_ARRAY:
if (func_id != BPF_FUNC_tail_call)
goto error;
break;
case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
if (func_id != BPF_FUNC_perf_event_read &&
func_id != BPF_FUNC_perf_event_output &&
func_id != BPF_FUNC_perf_event_read_value)
goto error;
break;
case BPF_MAP_TYPE_STACK_TRACE:
if (func_id != BPF_FUNC_get_stackid)
goto error;
break;
case BPF_MAP_TYPE_CGROUP_ARRAY:
if (func_id != BPF_FUNC_skb_under_cgroup &&
func_id != BPF_FUNC_current_task_under_cgroup)
goto error;
break;
case BPF_MAP_TYPE_CGROUP_STORAGE:
if (func_id != BPF_FUNC_get_local_storage)
goto error;
break;
/* devmap returns a pointer to a live net_device ifindex that we cannot
* allow to be modified from bpf side. So do not allow lookup elements
* for now.
*/
case BPF_MAP_TYPE_DEVMAP:
if (func_id != BPF_FUNC_redirect_map)
goto error;
break;
/* Restrict bpf side of cpumap and xskmap, open when use-cases
* appear.
*/
case BPF_MAP_TYPE_CPUMAP:
case BPF_MAP_TYPE_XSKMAP:
if (func_id != BPF_FUNC_redirect_map)
goto error;
break;
case BPF_MAP_TYPE_ARRAY_OF_MAPS:
case BPF_MAP_TYPE_HASH_OF_MAPS:
if (func_id != BPF_FUNC_map_lookup_elem)
goto error;
break;
case BPF_MAP_TYPE_SOCKMAP:
if (func_id != BPF_FUNC_sk_redirect_map &&
func_id != BPF_FUNC_sock_map_update &&
func_id != BPF_FUNC_map_delete_elem &&
func_id != BPF_FUNC_msg_redirect_map)
goto error;
break;
case BPF_MAP_TYPE_SOCKHASH:
if (func_id != BPF_FUNC_sk_redirect_hash &&
func_id != BPF_FUNC_sock_hash_update &&
func_id != BPF_FUNC_map_delete_elem &&
func_id != BPF_FUNC_msg_redirect_hash)
goto error;
break;
case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
if (func_id != BPF_FUNC_sk_select_reuseport)
goto error;
break;
default:
break;
}
/* ... and second from the function itself. */
switch (func_id) {
case BPF_FUNC_tail_call:
if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
goto error;
if (env->subprog_cnt > 1) {
verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
return -EINVAL;
}
break;
case BPF_FUNC_perf_event_read:
case BPF_FUNC_perf_event_output:
case BPF_FUNC_perf_event_read_value:
if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
goto error;
break;
case BPF_FUNC_get_stackid:
if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
goto error;
break;
case BPF_FUNC_current_task_under_cgroup:
case BPF_FUNC_skb_under_cgroup:
if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
goto error;
break;
case BPF_FUNC_redirect_map:
if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
map->map_type != BPF_MAP_TYPE_CPUMAP &&
map->map_type != BPF_MAP_TYPE_XSKMAP)
goto error;
break;
case BPF_FUNC_sk_redirect_map:
case BPF_FUNC_msg_redirect_map:
case BPF_FUNC_sock_map_update:
if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
goto error;
break;
case BPF_FUNC_sk_redirect_hash:
case BPF_FUNC_msg_redirect_hash:
case BPF_FUNC_sock_hash_update:
if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
goto error;
break;
case BPF_FUNC_get_local_storage:
if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE)
goto error;
break;
case BPF_FUNC_sk_select_reuseport:
if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY)
goto error;
break;
default:
break;
}
return 0;
error:
verbose(env, "cannot pass map_type %d into func %s#%d\n",
map->map_type, func_id_name(func_id), func_id);
return -EINVAL;
}
static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
{
int count = 0;
if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
count++;
/* We only support one arg being in raw mode at the moment,
* which is sufficient for the helper functions we have
* right now.
*/
return count <= 1;
}
static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
enum bpf_arg_type arg_next)
{
return (arg_type_is_mem_ptr(arg_curr) &&
!arg_type_is_mem_size(arg_next)) ||
(!arg_type_is_mem_ptr(arg_curr) &&
arg_type_is_mem_size(arg_next));
}
static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
{
/* bpf_xxx(..., buf, len) call will access 'len'
* bytes from memory 'buf'. Both arg types need
* to be paired, so make sure there's no buggy
* helper function specification.
*/
if (arg_type_is_mem_size(fn->arg1_type) ||
arg_type_is_mem_ptr(fn->arg5_type) ||
check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
return false;
return true;
}
static int check_func_proto(const struct bpf_func_proto *fn)
{
return check_raw_mode_ok(fn) &&
check_arg_pair_ok(fn) ? 0 : -EINVAL;
}
/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
* are now invalid, so turn them into unknown SCALAR_VALUE.
*/
static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
struct bpf_func_state *state)
{
struct bpf_reg_state *regs = state->regs, *reg;
int i;
for (i = 0; i < MAX_BPF_REG; i++)
if (reg_is_pkt_pointer_any(®s[i]))
mark_reg_unknown(env, regs, i);
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
reg = &state->stack[i].spilled_ptr;
if (reg_is_pkt_pointer_any(reg))
__mark_reg_unknown(reg);
}
}
static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
{
struct bpf_verifier_state *vstate = env->cur_state;
int i;
for (i = 0; i <= vstate->curframe; i++)
__clear_all_pkt_pointers(env, vstate->frame[i]);
}
static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
int *insn_idx)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_func_state *caller, *callee;
int i, subprog, target_insn;
if (state->curframe + 1 >= MAX_CALL_FRAMES) {
verbose(env, "the call stack of %d frames is too deep\n",
state->curframe + 2);
return -E2BIG;
}
target_insn = *insn_idx + insn->imm;
subprog = find_subprog(env, target_insn + 1);
if (subprog < 0) {
verbose(env, "verifier bug. No program starts at insn %d\n",
target_insn + 1);
return -EFAULT;
}
caller = state->frame[state->curframe];
if (state->frame[state->curframe + 1]) {
verbose(env, "verifier bug. Frame %d already allocated\n",
state->curframe + 1);
return -EFAULT;
}
callee = kzalloc(sizeof(*callee), GFP_KERNEL);
if (!callee)
return -ENOMEM;
state->frame[state->curframe + 1] = callee;
/* callee cannot access r0, r6 - r9 for reading and has to write
* into its own stack before reading from it.
* callee can read/write into caller's stack
*/
init_func_state(env, callee,
/* remember the callsite, it will be used by bpf_exit */
*insn_idx /* callsite */,
state->curframe + 1 /* frameno within this callchain */,
subprog /* subprog number within this prog */);
/* copy r1 - r5 args that callee can access */
for (i = BPF_REG_1; i <= BPF_REG_5; i++)
callee->regs[i] = caller->regs[i];
/* after the call regsiters r0 - r5 were scratched */
for (i = 0; i < CALLER_SAVED_REGS; i++) {
mark_reg_not_init(env, caller->regs, caller_saved[i]);
check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
}
/* only increment it after check_reg_arg() finished */
state->curframe++;
/* and go analyze first insn of the callee */
*insn_idx = target_insn;
if (env->log.level) {
verbose(env, "caller:\n");
print_verifier_state(env, caller);
verbose(env, "callee:\n");
print_verifier_state(env, callee);
}
return 0;
}
static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_func_state *caller, *callee;
struct bpf_reg_state *r0;
callee = state->frame[state->curframe];
r0 = &callee->regs[BPF_REG_0];
if (r0->type == PTR_TO_STACK) {
/* technically it's ok to return caller's stack pointer
* (or caller's caller's pointer) back to the caller,
* since these pointers are valid. Only current stack
* pointer will be invalid as soon as function exits,
* but let's be conservative
*/
verbose(env, "cannot return stack pointer to the caller\n");
return -EINVAL;
}
state->curframe--;
caller = state->frame[state->curframe];
/* return to the caller whatever r0 had in the callee */
caller->regs[BPF_REG_0] = *r0;
*insn_idx = callee->callsite + 1;
if (env->log.level) {
verbose(env, "returning from callee:\n");
print_verifier_state(env, callee);
verbose(env, "to caller at %d:\n", *insn_idx);
print_verifier_state(env, caller);
}
/* clear everything in the callee */
free_func_state(callee);
state->frame[state->curframe + 1] = NULL;
return 0;
}
static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
int func_id,
struct bpf_call_arg_meta *meta)
{
struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
if (ret_type != RET_INTEGER ||
(func_id != BPF_FUNC_get_stack &&
func_id != BPF_FUNC_probe_read_str))
return;
ret_reg->smax_value = meta->msize_smax_value;
ret_reg->umax_value = meta->msize_umax_value;
__reg_deduce_bounds(ret_reg);
__reg_bound_offset(ret_reg);
}
static int
record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
int func_id, int insn_idx)
{
struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
if (func_id != BPF_FUNC_tail_call &&
func_id != BPF_FUNC_map_lookup_elem &&
func_id != BPF_FUNC_map_update_elem &&
func_id != BPF_FUNC_map_delete_elem)
return 0;
if (meta->map_ptr == NULL) {
verbose(env, "kernel subsystem misconfigured verifier\n");
return -EINVAL;
}
if (!BPF_MAP_PTR(aux->map_state))
bpf_map_ptr_store(aux, meta->map_ptr,
meta->map_ptr->unpriv_array);
else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr)
bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
meta->map_ptr->unpriv_array);
return 0;
}
static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
{
const struct bpf_func_proto *fn = NULL;
struct bpf_reg_state *regs;
struct bpf_call_arg_meta meta;
bool changes_data;
int i, err;
/* find function prototype */
if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
func_id);
return -EINVAL;
}
if (env->ops->get_func_proto)
fn = env->ops->get_func_proto(func_id, env->prog);
if (!fn) {
verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
func_id);
return -EINVAL;
}
/* eBPF programs must be GPL compatible to use GPL-ed functions */
if (!env->prog->gpl_compatible && fn->gpl_only) {
verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
return -EINVAL;
}
/* With LD_ABS/IND some JITs save/restore skb from r1. */
changes_data = bpf_helper_changes_pkt_data(fn->func);
if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
func_id_name(func_id), func_id);
return -EINVAL;
}
memset(&meta, 0, sizeof(meta));
meta.pkt_access = fn->pkt_access;
err = check_func_proto(fn);
if (err) {
verbose(env, "kernel subsystem misconfigured func %s#%d\n",
func_id_name(func_id), func_id);
return err;
}
/* check args */
err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
if (err)
return err;
err = record_func_map(env, &meta, func_id, insn_idx);
if (err)
return err;
/* Mark slots with STACK_MISC in case of raw mode, stack offset
* is inferred from register state.
*/
for (i = 0; i < meta.access_size; i++) {
err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
BPF_WRITE, -1, false);
if (err)
return err;
}
regs = cur_regs(env);
/* check that flags argument in get_local_storage(map, flags) is 0,
* this is required because get_local_storage() can't return an error.
*/
if (func_id == BPF_FUNC_get_local_storage &&
!register_is_null(®s[BPF_REG_2])) {
verbose(env, "get_local_storage() doesn't support non-zero flags\n");
return -EINVAL;
}
/* reset caller saved regs */
for (i = 0; i < CALLER_SAVED_REGS; i++) {
mark_reg_not_init(env, regs, caller_saved[i]);
check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
}
/* update return register (already marked as written above) */
if (fn->ret_type == RET_INTEGER) {
/* sets type to SCALAR_VALUE */
mark_reg_unknown(env, regs, BPF_REG_0);
} else if (fn->ret_type == RET_VOID) {
regs[BPF_REG_0].type = NOT_INIT;
} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
fn->ret_type == RET_PTR_TO_MAP_VALUE) {
if (fn->ret_type == RET_PTR_TO_MAP_VALUE)
regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
else
regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
/* There is no offset yet applied, variable or fixed */
mark_reg_known_zero(env, regs, BPF_REG_0);
regs[BPF_REG_0].off = 0;
/* remember map_ptr, so that check_map_access()
* can check 'value_size' boundary of memory access
* to map element returned from bpf_map_lookup_elem()
*/
if (meta.map_ptr == NULL) {
verbose(env,
"kernel subsystem misconfigured verifier\n");
return -EINVAL;
}
regs[BPF_REG_0].map_ptr = meta.map_ptr;
regs[BPF_REG_0].id = ++env->id_gen;
} else {
verbose(env, "unknown return type %d of func %s#%d\n",
fn->ret_type, func_id_name(func_id), func_id);
return -EINVAL;
}
do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
err = check_map_func_compatibility(env, meta.map_ptr, func_id);
if (err)
return err;
if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
const char *err_str;
#ifdef CONFIG_PERF_EVENTS
err = get_callchain_buffers(sysctl_perf_event_max_stack);
err_str = "cannot get callchain buffer for func %s#%d\n";
#else
err = -ENOTSUPP;
err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
#endif
if (err) {
verbose(env, err_str, func_id_name(func_id), func_id);
return err;
}
env->prog->has_callchain_buf = true;
}
if (changes_data)
clear_all_pkt_pointers(env);
return 0;
}
static bool signed_add_overflows(s64 a, s64 b)
{
/* Do the add in u64, where overflow is well-defined */
s64 res = (s64)((u64)a + (u64)b);
if (b < 0)
return res > a;
return res < a;
}
static bool signed_sub_overflows(s64 a, s64 b)
{
/* Do the sub in u64, where overflow is well-defined */
s64 res = (s64)((u64)a - (u64)b);
if (b < 0)
return res < a;
return res > a;
}
static bool check_reg_sane_offset(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
enum bpf_reg_type type)
{
bool known = tnum_is_const(reg->var_off);
s64 val = reg->var_off.value;
s64 smin = reg->smin_value;
if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
verbose(env, "math between %s pointer and %lld is not allowed\n",
reg_type_str[type], val);
return false;
}
if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
verbose(env, "%s pointer offset %d is not allowed\n",
reg_type_str[type], reg->off);
return false;
}
if (smin == S64_MIN) {
verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
reg_type_str[type]);
return false;
}
if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
verbose(env, "value %lld makes %s pointer be out of bounds\n",
smin, reg_type_str[type]);
return false;
}
return true;
}
/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
* Caller should also handle BPF_MOV case separately.
* If we return -EACCES, caller may want to try again treating pointer as a
* scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
*/
static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
const struct bpf_reg_state *ptr_reg,
const struct bpf_reg_state *off_reg)
{
struct bpf_verifier_state *vstate = env->cur_state;
struct bpf_func_state *state = vstate->frame[vstate->curframe];
struct bpf_reg_state *regs = state->regs, *dst_reg;
bool known = tnum_is_const(off_reg->var_off);
s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
u8 opcode = BPF_OP(insn->code);
u32 dst = insn->dst_reg;
dst_reg = ®s[dst];
if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
smin_val > smax_val || umin_val > umax_val) {
/* Taint dst register if offset had invalid bounds derived from
* e.g. dead branches.
*/
__mark_reg_unknown(dst_reg);
return 0;
}
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops on pointers produce (meaningless) scalars */
verbose(env,
"R%d 32-bit pointer arithmetic prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
dst);
return -EACCES;
}
if (ptr_reg->type == CONST_PTR_TO_MAP) {
verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_PACKET_END) {
verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
dst);
return -EACCES;
}
/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
* The id may be overwritten later if we create a new variable offset.
*/
dst_reg->type = ptr_reg->type;
dst_reg->id = ptr_reg->id;
if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
!check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
return -EINVAL;
switch (opcode) {
case BPF_ADD:
/* We can take a fixed offset as long as it doesn't overflow
* the s32 'off' field
*/
if (known && (ptr_reg->off + smin_val ==
(s64)(s32)(ptr_reg->off + smin_val))) {
/* pointer += K. Accumulate it into fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->off = ptr_reg->off + smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. Note that off_reg->off
* == 0, since it's a scalar.
* dst_reg gets the pointer type and since some positive
* integer value was added to the pointer, give it a new 'id'
* if it's a PTR_TO_PACKET.
* this creates a new 'base' pointer, off_reg (variable) gets
* added into the variable offset, and we copy the fixed offset
* from ptr_reg.
*/
if (signed_add_overflows(smin_ptr, smin_val) ||
signed_add_overflows(smax_ptr, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr + smin_val;
dst_reg->smax_value = smax_ptr + smax_val;
}
if (umin_ptr + umin_val < umin_ptr ||
umax_ptr + umax_val < umax_ptr) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value = umin_ptr + umin_val;
dst_reg->umax_value = umax_ptr + umax_val;
}
dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
dst_reg->range = 0;
}
break;
case BPF_SUB:
if (dst_reg == off_reg) {
/* scalar -= pointer. Creates an unknown scalar */
verbose(env, "R%d tried to subtract pointer from scalar\n",
dst);
return -EACCES;
}
/* We don't allow subtraction from FP, because (according to
* test_verifier.c test "invalid fp arithmetic", JITs might not
* be able to deal with it.
*/
if (ptr_reg->type == PTR_TO_STACK) {
verbose(env, "R%d subtraction from stack pointer prohibited\n",
dst);
return -EACCES;
}
if (known && (ptr_reg->off - smin_val ==
(s64)(s32)(ptr_reg->off - smin_val))) {
/* pointer -= K. Subtract it from fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->id = ptr_reg->id;
dst_reg->off = ptr_reg->off - smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. If the subtrahend is known
* nonnegative, then any reg->range we had before is still good.
*/
if (signed_sub_overflows(smin_ptr, smax_val) ||
signed_sub_overflows(smax_ptr, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr - smax_val;
dst_reg->smax_value = smax_ptr - smin_val;
}
if (umin_ptr < umax_val) {
/* Overflow possible, we know nothing */
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
/* Cannot overflow (as long as bounds are consistent) */
dst_reg->umin_value = umin_ptr - umax_val;
dst_reg->umax_value = umax_ptr - umin_val;
}
dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
if (smin_val < 0)
dst_reg->range = 0;
}
break;
case BPF_AND:
case BPF_OR:
case BPF_XOR:
/* bitwise ops on pointers are troublesome, prohibit. */
verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
default:
/* other operators (e.g. MUL,LSH) produce non-pointer results */
verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
}
if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
return -EINVAL;
__update_reg_bounds(dst_reg);
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
}
/* WARNING: This function does calculations on 64-bit values, but the actual
* execution may occur on 32-bit values. Therefore, things like bitshifts
* need extra checks in the 32-bit case.
*/
static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
struct bpf_reg_state *dst_reg,
struct bpf_reg_state src_reg)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
bool src_known, dst_known;
s64 smin_val, smax_val;
u64 umin_val, umax_val;
u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
smin_val = src_reg.smin_value;
smax_val = src_reg.smax_value;
umin_val = src_reg.umin_value;
umax_val = src_reg.umax_value;
src_known = tnum_is_const(src_reg.var_off);
dst_known = tnum_is_const(dst_reg->var_off);
if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
smin_val > smax_val || umin_val > umax_val) {
/* Taint dst register if offset had invalid bounds derived from
* e.g. dead branches.
*/
__mark_reg_unknown(dst_reg);
return 0;
}
if (!src_known &&
opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
__mark_reg_unknown(dst_reg);
return 0;
}
switch (opcode) {
case BPF_ADD:
if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
signed_add_overflows(dst_reg->smax_value, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value += smin_val;
dst_reg->smax_value += smax_val;
}
if (dst_reg->umin_value + umin_val < umin_val ||
dst_reg->umax_value + umax_val < umax_val) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value += umin_val;
dst_reg->umax_value += umax_val;
}
dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
break;
case BPF_SUB:
if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
signed_sub_overflows(dst_reg->smax_value, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value -= smax_val;
dst_reg->smax_value -= smin_val;
}
if (dst_reg->umin_value < umax_val) {
/* Overflow possible, we know nothing */
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
/* Cannot overflow (as long as bounds are consistent) */
dst_reg->umin_value -= umax_val;
dst_reg->umax_value -= umin_val;
}
dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
break;
case BPF_MUL:
dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
if (smin_val < 0 || dst_reg->smin_value < 0) {
/* Ain't nobody got time to multiply that sign */
__mark_reg_unbounded(dst_reg);
__update_reg_bounds(dst_reg);
break;
}
/* Both values are positive, so we can work with unsigned and
* copy the result to signed (unless it exceeds S64_MAX).
*/
if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
/* Potential overflow, we know nothing */
__mark_reg_unbounded(dst_reg);
/* (except what we can learn from the var_off) */
__update_reg_bounds(dst_reg);
break;
}
dst_reg->umin_value *= umin_val;
dst_reg->umax_value *= umax_val;
if (dst_reg->umax_value > S64_MAX) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
break;
case BPF_AND:
if (src_known && dst_known) {
__mark_reg_known(dst_reg, dst_reg->var_off.value &
src_reg.var_off.value);
break;
}
/* We get our minimum from the var_off, since that's inherently
* bitwise. Our maximum is the minimum of the operands' maxima.
*/
dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
dst_reg->umin_value = dst_reg->var_off.value;
dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
if (dst_reg->smin_value < 0 || smin_val < 0) {
/* Lose signed bounds when ANDing negative numbers,
* ain't nobody got time for that.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
/* ANDing two positives gives a positive, so safe to
* cast result into s64.
*/
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_OR:
if (src_known && dst_known) {
__mark_reg_known(dst_reg, dst_reg->var_off.value |
src_reg.var_off.value);
break;
}
/* We get our maximum from the var_off, and our minimum is the
* maximum of the operands' minima
*/
dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
dst_reg->umax_value = dst_reg->var_off.value |
dst_reg->var_off.mask;
if (dst_reg->smin_value < 0 || smin_val < 0) {
/* Lose signed bounds when ORing negative numbers,
* ain't nobody got time for that.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
/* ORing two positives gives a positive, so safe to
* cast result into s64.
*/
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_LSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* We lose all sign bit information (except what we can pick
* up from var_off)
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
/* If we might shift our top bit out, then we know nothing */
if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value <<= umin_val;
dst_reg->umax_value <<= umax_val;
}
dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_RSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* BPF_RSH is an unsigned shift. If the value in dst_reg might
* be negative, then either:
* 1) src_reg might be zero, so the sign bit of the result is
* unknown, so we lose our signed bounds
* 2) it's known negative, thus the unsigned bounds capture the
* signed bounds
* 3) the signed bounds cross zero, so they tell us nothing
* about the result
* If the value in dst_reg is known nonnegative, then again the
* unsigned bounts capture the signed bounds.
* Thus, in all cases it suffices to blow away our signed bounds
* and rely on inferring new ones from the unsigned bounds and
* var_off of the result.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
dst_reg->umin_value >>= umax_val;
dst_reg->umax_value >>= umin_val;
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_ARSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* Upon reaching here, src_known is true and
* umax_val is equal to umin_val.
*/
dst_reg->smin_value >>= umin_val;
dst_reg->smax_value >>= umin_val;
dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val);
/* blow away the dst_reg umin_value/umax_value and rely on
* dst_reg var_off to refine the result.
*/
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
__update_reg_bounds(dst_reg);
break;
default:
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops are (32,32)->32 */
coerce_reg_to_size(dst_reg, 4);
coerce_reg_to_size(&src_reg, 4);
}
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
}
/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
* and var_off.
*/
static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn)
{
struct bpf_verifier_state *vstate = env->cur_state;
struct bpf_func_state *state = vstate->frame[vstate->curframe];
struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
u8 opcode = BPF_OP(insn->code);
dst_reg = ®s[insn->dst_reg];
src_reg = NULL;
if (dst_reg->type != SCALAR_VALUE)
ptr_reg = dst_reg;
if (BPF_SRC(insn->code) == BPF_X) {
src_reg = ®s[insn->src_reg];
if (src_reg->type != SCALAR_VALUE) {
if (dst_reg->type != SCALAR_VALUE) {
/* Combining two pointers by any ALU op yields
* an arbitrary scalar. Disallow all math except
* pointer subtraction
*/
if (opcode == BPF_SUB && env->allow_ptr_leaks) {
mark_reg_unknown(env, regs, insn->dst_reg);
return 0;
}
verbose(env, "R%d pointer %s pointer prohibited\n",
insn->dst_reg,
bpf_alu_string[opcode >> 4]);
return -EACCES;
} else {
/* scalar += pointer
* This is legal, but we have to reverse our
* src/dest handling in computing the range
*/
return adjust_ptr_min_max_vals(env, insn,
src_reg, dst_reg);
}
} else if (ptr_reg) {
/* pointer += scalar */
return adjust_ptr_min_max_vals(env, insn,
dst_reg, src_reg);
}
} else {
/* Pretend the src is a reg with a known value, since we only
* need to be able to read from this state.
*/
off_reg.type = SCALAR_VALUE;
__mark_reg_known(&off_reg, insn->imm);
src_reg = &off_reg;
if (ptr_reg) /* pointer += K */
return adjust_ptr_min_max_vals(env, insn,
ptr_reg, src_reg);
}
/* Got here implies adding two SCALAR_VALUEs */
if (WARN_ON_ONCE(ptr_reg)) {
print_verifier_state(env, state);
verbose(env, "verifier internal error: unexpected ptr_reg\n");
return -EINVAL;
}
if (WARN_ON(!src_reg)) {
print_verifier_state(env, state);
verbose(env, "verifier internal error: no src_reg\n");
return -EINVAL;
}
return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
}
/* check validity of 32-bit and 64-bit arithmetic operations */
static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode == BPF_END || opcode == BPF_NEG) {
if (opcode == BPF_NEG) {
if (BPF_SRC(insn->code) != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->off != 0 || insn->imm != 0) {
verbose(env, "BPF_NEG uses reserved fields\n");
return -EINVAL;
}
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
(insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
BPF_CLASS(insn->code) == BPF_ALU64) {
verbose(env, "BPF_END uses reserved fields\n");
return -EINVAL;
}
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer arithmetic prohibited\n",
insn->dst_reg);
return -EACCES;
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
} else if (opcode == BPF_MOV) {
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
}
/* check dest operand, mark as required later */
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
if (BPF_SRC(insn->code) == BPF_X) {
if (BPF_CLASS(insn->code) == BPF_ALU64) {
/* case: R1 = R2
* copy register state to dest reg
*/
regs[insn->dst_reg] = regs[insn->src_reg];
regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
} else {
/* R1 = (u32) R2 */
if (is_pointer_value(env, insn->src_reg)) {
verbose(env,
"R%d partial copy of pointer\n",
insn->src_reg);
return -EACCES;
}
mark_reg_unknown(env, regs, insn->dst_reg);
coerce_reg_to_size(®s[insn->dst_reg], 4);
}
} else {
/* case: R = imm
* remember the value we stored into this reg
*/
/* clear any state __mark_reg_known doesn't set */
mark_reg_unknown(env, regs, insn->dst_reg);
regs[insn->dst_reg].type = SCALAR_VALUE;
if (BPF_CLASS(insn->code) == BPF_ALU64) {
__mark_reg_known(regs + insn->dst_reg,
insn->imm);
} else {
__mark_reg_known(regs + insn->dst_reg,
(u32)insn->imm);
}
}
} else if (opcode > BPF_END) {
verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
return -EINVAL;
} else { /* all other ALU ops: and, sub, xor, add, ... */
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
verbose(env, "div by zero\n");
return -EINVAL;
}
if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
verbose(env, "BPF_ARSH not supported for 32 bit ALU\n");
return -EINVAL;
}
if ((opcode == BPF_LSH || opcode == BPF_RSH ||
opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
if (insn->imm < 0 || insn->imm >= size) {
verbose(env, "invalid shift %d\n", insn->imm);
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
return adjust_reg_min_max_vals(env, insn);
}
return 0;
}
static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
struct bpf_reg_state *dst_reg,
enum bpf_reg_type type,
bool range_right_open)
{
struct bpf_func_state *state = vstate->frame[vstate->curframe];
struct bpf_reg_state *regs = state->regs, *reg;
u16 new_range;
int i, j;
if (dst_reg->off < 0 ||
(dst_reg->off == 0 && range_right_open))
/* This doesn't give us any range */
return;
if (dst_reg->umax_value > MAX_PACKET_OFF ||
dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
/* Risk of overflow. For instance, ptr + (1<<63) may be less
* than pkt_end, but that's because it's also less than pkt.
*/
return;
new_range = dst_reg->off;
if (range_right_open)
new_range--;
/* Examples for register markings:
*
* pkt_data in dst register:
*
* r2 = r3;
* r2 += 8;
* if (r2 > pkt_end) goto <handle exception>
* <access okay>
*
* r2 = r3;
* r2 += 8;
* if (r2 < pkt_end) goto <access okay>
* <handle exception>
*
* Where:
* r2 == dst_reg, pkt_end == src_reg
* r2=pkt(id=n,off=8,r=0)
* r3=pkt(id=n,off=0,r=0)
*
* pkt_data in src register:
*
* r2 = r3;
* r2 += 8;
* if (pkt_end >= r2) goto <access okay>
* <handle exception>
*
* r2 = r3;
* r2 += 8;
* if (pkt_end <= r2) goto <handle exception>
* <access okay>
*
* Where:
* pkt_end == dst_reg, r2 == src_reg
* r2=pkt(id=n,off=8,r=0)
* r3=pkt(id=n,off=0,r=0)
*
* Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
* or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
* and [r3, r3 + 8-1) respectively is safe to access depending on
* the check.
*/
/* If our ids match, then we must have the same max_value. And we
* don't care about the other reg's fixed offset, since if it's too big
* the range won't allow anything.
* dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
*/
for (i = 0; i < MAX_BPF_REG; i++)
if (regs[i].type == type && regs[i].id == dst_reg->id)
/* keep the maximum range already checked */
regs[i].range = max(regs[i].range, new_range);
for (j = 0; j <= vstate->curframe; j++) {
state = vstate->frame[j];
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
reg = &state->stack[i].spilled_ptr;
if (reg->type == type && reg->id == dst_reg->id)
reg->range = max(reg->range, new_range);
}
}
}
/* Adjusts the register min/max values in the case that the dst_reg is the
* variable register that we are working on, and src_reg is a constant or we're
* simply doing a BPF_K check.
* In JEQ/JNE cases we also adjust the var_off values.
*/
static void reg_set_min_max(struct bpf_reg_state *true_reg,
struct bpf_reg_state *false_reg, u64 val,
u8 opcode)
{
/* If the dst_reg is a pointer, we can't learn anything about its
* variable offset from the compare (unless src_reg were a pointer into
* the same object, but we don't bother with that.
* Since false_reg and true_reg have the same type by construction, we
* only need to check one of them for pointerness.
*/
if (__is_pointer_value(false, false_reg))
return;
switch (opcode) {
case BPF_JEQ:
/* If this is false then we know nothing Jon Snow, but if it is
* true then we know for sure.
*/
__mark_reg_known(true_reg, val);
break;
case BPF_JNE:
/* If this is true we know nothing Jon Snow, but if it is false
* we know the value for sure;
*/
__mark_reg_known(false_reg, val);
break;
case BPF_JGT:
false_reg->umax_value = min(false_reg->umax_value, val);
true_reg->umin_value = max(true_reg->umin_value, val + 1);
break;
case BPF_JSGT:
false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
break;
case BPF_JLT:
false_reg->umin_value = max(false_reg->umin_value, val);
true_reg->umax_value = min(true_reg->umax_value, val - 1);
break;
case BPF_JSLT:
false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
break;
case BPF_JGE:
false_reg->umax_value = min(false_reg->umax_value, val - 1);
true_reg->umin_value = max(true_reg->umin_value, val);
break;
case BPF_JSGE:
false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
break;
case BPF_JLE:
false_reg->umin_value = max(false_reg->umin_value, val + 1);
true_reg->umax_value = min(true_reg->umax_value, val);
break;
case BPF_JSLE:
false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
break;
default:
break;
}
__reg_deduce_bounds(false_reg);
__reg_deduce_bounds(true_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(false_reg);
__reg_bound_offset(true_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(false_reg);
__update_reg_bounds(true_reg);
}
/* Same as above, but for the case that dst_reg holds a constant and src_reg is
* the variable reg.
*/
static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
struct bpf_reg_state *false_reg, u64 val,
u8 opcode)
{
if (__is_pointer_value(false, false_reg))
return;
switch (opcode) {
case BPF_JEQ:
/* If this is false then we know nothing Jon Snow, but if it is
* true then we know for sure.
*/
__mark_reg_known(true_reg, val);
break;
case BPF_JNE:
/* If this is true we know nothing Jon Snow, but if it is false
* we know the value for sure;
*/
__mark_reg_known(false_reg, val);
break;
case BPF_JGT:
true_reg->umax_value = min(true_reg->umax_value, val - 1);
false_reg->umin_value = max(false_reg->umin_value, val);
break;
case BPF_JSGT:
true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
break;
case BPF_JLT:
true_reg->umin_value = max(true_reg->umin_value, val + 1);
false_reg->umax_value = min(false_reg->umax_value, val);
break;
case BPF_JSLT:
true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
break;
case BPF_JGE:
true_reg->umax_value = min(true_reg->umax_value, val);
false_reg->umin_value = max(false_reg->umin_value, val + 1);
break;
case BPF_JSGE:
true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
break;
case BPF_JLE:
true_reg->umin_value = max(true_reg->umin_value, val);
false_reg->umax_value = min(false_reg->umax_value, val - 1);
break;
case BPF_JSLE:
true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
break;
default:
break;
}
__reg_deduce_bounds(false_reg);
__reg_deduce_bounds(true_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(false_reg);
__reg_bound_offset(true_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(false_reg);
__update_reg_bounds(true_reg);
}
/* Regs are known to be equal, so intersect their min/max/var_off */
static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
struct bpf_reg_state *dst_reg)
{
src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
dst_reg->umin_value);
src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
dst_reg->umax_value);
src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
dst_reg->smin_value);
src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
dst_reg->smax_value);
src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
dst_reg->var_off);
/* We might have learned new bounds from the var_off. */
__update_reg_bounds(src_reg);
__update_reg_bounds(dst_reg);
/* We might have learned something about the sign bit. */
__reg_deduce_bounds(src_reg);
__reg_deduce_bounds(dst_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(src_reg);
__reg_bound_offset(dst_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(src_reg);
__update_reg_bounds(dst_reg);
}
static void reg_combine_min_max(struct bpf_reg_state *true_src,
struct bpf_reg_state *true_dst,
struct bpf_reg_state *false_src,
struct bpf_reg_state *false_dst,
u8 opcode)
{
switch (opcode) {
case BPF_JEQ:
__reg_combine_min_max(true_src, true_dst);
break;
case BPF_JNE:
__reg_combine_min_max(false_src, false_dst);
break;
}
}
static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
bool is_null)
{
struct bpf_reg_state *reg = ®s[regno];
if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
/* Old offset (both fixed and variable parts) should
* have been known-zero, because we don't allow pointer
* arithmetic on pointers that might be NULL.
*/
if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
!tnum_equals_const(reg->var_off, 0) ||
reg->off)) {
__mark_reg_known_zero(reg);
reg->off = 0;
}
if (is_null) {
reg->type = SCALAR_VALUE;
} else if (reg->map_ptr->inner_map_meta) {
reg->type = CONST_PTR_TO_MAP;
reg->map_ptr = reg->map_ptr->inner_map_meta;
} else {
reg->type = PTR_TO_MAP_VALUE;
}
/* We don't need id from this point onwards anymore, thus we
* should better reset it, so that state pruning has chances
* to take effect.
*/
reg->id = 0;
}
}
/* The logic is similar to find_good_pkt_pointers(), both could eventually
* be folded together at some point.
*/
static void mark_map_regs(struct bpf_verifier_state *vstate, u32 regno,
bool is_null)
{
struct bpf_func_state *state = vstate->frame[vstate->curframe];
struct bpf_reg_state *regs = state->regs;
u32 id = regs[regno].id;
int i, j;
for (i = 0; i < MAX_BPF_REG; i++)
mark_map_reg(regs, i, id, is_null);
for (j = 0; j <= vstate->curframe; j++) {
state = vstate->frame[j];
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
}
}
}
static bool try_match_pkt_pointers(const struct bpf_insn *insn,
struct bpf_reg_state *dst_reg,
struct bpf_reg_state *src_reg,
struct bpf_verifier_state *this_branch,
struct bpf_verifier_state *other_branch)
{
if (BPF_SRC(insn->code) != BPF_X)
return false;
switch (BPF_OP(insn->code)) {
case BPF_JGT:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
find_good_pkt_pointers(this_branch, dst_reg,
dst_reg->type, false);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end > pkt_data', pkt_data > pkt_meta' */
find_good_pkt_pointers(other_branch, src_reg,
src_reg->type, true);
} else {
return false;
}
break;
case BPF_JLT:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
find_good_pkt_pointers(other_branch, dst_reg,
dst_reg->type, true);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end < pkt_data', pkt_data > pkt_meta' */
find_good_pkt_pointers(this_branch, src_reg,
src_reg->type, false);
} else {
return false;
}
break;
case BPF_JGE:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
find_good_pkt_pointers(this_branch, dst_reg,
dst_reg->type, true);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
find_good_pkt_pointers(other_branch, src_reg,
src_reg->type, false);
} else {
return false;
}
break;
case BPF_JLE:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
find_good_pkt_pointers(other_branch, dst_reg,
dst_reg->type, false);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
find_good_pkt_pointers(this_branch, src_reg,
src_reg->type, true);
} else {
return false;
}
break;
default:
return false;
}
return true;
}
static int check_cond_jmp_op(struct bpf_verifier_env *env,
struct bpf_insn *insn, int *insn_idx)
{
struct bpf_verifier_state *this_branch = env->cur_state;
struct bpf_verifier_state *other_branch;
struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
struct bpf_reg_state *dst_reg, *other_branch_regs;
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode > BPF_JSLE) {
verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
return -EINVAL;
}
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0) {
verbose(env, "BPF_JMP uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->src_reg)) {
verbose(env, "R%d pointer comparison prohibited\n",
insn->src_reg);
return -EACCES;
}
} else {
if (insn->src_reg != BPF_REG_0) {
verbose(env, "BPF_JMP uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
dst_reg = ®s[insn->dst_reg];
/* detect if R == 0 where R was initialized to zero earlier */
if (BPF_SRC(insn->code) == BPF_K &&
(opcode == BPF_JEQ || opcode == BPF_JNE) &&
dst_reg->type == SCALAR_VALUE &&
tnum_is_const(dst_reg->var_off)) {
if ((opcode == BPF_JEQ && dst_reg->var_off.value == insn->imm) ||
(opcode == BPF_JNE && dst_reg->var_off.value != insn->imm)) {
/* if (imm == imm) goto pc+off;
* only follow the goto, ignore fall-through
*/
*insn_idx += insn->off;
return 0;
} else {
/* if (imm != imm) goto pc+off;
* only follow fall-through branch, since
* that's where the program will go
*/
return 0;
}
}
other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
if (!other_branch)
return -EFAULT;
other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
/* detect if we are comparing against a constant value so we can adjust
* our min/max values for our dst register.
* this is only legit if both are scalars (or pointers to the same
* object, I suppose, but we don't support that right now), because
* otherwise the different base pointers mean the offsets aren't
* comparable.
*/
if (BPF_SRC(insn->code) == BPF_X) {
if (dst_reg->type == SCALAR_VALUE &&
regs[insn->src_reg].type == SCALAR_VALUE) {
if (tnum_is_const(regs[insn->src_reg].var_off))
reg_set_min_max(&other_branch_regs[insn->dst_reg],
dst_reg, regs[insn->src_reg].var_off.value,
opcode);
else if (tnum_is_const(dst_reg->var_off))
reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
®s[insn->src_reg],
dst_reg->var_off.value, opcode);
else if (opcode == BPF_JEQ || opcode == BPF_JNE)
/* Comparing for equality, we can combine knowledge */
reg_combine_min_max(&other_branch_regs[insn->src_reg],
&other_branch_regs[insn->dst_reg],
®s[insn->src_reg],
®s[insn->dst_reg], opcode);
}
} else if (dst_reg->type == SCALAR_VALUE) {
reg_set_min_max(&other_branch_regs[insn->dst_reg],
dst_reg, insn->imm, opcode);
}
/* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
if (BPF_SRC(insn->code) == BPF_K &&
insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
/* Mark all identical map registers in each branch as either
* safe or unknown depending R == 0 or R != 0 conditional.
*/
mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
} else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
this_branch, other_branch) &&
is_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer comparison prohibited\n",
insn->dst_reg);
return -EACCES;
}
if (env->log.level)
print_verifier_state(env, this_branch->frame[this_branch->curframe]);
return 0;
}
/* return the map pointer stored inside BPF_LD_IMM64 instruction */
static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
{
u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
return (struct bpf_map *) (unsigned long) imm64;
}
/* verify BPF_LD_IMM64 instruction */
static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
int err;
if (BPF_SIZE(insn->code) != BPF_DW) {
verbose(env, "invalid BPF_LD_IMM insn\n");
return -EINVAL;
}
if (insn->off != 0) {
verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
return -EINVAL;
}
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
if (insn->src_reg == 0) {
u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
regs[insn->dst_reg].type = SCALAR_VALUE;
__mark_reg_known(®s[insn->dst_reg], imm);
return 0;
}
/* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
return 0;
}
static bool may_access_skb(enum bpf_prog_type type)
{
switch (type) {
case BPF_PROG_TYPE_SOCKET_FILTER:
case BPF_PROG_TYPE_SCHED_CLS:
case BPF_PROG_TYPE_SCHED_ACT:
return true;
default:
return false;
}
}
/* verify safety of LD_ABS|LD_IND instructions:
* - they can only appear in the programs where ctx == skb
* - since they are wrappers of function calls, they scratch R1-R5 registers,
* preserve R6-R9, and store return value into R0
*
* Implicit input:
* ctx == skb == R6 == CTX
*
* Explicit input:
* SRC == any register
* IMM == 32-bit immediate
*
* Output:
* R0 - 8/16/32-bit skb data converted to cpu endianness
*/
static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 mode = BPF_MODE(insn->code);
int i, err;
if (!may_access_skb(env->prog->type)) {
verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
return -EINVAL;
}
if (!env->ops->gen_ld_abs) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
}
if (env->subprog_cnt > 1) {
/* when program has LD_ABS insn JITs and interpreter assume
* that r1 == ctx == skb which is not the case for callees
* that can have arbitrary arguments. It's problematic
* for main prog as well since JITs would need to analyze
* all functions in order to make proper register save/restore
* decisions in the main prog. Hence disallow LD_ABS with calls
*/
verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
return -EINVAL;
}
if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
BPF_SIZE(insn->code) == BPF_DW ||
(mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
return -EINVAL;
}
/* check whether implicit source operand (register R6) is readable */
err = check_reg_arg(env, BPF_REG_6, SRC_OP);
if (err)
return err;
if (regs[BPF_REG_6].type != PTR_TO_CTX) {
verbose(env,
"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
return -EINVAL;
}
if (mode == BPF_IND) {
/* check explicit source operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
}
/* reset caller saved regs to unreadable */
for (i = 0; i < CALLER_SAVED_REGS; i++) {
mark_reg_not_init(env, regs, caller_saved[i]);
check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
}
/* mark destination R0 register as readable, since it contains
* the value fetched from the packet.
* Already marked as written above.
*/
mark_reg_unknown(env, regs, BPF_REG_0);
return 0;
}
static int check_return_code(struct bpf_verifier_env *env)
{
struct bpf_reg_state *reg;
struct tnum range = tnum_range(0, 1);
switch (env->prog->type) {
case BPF_PROG_TYPE_CGROUP_SKB:
case BPF_PROG_TYPE_CGROUP_SOCK:
case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
case BPF_PROG_TYPE_SOCK_OPS:
case BPF_PROG_TYPE_CGROUP_DEVICE:
break;
default:
return 0;
}
reg = cur_regs(env) + BPF_REG_0;
if (reg->type != SCALAR_VALUE) {
verbose(env, "At program exit the register R0 is not a known value (%s)\n",
reg_type_str[reg->type]);
return -EINVAL;
}
if (!tnum_in(range, reg->var_off)) {
verbose(env, "At program exit the register R0 ");
if (!tnum_is_unknown(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "has value %s", tn_buf);
} else {
verbose(env, "has unknown scalar value");
}
verbose(env, " should have been 0 or 1\n");
return -EINVAL;
}
return 0;
}
/* non-recursive DFS pseudo code
* 1 procedure DFS-iterative(G,v):
* 2 label v as discovered
* 3 let S be a stack
* 4 S.push(v)
* 5 while S is not empty
* 6 t <- S.pop()
* 7 if t is what we're looking for:
* 8 return t
* 9 for all edges e in G.adjacentEdges(t) do
* 10 if edge e is already labelled
* 11 continue with the next edge
* 12 w <- G.adjacentVertex(t,e)
* 13 if vertex w is not discovered and not explored
* 14 label e as tree-edge
* 15 label w as discovered
* 16 S.push(w)
* 17 continue at 5
* 18 else if vertex w is discovered
* 19 label e as back-edge
* 20 else
* 21 // vertex w is explored
* 22 label e as forward- or cross-edge
* 23 label t as explored
* 24 S.pop()
*
* convention:
* 0x10 - discovered
* 0x11 - discovered and fall-through edge labelled
* 0x12 - discovered and fall-through and branch edges labelled
* 0x20 - explored
*/
enum {
DISCOVERED = 0x10,
EXPLORED = 0x20,
FALLTHROUGH = 1,
BRANCH = 2,
};
#define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
static int *insn_stack; /* stack of insns to process */
static int cur_stack; /* current stack index */
static int *insn_state;
/* t, w, e - match pseudo-code above:
* t - index of current instruction
* w - next instruction
* e - edge
*/
static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
{
if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
return 0;
if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
return 0;
if (w < 0 || w >= env->prog->len) {
verbose(env, "jump out of range from insn %d to %d\n", t, w);
return -EINVAL;
}
if (e == BRANCH)
/* mark branch target for state pruning */
env->explored_states[w] = STATE_LIST_MARK;
if (insn_state[w] == 0) {
/* tree-edge */
insn_state[t] = DISCOVERED | e;
insn_state[w] = DISCOVERED;
if (cur_stack >= env->prog->len)
return -E2BIG;
insn_stack[cur_stack++] = w;
return 1;
} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
verbose(env, "back-edge from insn %d to %d\n", t, w);
return -EINVAL;
} else if (insn_state[w] == EXPLORED) {
/* forward- or cross-edge */
insn_state[t] = DISCOVERED | e;
} else {
verbose(env, "insn state internal bug\n");
return -EFAULT;
}
return 0;
}
/* non-recursive depth-first-search to detect loops in BPF program
* loop == back-edge in directed graph
*/
static int check_cfg(struct bpf_verifier_env *env)
{
struct bpf_insn *insns = env->prog->insnsi;
int insn_cnt = env->prog->len;
int ret = 0;
int i, t;
ret = check_subprogs(env);
if (ret < 0)
return ret;
insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
if (!insn_state)
return -ENOMEM;
insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
if (!insn_stack) {
kfree(insn_state);
return -ENOMEM;
}
insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
insn_stack[0] = 0; /* 0 is the first instruction */
cur_stack = 1;
peek_stack:
if (cur_stack == 0)
goto check_state;
t = insn_stack[cur_stack - 1];
if (BPF_CLASS(insns[t].code) == BPF_JMP) {
u8 opcode = BPF_OP(insns[t].code);
if (opcode == BPF_EXIT) {
goto mark_explored;
} else if (opcode == BPF_CALL) {
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
if (t + 1 < insn_cnt)
env->explored_states[t + 1] = STATE_LIST_MARK;
if (insns[t].src_reg == BPF_PSEUDO_CALL) {
env->explored_states[t] = STATE_LIST_MARK;
ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
}
} else if (opcode == BPF_JA) {
if (BPF_SRC(insns[t].code) != BPF_K) {
ret = -EINVAL;
goto err_free;
}
/* unconditional jump with single edge */
ret = push_insn(t, t + insns[t].off + 1,
FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
/* tell verifier to check for equivalent states
* after every call and jump
*/
if (t + 1 < insn_cnt)
env->explored_states[t + 1] = STATE_LIST_MARK;
} else {
/* conditional jump with two edges */
env->explored_states[t] = STATE_LIST_MARK;
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
}
} else {
/* all other non-branch instructions with single
* fall-through edge
*/
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
}
mark_explored:
insn_state[t] = EXPLORED;
if (cur_stack-- <= 0) {
verbose(env, "pop stack internal bug\n");
ret = -EFAULT;
goto err_free;
}
goto peek_stack;
check_state:
for (i = 0; i < insn_cnt; i++) {
if (insn_state[i] != EXPLORED) {
verbose(env, "unreachable insn %d\n", i);
ret = -EINVAL;
goto err_free;
}
}
ret = 0; /* cfg looks good */
err_free:
kfree(insn_state);
kfree(insn_stack);
return ret;
}
/* check %cur's range satisfies %old's */
static bool range_within(struct bpf_reg_state *old,
struct bpf_reg_state *cur)
{
return old->umin_value <= cur->umin_value &&
old->umax_value >= cur->umax_value &&
old->smin_value <= cur->smin_value &&
old->smax_value >= cur->smax_value;
}
/* Maximum number of register states that can exist at once */
#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
struct idpair {
u32 old;
u32 cur;
};
/* If in the old state two registers had the same id, then they need to have
* the same id in the new state as well. But that id could be different from
* the old state, so we need to track the mapping from old to new ids.
* Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
* regs with old id 5 must also have new id 9 for the new state to be safe. But
* regs with a different old id could still have new id 9, we don't care about
* that.
* So we look through our idmap to see if this old id has been seen before. If
* so, we require the new id to match; otherwise, we add the id pair to the map.
*/
static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
{
unsigned int i;
for (i = 0; i < ID_MAP_SIZE; i++) {
if (!idmap[i].old) {
/* Reached an empty slot; haven't seen this id before */
idmap[i].old = old_id;
idmap[i].cur = cur_id;
return true;
}
if (idmap[i].old == old_id)
return idmap[i].cur == cur_id;
}
/* We ran out of idmap slots, which should be impossible */
WARN_ON_ONCE(1);
return false;
}
/* Returns true if (rold safe implies rcur safe) */
static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
struct idpair *idmap)
{
bool equal;
if (!(rold->live & REG_LIVE_READ))
/* explored state didn't use this */
return true;
equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, frameno)) == 0;
if (rold->type == PTR_TO_STACK)
/* two stack pointers are equal only if they're pointing to
* the same stack frame, since fp-8 in foo != fp-8 in bar
*/
return equal && rold->frameno == rcur->frameno;
if (equal)
return true;
if (rold->type == NOT_INIT)
/* explored state can't have used this */
return true;
if (rcur->type == NOT_INIT)
return false;
switch (rold->type) {
case SCALAR_VALUE:
if (rcur->type == SCALAR_VALUE) {
/* new val must satisfy old val knowledge */
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
} else {
/* We're trying to use a pointer in place of a scalar.
* Even if the scalar was unbounded, this could lead to
* pointer leaks because scalars are allowed to leak
* while pointers are not. We could make this safe in
* special cases if root is calling us, but it's
* probably not worth the hassle.
*/
return false;
}
case PTR_TO_MAP_VALUE:
/* If the new min/max/var_off satisfy the old ones and
* everything else matches, we are OK.
* We don't care about the 'id' value, because nothing
* uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
*/
return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_MAP_VALUE_OR_NULL:
/* a PTR_TO_MAP_VALUE could be safe to use as a
* PTR_TO_MAP_VALUE_OR_NULL into the same map.
* However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
* checked, doing so could have affected others with the same
* id, and we can't check for that because we lost the id when
* we converted to a PTR_TO_MAP_VALUE.
*/
if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
return false;
if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
return false;
/* Check our ids match any regs they're supposed to */
return check_ids(rold->id, rcur->id, idmap);
case PTR_TO_PACKET_META:
case PTR_TO_PACKET:
if (rcur->type != rold->type)
return false;
/* We must have at least as much range as the old ptr
* did, so that any accesses which were safe before are
* still safe. This is true even if old range < old off,
* since someone could have accessed through (ptr - k), or
* even done ptr -= k in a register, to get a safe access.
*/
if (rold->range > rcur->range)
return false;
/* If the offsets don't match, we can't trust our alignment;
* nor can we be sure that we won't fall out of range.
*/
if (rold->off != rcur->off)
return false;
/* id relations must be preserved */
if (rold->id && !check_ids(rold->id, rcur->id, idmap))
return false;
/* new val must satisfy old val knowledge */
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_CTX:
case CONST_PTR_TO_MAP:
case PTR_TO_PACKET_END:
/* Only valid matches are exact, which memcmp() above
* would have accepted
*/
default:
/* Don't know what's going on, just say it's not safe */
return false;
}
/* Shouldn't get here; if we do, say it's not safe */
WARN_ON_ONCE(1);
return false;
}
static bool stacksafe(struct bpf_func_state *old,
struct bpf_func_state *cur,
struct idpair *idmap)
{
int i, spi;
/* if explored stack has more populated slots than current stack
* such stacks are not equivalent
*/
if (old->allocated_stack > cur->allocated_stack)
return false;
/* walk slots of the explored stack and ignore any additional
* slots in the current stack, since explored(safe) state
* didn't use them
*/
for (i = 0; i < old->allocated_stack; i++) {
spi = i / BPF_REG_SIZE;
if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ))
/* explored state didn't use this */
continue;
if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
continue;
/* if old state was safe with misc data in the stack
* it will be safe with zero-initialized stack.
* The opposite is not true
*/
if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
continue;
if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
cur->stack[spi].slot_type[i % BPF_REG_SIZE])
/* Ex: old explored (safe) state has STACK_SPILL in
* this stack slot, but current has has STACK_MISC ->
* this verifier states are not equivalent,
* return false to continue verification of this path
*/
return false;
if (i % BPF_REG_SIZE)
continue;
if (old->stack[spi].slot_type[0] != STACK_SPILL)
continue;
if (!regsafe(&old->stack[spi].spilled_ptr,
&cur->stack[spi].spilled_ptr,
idmap))
/* when explored and current stack slot are both storing
* spilled registers, check that stored pointers types
* are the same as well.
* Ex: explored safe path could have stored
* (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
* but current path has stored:
* (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
* such verifier states are not equivalent.
* return false to continue verification of this path
*/
return false;
}
return true;
}
/* compare two verifier states
*
* all states stored in state_list are known to be valid, since
* verifier reached 'bpf_exit' instruction through them
*
* this function is called when verifier exploring different branches of
* execution popped from the state stack. If it sees an old state that has
* more strict register state and more strict stack state then this execution
* branch doesn't need to be explored further, since verifier already
* concluded that more strict state leads to valid finish.
*
* Therefore two states are equivalent if register state is more conservative
* and explored stack state is more conservative than the current one.
* Example:
* explored current
* (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
* (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
*
* In other words if current stack state (one being explored) has more
* valid slots than old one that already passed validation, it means
* the verifier can stop exploring and conclude that current state is valid too
*
* Similarly with registers. If explored state has register type as invalid
* whereas register type in current state is meaningful, it means that
* the current state will reach 'bpf_exit' instruction safely
*/
static bool func_states_equal(struct bpf_func_state *old,
struct bpf_func_state *cur)
{
struct idpair *idmap;
bool ret = false;
int i;
idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
/* If we failed to allocate the idmap, just say it's not safe */
if (!idmap)
return false;
for (i = 0; i < MAX_BPF_REG; i++) {
if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
goto out_free;
}
if (!stacksafe(old, cur, idmap))
goto out_free;
ret = true;
out_free:
kfree(idmap);
return ret;
}
static bool states_equal(struct bpf_verifier_env *env,
struct bpf_verifier_state *old,
struct bpf_verifier_state *cur)
{
int i;
if (old->curframe != cur->curframe)
return false;
/* for states to be equal callsites have to be the same
* and all frame states need to be equivalent
*/
for (i = 0; i <= old->curframe; i++) {
if (old->frame[i]->callsite != cur->frame[i]->callsite)
return false;
if (!func_states_equal(old->frame[i], cur->frame[i]))
return false;
}
return true;
}
/* A write screens off any subsequent reads; but write marks come from the
* straight-line code between a state and its parent. When we arrive at an
* equivalent state (jump target or such) we didn't arrive by the straight-line
* code, so read marks in the state must propagate to the parent regardless
* of the state's write marks. That's what 'parent == state->parent' comparison
* in mark_reg_read() and mark_stack_slot_read() is for.
*/
static int propagate_liveness(struct bpf_verifier_env *env,
const struct bpf_verifier_state *vstate,
struct bpf_verifier_state *vparent)
{
int i, frame, err = 0;
struct bpf_func_state *state, *parent;
if (vparent->curframe != vstate->curframe) {
WARN(1, "propagate_live: parent frame %d current frame %d\n",
vparent->curframe, vstate->curframe);
return -EFAULT;
}
/* Propagate read liveness of registers... */
BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
/* We don't need to worry about FP liveness because it's read-only */
for (i = 0; i < BPF_REG_FP; i++) {
if (vparent->frame[vparent->curframe]->regs[i].live & REG_LIVE_READ)
continue;
if (vstate->frame[vstate->curframe]->regs[i].live & REG_LIVE_READ) {
err = mark_reg_read(env, vstate, vparent, i);
if (err)
return err;
}
}
/* ... and stack slots */
for (frame = 0; frame <= vstate->curframe; frame++) {
state = vstate->frame[frame];
parent = vparent->frame[frame];
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
i < parent->allocated_stack / BPF_REG_SIZE; i++) {
if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
continue;
if (state->stack[i].spilled_ptr.live & REG_LIVE_READ)
mark_stack_slot_read(env, vstate, vparent, i, frame);
}
}
return err;
}
static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
{
struct bpf_verifier_state_list *new_sl;
struct bpf_verifier_state_list *sl;
struct bpf_verifier_state *cur = env->cur_state;
int i, j, err;
sl = env->explored_states[insn_idx];
if (!sl)
/* this 'insn_idx' instruction wasn't marked, so we will not
* be doing state search here
*/
return 0;
while (sl != STATE_LIST_MARK) {
if (states_equal(env, &sl->state, cur)) {
/* reached equivalent register/stack state,
* prune the search.
* Registers read by the continuation are read by us.
* If we have any write marks in env->cur_state, they
* will prevent corresponding reads in the continuation
* from reaching our parent (an explored_state). Our
* own state will get the read marks recorded, but
* they'll be immediately forgotten as we're pruning
* this state and will pop a new one.
*/
err = propagate_liveness(env, &sl->state, cur);
if (err)
return err;
return 1;
}
sl = sl->next;
}
/* there were no equivalent states, remember current one.
* technically the current state is not proven to be safe yet,
* but it will either reach outer most bpf_exit (which means it's safe)
* or it will be rejected. Since there are no loops, we won't be
* seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
* again on the way to bpf_exit
*/
new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
if (!new_sl)
return -ENOMEM;
/* add new state to the head of linked list */
err = copy_verifier_state(&new_sl->state, cur);
if (err) {
free_verifier_state(&new_sl->state, false);
kfree(new_sl);
return err;
}
new_sl->next = env->explored_states[insn_idx];
env->explored_states[insn_idx] = new_sl;
/* connect new state to parentage chain */
cur->parent = &new_sl->state;
/* clear write marks in current state: the writes we did are not writes
* our child did, so they don't screen off its reads from us.
* (There are no read marks in current state, because reads always mark
* their parent and current state never has children yet. Only
* explored_states can get read marks.)
*/
for (i = 0; i < BPF_REG_FP; i++)
cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
/* all stack frames are accessible from callee, clear them all */
for (j = 0; j <= cur->curframe; j++) {
struct bpf_func_state *frame = cur->frame[j];
for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++)
frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
}
return 0;
}
static int do_check(struct bpf_verifier_env *env)
{
struct bpf_verifier_state *state;
struct bpf_insn *insns = env->prog->insnsi;
struct bpf_reg_state *regs;
int insn_cnt = env->prog->len, i;
int insn_idx, prev_insn_idx = 0;
int insn_processed = 0;
bool do_print_state = false;
state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
if (!state)
return -ENOMEM;
state->curframe = 0;
state->parent = NULL;
state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
if (!state->frame[0]) {
kfree(state);
return -ENOMEM;
}
env->cur_state = state;
init_func_state(env, state->frame[0],
BPF_MAIN_FUNC /* callsite */,
0 /* frameno */,
0 /* subprogno, zero == main subprog */);
insn_idx = 0;
for (;;) {
struct bpf_insn *insn;
u8 class;
int err;
if (insn_idx >= insn_cnt) {
verbose(env, "invalid insn idx %d insn_cnt %d\n",
insn_idx, insn_cnt);
return -EFAULT;
}
insn = &insns[insn_idx];
class = BPF_CLASS(insn->code);
if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
verbose(env,
"BPF program is too large. Processed %d insn\n",
insn_processed);
return -E2BIG;
}
err = is_state_visited(env, insn_idx);
if (err < 0)
return err;
if (err == 1) {
/* found equivalent state, can prune the search */
if (env->log.level) {
if (do_print_state)
verbose(env, "\nfrom %d to %d: safe\n",
prev_insn_idx, insn_idx);
else
verbose(env, "%d: safe\n", insn_idx);
}
goto process_bpf_exit;
}
if (need_resched())
cond_resched();
if (env->log.level > 1 || (env->log.level && do_print_state)) {
if (env->log.level > 1)
verbose(env, "%d:", insn_idx);
else
verbose(env, "\nfrom %d to %d:",
prev_insn_idx, insn_idx);
print_verifier_state(env, state->frame[state->curframe]);
do_print_state = false;
}
if (env->log.level) {
const struct bpf_insn_cbs cbs = {
.cb_print = verbose,
.private_data = env,
};
verbose(env, "%d: ", insn_idx);
print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
}
if (bpf_prog_is_dev_bound(env->prog->aux)) {
err = bpf_prog_offload_verify_insn(env, insn_idx,
prev_insn_idx);
if (err)
return err;
}
regs = cur_regs(env);
env->insn_aux_data[insn_idx].seen = true;
if (class == BPF_ALU || class == BPF_ALU64) {
err = check_alu_op(env, insn);
if (err)
return err;
} else if (class == BPF_LDX) {
enum bpf_reg_type *prev_src_type, src_reg_type;
/* check for reserved fields is already done */
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
src_reg_type = regs[insn->src_reg].type;
/* check that memory (src_reg + off) is readable,
* the state of dst_reg will be updated by this func
*/
err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
BPF_SIZE(insn->code), BPF_READ,
insn->dst_reg, false);
if (err)
return err;
prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
if (*prev_src_type == NOT_INIT) {
/* saw a valid insn
* dst_reg = *(u32 *)(src_reg + off)
* save type to validate intersecting paths
*/
*prev_src_type = src_reg_type;
} else if (src_reg_type != *prev_src_type &&
(src_reg_type == PTR_TO_CTX ||
*prev_src_type == PTR_TO_CTX)) {
/* ABuser program is trying to use the same insn
* dst_reg = *(u32*) (src_reg + off)
* with different pointer types:
* src_reg == ctx in one branch and
* src_reg == stack|map in some other branch.
* Reject it.
*/
verbose(env, "same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_STX) {
enum bpf_reg_type *prev_dst_type, dst_reg_type;
if (BPF_MODE(insn->code) == BPF_XADD) {
err = check_xadd(env, insn_idx, insn);
if (err)
return err;
insn_idx++;
continue;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
dst_reg_type = regs[insn->dst_reg].type;
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE,
insn->src_reg, false);
if (err)
return err;
prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
if (*prev_dst_type == NOT_INIT) {
*prev_dst_type = dst_reg_type;
} else if (dst_reg_type != *prev_dst_type &&
(dst_reg_type == PTR_TO_CTX ||
*prev_dst_type == PTR_TO_CTX)) {
verbose(env, "same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_ST) {
if (BPF_MODE(insn->code) != BPF_MEM ||
insn->src_reg != BPF_REG_0) {
verbose(env, "BPF_ST uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_ctx_reg(env, insn->dst_reg)) {
verbose(env, "BPF_ST stores into R%d context is not allowed\n",
insn->dst_reg);
return -EACCES;
}
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE,
-1, false);
if (err)
return err;
} else if (class == BPF_JMP) {
u8 opcode = BPF_OP(insn->code);
if (opcode == BPF_CALL) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->off != 0 ||
(insn->src_reg != BPF_REG_0 &&
insn->src_reg != BPF_PSEUDO_CALL) ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_CALL uses reserved fields\n");
return -EINVAL;
}
if (insn->src_reg == BPF_PSEUDO_CALL)
err = check_func_call(env, insn, &insn_idx);
else
err = check_helper_call(env, insn->imm, insn_idx);
if (err)
return err;
} else if (opcode == BPF_JA) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_JA uses reserved fields\n");
return -EINVAL;
}
insn_idx += insn->off + 1;
continue;
} else if (opcode == BPF_EXIT) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_EXIT uses reserved fields\n");
return -EINVAL;
}
if (state->curframe) {
/* exit from nested function */
prev_insn_idx = insn_idx;
err = prepare_func_exit(env, &insn_idx);
if (err)
return err;
do_print_state = true;
continue;
}
/* eBPF calling convetion is such that R0 is used
* to return the value from eBPF program.
* Make sure that it's readable at this time
* of bpf_exit, which means that program wrote
* something into it earlier
*/
err = check_reg_arg(env, BPF_REG_0, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, BPF_REG_0)) {
verbose(env, "R0 leaks addr as return value\n");
return -EACCES;
}
err = check_return_code(env);
if (err)
return err;
process_bpf_exit:
err = pop_stack(env, &prev_insn_idx, &insn_idx);
if (err < 0) {
if (err != -ENOENT)
return err;
break;
} else {
do_print_state = true;
continue;
}
} else {
err = check_cond_jmp_op(env, insn, &insn_idx);
if (err)
return err;
}
} else if (class == BPF_LD) {
u8 mode = BPF_MODE(insn->code);
if (mode == BPF_ABS || mode == BPF_IND) {
err = check_ld_abs(env, insn);
if (err)
return err;
} else if (mode == BPF_IMM) {
err = check_ld_imm(env, insn);
if (err)
return err;
insn_idx++;
env->insn_aux_data[insn_idx].seen = true;
} else {
verbose(env, "invalid BPF_LD mode\n");
return -EINVAL;
}
} else {
verbose(env, "unknown insn class %d\n", class);
return -EINVAL;
}
insn_idx++;
}
verbose(env, "processed %d insns (limit %d), stack depth ",
insn_processed, BPF_COMPLEXITY_LIMIT_INSNS);
for (i = 0; i < env->subprog_cnt; i++) {
u32 depth = env->subprog_info[i].stack_depth;
verbose(env, "%d", depth);
if (i + 1 < env->subprog_cnt)
verbose(env, "+");
}
verbose(env, "\n");
env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
return 0;
}
static int check_map_prealloc(struct bpf_map *map)
{
return (map->map_type != BPF_MAP_TYPE_HASH &&
map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
!(map->map_flags & BPF_F_NO_PREALLOC);
}
static int check_map_prog_compatibility(struct bpf_verifier_env *env,
struct bpf_map *map,
struct bpf_prog *prog)
{
/* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
* preallocated hash maps, since doing memory allocation
* in overflow_handler can crash depending on where nmi got
* triggered.
*/
if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
if (!check_map_prealloc(map)) {
verbose(env, "perf_event programs can only use preallocated hash map\n");
return -EINVAL;
}
if (map->inner_map_meta &&
!check_map_prealloc(map->inner_map_meta)) {
verbose(env, "perf_event programs can only use preallocated inner hash map\n");
return -EINVAL;
}
}
if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
!bpf_offload_prog_map_match(prog, map)) {
verbose(env, "offload device mismatch between prog and map\n");
return -EINVAL;
}
return 0;
}
/* look for pseudo eBPF instructions that access map FDs and
* replace them with actual map pointers
*/
static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
{
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
int i, j, err;
err = bpf_prog_calc_tag(env->prog);
if (err)
return err;
for (i = 0; i < insn_cnt; i++, insn++) {
if (BPF_CLASS(insn->code) == BPF_LDX &&
(BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
verbose(env, "BPF_LDX uses reserved fields\n");
return -EINVAL;
}
if (BPF_CLASS(insn->code) == BPF_STX &&
((BPF_MODE(insn->code) != BPF_MEM &&
BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
verbose(env, "BPF_STX uses reserved fields\n");
return -EINVAL;
}
if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
struct bpf_map *map;
struct fd f;
if (i == insn_cnt - 1 || insn[1].code != 0 ||
insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
insn[1].off != 0) {
verbose(env, "invalid bpf_ld_imm64 insn\n");
return -EINVAL;
}
if (insn->src_reg == 0)
/* valid generic load 64-bit imm */
goto next_insn;
if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
verbose(env,
"unrecognized bpf_ld_imm64 insn\n");
return -EINVAL;
}
f = fdget(insn->imm);
map = __bpf_map_get(f);
if (IS_ERR(map)) {
verbose(env, "fd %d is not pointing to valid bpf_map\n",
insn->imm);
return PTR_ERR(map);
}
err = check_map_prog_compatibility(env, map, env->prog);
if (err) {
fdput(f);
return err;
}
/* store map pointer inside BPF_LD_IMM64 instruction */
insn[0].imm = (u32) (unsigned long) map;
insn[1].imm = ((u64) (unsigned long) map) >> 32;
/* check whether we recorded this map already */
for (j = 0; j < env->used_map_cnt; j++)
if (env->used_maps[j] == map) {
fdput(f);
goto next_insn;
}
if (env->used_map_cnt >= MAX_USED_MAPS) {
fdput(f);
return -E2BIG;
}
/* hold the map. If the program is rejected by verifier,
* the map will be released by release_maps() or it
* will be used by the valid program until it's unloaded
* and all maps are released in free_used_maps()
*/
map = bpf_map_inc(map, false);
if (IS_ERR(map)) {
fdput(f);
return PTR_ERR(map);
}
env->used_maps[env->used_map_cnt++] = map;
if (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE &&
bpf_cgroup_storage_assign(env->prog, map)) {
verbose(env,
"only one cgroup storage is allowed\n");
fdput(f);
return -EBUSY;
}
fdput(f);
next_insn:
insn++;
i++;
continue;
}
/* Basic sanity check before we invest more work here. */
if (!bpf_opcode_in_insntable(insn->code)) {
verbose(env, "unknown opcode %02x\n", insn->code);
return -EINVAL;
}
}
/* now all pseudo BPF_LD_IMM64 instructions load valid
* 'struct bpf_map *' into a register instead of user map_fd.
* These pointers will be used later by verifier to validate map access.
*/
return 0;
}
/* drop refcnt of maps used by the rejected program */
static void release_maps(struct bpf_verifier_env *env)
{
int i;
if (env->prog->aux->cgroup_storage)
bpf_cgroup_storage_release(env->prog,
env->prog->aux->cgroup_storage);
for (i = 0; i < env->used_map_cnt; i++)
bpf_map_put(env->used_maps[i]);
}
/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
{
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
int i;
for (i = 0; i < insn_cnt; i++, insn++)
if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
insn->src_reg = 0;
}
/* single env->prog->insni[off] instruction was replaced with the range
* insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
* [0, off) and [off, end) to new locations, so the patched range stays zero
*/
static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
u32 off, u32 cnt)
{
struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
int i;
if (cnt == 1)
return 0;
new_data = vzalloc(array_size(prog_len,
sizeof(struct bpf_insn_aux_data)));
if (!new_data)
return -ENOMEM;
memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
memcpy(new_data + off + cnt - 1, old_data + off,
sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
for (i = off; i < off + cnt - 1; i++)
new_data[i].seen = true;
env->insn_aux_data = new_data;
vfree(old_data);
return 0;
}
static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
{
int i;
if (len == 1)
return;
/* NOTE: fake 'exit' subprog should be updated as well. */
for (i = 0; i <= env->subprog_cnt; i++) {
if (env->subprog_info[i].start < off)
continue;
env->subprog_info[i].start += len - 1;
}
}
static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
const struct bpf_insn *patch, u32 len)
{
struct bpf_prog *new_prog;
new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
if (!new_prog)
return NULL;
if (adjust_insn_aux_data(env, new_prog->len, off, len))
return NULL;
adjust_subprog_starts(env, off, len);
return new_prog;
}
/* The verifier does more data flow analysis than llvm and will not
* explore branches that are dead at run time. Malicious programs can
* have dead code too. Therefore replace all dead at-run-time code
* with 'ja -1'.
*
* Just nops are not optimal, e.g. if they would sit at the end of the
* program and through another bug we would manage to jump there, then
* we'd execute beyond program memory otherwise. Returning exception
* code also wouldn't work since we can have subprogs where the dead
* code could be located.
*/
static void sanitize_dead_code(struct bpf_verifier_env *env)
{
struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
struct bpf_insn *insn = env->prog->insnsi;
const int insn_cnt = env->prog->len;
int i;
for (i = 0; i < insn_cnt; i++) {
if (aux_data[i].seen)
continue;
memcpy(insn + i, &trap, sizeof(trap));
}
}
/* convert load instructions that access fields of 'struct __sk_buff'
* into sequence of instructions that access fields of 'struct sk_buff'
*/
static int convert_ctx_accesses(struct bpf_verifier_env *env)
{
const struct bpf_verifier_ops *ops = env->ops;
int i, cnt, size, ctx_field_size, delta = 0;
const int insn_cnt = env->prog->len;
struct bpf_insn insn_buf[16], *insn;
struct bpf_prog *new_prog;
enum bpf_access_type type;
bool is_narrower_load;
u32 target_size;
if (ops->gen_prologue) {
cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
env->prog);
if (cnt >= ARRAY_SIZE(insn_buf)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
} else if (cnt) {
new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
env->prog = new_prog;
delta += cnt - 1;
}
}
if (!ops->convert_ctx_access || bpf_prog_is_dev_bound(env->prog->aux))
return 0;
insn = env->prog->insnsi + delta;
for (i = 0; i < insn_cnt; i++, insn++) {
if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
type = BPF_READ;
else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
insn->code == (BPF_STX | BPF_MEM | BPF_DW))
type = BPF_WRITE;
else
continue;
if (type == BPF_WRITE &&
env->insn_aux_data[i + delta].sanitize_stack_off) {
struct bpf_insn patch[] = {
/* Sanitize suspicious stack slot with zero.
* There are no memory dependencies for this store,
* since it's only using frame pointer and immediate
* constant of zero
*/
BPF_ST_MEM(BPF_DW, BPF_REG_FP,
env->insn_aux_data[i + delta].sanitize_stack_off,
0),
/* the original STX instruction will immediately
* overwrite the same stack slot with appropriate value
*/
*insn,
};
cnt = ARRAY_SIZE(patch);
new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
env->prog = new_prog;
insn = new_prog->insnsi + i + delta;
continue;
}
if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
continue;
ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
size = BPF_LDST_BYTES(insn);
/* If the read access is a narrower load of the field,
* convert to a 4/8-byte load, to minimum program type specific
* convert_ctx_access changes. If conversion is successful,
* we will apply proper mask to the result.
*/
is_narrower_load = size < ctx_field_size;
if (is_narrower_load) {
u32 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
u32 off = insn->off;
u8 size_code;
if (type == BPF_WRITE) {
verbose(env, "bpf verifier narrow ctx access misconfigured\n");
return -EINVAL;
}
size_code = BPF_H;
if (ctx_field_size == 4)
size_code = BPF_W;
else if (ctx_field_size == 8)
size_code = BPF_DW;
insn->off = off & ~(size_default - 1);
insn->code = BPF_LDX | BPF_MEM | size_code;
}
target_size = 0;
cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
&target_size);
if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
(ctx_field_size && !target_size)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
}
if (is_narrower_load && size < target_size) {
if (ctx_field_size <= 4)
insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
(1 << size * 8) - 1);
else
insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
(1 << size * 8) - 1);
}
new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
/* keep walking new program and skip insns we just inserted */
env->prog = new_prog;
insn = new_prog->insnsi + i + delta;
}
return 0;
}
static int jit_subprogs(struct bpf_verifier_env *env)
{
struct bpf_prog *prog = env->prog, **func, *tmp;
int i, j, subprog_start, subprog_end = 0, len, subprog;
struct bpf_insn *insn;
void *old_bpf_func;
int err = -ENOMEM;
if (env->subprog_cnt <= 1)
return 0;
for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
if (insn->code != (BPF_JMP | BPF_CALL) ||
insn->src_reg != BPF_PSEUDO_CALL)
continue;
/* Upon error here we cannot fall back to interpreter but
* need a hard reject of the program. Thus -EFAULT is
* propagated in any case.
*/
subprog = find_subprog(env, i + insn->imm + 1);
if (subprog < 0) {
WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
i + insn->imm + 1);
return -EFAULT;
}
/* temporarily remember subprog id inside insn instead of
* aux_data, since next loop will split up all insns into funcs
*/
insn->off = subprog;
/* remember original imm in case JIT fails and fallback
* to interpreter will be needed
*/
env->insn_aux_data[i].call_imm = insn->imm;
/* point imm to __bpf_call_base+1 from JITs point of view */
insn->imm = 1;
}
func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
if (!func)
goto out_undo_insn;
for (i = 0; i < env->subprog_cnt; i++) {
subprog_start = subprog_end;
subprog_end = env->subprog_info[i + 1].start;
len = subprog_end - subprog_start;
func[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER);
if (!func[i])
goto out_free;
memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
len * sizeof(struct bpf_insn));
func[i]->type = prog->type;
func[i]->len = len;
if (bpf_prog_calc_tag(func[i]))
goto out_free;
func[i]->is_func = 1;
/* Use bpf_prog_F_tag to indicate functions in stack traces.
* Long term would need debug info to populate names
*/
func[i]->aux->name[0] = 'F';
func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
func[i]->jit_requested = 1;
func[i] = bpf_int_jit_compile(func[i]);
if (!func[i]->jited) {
err = -ENOTSUPP;
goto out_free;
}
cond_resched();
}
/* at this point all bpf functions were successfully JITed
* now populate all bpf_calls with correct addresses and
* run last pass of JIT
*/
for (i = 0; i < env->subprog_cnt; i++) {
insn = func[i]->insnsi;
for (j = 0; j < func[i]->len; j++, insn++) {
if (insn->code != (BPF_JMP | BPF_CALL) ||
insn->src_reg != BPF_PSEUDO_CALL)
continue;
subprog = insn->off;
insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
func[subprog]->bpf_func -
__bpf_call_base;
}
/* we use the aux data to keep a list of the start addresses
* of the JITed images for each function in the program
*
* for some architectures, such as powerpc64, the imm field
* might not be large enough to hold the offset of the start
* address of the callee's JITed image from __bpf_call_base
*
* in such cases, we can lookup the start address of a callee
* by using its subprog id, available from the off field of
* the call instruction, as an index for this list
*/
func[i]->aux->func = func;
func[i]->aux->func_cnt = env->subprog_cnt;
}
for (i = 0; i < env->subprog_cnt; i++) {
old_bpf_func = func[i]->bpf_func;
tmp = bpf_int_jit_compile(func[i]);
if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
err = -ENOTSUPP;
goto out_free;
}
cond_resched();
}
/* finally lock prog and jit images for all functions and
* populate kallsysm
*/
for (i = 0; i < env->subprog_cnt; i++) {
bpf_prog_lock_ro(func[i]);
bpf_prog_kallsyms_add(func[i]);
}
/* Last step: make now unused interpreter insns from main
* prog consistent for later dump requests, so they can
* later look the same as if they were interpreted only.
*/
for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
if (insn->code != (BPF_JMP | BPF_CALL) ||
insn->src_reg != BPF_PSEUDO_CALL)
continue;
insn->off = env->insn_aux_data[i].call_imm;
subprog = find_subprog(env, i + insn->off + 1);
insn->imm = subprog;
}
prog->jited = 1;
prog->bpf_func = func[0]->bpf_func;
prog->aux->func = func;
prog->aux->func_cnt = env->subprog_cnt;
return 0;
out_free:
for (i = 0; i < env->subprog_cnt; i++)
if (func[i])
bpf_jit_free(func[i]);
kfree(func);
out_undo_insn:
/* cleanup main prog to be interpreted */
prog->jit_requested = 0;
for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
if (insn->code != (BPF_JMP | BPF_CALL) ||
insn->src_reg != BPF_PSEUDO_CALL)
continue;
insn->off = 0;
insn->imm = env->insn_aux_data[i].call_imm;
}
return err;
}
static int fixup_call_args(struct bpf_verifier_env *env)
{
#ifndef CONFIG_BPF_JIT_ALWAYS_ON
struct bpf_prog *prog = env->prog;
struct bpf_insn *insn = prog->insnsi;
int i, depth;
#endif
int err;
err = 0;
if (env->prog->jit_requested) {
err = jit_subprogs(env);
if (err == 0)
return 0;
if (err == -EFAULT)
return err;
}
#ifndef CONFIG_BPF_JIT_ALWAYS_ON
for (i = 0; i < prog->len; i++, insn++) {
if (insn->code != (BPF_JMP | BPF_CALL) ||
insn->src_reg != BPF_PSEUDO_CALL)
continue;
depth = get_callee_stack_depth(env, insn, i);
if (depth < 0)
return depth;
bpf_patch_call_args(insn, depth);
}
err = 0;
#endif
return err;
}
/* fixup insn->imm field of bpf_call instructions
* and inline eligible helpers as explicit sequence of BPF instructions
*
* this function is called after eBPF program passed verification
*/
static int fixup_bpf_calls(struct bpf_verifier_env *env)
{
struct bpf_prog *prog = env->prog;
struct bpf_insn *insn = prog->insnsi;
const struct bpf_func_proto *fn;
const int insn_cnt = prog->len;
const struct bpf_map_ops *ops;
struct bpf_insn_aux_data *aux;
struct bpf_insn insn_buf[16];
struct bpf_prog *new_prog;
struct bpf_map *map_ptr;
int i, cnt, delta = 0;
for (i = 0; i < insn_cnt; i++, insn++) {
if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
struct bpf_insn mask_and_div[] = {
BPF_MOV32_REG(insn->src_reg, insn->src_reg),
/* Rx div 0 -> 0 */
BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
BPF_JMP_IMM(BPF_JA, 0, 0, 1),
*insn,
};
struct bpf_insn mask_and_mod[] = {
BPF_MOV32_REG(insn->src_reg, insn->src_reg),
/* Rx mod 0 -> Rx */
BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
*insn,
};
struct bpf_insn *patchlet;
if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
patchlet = mask_and_div + (is64 ? 1 : 0);
cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
} else {
patchlet = mask_and_mod + (is64 ? 1 : 0);
cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
}
new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
continue;
}
if (BPF_CLASS(insn->code) == BPF_LD &&
(BPF_MODE(insn->code) == BPF_ABS ||
BPF_MODE(insn->code) == BPF_IND)) {
cnt = env->ops->gen_ld_abs(insn, insn_buf);
if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
}
new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
continue;
}
if (insn->code != (BPF_JMP | BPF_CALL))
continue;
if (insn->src_reg == BPF_PSEUDO_CALL)
continue;
if (insn->imm == BPF_FUNC_get_route_realm)
prog->dst_needed = 1;
if (insn->imm == BPF_FUNC_get_prandom_u32)
bpf_user_rnd_init_once();
if (insn->imm == BPF_FUNC_override_return)
prog->kprobe_override = 1;
if (insn->imm == BPF_FUNC_tail_call) {
/* If we tail call into other programs, we
* cannot make any assumptions since they can
* be replaced dynamically during runtime in
* the program array.
*/
prog->cb_access = 1;
env->prog->aux->stack_depth = MAX_BPF_STACK;
/* mark bpf_tail_call as different opcode to avoid
* conditional branch in the interpeter for every normal
* call and to prevent accidental JITing by JIT compiler
* that doesn't support bpf_tail_call yet
*/
insn->imm = 0;
insn->code = BPF_JMP | BPF_TAIL_CALL;
aux = &env->insn_aux_data[i + delta];
if (!bpf_map_ptr_unpriv(aux))
continue;
/* instead of changing every JIT dealing with tail_call
* emit two extra insns:
* if (index >= max_entries) goto out;
* index &= array->index_mask;
* to avoid out-of-bounds cpu speculation
*/
if (bpf_map_ptr_poisoned(aux)) {
verbose(env, "tail_call abusing map_ptr\n");
return -EINVAL;
}
map_ptr = BPF_MAP_PTR(aux->map_state);
insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
map_ptr->max_entries, 2);
insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
container_of(map_ptr,
struct bpf_array,
map)->index_mask);
insn_buf[2] = *insn;
cnt = 3;
new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
continue;
}
/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
* and other inlining handlers are currently limited to 64 bit
* only.
*/
if (prog->jit_requested && BITS_PER_LONG == 64 &&
(insn->imm == BPF_FUNC_map_lookup_elem ||
insn->imm == BPF_FUNC_map_update_elem ||
insn->imm == BPF_FUNC_map_delete_elem)) {
aux = &env->insn_aux_data[i + delta];
if (bpf_map_ptr_poisoned(aux))
goto patch_call_imm;
map_ptr = BPF_MAP_PTR(aux->map_state);
ops = map_ptr->ops;
if (insn->imm == BPF_FUNC_map_lookup_elem &&
ops->map_gen_lookup) {
cnt = ops->map_gen_lookup(map_ptr, insn_buf);
if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
}
new_prog = bpf_patch_insn_data(env, i + delta,
insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
continue;
}
BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
(void *(*)(struct bpf_map *map, void *key))NULL));
BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
(int (*)(struct bpf_map *map, void *key))NULL));
BUILD_BUG_ON(!__same_type(ops->map_update_elem,
(int (*)(struct bpf_map *map, void *key, void *value,
u64 flags))NULL));
switch (insn->imm) {
case BPF_FUNC_map_lookup_elem:
insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
__bpf_call_base;
continue;
case BPF_FUNC_map_update_elem:
insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
__bpf_call_base;
continue;
case BPF_FUNC_map_delete_elem:
insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
__bpf_call_base;
continue;
}
goto patch_call_imm;
}
patch_call_imm:
fn = env->ops->get_func_proto(insn->imm, env->prog);
/* all functions that have prototype and verifier allowed
* programs to call them, must be real in-kernel functions
*/
if (!fn->func) {
verbose(env,
"kernel subsystem misconfigured func %s#%d\n",
func_id_name(insn->imm), insn->imm);
return -EFAULT;
}
insn->imm = fn->func - __bpf_call_base;
}
return 0;
}
static void free_states(struct bpf_verifier_env *env)
{
struct bpf_verifier_state_list *sl, *sln;
int i;
if (!env->explored_states)
return;
for (i = 0; i < env->prog->len; i++) {
sl = env->explored_states[i];
if (sl)
while (sl != STATE_LIST_MARK) {
sln = sl->next;
free_verifier_state(&sl->state, false);
kfree(sl);
sl = sln;
}
}
kfree(env->explored_states);
}
int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
{
struct bpf_verifier_env *env;
struct bpf_verifier_log *log;
int ret = -EINVAL;
/* no program is valid */
if (ARRAY_SIZE(bpf_verifier_ops) == 0)
return -EINVAL;
/* 'struct bpf_verifier_env' can be global, but since it's not small,
* allocate/free it every time bpf_check() is called
*/
env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
if (!env)
return -ENOMEM;
log = &env->log;
env->insn_aux_data =
vzalloc(array_size(sizeof(struct bpf_insn_aux_data),
(*prog)->len));
ret = -ENOMEM;
if (!env->insn_aux_data)
goto err_free_env;
env->prog = *prog;
env->ops = bpf_verifier_ops[env->prog->type];
/* grab the mutex to protect few globals used by verifier */
mutex_lock(&bpf_verifier_lock);
if (attr->log_level || attr->log_buf || attr->log_size) {
/* user requested verbose verifier output
* and supplied buffer to store the verification trace
*/
log->level = attr->log_level;
log->ubuf = (char __user *) (unsigned long) attr->log_buf;
log->len_total = attr->log_size;
ret = -EINVAL;
/* log attributes have to be sane */
if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
!log->level || !log->ubuf)
goto err_unlock;
}
env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
env->strict_alignment = true;
ret = replace_map_fd_with_map_ptr(env);
if (ret < 0)
goto skip_full_check;
if (bpf_prog_is_dev_bound(env->prog->aux)) {
ret = bpf_prog_offload_verifier_prep(env);
if (ret)
goto skip_full_check;
}
env->explored_states = kcalloc(env->prog->len,
sizeof(struct bpf_verifier_state_list *),
GFP_USER);
ret = -ENOMEM;
if (!env->explored_states)
goto skip_full_check;
env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
ret = check_cfg(env);
if (ret < 0)
goto skip_full_check;
ret = do_check(env);
if (env->cur_state) {
free_verifier_state(env->cur_state, true);
env->cur_state = NULL;
}
skip_full_check:
while (!pop_stack(env, NULL, NULL));
free_states(env);
if (ret == 0)
sanitize_dead_code(env);
if (ret == 0)
ret = check_max_stack_depth(env);
if (ret == 0)
/* program is valid, convert *(u32*)(ctx + off) accesses */
ret = convert_ctx_accesses(env);
if (ret == 0)
ret = fixup_bpf_calls(env);
if (ret == 0)
ret = fixup_call_args(env);
if (log->level && bpf_verifier_log_full(log))
ret = -ENOSPC;
if (log->level && !log->ubuf) {
ret = -EFAULT;
goto err_release_maps;
}
if (ret == 0 && env->used_map_cnt) {
/* if program passed verifier, update used_maps in bpf_prog_info */
env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
sizeof(env->used_maps[0]),
GFP_KERNEL);
if (!env->prog->aux->used_maps) {
ret = -ENOMEM;
goto err_release_maps;
}
memcpy(env->prog->aux->used_maps, env->used_maps,
sizeof(env->used_maps[0]) * env->used_map_cnt);
env->prog->aux->used_map_cnt = env->used_map_cnt;
/* program is valid. Convert pseudo bpf_ld_imm64 into generic
* bpf_ld_imm64 instructions
*/
convert_pseudo_ld_imm64(env);
}
err_release_maps:
if (!env->prog->aux->used_maps)
/* if we didn't copy map pointers into bpf_prog_info, release
* them now. Otherwise free_used_maps() will release them.
*/
release_maps(env);
*prog = env->prog;
err_unlock:
mutex_unlock(&bpf_verifier_lock);
vfree(env->insn_aux_data);
err_free_env:
kfree(env);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_417_0 |
crossvul-cpp_data_bad_2717_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994
* 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: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IPv6 Internet Control Message Protocol (ICMPv6) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "addrtostr.h"
#include "extract.h"
#include "ip6.h"
#include "ipproto.h"
#include "udp.h"
#include "ah.h"
/* NetBSD: icmp6.h,v 1.13 2000/08/03 16:30:37 itojun Exp */
/* $KAME: icmp6.h,v 1.22 2000/08/03 15:25:16 jinmei Exp $ */
/*
* Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
* 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 project 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 PROJECT 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 PROJECT 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 icmp6_hdr {
uint8_t icmp6_type; /* type field */
uint8_t icmp6_code; /* code field */
uint16_t icmp6_cksum; /* checksum field */
union {
uint32_t icmp6_un_data32[1]; /* type-specific field */
uint16_t icmp6_un_data16[2]; /* type-specific field */
uint8_t icmp6_un_data8[4]; /* type-specific field */
} icmp6_dataun;
};
#define icmp6_data32 icmp6_dataun.icmp6_un_data32
#define icmp6_data16 icmp6_dataun.icmp6_un_data16
#define icmp6_data8 icmp6_dataun.icmp6_un_data8
#define icmp6_pptr icmp6_data32[0] /* parameter prob */
#define icmp6_mtu icmp6_data32[0] /* packet too big */
#define icmp6_id icmp6_data16[0] /* echo request/reply */
#define icmp6_seq icmp6_data16[1] /* echo request/reply */
#define icmp6_maxdelay icmp6_data16[0] /* mcast group membership */
#define ICMP6_DST_UNREACH 1 /* dest unreachable, codes: */
#define ICMP6_PACKET_TOO_BIG 2 /* packet too big */
#define ICMP6_TIME_EXCEEDED 3 /* time exceeded, code: */
#define ICMP6_PARAM_PROB 4 /* ip6 header bad */
#define ICMP6_ECHO_REQUEST 128 /* echo service */
#define ICMP6_ECHO_REPLY 129 /* echo reply */
#define ICMP6_MEMBERSHIP_QUERY 130 /* group membership query */
#define MLD6_LISTENER_QUERY 130 /* multicast listener query */
#define ICMP6_MEMBERSHIP_REPORT 131 /* group membership report */
#define MLD6_LISTENER_REPORT 131 /* multicast listener report */
#define ICMP6_MEMBERSHIP_REDUCTION 132 /* group membership termination */
#define MLD6_LISTENER_DONE 132 /* multicast listener done */
#define ND_ROUTER_SOLICIT 133 /* router solicitation */
#define ND_ROUTER_ADVERT 134 /* router advertisement */
#define ND_NEIGHBOR_SOLICIT 135 /* neighbor solicitation */
#define ND_NEIGHBOR_ADVERT 136 /* neighbor advertisement */
#define ND_REDIRECT 137 /* redirect */
#define ICMP6_ROUTER_RENUMBERING 138 /* router renumbering */
#define ICMP6_WRUREQUEST 139 /* who are you request */
#define ICMP6_WRUREPLY 140 /* who are you reply */
#define ICMP6_FQDN_QUERY 139 /* FQDN query */
#define ICMP6_FQDN_REPLY 140 /* FQDN reply */
#define ICMP6_NI_QUERY 139 /* node information request */
#define ICMP6_NI_REPLY 140 /* node information reply */
#define IND_SOLICIT 141 /* inverse neighbor solicitation */
#define IND_ADVERT 142 /* inverse neighbor advertisement */
#define ICMP6_V2_MEMBERSHIP_REPORT 143 /* v2 membership report */
#define MLDV2_LISTENER_REPORT 143 /* v2 multicast listener report */
#define ICMP6_HADISCOV_REQUEST 144
#define ICMP6_HADISCOV_REPLY 145
#define ICMP6_MOBILEPREFIX_SOLICIT 146
#define ICMP6_MOBILEPREFIX_ADVERT 147
#define MLD6_MTRACE_RESP 200 /* mtrace response(to sender) */
#define MLD6_MTRACE 201 /* mtrace messages */
#define ICMP6_MAXTYPE 201
#define ICMP6_DST_UNREACH_NOROUTE 0 /* no route to destination */
#define ICMP6_DST_UNREACH_ADMIN 1 /* administratively prohibited */
#define ICMP6_DST_UNREACH_NOTNEIGHBOR 2 /* not a neighbor(obsolete) */
#define ICMP6_DST_UNREACH_BEYONDSCOPE 2 /* beyond scope of source address */
#define ICMP6_DST_UNREACH_ADDR 3 /* address unreachable */
#define ICMP6_DST_UNREACH_NOPORT 4 /* port unreachable */
#define ICMP6_TIME_EXCEED_TRANSIT 0 /* ttl==0 in transit */
#define ICMP6_TIME_EXCEED_REASSEMBLY 1 /* ttl==0 in reass */
#define ICMP6_PARAMPROB_HEADER 0 /* erroneous header field */
#define ICMP6_PARAMPROB_NEXTHEADER 1 /* unrecognized next header */
#define ICMP6_PARAMPROB_OPTION 2 /* unrecognized option */
#define ICMP6_INFOMSG_MASK 0x80 /* all informational messages */
#define ICMP6_NI_SUBJ_IPV6 0 /* Query Subject is an IPv6 address */
#define ICMP6_NI_SUBJ_FQDN 1 /* Query Subject is a Domain name */
#define ICMP6_NI_SUBJ_IPV4 2 /* Query Subject is an IPv4 address */
#define ICMP6_NI_SUCCESS 0 /* node information successful reply */
#define ICMP6_NI_REFUSED 1 /* node information request is refused */
#define ICMP6_NI_UNKNOWN 2 /* unknown Qtype */
#define ICMP6_ROUTER_RENUMBERING_COMMAND 0 /* rr command */
#define ICMP6_ROUTER_RENUMBERING_RESULT 1 /* rr result */
#define ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET 255 /* rr seq num reset */
/* Used in kernel only */
#define ND_REDIRECT_ONLINK 0 /* redirect to an on-link node */
#define ND_REDIRECT_ROUTER 1 /* redirect to a better router */
/*
* Multicast Listener Discovery
*/
struct mld6_hdr {
struct icmp6_hdr mld6_hdr;
struct in6_addr mld6_addr; /* multicast address */
};
#define mld6_type mld6_hdr.icmp6_type
#define mld6_code mld6_hdr.icmp6_code
#define mld6_cksum mld6_hdr.icmp6_cksum
#define mld6_maxdelay mld6_hdr.icmp6_data16[0]
#define mld6_reserved mld6_hdr.icmp6_data16[1]
#define MLD_MINLEN 24
#define MLDV2_MINLEN 28
/*
* Neighbor Discovery
*/
struct nd_router_solicit { /* router solicitation */
struct icmp6_hdr nd_rs_hdr;
/* could be followed by options */
};
#define nd_rs_type nd_rs_hdr.icmp6_type
#define nd_rs_code nd_rs_hdr.icmp6_code
#define nd_rs_cksum nd_rs_hdr.icmp6_cksum
#define nd_rs_reserved nd_rs_hdr.icmp6_data32[0]
struct nd_router_advert { /* router advertisement */
struct icmp6_hdr nd_ra_hdr;
uint32_t nd_ra_reachable; /* reachable time */
uint32_t nd_ra_retransmit; /* retransmit timer */
/* could be followed by options */
};
#define nd_ra_type nd_ra_hdr.icmp6_type
#define nd_ra_code nd_ra_hdr.icmp6_code
#define nd_ra_cksum nd_ra_hdr.icmp6_cksum
#define nd_ra_curhoplimit nd_ra_hdr.icmp6_data8[0]
#define nd_ra_flags_reserved nd_ra_hdr.icmp6_data8[1]
#define ND_RA_FLAG_MANAGED 0x80
#define ND_RA_FLAG_OTHER 0x40
#define ND_RA_FLAG_HOME_AGENT 0x20
/*
* Router preference values based on draft-draves-ipngwg-router-selection-01.
* These are non-standard definitions.
*/
#define ND_RA_FLAG_RTPREF_MASK 0x18 /* 00011000 */
#define ND_RA_FLAG_RTPREF_HIGH 0x08 /* 00001000 */
#define ND_RA_FLAG_RTPREF_MEDIUM 0x00 /* 00000000 */
#define ND_RA_FLAG_RTPREF_LOW 0x18 /* 00011000 */
#define ND_RA_FLAG_RTPREF_RSV 0x10 /* 00010000 */
#define nd_ra_router_lifetime nd_ra_hdr.icmp6_data16[1]
struct nd_neighbor_solicit { /* neighbor solicitation */
struct icmp6_hdr nd_ns_hdr;
struct in6_addr nd_ns_target; /*target address */
/* could be followed by options */
};
#define nd_ns_type nd_ns_hdr.icmp6_type
#define nd_ns_code nd_ns_hdr.icmp6_code
#define nd_ns_cksum nd_ns_hdr.icmp6_cksum
#define nd_ns_reserved nd_ns_hdr.icmp6_data32[0]
struct nd_neighbor_advert { /* neighbor advertisement */
struct icmp6_hdr nd_na_hdr;
struct in6_addr nd_na_target; /* target address */
/* could be followed by options */
};
#define nd_na_type nd_na_hdr.icmp6_type
#define nd_na_code nd_na_hdr.icmp6_code
#define nd_na_cksum nd_na_hdr.icmp6_cksum
#define nd_na_flags_reserved nd_na_hdr.icmp6_data32[0]
#define ND_NA_FLAG_ROUTER 0x80000000
#define ND_NA_FLAG_SOLICITED 0x40000000
#define ND_NA_FLAG_OVERRIDE 0x20000000
struct nd_redirect { /* redirect */
struct icmp6_hdr nd_rd_hdr;
struct in6_addr nd_rd_target; /* target address */
struct in6_addr nd_rd_dst; /* destination address */
/* could be followed by options */
};
#define nd_rd_type nd_rd_hdr.icmp6_type
#define nd_rd_code nd_rd_hdr.icmp6_code
#define nd_rd_cksum nd_rd_hdr.icmp6_cksum
#define nd_rd_reserved nd_rd_hdr.icmp6_data32[0]
struct nd_opt_hdr { /* Neighbor discovery option header */
uint8_t nd_opt_type;
uint8_t nd_opt_len;
/* followed by option specific data*/
};
#define ND_OPT_SOURCE_LINKADDR 1
#define ND_OPT_TARGET_LINKADDR 2
#define ND_OPT_PREFIX_INFORMATION 3
#define ND_OPT_REDIRECTED_HEADER 4
#define ND_OPT_MTU 5
#define ND_OPT_ADVINTERVAL 7
#define ND_OPT_HOMEAGENT_INFO 8
#define ND_OPT_ROUTE_INFO 24 /* RFC4191 */
#define ND_OPT_RDNSS 25
#define ND_OPT_DNSSL 31
struct nd_opt_prefix_info { /* prefix information */
nd_uint8_t nd_opt_pi_type;
nd_uint8_t nd_opt_pi_len;
nd_uint8_t nd_opt_pi_prefix_len;
nd_uint8_t nd_opt_pi_flags_reserved;
nd_uint32_t nd_opt_pi_valid_time;
nd_uint32_t nd_opt_pi_preferred_time;
nd_uint32_t nd_opt_pi_reserved2;
struct in6_addr nd_opt_pi_prefix;
};
#define ND_OPT_PI_FLAG_ONLINK 0x80
#define ND_OPT_PI_FLAG_AUTO 0x40
#define ND_OPT_PI_FLAG_ROUTER 0x20 /*2292bis*/
struct nd_opt_rd_hdr { /* redirected header */
uint8_t nd_opt_rh_type;
uint8_t nd_opt_rh_len;
uint16_t nd_opt_rh_reserved1;
uint32_t nd_opt_rh_reserved2;
/* followed by IP header and data */
};
struct nd_opt_mtu { /* MTU option */
uint8_t nd_opt_mtu_type;
uint8_t nd_opt_mtu_len;
uint16_t nd_opt_mtu_reserved;
uint32_t nd_opt_mtu_mtu;
};
struct nd_opt_rdnss { /* RDNSS RFC 6106 5.1 */
uint8_t nd_opt_rdnss_type;
uint8_t nd_opt_rdnss_len;
uint16_t nd_opt_rdnss_reserved;
uint32_t nd_opt_rdnss_lifetime;
struct in6_addr nd_opt_rdnss_addr[1]; /* variable-length */
};
struct nd_opt_dnssl { /* DNSSL RFC 6106 5.2 */
uint8_t nd_opt_dnssl_type;
uint8_t nd_opt_dnssl_len;
uint16_t nd_opt_dnssl_reserved;
uint32_t nd_opt_dnssl_lifetime;
/* followed by list of DNS search domains, variable-length */
};
struct nd_opt_advinterval { /* Advertisement interval option */
uint8_t nd_opt_adv_type;
uint8_t nd_opt_adv_len;
uint16_t nd_opt_adv_reserved;
uint32_t nd_opt_adv_interval;
};
struct nd_opt_homeagent_info { /* Home Agent info */
uint8_t nd_opt_hai_type;
uint8_t nd_opt_hai_len;
uint16_t nd_opt_hai_reserved;
int16_t nd_opt_hai_preference;
uint16_t nd_opt_hai_lifetime;
};
struct nd_opt_route_info { /* route info */
uint8_t nd_opt_rti_type;
uint8_t nd_opt_rti_len;
uint8_t nd_opt_rti_prefixlen;
uint8_t nd_opt_rti_flags;
uint32_t nd_opt_rti_lifetime;
/* prefix follows */
};
/*
* icmp6 namelookup
*/
struct icmp6_namelookup {
struct icmp6_hdr icmp6_nl_hdr;
uint8_t icmp6_nl_nonce[8];
int32_t icmp6_nl_ttl;
#if 0
uint8_t icmp6_nl_len;
uint8_t icmp6_nl_name[3];
#endif
/* could be followed by options */
};
/*
* icmp6 node information
*/
struct icmp6_nodeinfo {
struct icmp6_hdr icmp6_ni_hdr;
uint8_t icmp6_ni_nonce[8];
/* could be followed by reply data */
};
#define ni_type icmp6_ni_hdr.icmp6_type
#define ni_code icmp6_ni_hdr.icmp6_code
#define ni_cksum icmp6_ni_hdr.icmp6_cksum
#define ni_qtype icmp6_ni_hdr.icmp6_data16[0]
#define ni_flags icmp6_ni_hdr.icmp6_data16[1]
#define NI_QTYPE_NOOP 0 /* NOOP */
#define NI_QTYPE_SUPTYPES 1 /* Supported Qtypes */
#define NI_QTYPE_FQDN 2 /* FQDN (draft 04) */
#define NI_QTYPE_DNSNAME 2 /* DNS Name */
#define NI_QTYPE_NODEADDR 3 /* Node Addresses */
#define NI_QTYPE_IPV4ADDR 4 /* IPv4 Addresses */
/* network endian */
#define NI_SUPTYPE_FLAG_COMPRESS ((uint16_t)htons(0x1))
#define NI_FQDN_FLAG_VALIDTTL ((uint16_t)htons(0x1))
/* network endian */
#define NI_NODEADDR_FLAG_TRUNCATE ((uint16_t)htons(0x1))
#define NI_NODEADDR_FLAG_ALL ((uint16_t)htons(0x2))
#define NI_NODEADDR_FLAG_COMPAT ((uint16_t)htons(0x4))
#define NI_NODEADDR_FLAG_LINKLOCAL ((uint16_t)htons(0x8))
#define NI_NODEADDR_FLAG_SITELOCAL ((uint16_t)htons(0x10))
#define NI_NODEADDR_FLAG_GLOBAL ((uint16_t)htons(0x20))
#define NI_NODEADDR_FLAG_ANYCAST ((uint16_t)htons(0x40)) /* just experimental. not in spec */
struct ni_reply_fqdn {
uint32_t ni_fqdn_ttl; /* TTL */
uint8_t ni_fqdn_namelen; /* length in octets of the FQDN */
uint8_t ni_fqdn_name[3]; /* XXX: alignment */
};
/*
* Router Renumbering. as router-renum-08.txt
*/
struct icmp6_router_renum { /* router renumbering header */
struct icmp6_hdr rr_hdr;
uint8_t rr_segnum;
uint8_t rr_flags;
uint16_t rr_maxdelay;
uint32_t rr_reserved;
};
#define ICMP6_RR_FLAGS_TEST 0x80
#define ICMP6_RR_FLAGS_REQRESULT 0x40
#define ICMP6_RR_FLAGS_FORCEAPPLY 0x20
#define ICMP6_RR_FLAGS_SPECSITE 0x10
#define ICMP6_RR_FLAGS_PREVDONE 0x08
#define rr_type rr_hdr.icmp6_type
#define rr_code rr_hdr.icmp6_code
#define rr_cksum rr_hdr.icmp6_cksum
#define rr_seqnum rr_hdr.icmp6_data32[0]
struct rr_pco_match { /* match prefix part */
uint8_t rpm_code;
uint8_t rpm_len;
uint8_t rpm_ordinal;
uint8_t rpm_matchlen;
uint8_t rpm_minlen;
uint8_t rpm_maxlen;
uint16_t rpm_reserved;
struct in6_addr rpm_prefix;
};
#define RPM_PCO_ADD 1
#define RPM_PCO_CHANGE 2
#define RPM_PCO_SETGLOBAL 3
#define RPM_PCO_MAX 4
struct rr_pco_use { /* use prefix part */
uint8_t rpu_uselen;
uint8_t rpu_keeplen;
uint8_t rpu_ramask;
uint8_t rpu_raflags;
uint32_t rpu_vltime;
uint32_t rpu_pltime;
uint32_t rpu_flags;
struct in6_addr rpu_prefix;
};
#define ICMP6_RR_PCOUSE_RAFLAGS_ONLINK 0x80
#define ICMP6_RR_PCOUSE_RAFLAGS_AUTO 0x40
/* network endian */
#define ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME ((uint32_t)htonl(0x80000000))
#define ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME ((uint32_t)htonl(0x40000000))
struct rr_result { /* router renumbering result message */
uint16_t rrr_flags;
uint8_t rrr_ordinal;
uint8_t rrr_matchedlen;
uint32_t rrr_ifid;
struct in6_addr rrr_prefix;
};
/* network endian */
#define ICMP6_RR_RESULT_FLAGS_OOB ((uint16_t)htons(0x0002))
#define ICMP6_RR_RESULT_FLAGS_FORBIDDEN ((uint16_t)htons(0x0001))
static const char *get_rtpref(u_int);
static const char *get_lifetime(uint32_t);
static void print_lladdr(netdissect_options *ndo, const u_char *, size_t);
static void icmp6_opt_print(netdissect_options *ndo, const u_char *, int);
static void mld6_print(netdissect_options *ndo, const u_char *);
static void mldv2_report_print(netdissect_options *ndo, const u_char *, u_int);
static void mldv2_query_print(netdissect_options *ndo, const u_char *, u_int);
static const struct udphdr *get_upperlayer(netdissect_options *ndo, const u_char *, u_int *);
static void dnsname_print(netdissect_options *ndo, const u_char *, const u_char *);
static void icmp6_nodeinfo_print(netdissect_options *ndo, u_int, const u_char *, const u_char *);
static void icmp6_rrenum_print(netdissect_options *ndo, const u_char *, const u_char *);
#ifndef abs
#define abs(a) ((0 < (a)) ? (a) : -(a))
#endif
#include "rpl.h"
static const struct tok icmp6_type_values[] = {
{ ICMP6_DST_UNREACH, "destination unreachable"},
{ ICMP6_PACKET_TOO_BIG, "packet too big"},
{ ICMP6_TIME_EXCEEDED, "time exceeded in-transit"},
{ ICMP6_PARAM_PROB, "parameter problem"},
{ ICMP6_ECHO_REQUEST, "echo request"},
{ ICMP6_ECHO_REPLY, "echo reply"},
{ MLD6_LISTENER_QUERY, "multicast listener query"},
{ MLD6_LISTENER_REPORT, "multicast listener report"},
{ MLD6_LISTENER_DONE, "multicast listener done"},
{ ND_ROUTER_SOLICIT, "router solicitation"},
{ ND_ROUTER_ADVERT, "router advertisement"},
{ ND_NEIGHBOR_SOLICIT, "neighbor solicitation"},
{ ND_NEIGHBOR_ADVERT, "neighbor advertisement"},
{ ND_REDIRECT, "redirect"},
{ ICMP6_ROUTER_RENUMBERING, "router renumbering"},
{ IND_SOLICIT, "inverse neighbor solicitation"},
{ IND_ADVERT, "inverse neighbor advertisement"},
{ MLDV2_LISTENER_REPORT, "multicast listener report v2"},
{ ICMP6_HADISCOV_REQUEST, "ha discovery request"},
{ ICMP6_HADISCOV_REPLY, "ha discovery reply"},
{ ICMP6_MOBILEPREFIX_SOLICIT, "mobile router solicitation"},
{ ICMP6_MOBILEPREFIX_ADVERT, "mobile router advertisement"},
{ ICMP6_WRUREQUEST, "who-are-you request"},
{ ICMP6_WRUREPLY, "who-are-you reply"},
{ ICMP6_NI_QUERY, "node information query"},
{ ICMP6_NI_REPLY, "node information reply"},
{ MLD6_MTRACE, "mtrace message"},
{ MLD6_MTRACE_RESP, "mtrace response"},
{ ND_RPL_MESSAGE, "RPL"},
{ 0, NULL }
};
static const struct tok icmp6_dst_unreach_code_values[] = {
{ ICMP6_DST_UNREACH_NOROUTE, "unreachable route" },
{ ICMP6_DST_UNREACH_ADMIN, " unreachable prohibited"},
{ ICMP6_DST_UNREACH_BEYONDSCOPE, "beyond scope"},
{ ICMP6_DST_UNREACH_ADDR, "unreachable address"},
{ ICMP6_DST_UNREACH_NOPORT, "unreachable port"},
{ 0, NULL }
};
static const struct tok icmp6_opt_pi_flag_values[] = {
{ ND_OPT_PI_FLAG_ONLINK, "onlink" },
{ ND_OPT_PI_FLAG_AUTO, "auto" },
{ ND_OPT_PI_FLAG_ROUTER, "router" },
{ 0, NULL }
};
static const struct tok icmp6_opt_ra_flag_values[] = {
{ ND_RA_FLAG_MANAGED, "managed" },
{ ND_RA_FLAG_OTHER, "other stateful"},
{ ND_RA_FLAG_HOME_AGENT, "home agent"},
{ 0, NULL }
};
static const struct tok icmp6_nd_na_flag_values[] = {
{ ND_NA_FLAG_ROUTER, "router" },
{ ND_NA_FLAG_SOLICITED, "solicited" },
{ ND_NA_FLAG_OVERRIDE, "override" },
{ 0, NULL }
};
static const struct tok icmp6_opt_values[] = {
{ ND_OPT_SOURCE_LINKADDR, "source link-address"},
{ ND_OPT_TARGET_LINKADDR, "destination link-address"},
{ ND_OPT_PREFIX_INFORMATION, "prefix info"},
{ ND_OPT_REDIRECTED_HEADER, "redirected header"},
{ ND_OPT_MTU, "mtu"},
{ ND_OPT_RDNSS, "rdnss"},
{ ND_OPT_DNSSL, "dnssl"},
{ ND_OPT_ADVINTERVAL, "advertisement interval"},
{ ND_OPT_HOMEAGENT_INFO, "homeagent information"},
{ ND_OPT_ROUTE_INFO, "route info"},
{ 0, NULL }
};
/* mldv2 report types */
static const struct tok mldv2report2str[] = {
{ 1, "is_in" },
{ 2, "is_ex" },
{ 3, "to_in" },
{ 4, "to_ex" },
{ 5, "allow" },
{ 6, "block" },
{ 0, NULL }
};
static const char *
get_rtpref(u_int v)
{
static const char *rtpref_str[] = {
"medium", /* 00 */
"high", /* 01 */
"rsv", /* 10 */
"low" /* 11 */
};
return rtpref_str[((v & ND_RA_FLAG_RTPREF_MASK) >> 3) & 0xff];
}
static const char *
get_lifetime(uint32_t v)
{
static char buf[20];
if (v == (uint32_t)~0UL)
return "infinity";
else {
snprintf(buf, sizeof(buf), "%us", v);
return buf;
}
}
static void
print_lladdr(netdissect_options *ndo, const uint8_t *p, size_t l)
{
const uint8_t *ep, *q;
q = p;
ep = p + l;
while (l > 0 && q < ep) {
if (q > p)
ND_PRINT((ndo,":"));
ND_PRINT((ndo,"%02x", *q++));
l--;
}
}
static int icmp6_cksum(netdissect_options *ndo, const struct ip6_hdr *ip6,
const struct icmp6_hdr *icp, u_int len)
{
return nextproto6_cksum(ndo, ip6, (const uint8_t *)(const void *)icp, len, len,
IPPROTO_ICMPV6);
}
static const struct tok rpl_mop_values[] = {
{ RPL_DIO_NONSTORING, "nonstoring"},
{ RPL_DIO_STORING, "storing"},
{ RPL_DIO_NONSTORING_MULTICAST, "nonstoring-multicast"},
{ RPL_DIO_STORING_MULTICAST, "storing-multicast"},
{ 0, NULL},
};
static const struct tok rpl_subopt_values[] = {
{ RPL_OPT_PAD0, "pad0"},
{ RPL_OPT_PADN, "padN"},
{ RPL_DIO_METRICS, "metrics"},
{ RPL_DIO_ROUTINGINFO, "routinginfo"},
{ RPL_DIO_CONFIG, "config"},
{ RPL_DAO_RPLTARGET, "rpltarget"},
{ RPL_DAO_TRANSITINFO, "transitinfo"},
{ RPL_DIO_DESTPREFIX, "destprefix"},
{ RPL_DAO_RPLTARGET_DESC, "rpltargetdesc"},
{ 0, NULL},
};
static void
rpl_dio_printopt(netdissect_options *ndo,
const struct rpl_dio_genoption *opt,
u_int length)
{
if(length < RPL_DIO_GENOPTION_LEN) return;
length -= RPL_DIO_GENOPTION_LEN;
ND_TCHECK(opt->rpl_dio_len);
while((opt->rpl_dio_type == RPL_OPT_PAD0 &&
(const u_char *)opt < ndo->ndo_snapend) ||
ND_TTEST2(*opt,(opt->rpl_dio_len+2))) {
unsigned int optlen = opt->rpl_dio_len+2;
if(opt->rpl_dio_type == RPL_OPT_PAD0) {
optlen = 1;
ND_PRINT((ndo, " opt:pad0"));
} else {
ND_PRINT((ndo, " opt:%s len:%u ",
tok2str(rpl_subopt_values, "subopt:%u", opt->rpl_dio_type),
optlen));
if(ndo->ndo_vflag > 2) {
unsigned int paylen = opt->rpl_dio_len;
if(paylen > length) paylen = length;
hex_print(ndo,
" ",
((const uint8_t *)opt) + RPL_DIO_GENOPTION_LEN, /* content of DIO option */
paylen);
}
}
opt = (const struct rpl_dio_genoption *)(((const char *)opt) + optlen);
length -= optlen;
}
return;
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
}
static void
rpl_dio_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_dio *dio = (const struct nd_rpl_dio *)bp;
const char *dagid_str;
ND_TCHECK(*dio);
dagid_str = ip6addr_string (ndo, dio->rpl_dagid);
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,rank:%u,%smop:%s,prf:%u]",
dagid_str,
dio->rpl_dtsn,
dio->rpl_instanceid,
EXTRACT_16BITS(&dio->rpl_dagrank),
RPL_DIO_GROUNDED(dio->rpl_mopprf) ? "grounded,":"",
tok2str(rpl_mop_values, "mop%u", RPL_DIO_MOP(dio->rpl_mopprf)),
RPL_DIO_PRF(dio->rpl_mopprf)));
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)&dio[1];
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
}
static void
rpl_dao_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_dao *dao = (const struct nd_rpl_dao *)bp;
const char *dagid_str = "<elided>";
ND_TCHECK(*dao);
if (length < ND_RPL_DAO_MIN_LEN)
goto tooshort;
bp += ND_RPL_DAO_MIN_LEN;
length -= ND_RPL_DAO_MIN_LEN;
if(RPL_DAO_D(dao->rpl_flags)) {
ND_TCHECK2(dao->rpl_dagid, DAGID_LEN);
if (length < DAGID_LEN)
goto tooshort;
dagid_str = ip6addr_string (ndo, dao->rpl_dagid);
bp += DAGID_LEN;
length -= DAGID_LEN;
}
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u%s%s,%02x]",
dagid_str,
dao->rpl_daoseq,
dao->rpl_instanceid,
RPL_DAO_K(dao->rpl_flags) ? ",acK":"",
RPL_DAO_D(dao->rpl_flags) ? ",Dagid":"",
dao->rpl_flags));
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp;
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
tooshort:
ND_PRINT((ndo," [|length too short]"));
return;
}
static void
rpl_daoack_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_daoack *daoack = (const struct nd_rpl_daoack *)bp;
const char *dagid_str = "<elided>";
ND_TCHECK2(*daoack, ND_RPL_DAOACK_MIN_LEN);
if (length < ND_RPL_DAOACK_MIN_LEN)
goto tooshort;
bp += ND_RPL_DAOACK_MIN_LEN;
length -= ND_RPL_DAOACK_MIN_LEN;
if(RPL_DAOACK_D(daoack->rpl_flags)) {
ND_TCHECK2(daoack->rpl_dagid, DAGID_LEN);
if (length < DAGID_LEN)
goto tooshort;
dagid_str = ip6addr_string (ndo, daoack->rpl_dagid);
bp += DAGID_LEN;
length -= DAGID_LEN;
}
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,status:%u]",
dagid_str,
daoack->rpl_daoseq,
daoack->rpl_instanceid,
daoack->rpl_status));
/* no officially defined options for DAOACK, but print any we find */
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp;
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|dao-truncated]"));
return;
tooshort:
ND_PRINT((ndo," [|dao-length too short]"));
return;
}
static void
rpl_print(netdissect_options *ndo,
const struct icmp6_hdr *hdr,
const u_char *bp, u_int length)
{
int secured = hdr->icmp6_code & 0x80;
int basecode= hdr->icmp6_code & 0x7f;
if(secured) {
ND_PRINT((ndo, ", (SEC) [worktodo]"));
/* XXX
* the next header pointer needs to move forward to
* skip the secure part.
*/
return;
} else {
ND_PRINT((ndo, ", (CLR)"));
}
switch(basecode) {
case ND_RPL_DAG_IS:
ND_PRINT((ndo, "DODAG Information Solicitation"));
if(ndo->ndo_vflag) {
}
break;
case ND_RPL_DAG_IO:
ND_PRINT((ndo, "DODAG Information Object"));
if(ndo->ndo_vflag) {
rpl_dio_print(ndo, bp, length);
}
break;
case ND_RPL_DAO:
ND_PRINT((ndo, "Destination Advertisement Object"));
if(ndo->ndo_vflag) {
rpl_dao_print(ndo, bp, length);
}
break;
case ND_RPL_DAO_ACK:
ND_PRINT((ndo, "Destination Advertisement Object Ack"));
if(ndo->ndo_vflag) {
rpl_daoack_print(ndo, bp, length);
}
break;
default:
ND_PRINT((ndo, "RPL message, unknown code %u",hdr->icmp6_code));
break;
}
return;
#if 0
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
#endif
}
void
icmp6_print(netdissect_options *ndo,
const u_char *bp, u_int length, const u_char *bp2, int fragmented)
{
const struct icmp6_hdr *dp;
const struct ip6_hdr *ip;
const struct ip6_hdr *oip;
const struct udphdr *ouh;
int dport;
const u_char *ep;
u_int prot;
dp = (const struct icmp6_hdr *)bp;
ip = (const struct ip6_hdr *)bp2;
oip = (const struct ip6_hdr *)(dp + 1);
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
ND_TCHECK(dp->icmp6_cksum);
if (ndo->ndo_vflag && !fragmented) {
uint16_t sum, udp_sum;
if (ND_TTEST2(bp[0], length)) {
udp_sum = EXTRACT_16BITS(&dp->icmp6_cksum);
sum = icmp6_cksum(ndo, ip, dp, length);
if (sum != 0)
ND_PRINT((ndo,"[bad icmp6 cksum 0x%04x -> 0x%04x!] ",
udp_sum,
in_cksum_shouldbe(udp_sum, sum)));
else
ND_PRINT((ndo,"[icmp6 sum ok] "));
}
}
ND_PRINT((ndo,"ICMP6, %s", tok2str(icmp6_type_values,"unknown icmp6 type (%u)",dp->icmp6_type)));
/* display cosmetics: print the packet length for printer that use the vflag now */
if (ndo->ndo_vflag && (dp->icmp6_type == ND_ROUTER_SOLICIT ||
dp->icmp6_type == ND_ROUTER_ADVERT ||
dp->icmp6_type == ND_NEIGHBOR_ADVERT ||
dp->icmp6_type == ND_NEIGHBOR_SOLICIT ||
dp->icmp6_type == ND_REDIRECT ||
dp->icmp6_type == ICMP6_HADISCOV_REPLY ||
dp->icmp6_type == ICMP6_MOBILEPREFIX_ADVERT ))
ND_PRINT((ndo,", length %u", length));
switch (dp->icmp6_type) {
case ICMP6_DST_UNREACH:
ND_TCHECK(oip->ip6_dst);
ND_PRINT((ndo,", %s", tok2str(icmp6_dst_unreach_code_values,"unknown unreach code (%u)",dp->icmp6_code)));
switch (dp->icmp6_code) {
case ICMP6_DST_UNREACH_NOROUTE: /* fall through */
case ICMP6_DST_UNREACH_ADMIN:
case ICMP6_DST_UNREACH_ADDR:
ND_PRINT((ndo," %s",ip6addr_string(ndo, &oip->ip6_dst)));
break;
case ICMP6_DST_UNREACH_BEYONDSCOPE:
ND_PRINT((ndo," %s, source address %s",
ip6addr_string(ndo, &oip->ip6_dst),
ip6addr_string(ndo, &oip->ip6_src)));
break;
case ICMP6_DST_UNREACH_NOPORT:
if ((ouh = get_upperlayer(ndo, (const u_char *)oip, &prot))
== NULL)
goto trunc;
dport = EXTRACT_16BITS(&ouh->uh_dport);
switch (prot) {
case IPPROTO_TCP:
ND_PRINT((ndo,", %s tcp port %s",
ip6addr_string(ndo, &oip->ip6_dst),
tcpport_string(ndo, dport)));
break;
case IPPROTO_UDP:
ND_PRINT((ndo,", %s udp port %s",
ip6addr_string(ndo, &oip->ip6_dst),
udpport_string(ndo, dport)));
break;
default:
ND_PRINT((ndo,", %s protocol %d port %d unreachable",
ip6addr_string(ndo, &oip->ip6_dst),
oip->ip6_nxt, dport));
break;
}
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, bp,"\n\t",length);
return;
}
break;
}
break;
case ICMP6_PACKET_TOO_BIG:
ND_TCHECK(dp->icmp6_mtu);
ND_PRINT((ndo,", mtu %u", EXTRACT_32BITS(&dp->icmp6_mtu)));
break;
case ICMP6_TIME_EXCEEDED:
ND_TCHECK(oip->ip6_dst);
switch (dp->icmp6_code) {
case ICMP6_TIME_EXCEED_TRANSIT:
ND_PRINT((ndo," for %s",
ip6addr_string(ndo, &oip->ip6_dst)));
break;
case ICMP6_TIME_EXCEED_REASSEMBLY:
ND_PRINT((ndo," (reassembly)"));
break;
default:
ND_PRINT((ndo,", unknown code (%u)", dp->icmp6_code));
break;
}
break;
case ICMP6_PARAM_PROB:
ND_TCHECK(oip->ip6_dst);
switch (dp->icmp6_code) {
case ICMP6_PARAMPROB_HEADER:
ND_PRINT((ndo,", erroneous - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr)));
break;
case ICMP6_PARAMPROB_NEXTHEADER:
ND_PRINT((ndo,", next header - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr)));
break;
case ICMP6_PARAMPROB_OPTION:
ND_PRINT((ndo,", option - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr)));
break;
default:
ND_PRINT((ndo,", code-#%d",
dp->icmp6_code));
break;
}
break;
case ICMP6_ECHO_REQUEST:
case ICMP6_ECHO_REPLY:
ND_TCHECK(dp->icmp6_seq);
ND_PRINT((ndo,", seq %u", EXTRACT_16BITS(&dp->icmp6_seq)));
break;
case ICMP6_MEMBERSHIP_QUERY:
if (length == MLD_MINLEN) {
mld6_print(ndo, (const u_char *)dp);
} else if (length >= MLDV2_MINLEN) {
ND_PRINT((ndo," v2"));
mldv2_query_print(ndo, (const u_char *)dp, length);
} else {
ND_PRINT((ndo," unknown-version (len %u) ", length));
}
break;
case ICMP6_MEMBERSHIP_REPORT:
mld6_print(ndo, (const u_char *)dp);
break;
case ICMP6_MEMBERSHIP_REDUCTION:
mld6_print(ndo, (const u_char *)dp);
break;
case ND_ROUTER_SOLICIT:
#define RTSOLLEN 8
if (ndo->ndo_vflag) {
icmp6_opt_print(ndo, (const u_char *)dp + RTSOLLEN,
length - RTSOLLEN);
}
break;
case ND_ROUTER_ADVERT:
#define RTADVLEN 16
if (ndo->ndo_vflag) {
const struct nd_router_advert *p;
p = (const struct nd_router_advert *)dp;
ND_TCHECK(p->nd_ra_retransmit);
ND_PRINT((ndo,"\n\thop limit %u, Flags [%s]" \
", pref %s, router lifetime %us, reachable time %us, retrans time %us",
(u_int)p->nd_ra_curhoplimit,
bittok2str(icmp6_opt_ra_flag_values,"none",(p->nd_ra_flags_reserved)),
get_rtpref(p->nd_ra_flags_reserved),
EXTRACT_16BITS(&p->nd_ra_router_lifetime),
EXTRACT_32BITS(&p->nd_ra_reachable),
EXTRACT_32BITS(&p->nd_ra_retransmit)));
icmp6_opt_print(ndo, (const u_char *)dp + RTADVLEN,
length - RTADVLEN);
}
break;
case ND_NEIGHBOR_SOLICIT:
{
const struct nd_neighbor_solicit *p;
p = (const struct nd_neighbor_solicit *)dp;
ND_TCHECK(p->nd_ns_target);
ND_PRINT((ndo,", who has %s", ip6addr_string(ndo, &p->nd_ns_target)));
if (ndo->ndo_vflag) {
#define NDSOLLEN 24
icmp6_opt_print(ndo, (const u_char *)dp + NDSOLLEN,
length - NDSOLLEN);
}
}
break;
case ND_NEIGHBOR_ADVERT:
{
const struct nd_neighbor_advert *p;
p = (const struct nd_neighbor_advert *)dp;
ND_TCHECK(p->nd_na_target);
ND_PRINT((ndo,", tgt is %s",
ip6addr_string(ndo, &p->nd_na_target)));
if (ndo->ndo_vflag) {
ND_PRINT((ndo,", Flags [%s]",
bittok2str(icmp6_nd_na_flag_values,
"none",
EXTRACT_32BITS(&p->nd_na_flags_reserved))));
#define NDADVLEN 24
icmp6_opt_print(ndo, (const u_char *)dp + NDADVLEN,
length - NDADVLEN);
#undef NDADVLEN
}
}
break;
case ND_REDIRECT:
#define RDR(i) ((const struct nd_redirect *)(i))
ND_TCHECK(RDR(dp)->nd_rd_dst);
ND_PRINT((ndo,", %s", ip6addr_string(ndo, &RDR(dp)->nd_rd_dst)));
ND_TCHECK(RDR(dp)->nd_rd_target);
ND_PRINT((ndo," to %s",
ip6addr_string(ndo, &RDR(dp)->nd_rd_target)));
#define REDIRECTLEN 40
if (ndo->ndo_vflag) {
icmp6_opt_print(ndo, (const u_char *)dp + REDIRECTLEN,
length - REDIRECTLEN);
}
break;
#undef REDIRECTLEN
#undef RDR
case ICMP6_ROUTER_RENUMBERING:
icmp6_rrenum_print(ndo, bp, ep);
break;
case ICMP6_NI_QUERY:
case ICMP6_NI_REPLY:
icmp6_nodeinfo_print(ndo, length, bp, ep);
break;
case IND_SOLICIT:
case IND_ADVERT:
break;
case ICMP6_V2_MEMBERSHIP_REPORT:
mldv2_report_print(ndo, (const u_char *) dp, length);
break;
case ICMP6_MOBILEPREFIX_SOLICIT: /* fall through */
case ICMP6_HADISCOV_REQUEST:
ND_TCHECK(dp->icmp6_data16[0]);
ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0])));
break;
case ICMP6_HADISCOV_REPLY:
if (ndo->ndo_vflag) {
const struct in6_addr *in6;
const u_char *cp;
ND_TCHECK(dp->icmp6_data16[0]);
ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0])));
cp = (const u_char *)dp + length;
in6 = (const struct in6_addr *)(dp + 1);
for (; (const u_char *)in6 < cp; in6++) {
ND_TCHECK(*in6);
ND_PRINT((ndo,", %s", ip6addr_string(ndo, in6)));
}
}
break;
case ICMP6_MOBILEPREFIX_ADVERT:
if (ndo->ndo_vflag) {
ND_TCHECK(dp->icmp6_data16[0]);
ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0])));
ND_TCHECK(dp->icmp6_data16[1]);
if (dp->icmp6_data16[1] & 0xc0)
ND_PRINT((ndo," "));
if (dp->icmp6_data16[1] & 0x80)
ND_PRINT((ndo,"M"));
if (dp->icmp6_data16[1] & 0x40)
ND_PRINT((ndo,"O"));
#define MPADVLEN 8
icmp6_opt_print(ndo, (const u_char *)dp + MPADVLEN,
length - MPADVLEN);
}
break;
case ND_RPL_MESSAGE:
/* plus 4, because struct icmp6_hdr contains 4 bytes of icmp payload */
rpl_print(ndo, dp, &dp->icmp6_data8[0], length-sizeof(struct icmp6_hdr)+4);
break;
default:
ND_PRINT((ndo,", length %u", length));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, bp,"\n\t", length);
return;
}
if (!ndo->ndo_vflag)
ND_PRINT((ndo,", length %u", length));
return;
trunc:
ND_PRINT((ndo, "[|icmp6]"));
}
static const struct udphdr *
get_upperlayer(netdissect_options *ndo, const u_char *bp, u_int *prot)
{
const u_char *ep;
const struct ip6_hdr *ip6 = (const struct ip6_hdr *)bp;
const struct udphdr *uh;
const struct ip6_hbh *hbh;
const struct ip6_frag *fragh;
const struct ah *ah;
u_int nh;
int hlen;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
if (!ND_TTEST(ip6->ip6_nxt))
return NULL;
nh = ip6->ip6_nxt;
hlen = sizeof(struct ip6_hdr);
while (bp < ep) {
bp += hlen;
switch(nh) {
case IPPROTO_UDP:
case IPPROTO_TCP:
uh = (const struct udphdr *)bp;
if (ND_TTEST(uh->uh_dport)) {
*prot = nh;
return(uh);
}
else
return(NULL);
/* NOTREACHED */
case IPPROTO_HOPOPTS:
case IPPROTO_DSTOPTS:
case IPPROTO_ROUTING:
hbh = (const struct ip6_hbh *)bp;
if (!ND_TTEST(hbh->ip6h_len))
return(NULL);
nh = hbh->ip6h_nxt;
hlen = (hbh->ip6h_len + 1) << 3;
break;
case IPPROTO_FRAGMENT: /* this should be odd, but try anyway */
fragh = (const struct ip6_frag *)bp;
if (!ND_TTEST(fragh->ip6f_offlg))
return(NULL);
/* fragments with non-zero offset are meaningless */
if ((EXTRACT_16BITS(&fragh->ip6f_offlg) & IP6F_OFF_MASK) != 0)
return(NULL);
nh = fragh->ip6f_nxt;
hlen = sizeof(struct ip6_frag);
break;
case IPPROTO_AH:
ah = (const struct ah *)bp;
if (!ND_TTEST(ah->ah_len))
return(NULL);
nh = ah->ah_nxt;
hlen = (ah->ah_len + 2) << 2;
break;
default: /* unknown or undecodable header */
*prot = nh; /* meaningless, but set here anyway */
return(NULL);
}
}
return(NULL); /* should be notreached, though */
}
static void
icmp6_opt_print(netdissect_options *ndo, const u_char *bp, int resid)
{
const struct nd_opt_hdr *op;
const struct nd_opt_prefix_info *opp;
const struct nd_opt_mtu *opm;
const struct nd_opt_rdnss *oprd;
const struct nd_opt_dnssl *opds;
const struct nd_opt_advinterval *opa;
const struct nd_opt_homeagent_info *oph;
const struct nd_opt_route_info *opri;
const u_char *cp, *ep, *domp;
struct in6_addr in6;
const struct in6_addr *in6p;
size_t l;
u_int i;
#define ECHECK(var) if ((const u_char *)&(var) > ep - sizeof(var)) return
cp = bp;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
while (cp < ep) {
op = (const struct nd_opt_hdr *)cp;
ECHECK(op->nd_opt_len);
if (resid <= 0)
return;
if (op->nd_opt_len == 0)
goto trunc;
if (cp + (op->nd_opt_len << 3) > ep)
goto trunc;
ND_PRINT((ndo,"\n\t %s option (%u), length %u (%u): ",
tok2str(icmp6_opt_values, "unknown", op->nd_opt_type),
op->nd_opt_type,
op->nd_opt_len << 3,
op->nd_opt_len));
switch (op->nd_opt_type) {
case ND_OPT_SOURCE_LINKADDR:
l = (op->nd_opt_len << 3) - 2;
print_lladdr(ndo, cp + 2, l);
break;
case ND_OPT_TARGET_LINKADDR:
l = (op->nd_opt_len << 3) - 2;
print_lladdr(ndo, cp + 2, l);
break;
case ND_OPT_PREFIX_INFORMATION:
opp = (const struct nd_opt_prefix_info *)op;
ND_TCHECK(opp->nd_opt_pi_prefix);
ND_PRINT((ndo,"%s/%u%s, Flags [%s], valid time %s",
ip6addr_string(ndo, &opp->nd_opt_pi_prefix),
opp->nd_opt_pi_prefix_len,
(op->nd_opt_len != 4) ? "badlen" : "",
bittok2str(icmp6_opt_pi_flag_values, "none", opp->nd_opt_pi_flags_reserved),
get_lifetime(EXTRACT_32BITS(&opp->nd_opt_pi_valid_time))));
ND_PRINT((ndo,", pref. time %s", get_lifetime(EXTRACT_32BITS(&opp->nd_opt_pi_preferred_time))));
break;
case ND_OPT_REDIRECTED_HEADER:
print_unknown_data(ndo, bp,"\n\t ",op->nd_opt_len<<3);
/* xxx */
break;
case ND_OPT_MTU:
opm = (const struct nd_opt_mtu *)op;
ND_TCHECK(opm->nd_opt_mtu_mtu);
ND_PRINT((ndo," %u%s",
EXTRACT_32BITS(&opm->nd_opt_mtu_mtu),
(op->nd_opt_len != 1) ? "bad option length" : "" ));
break;
case ND_OPT_RDNSS:
oprd = (const struct nd_opt_rdnss *)op;
l = (op->nd_opt_len - 1) / 2;
ND_PRINT((ndo," lifetime %us,",
EXTRACT_32BITS(&oprd->nd_opt_rdnss_lifetime)));
for (i = 0; i < l; i++) {
ND_TCHECK(oprd->nd_opt_rdnss_addr[i]);
ND_PRINT((ndo," addr: %s",
ip6addr_string(ndo, &oprd->nd_opt_rdnss_addr[i])));
}
break;
case ND_OPT_DNSSL:
opds = (const struct nd_opt_dnssl *)op;
ND_PRINT((ndo," lifetime %us, domain(s):",
EXTRACT_32BITS(&opds->nd_opt_dnssl_lifetime)));
domp = cp + 8; /* domain names, variable-sized, RFC1035-encoded */
while (domp < cp + (op->nd_opt_len << 3) && *domp != '\0')
{
ND_PRINT((ndo, " "));
if ((domp = ns_nprint (ndo, domp, bp)) == NULL)
goto trunc;
}
break;
case ND_OPT_ADVINTERVAL:
opa = (const struct nd_opt_advinterval *)op;
ND_TCHECK(opa->nd_opt_adv_interval);
ND_PRINT((ndo," %ums", EXTRACT_32BITS(&opa->nd_opt_adv_interval)));
break;
case ND_OPT_HOMEAGENT_INFO:
oph = (const struct nd_opt_homeagent_info *)op;
ND_TCHECK(oph->nd_opt_hai_lifetime);
ND_PRINT((ndo," preference %u, lifetime %u",
EXTRACT_16BITS(&oph->nd_opt_hai_preference),
EXTRACT_16BITS(&oph->nd_opt_hai_lifetime)));
break;
case ND_OPT_ROUTE_INFO:
opri = (const struct nd_opt_route_info *)op;
ND_TCHECK(opri->nd_opt_rti_lifetime);
memset(&in6, 0, sizeof(in6));
in6p = (const struct in6_addr *)(opri + 1);
switch (op->nd_opt_len) {
case 1:
break;
case 2:
ND_TCHECK2(*in6p, 8);
memcpy(&in6, opri + 1, 8);
break;
case 3:
ND_TCHECK(*in6p);
memcpy(&in6, opri + 1, sizeof(in6));
break;
default:
goto trunc;
}
ND_PRINT((ndo," %s/%u", ip6addr_string(ndo, &in6),
opri->nd_opt_rti_prefixlen));
ND_PRINT((ndo,", pref=%s", get_rtpref(opri->nd_opt_rti_flags)));
ND_PRINT((ndo,", lifetime=%s",
get_lifetime(EXTRACT_32BITS(&opri->nd_opt_rti_lifetime))));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo,cp+2,"\n\t ", (op->nd_opt_len << 3) - 2); /* skip option header */
return;
}
break;
}
/* do we want to see an additional hexdump ? */
if (ndo->ndo_vflag> 1)
print_unknown_data(ndo, cp+2,"\n\t ", (op->nd_opt_len << 3) - 2); /* skip option header */
cp += op->nd_opt_len << 3;
resid -= op->nd_opt_len << 3;
}
return;
trunc:
ND_PRINT((ndo, "[ndp opt]"));
return;
#undef ECHECK
}
static void
mld6_print(netdissect_options *ndo, const u_char *bp)
{
const struct mld6_hdr *mp = (const struct mld6_hdr *)bp;
const u_char *ep;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
if ((const u_char *)mp + sizeof(*mp) > ep)
return;
ND_PRINT((ndo,"max resp delay: %d ", EXTRACT_16BITS(&mp->mld6_maxdelay)));
ND_PRINT((ndo,"addr: %s", ip6addr_string(ndo, &mp->mld6_addr)));
}
static void
mldv2_report_print(netdissect_options *ndo, const u_char *bp, u_int len)
{
const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp;
u_int group, nsrcs, ngroups;
u_int i, j;
/* Minimum len is 8 */
if (len < 8) {
ND_PRINT((ndo," [invalid len %d]", len));
return;
}
ND_TCHECK(icp->icmp6_data16[1]);
ngroups = EXTRACT_16BITS(&icp->icmp6_data16[1]);
ND_PRINT((ndo,", %d group record(s)", ngroups));
if (ndo->ndo_vflag > 0) {
/* Print the group records */
group = 8;
for (i = 0; i < ngroups; i++) {
/* type(1) + auxlen(1) + numsrc(2) + grp(16) */
if (len < group + 20) {
ND_PRINT((ndo," [invalid number of groups]"));
return;
}
ND_TCHECK2(bp[group + 4], sizeof(struct in6_addr));
ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[group + 4])));
ND_PRINT((ndo," %s", tok2str(mldv2report2str, " [v2-report-#%d]",
bp[group])));
nsrcs = (bp[group + 2] << 8) + bp[group + 3];
/* Check the number of sources and print them */
if (len < group + 20 + (nsrcs * sizeof(struct in6_addr))) {
ND_PRINT((ndo," [invalid number of sources %d]", nsrcs));
return;
}
if (ndo->ndo_vflag == 1)
ND_PRINT((ndo,", %d source(s)", nsrcs));
else {
/* Print the sources */
ND_PRINT((ndo," {"));
for (j = 0; j < nsrcs; j++) {
ND_TCHECK2(bp[group + 20 + j * sizeof(struct in6_addr)],
sizeof(struct in6_addr));
ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[group + 20 + j * sizeof(struct in6_addr)])));
}
ND_PRINT((ndo," }"));
}
/* Next group record */
group += 20 + nsrcs * sizeof(struct in6_addr);
ND_PRINT((ndo,"]"));
}
}
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
return;
}
static void
mldv2_query_print(netdissect_options *ndo, const u_char *bp, u_int len)
{
const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp;
u_int mrc;
int mrt, qqi;
u_int nsrcs;
register u_int i;
/* Minimum len is 28 */
if (len < 28) {
ND_PRINT((ndo," [invalid len %d]", len));
return;
}
ND_TCHECK(icp->icmp6_data16[0]);
mrc = EXTRACT_16BITS(&icp->icmp6_data16[0]);
if (mrc < 32768) {
mrt = mrc;
} else {
mrt = ((mrc & 0x0fff) | 0x1000) << (((mrc & 0x7000) >> 12) + 3);
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo," [max resp delay=%d]", mrt));
}
ND_TCHECK2(bp[8], sizeof(struct in6_addr));
ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[8])));
if (ndo->ndo_vflag) {
ND_TCHECK(bp[25]);
if (bp[24] & 0x08) {
ND_PRINT((ndo," sflag"));
}
if (bp[24] & 0x07) {
ND_PRINT((ndo," robustness=%d", bp[24] & 0x07));
}
if (bp[25] < 128) {
qqi = bp[25];
} else {
qqi = ((bp[25] & 0x0f) | 0x10) << (((bp[25] & 0x70) >> 4) + 3);
}
ND_PRINT((ndo," qqi=%d", qqi));
}
ND_TCHECK2(bp[26], 2);
nsrcs = EXTRACT_16BITS(&bp[26]);
if (nsrcs > 0) {
if (len < 28 + nsrcs * sizeof(struct in6_addr))
ND_PRINT((ndo," [invalid number of sources]"));
else if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo," {"));
for (i = 0; i < nsrcs; i++) {
ND_TCHECK2(bp[28 + i * sizeof(struct in6_addr)],
sizeof(struct in6_addr));
ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[28 + i * sizeof(struct in6_addr)])));
}
ND_PRINT((ndo," }"));
} else
ND_PRINT((ndo,", %d source(s)", nsrcs));
}
ND_PRINT((ndo,"]"));
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
return;
}
static void
dnsname_print(netdissect_options *ndo, const u_char *cp, const u_char *ep)
{
int i;
/* DNS name decoding - no decompression */
ND_PRINT((ndo,", \""));
while (cp < ep) {
i = *cp++;
if (i) {
if (i > ep - cp) {
ND_PRINT((ndo,"???"));
break;
}
while (i-- && cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
if (cp + 1 < ep && *cp)
ND_PRINT((ndo,"."));
} else {
if (cp == ep) {
/* FQDN */
ND_PRINT((ndo,"."));
} else if (cp + 1 == ep && *cp == '\0') {
/* truncated */
} else {
/* invalid */
ND_PRINT((ndo,"???"));
}
break;
}
}
ND_PRINT((ndo,"\""));
}
static void
icmp6_nodeinfo_print(netdissect_options *ndo, u_int icmp6len, const u_char *bp, const u_char *ep)
{
const struct icmp6_nodeinfo *ni6;
const struct icmp6_hdr *dp;
const u_char *cp;
size_t siz, i;
int needcomma;
if (ep < bp)
return;
dp = (const struct icmp6_hdr *)bp;
ni6 = (const struct icmp6_nodeinfo *)bp;
siz = ep - bp;
switch (ni6->ni_type) {
case ICMP6_NI_QUERY:
if (siz == sizeof(*dp) + 4) {
/* KAME who-are-you */
ND_PRINT((ndo," who-are-you request"));
break;
}
ND_PRINT((ndo," node information query"));
ND_TCHECK2(*dp, sizeof(*ni6));
ni6 = (const struct icmp6_nodeinfo *)dp;
ND_PRINT((ndo," (")); /*)*/
switch (EXTRACT_16BITS(&ni6->ni_qtype)) {
case NI_QTYPE_NOOP:
ND_PRINT((ndo,"noop"));
break;
case NI_QTYPE_SUPTYPES:
ND_PRINT((ndo,"supported qtypes"));
i = EXTRACT_16BITS(&ni6->ni_flags);
if (i)
ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : ""));
break;
case NI_QTYPE_FQDN:
ND_PRINT((ndo,"DNS name"));
break;
case NI_QTYPE_NODEADDR:
ND_PRINT((ndo,"node addresses"));
i = ni6->ni_flags;
if (!i)
break;
/* NI_NODEADDR_FLAG_TRUNCATE undefined for query */
ND_PRINT((ndo," [%s%s%s%s%s%s]",
(i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "",
(i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "",
(i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "",
(i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "",
(i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "",
(i & NI_NODEADDR_FLAG_ALL) ? "A" : ""));
break;
default:
ND_PRINT((ndo,"unknown"));
break;
}
if (ni6->ni_qtype == NI_QTYPE_NOOP ||
ni6->ni_qtype == NI_QTYPE_SUPTYPES) {
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid len"));
/*(*/
ND_PRINT((ndo,")"));
break;
}
/* XXX backward compat, icmp-name-lookup-03 */
if (siz == sizeof(*ni6)) {
ND_PRINT((ndo,", 03 draft"));
/*(*/
ND_PRINT((ndo,")"));
break;
}
switch (ni6->ni_code) {
case ICMP6_NI_SUBJ_IPV6:
if (!ND_TTEST2(*dp,
sizeof(*ni6) + sizeof(struct in6_addr)))
break;
if (siz != sizeof(*ni6) + sizeof(struct in6_addr)) {
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid subject len"));
break;
}
ND_PRINT((ndo,", subject=%s",
ip6addr_string(ndo, ni6 + 1)));
break;
case ICMP6_NI_SUBJ_FQDN:
ND_PRINT((ndo,", subject=DNS name"));
cp = (const u_char *)(ni6 + 1);
if (cp[0] == ep - cp - 1) {
/* icmp-name-lookup-03, pascal string */
if (ndo->ndo_vflag)
ND_PRINT((ndo,", 03 draft"));
cp++;
ND_PRINT((ndo,", \""));
while (cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
ND_PRINT((ndo,"\""));
} else
dnsname_print(ndo, cp, ep);
break;
case ICMP6_NI_SUBJ_IPV4:
if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in_addr)))
break;
if (siz != sizeof(*ni6) + sizeof(struct in_addr)) {
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid subject len"));
break;
}
ND_PRINT((ndo,", subject=%s",
ipaddr_string(ndo, ni6 + 1)));
break;
default:
ND_PRINT((ndo,", unknown subject"));
break;
}
/*(*/
ND_PRINT((ndo,")"));
break;
case ICMP6_NI_REPLY:
if (icmp6len > siz) {
ND_PRINT((ndo,"[|icmp6: node information reply]"));
break;
}
needcomma = 0;
ni6 = (const struct icmp6_nodeinfo *)dp;
ND_PRINT((ndo," node information reply"));
ND_PRINT((ndo," (")); /*)*/
switch (ni6->ni_code) {
case ICMP6_NI_SUCCESS:
if (ndo->ndo_vflag) {
ND_PRINT((ndo,"success"));
needcomma++;
}
break;
case ICMP6_NI_REFUSED:
ND_PRINT((ndo,"refused"));
needcomma++;
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
case ICMP6_NI_UNKNOWN:
ND_PRINT((ndo,"unknown"));
needcomma++;
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
}
if (ni6->ni_code != ICMP6_NI_SUCCESS) {
/*(*/
ND_PRINT((ndo,")"));
break;
}
switch (EXTRACT_16BITS(&ni6->ni_qtype)) {
case NI_QTYPE_NOOP:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"noop"));
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
case NI_QTYPE_SUPTYPES:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"supported qtypes"));
i = EXTRACT_16BITS(&ni6->ni_flags);
if (i)
ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : ""));
break;
case NI_QTYPE_FQDN:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"DNS name"));
cp = (const u_char *)(ni6 + 1) + 4;
if (cp[0] == ep - cp - 1) {
/* icmp-name-lookup-03, pascal string */
if (ndo->ndo_vflag)
ND_PRINT((ndo,", 03 draft"));
cp++;
ND_PRINT((ndo,", \""));
while (cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
ND_PRINT((ndo,"\""));
} else
dnsname_print(ndo, cp, ep);
if ((EXTRACT_16BITS(&ni6->ni_flags) & 0x01) != 0)
ND_PRINT((ndo," [TTL=%u]", EXTRACT_32BITS(ni6 + 1)));
break;
case NI_QTYPE_NODEADDR:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"node addresses"));
i = sizeof(*ni6);
while (i < siz) {
if (i + sizeof(struct in6_addr) + sizeof(int32_t) > siz)
break;
ND_PRINT((ndo," %s", ip6addr_string(ndo, bp + i)));
i += sizeof(struct in6_addr);
ND_PRINT((ndo,"(%d)", (int32_t)EXTRACT_32BITS(bp + i)));
i += sizeof(int32_t);
}
i = ni6->ni_flags;
if (!i)
break;
ND_PRINT((ndo," [%s%s%s%s%s%s%s]",
(i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "",
(i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "",
(i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "",
(i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "",
(i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "",
(i & NI_NODEADDR_FLAG_ALL) ? "A" : "",
(i & NI_NODEADDR_FLAG_TRUNCATE) ? "T" : ""));
break;
default:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"unknown"));
break;
}
/*(*/
ND_PRINT((ndo,")"));
break;
}
return;
trunc:
ND_PRINT((ndo, "[|icmp6]"));
}
static void
icmp6_rrenum_print(netdissect_options *ndo, const u_char *bp, const u_char *ep)
{
const struct icmp6_router_renum *rr6;
const char *cp;
const struct rr_pco_match *match;
const struct rr_pco_use *use;
char hbuf[NI_MAXHOST];
int n;
if (ep < bp)
return;
rr6 = (const struct icmp6_router_renum *)bp;
cp = (const char *)(rr6 + 1);
ND_TCHECK(rr6->rr_reserved);
switch (rr6->rr_code) {
case ICMP6_ROUTER_RENUMBERING_COMMAND:
ND_PRINT((ndo,"router renum: command"));
break;
case ICMP6_ROUTER_RENUMBERING_RESULT:
ND_PRINT((ndo,"router renum: result"));
break;
case ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET:
ND_PRINT((ndo,"router renum: sequence number reset"));
break;
default:
ND_PRINT((ndo,"router renum: code-#%d", rr6->rr_code));
break;
}
ND_PRINT((ndo,", seq=%u", EXTRACT_32BITS(&rr6->rr_seqnum)));
if (ndo->ndo_vflag) {
#define F(x, y) ((rr6->rr_flags) & (x) ? (y) : "")
ND_PRINT((ndo,"[")); /*]*/
if (rr6->rr_flags) {
ND_PRINT((ndo,"%s%s%s%s%s,", F(ICMP6_RR_FLAGS_TEST, "T"),
F(ICMP6_RR_FLAGS_REQRESULT, "R"),
F(ICMP6_RR_FLAGS_FORCEAPPLY, "A"),
F(ICMP6_RR_FLAGS_SPECSITE, "S"),
F(ICMP6_RR_FLAGS_PREVDONE, "P")));
}
ND_PRINT((ndo,"seg=%u,", rr6->rr_segnum));
ND_PRINT((ndo,"maxdelay=%u", EXTRACT_16BITS(&rr6->rr_maxdelay)));
if (rr6->rr_reserved)
ND_PRINT((ndo,"rsvd=0x%x", EXTRACT_32BITS(&rr6->rr_reserved)));
/*[*/
ND_PRINT((ndo,"]"));
#undef F
}
if (rr6->rr_code == ICMP6_ROUTER_RENUMBERING_COMMAND) {
match = (const struct rr_pco_match *)cp;
cp = (const char *)(match + 1);
ND_TCHECK(match->rpm_prefix);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo,"\n\t"));
else
ND_PRINT((ndo," "));
ND_PRINT((ndo,"match(")); /*)*/
switch (match->rpm_code) {
case RPM_PCO_ADD: ND_PRINT((ndo,"add")); break;
case RPM_PCO_CHANGE: ND_PRINT((ndo,"change")); break;
case RPM_PCO_SETGLOBAL: ND_PRINT((ndo,"setglobal")); break;
default: ND_PRINT((ndo,"#%u", match->rpm_code)); break;
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo,",ord=%u", match->rpm_ordinal));
ND_PRINT((ndo,",min=%u", match->rpm_minlen));
ND_PRINT((ndo,",max=%u", match->rpm_maxlen));
}
if (addrtostr6(&match->rpm_prefix, hbuf, sizeof(hbuf)))
ND_PRINT((ndo,",%s/%u", hbuf, match->rpm_matchlen));
else
ND_PRINT((ndo,",?/%u", match->rpm_matchlen));
/*(*/
ND_PRINT((ndo,")"));
n = match->rpm_len - 3;
if (n % 4)
goto trunc;
n /= 4;
while (n-- > 0) {
use = (const struct rr_pco_use *)cp;
cp = (const char *)(use + 1);
ND_TCHECK(use->rpu_prefix);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo,"\n\t"));
else
ND_PRINT((ndo," "));
ND_PRINT((ndo,"use(")); /*)*/
if (use->rpu_flags) {
#define F(x, y) ((use->rpu_flags) & (x) ? (y) : "")
ND_PRINT((ndo,"%s%s,",
F(ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME, "V"),
F(ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME, "P")));
#undef F
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo,"mask=0x%x,", use->rpu_ramask));
ND_PRINT((ndo,"raflags=0x%x,", use->rpu_raflags));
if (~use->rpu_vltime == 0)
ND_PRINT((ndo,"vltime=infty,"));
else
ND_PRINT((ndo,"vltime=%u,",
EXTRACT_32BITS(&use->rpu_vltime)));
if (~use->rpu_pltime == 0)
ND_PRINT((ndo,"pltime=infty,"));
else
ND_PRINT((ndo,"pltime=%u,",
EXTRACT_32BITS(&use->rpu_pltime)));
}
if (addrtostr6(&use->rpu_prefix, hbuf, sizeof(hbuf)))
ND_PRINT((ndo,"%s/%u/%u", hbuf, use->rpu_uselen,
use->rpu_keeplen));
else
ND_PRINT((ndo,"?/%u/%u", use->rpu_uselen,
use->rpu_keeplen));
/*(*/
ND_PRINT((ndo,")"));
}
}
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2717_0 |
crossvul-cpp_data_good_2671_0 | /*
* Copyright (c) 1992, 1993, 1994, 1995, 1996
* 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: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Original code by Matt Thomas, Digital Equipment Corporation
*
* Extensively modified by Hannes Gredler (hannes@gredler.at) for more
* complete IS-IS & CLNP support.
*/
/* \summary: ISO CLNS, ESIS, and ISIS printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "ether.h"
#include "nlpid.h"
#include "extract.h"
#include "gmpls.h"
#include "oui.h"
#include "signature.h"
static const char tstr[] = " [|isis]";
/*
* IS-IS is defined in ISO 10589. Look there for protocol definitions.
*/
#define SYSTEM_ID_LEN ETHER_ADDR_LEN
#define NODE_ID_LEN SYSTEM_ID_LEN+1
#define LSP_ID_LEN SYSTEM_ID_LEN+2
#define ISIS_VERSION 1
#define ESIS_VERSION 1
#define CLNP_VERSION 1
#define ISIS_PDU_TYPE_MASK 0x1F
#define ESIS_PDU_TYPE_MASK 0x1F
#define CLNP_PDU_TYPE_MASK 0x1F
#define CLNP_FLAG_MASK 0xE0
#define ISIS_LAN_PRIORITY_MASK 0x7F
#define ISIS_PDU_L1_LAN_IIH 15
#define ISIS_PDU_L2_LAN_IIH 16
#define ISIS_PDU_PTP_IIH 17
#define ISIS_PDU_L1_LSP 18
#define ISIS_PDU_L2_LSP 20
#define ISIS_PDU_L1_CSNP 24
#define ISIS_PDU_L2_CSNP 25
#define ISIS_PDU_L1_PSNP 26
#define ISIS_PDU_L2_PSNP 27
static const struct tok isis_pdu_values[] = {
{ ISIS_PDU_L1_LAN_IIH, "L1 Lan IIH"},
{ ISIS_PDU_L2_LAN_IIH, "L2 Lan IIH"},
{ ISIS_PDU_PTP_IIH, "p2p IIH"},
{ ISIS_PDU_L1_LSP, "L1 LSP"},
{ ISIS_PDU_L2_LSP, "L2 LSP"},
{ ISIS_PDU_L1_CSNP, "L1 CSNP"},
{ ISIS_PDU_L2_CSNP, "L2 CSNP"},
{ ISIS_PDU_L1_PSNP, "L1 PSNP"},
{ ISIS_PDU_L2_PSNP, "L2 PSNP"},
{ 0, NULL}
};
/*
* A TLV is a tuple of a type, length and a value and is normally used for
* encoding information in all sorts of places. This is an enumeration of
* the well known types.
*
* list taken from rfc3359 plus some memory from veterans ;-)
*/
#define ISIS_TLV_AREA_ADDR 1 /* iso10589 */
#define ISIS_TLV_IS_REACH 2 /* iso10589 */
#define ISIS_TLV_ESNEIGH 3 /* iso10589 */
#define ISIS_TLV_PART_DIS 4 /* iso10589 */
#define ISIS_TLV_PREFIX_NEIGH 5 /* iso10589 */
#define ISIS_TLV_ISNEIGH 6 /* iso10589 */
#define ISIS_TLV_ISNEIGH_VARLEN 7 /* iso10589 */
#define ISIS_TLV_PADDING 8 /* iso10589 */
#define ISIS_TLV_LSP 9 /* iso10589 */
#define ISIS_TLV_AUTH 10 /* iso10589, rfc3567 */
#define ISIS_TLV_CHECKSUM 12 /* rfc3358 */
#define ISIS_TLV_CHECKSUM_MINLEN 2
#define ISIS_TLV_POI 13 /* rfc6232 */
#define ISIS_TLV_LSP_BUFFERSIZE 14 /* iso10589 rev2 */
#define ISIS_TLV_LSP_BUFFERSIZE_MINLEN 2
#define ISIS_TLV_EXT_IS_REACH 22 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_IS_ALIAS_ID 24 /* draft-ietf-isis-ext-lsp-frags-02 */
#define ISIS_TLV_DECNET_PHASE4 42
#define ISIS_TLV_LUCENT_PRIVATE 66
#define ISIS_TLV_INT_IP_REACH 128 /* rfc1195, rfc2966 */
#define ISIS_TLV_PROTOCOLS 129 /* rfc1195 */
#define ISIS_TLV_EXT_IP_REACH 130 /* rfc1195, rfc2966 */
#define ISIS_TLV_IDRP_INFO 131 /* rfc1195 */
#define ISIS_TLV_IDRP_INFO_MINLEN 1
#define ISIS_TLV_IPADDR 132 /* rfc1195 */
#define ISIS_TLV_IPAUTH 133 /* rfc1195 */
#define ISIS_TLV_TE_ROUTER_ID 134 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_EXTD_IP_REACH 135 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_HOSTNAME 137 /* rfc2763 */
#define ISIS_TLV_SHARED_RISK_GROUP 138 /* draft-ietf-isis-gmpls-extensions */
#define ISIS_TLV_MT_PORT_CAP 143 /* rfc6165 */
#define ISIS_TLV_MT_CAPABILITY 144 /* rfc6329 */
#define ISIS_TLV_NORTEL_PRIVATE1 176
#define ISIS_TLV_NORTEL_PRIVATE2 177
#define ISIS_TLV_RESTART_SIGNALING 211 /* rfc3847 */
#define ISIS_TLV_RESTART_SIGNALING_FLAGLEN 1
#define ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN 2
#define ISIS_TLV_MT_IS_REACH 222 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_MT_SUPPORTED 229 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_MT_SUPPORTED_MINLEN 2
#define ISIS_TLV_IP6ADDR 232 /* draft-ietf-isis-ipv6-02 */
#define ISIS_TLV_MT_IP_REACH 235 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_IP6_REACH 236 /* draft-ietf-isis-ipv6-02 */
#define ISIS_TLV_MT_IP6_REACH 237 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_PTP_ADJ 240 /* rfc3373 */
#define ISIS_TLV_IIH_SEQNR 241 /* draft-shen-isis-iih-sequence-00 */
#define ISIS_TLV_IIH_SEQNR_MINLEN 4
#define ISIS_TLV_VENDOR_PRIVATE 250 /* draft-ietf-isis-experimental-tlv-01 */
#define ISIS_TLV_VENDOR_PRIVATE_MINLEN 3
static const struct tok isis_tlv_values[] = {
{ ISIS_TLV_AREA_ADDR, "Area address(es)"},
{ ISIS_TLV_IS_REACH, "IS Reachability"},
{ ISIS_TLV_ESNEIGH, "ES Neighbor(s)"},
{ ISIS_TLV_PART_DIS, "Partition DIS"},
{ ISIS_TLV_PREFIX_NEIGH, "Prefix Neighbors"},
{ ISIS_TLV_ISNEIGH, "IS Neighbor(s)"},
{ ISIS_TLV_ISNEIGH_VARLEN, "IS Neighbor(s) (variable length)"},
{ ISIS_TLV_PADDING, "Padding"},
{ ISIS_TLV_LSP, "LSP entries"},
{ ISIS_TLV_AUTH, "Authentication"},
{ ISIS_TLV_CHECKSUM, "Checksum"},
{ ISIS_TLV_POI, "Purge Originator Identifier"},
{ ISIS_TLV_LSP_BUFFERSIZE, "LSP Buffersize"},
{ ISIS_TLV_EXT_IS_REACH, "Extended IS Reachability"},
{ ISIS_TLV_IS_ALIAS_ID, "IS Alias ID"},
{ ISIS_TLV_DECNET_PHASE4, "DECnet Phase IV"},
{ ISIS_TLV_LUCENT_PRIVATE, "Lucent Proprietary"},
{ ISIS_TLV_INT_IP_REACH, "IPv4 Internal Reachability"},
{ ISIS_TLV_PROTOCOLS, "Protocols supported"},
{ ISIS_TLV_EXT_IP_REACH, "IPv4 External Reachability"},
{ ISIS_TLV_IDRP_INFO, "Inter-Domain Information Type"},
{ ISIS_TLV_IPADDR, "IPv4 Interface address(es)"},
{ ISIS_TLV_IPAUTH, "IPv4 authentication (deprecated)"},
{ ISIS_TLV_TE_ROUTER_ID, "Traffic Engineering Router ID"},
{ ISIS_TLV_EXTD_IP_REACH, "Extended IPv4 Reachability"},
{ ISIS_TLV_SHARED_RISK_GROUP, "Shared Risk Link Group"},
{ ISIS_TLV_MT_PORT_CAP, "Multi-Topology-Aware Port Capability"},
{ ISIS_TLV_MT_CAPABILITY, "Multi-Topology Capability"},
{ ISIS_TLV_NORTEL_PRIVATE1, "Nortel Proprietary"},
{ ISIS_TLV_NORTEL_PRIVATE2, "Nortel Proprietary"},
{ ISIS_TLV_HOSTNAME, "Hostname"},
{ ISIS_TLV_RESTART_SIGNALING, "Restart Signaling"},
{ ISIS_TLV_MT_IS_REACH, "Multi Topology IS Reachability"},
{ ISIS_TLV_MT_SUPPORTED, "Multi Topology"},
{ ISIS_TLV_IP6ADDR, "IPv6 Interface address(es)"},
{ ISIS_TLV_MT_IP_REACH, "Multi-Topology IPv4 Reachability"},
{ ISIS_TLV_IP6_REACH, "IPv6 reachability"},
{ ISIS_TLV_MT_IP6_REACH, "Multi-Topology IP6 Reachability"},
{ ISIS_TLV_PTP_ADJ, "Point-to-point Adjacency State"},
{ ISIS_TLV_IIH_SEQNR, "Hello PDU Sequence Number"},
{ ISIS_TLV_VENDOR_PRIVATE, "Vendor Private"},
{ 0, NULL }
};
#define ESIS_OPTION_PROTOCOLS 129
#define ESIS_OPTION_QOS_MAINTENANCE 195 /* iso9542 */
#define ESIS_OPTION_SECURITY 197 /* iso9542 */
#define ESIS_OPTION_ES_CONF_TIME 198 /* iso9542 */
#define ESIS_OPTION_PRIORITY 205 /* iso9542 */
#define ESIS_OPTION_ADDRESS_MASK 225 /* iso9542 */
#define ESIS_OPTION_SNPA_MASK 226 /* iso9542 */
static const struct tok esis_option_values[] = {
{ ESIS_OPTION_PROTOCOLS, "Protocols supported"},
{ ESIS_OPTION_QOS_MAINTENANCE, "QoS Maintenance" },
{ ESIS_OPTION_SECURITY, "Security" },
{ ESIS_OPTION_ES_CONF_TIME, "ES Configuration Time" },
{ ESIS_OPTION_PRIORITY, "Priority" },
{ ESIS_OPTION_ADDRESS_MASK, "Addressk Mask" },
{ ESIS_OPTION_SNPA_MASK, "SNPA Mask" },
{ 0, NULL }
};
#define CLNP_OPTION_DISCARD_REASON 193
#define CLNP_OPTION_QOS_MAINTENANCE 195 /* iso8473 */
#define CLNP_OPTION_SECURITY 197 /* iso8473 */
#define CLNP_OPTION_SOURCE_ROUTING 200 /* iso8473 */
#define CLNP_OPTION_ROUTE_RECORDING 203 /* iso8473 */
#define CLNP_OPTION_PADDING 204 /* iso8473 */
#define CLNP_OPTION_PRIORITY 205 /* iso8473 */
static const struct tok clnp_option_values[] = {
{ CLNP_OPTION_DISCARD_REASON, "Discard Reason"},
{ CLNP_OPTION_PRIORITY, "Priority"},
{ CLNP_OPTION_QOS_MAINTENANCE, "QoS Maintenance"},
{ CLNP_OPTION_SECURITY, "Security"},
{ CLNP_OPTION_SOURCE_ROUTING, "Source Routing"},
{ CLNP_OPTION_ROUTE_RECORDING, "Route Recording"},
{ CLNP_OPTION_PADDING, "Padding"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_class_values[] = {
{ 0x0, "General"},
{ 0x8, "Address"},
{ 0x9, "Source Routeing"},
{ 0xa, "Lifetime"},
{ 0xb, "PDU Discarded"},
{ 0xc, "Reassembly"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_general_values[] = {
{ 0x0, "Reason not specified"},
{ 0x1, "Protocol procedure error"},
{ 0x2, "Incorrect checksum"},
{ 0x3, "PDU discarded due to congestion"},
{ 0x4, "Header syntax error (cannot be parsed)"},
{ 0x5, "Segmentation needed but not permitted"},
{ 0x6, "Incomplete PDU received"},
{ 0x7, "Duplicate option"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_address_values[] = {
{ 0x0, "Destination address unreachable"},
{ 0x1, "Destination address unknown"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_source_routeing_values[] = {
{ 0x0, "Unspecified source routeing error"},
{ 0x1, "Syntax error in source routeing field"},
{ 0x2, "Unknown address in source routeing field"},
{ 0x3, "Path not acceptable"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_lifetime_values[] = {
{ 0x0, "Lifetime expired while data unit in transit"},
{ 0x1, "Lifetime expired during reassembly"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_pdu_discard_values[] = {
{ 0x0, "Unsupported option not specified"},
{ 0x1, "Unsupported protocol version"},
{ 0x2, "Unsupported security option"},
{ 0x3, "Unsupported source routeing option"},
{ 0x4, "Unsupported recording of route option"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_reassembly_values[] = {
{ 0x0, "Reassembly interference"},
{ 0, NULL }
};
/* array of 16 error-classes */
static const struct tok *clnp_option_rfd_error_class[] = {
clnp_option_rfd_general_values,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
clnp_option_rfd_address_values,
clnp_option_rfd_source_routeing_values,
clnp_option_rfd_lifetime_values,
clnp_option_rfd_pdu_discard_values,
clnp_option_rfd_reassembly_values,
NULL,
NULL,
NULL
};
#define CLNP_OPTION_OPTION_QOS_MASK 0x3f
#define CLNP_OPTION_SCOPE_MASK 0xc0
#define CLNP_OPTION_SCOPE_SA_SPEC 0x40
#define CLNP_OPTION_SCOPE_DA_SPEC 0x80
#define CLNP_OPTION_SCOPE_GLOBAL 0xc0
static const struct tok clnp_option_scope_values[] = {
{ CLNP_OPTION_SCOPE_SA_SPEC, "Source Address Specific"},
{ CLNP_OPTION_SCOPE_DA_SPEC, "Destination Address Specific"},
{ CLNP_OPTION_SCOPE_GLOBAL, "Globally unique"},
{ 0, NULL }
};
static const struct tok clnp_option_sr_rr_values[] = {
{ 0x0, "partial"},
{ 0x1, "complete"},
{ 0, NULL }
};
static const struct tok clnp_option_sr_rr_string_values[] = {
{ CLNP_OPTION_SOURCE_ROUTING, "source routing"},
{ CLNP_OPTION_ROUTE_RECORDING, "recording of route in progress"},
{ 0, NULL }
};
static const struct tok clnp_option_qos_global_values[] = {
{ 0x20, "reserved"},
{ 0x10, "sequencing vs. delay"},
{ 0x08, "congested"},
{ 0x04, "delay vs. cost"},
{ 0x02, "error vs. delay"},
{ 0x01, "error vs. cost"},
{ 0, NULL }
};
#define ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP 3 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID 4 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID 5 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR 6 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR 8 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW 9 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW 10 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW 11 /* rfc4124 */
#define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD 12 /* draft-ietf-tewg-diff-te-proto-06 */
#define ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC 18 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE 19 /* draft-ietf-isis-link-attr-01 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE 20 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR 21 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS 22 /* rfc4124 */
#define ISIS_SUBTLV_SPB_METRIC 29 /* rfc6329 */
static const struct tok isis_ext_is_reach_subtlv_values[] = {
{ ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP, "Administrative groups" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID, "Link Local/Remote Identifier" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID, "Link Remote Identifier" },
{ ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR, "IPv4 interface address" },
{ ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR, "IPv4 neighbor address" },
{ ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW, "Maximum link bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW, "Reservable link bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW, "Unreserved bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC, "Traffic Engineering Metric" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE, "Link Attribute" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE, "Link Protection Type" },
{ ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR, "Interface Switching Capability" },
{ ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD, "Bandwidth Constraints (old)" },
{ ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS, "Bandwidth Constraints" },
{ ISIS_SUBTLV_SPB_METRIC, "SPB Metric" },
{ 250, "Reserved for cisco specific extensions" },
{ 251, "Reserved for cisco specific extensions" },
{ 252, "Reserved for cisco specific extensions" },
{ 253, "Reserved for cisco specific extensions" },
{ 254, "Reserved for cisco specific extensions" },
{ 255, "Reserved for future expansion" },
{ 0, NULL }
};
#define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32 1 /* draft-ietf-isis-admin-tags-01 */
#define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64 2 /* draft-ietf-isis-admin-tags-01 */
#define ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR 117 /* draft-ietf-isis-wg-multi-topology-05 */
static const struct tok isis_ext_ip_reach_subtlv_values[] = {
{ ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32, "32-Bit Administrative tag" },
{ ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64, "64-Bit Administrative tag" },
{ ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR, "Management Prefix Color" },
{ 0, NULL }
};
static const struct tok isis_subtlv_link_attribute_values[] = {
{ 0x01, "Local Protection Available" },
{ 0x02, "Link excluded from local protection path" },
{ 0x04, "Local maintenance required"},
{ 0, NULL }
};
#define ISIS_SUBTLV_AUTH_SIMPLE 1
#define ISIS_SUBTLV_AUTH_GENERIC 3 /* rfc 5310 */
#define ISIS_SUBTLV_AUTH_MD5 54
#define ISIS_SUBTLV_AUTH_MD5_LEN 16
#define ISIS_SUBTLV_AUTH_PRIVATE 255
static const struct tok isis_subtlv_auth_values[] = {
{ ISIS_SUBTLV_AUTH_SIMPLE, "simple text password"},
{ ISIS_SUBTLV_AUTH_GENERIC, "Generic Crypto key-id"},
{ ISIS_SUBTLV_AUTH_MD5, "HMAC-MD5 password"},
{ ISIS_SUBTLV_AUTH_PRIVATE, "Routing Domain private password"},
{ 0, NULL }
};
#define ISIS_SUBTLV_IDRP_RES 0
#define ISIS_SUBTLV_IDRP_LOCAL 1
#define ISIS_SUBTLV_IDRP_ASN 2
static const struct tok isis_subtlv_idrp_values[] = {
{ ISIS_SUBTLV_IDRP_RES, "Reserved"},
{ ISIS_SUBTLV_IDRP_LOCAL, "Routing-Domain Specific"},
{ ISIS_SUBTLV_IDRP_ASN, "AS Number Tag"},
{ 0, NULL}
};
#define ISIS_SUBTLV_SPB_MCID 4
#define ISIS_SUBTLV_SPB_DIGEST 5
#define ISIS_SUBTLV_SPB_BVID 6
#define ISIS_SUBTLV_SPB_INSTANCE 1
#define ISIS_SUBTLV_SPBM_SI 3
#define ISIS_SPB_MCID_LEN 51
#define ISIS_SUBTLV_SPB_MCID_MIN_LEN 102
#define ISIS_SUBTLV_SPB_DIGEST_MIN_LEN 33
#define ISIS_SUBTLV_SPB_BVID_MIN_LEN 6
#define ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN 19
#define ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN 8
static const struct tok isis_mt_port_cap_subtlv_values[] = {
{ ISIS_SUBTLV_SPB_MCID, "SPB MCID" },
{ ISIS_SUBTLV_SPB_DIGEST, "SPB Digest" },
{ ISIS_SUBTLV_SPB_BVID, "SPB BVID" },
{ 0, NULL }
};
static const struct tok isis_mt_capability_subtlv_values[] = {
{ ISIS_SUBTLV_SPB_INSTANCE, "SPB Instance" },
{ ISIS_SUBTLV_SPBM_SI, "SPBM Service Identifier and Unicast Address" },
{ 0, NULL }
};
struct isis_spb_mcid {
uint8_t format_id;
uint8_t name[32];
uint8_t revision_lvl[2];
uint8_t digest[16];
};
struct isis_subtlv_spb_mcid {
struct isis_spb_mcid mcid;
struct isis_spb_mcid aux_mcid;
};
struct isis_subtlv_spb_instance {
uint8_t cist_root_id[8];
uint8_t cist_external_root_path_cost[4];
uint8_t bridge_priority[2];
uint8_t spsourceid[4];
uint8_t no_of_trees;
};
#define CLNP_SEGMENT_PART 0x80
#define CLNP_MORE_SEGMENTS 0x40
#define CLNP_REQUEST_ER 0x20
static const struct tok clnp_flag_values[] = {
{ CLNP_SEGMENT_PART, "Segmentation permitted"},
{ CLNP_MORE_SEGMENTS, "more Segments"},
{ CLNP_REQUEST_ER, "request Error Report"},
{ 0, NULL}
};
#define ISIS_MASK_LSP_OL_BIT(x) ((x)&0x4)
#define ISIS_MASK_LSP_ISTYPE_BITS(x) ((x)&0x3)
#define ISIS_MASK_LSP_PARTITION_BIT(x) ((x)&0x80)
#define ISIS_MASK_LSP_ATT_BITS(x) ((x)&0x78)
#define ISIS_MASK_LSP_ATT_ERROR_BIT(x) ((x)&0x40)
#define ISIS_MASK_LSP_ATT_EXPENSE_BIT(x) ((x)&0x20)
#define ISIS_MASK_LSP_ATT_DELAY_BIT(x) ((x)&0x10)
#define ISIS_MASK_LSP_ATT_DEFAULT_BIT(x) ((x)&0x8)
#define ISIS_MASK_MTID(x) ((x)&0x0fff)
#define ISIS_MASK_MTFLAGS(x) ((x)&0xf000)
static const struct tok isis_mt_flag_values[] = {
{ 0x4000, "ATT bit set"},
{ 0x8000, "Overload bit set"},
{ 0, NULL}
};
#define ISIS_MASK_TLV_EXTD_IP_UPDOWN(x) ((x)&0x80)
#define ISIS_MASK_TLV_EXTD_IP_SUBTLV(x) ((x)&0x40)
#define ISIS_MASK_TLV_EXTD_IP6_IE(x) ((x)&0x40)
#define ISIS_MASK_TLV_EXTD_IP6_SUBTLV(x) ((x)&0x20)
#define ISIS_LSP_TLV_METRIC_SUPPORTED(x) ((x)&0x80)
#define ISIS_LSP_TLV_METRIC_IE(x) ((x)&0x40)
#define ISIS_LSP_TLV_METRIC_UPDOWN(x) ((x)&0x80)
#define ISIS_LSP_TLV_METRIC_VALUE(x) ((x)&0x3f)
#define ISIS_MASK_TLV_SHARED_RISK_GROUP(x) ((x)&0x1)
static const struct tok isis_mt_values[] = {
{ 0, "IPv4 unicast"},
{ 1, "In-Band Management"},
{ 2, "IPv6 unicast"},
{ 3, "Multicast"},
{ 4095, "Development, Experimental or Proprietary"},
{ 0, NULL }
};
static const struct tok isis_iih_circuit_type_values[] = {
{ 1, "Level 1 only"},
{ 2, "Level 2 only"},
{ 3, "Level 1, Level 2"},
{ 0, NULL}
};
#define ISIS_LSP_TYPE_UNUSED0 0
#define ISIS_LSP_TYPE_LEVEL_1 1
#define ISIS_LSP_TYPE_UNUSED2 2
#define ISIS_LSP_TYPE_LEVEL_2 3
static const struct tok isis_lsp_istype_values[] = {
{ ISIS_LSP_TYPE_UNUSED0, "Unused 0x0 (invalid)"},
{ ISIS_LSP_TYPE_LEVEL_1, "L1 IS"},
{ ISIS_LSP_TYPE_UNUSED2, "Unused 0x2 (invalid)"},
{ ISIS_LSP_TYPE_LEVEL_2, "L2 IS"},
{ 0, NULL }
};
/*
* Katz's point to point adjacency TLV uses codes to tell us the state of
* the remote adjacency. Enumerate them.
*/
#define ISIS_PTP_ADJ_UP 0
#define ISIS_PTP_ADJ_INIT 1
#define ISIS_PTP_ADJ_DOWN 2
static const struct tok isis_ptp_adjancey_values[] = {
{ ISIS_PTP_ADJ_UP, "Up" },
{ ISIS_PTP_ADJ_INIT, "Initializing" },
{ ISIS_PTP_ADJ_DOWN, "Down" },
{ 0, NULL}
};
struct isis_tlv_ptp_adj {
uint8_t adjacency_state;
uint8_t extd_local_circuit_id[4];
uint8_t neighbor_sysid[SYSTEM_ID_LEN];
uint8_t neighbor_extd_local_circuit_id[4];
};
static void osi_print_cksum(netdissect_options *, const uint8_t *pptr,
uint16_t checksum, int checksum_offset, u_int length);
static int clnp_print(netdissect_options *, const uint8_t *, u_int);
static void esis_print(netdissect_options *, const uint8_t *, u_int);
static int isis_print(netdissect_options *, const uint8_t *, u_int);
struct isis_metric_block {
uint8_t metric_default;
uint8_t metric_delay;
uint8_t metric_expense;
uint8_t metric_error;
};
struct isis_tlv_is_reach {
struct isis_metric_block isis_metric_block;
uint8_t neighbor_nodeid[NODE_ID_LEN];
};
struct isis_tlv_es_reach {
struct isis_metric_block isis_metric_block;
uint8_t neighbor_sysid[SYSTEM_ID_LEN];
};
struct isis_tlv_ip_reach {
struct isis_metric_block isis_metric_block;
uint8_t prefix[4];
uint8_t mask[4];
};
static const struct tok isis_is_reach_virtual_values[] = {
{ 0, "IsNotVirtual"},
{ 1, "IsVirtual"},
{ 0, NULL }
};
static const struct tok isis_restart_flag_values[] = {
{ 0x1, "Restart Request"},
{ 0x2, "Restart Acknowledgement"},
{ 0x4, "Suppress adjacency advertisement"},
{ 0, NULL }
};
struct isis_common_header {
uint8_t nlpid;
uint8_t fixed_len;
uint8_t version; /* Protocol version */
uint8_t id_length;
uint8_t pdu_type; /* 3 MSbits are reserved */
uint8_t pdu_version; /* Packet format version */
uint8_t reserved;
uint8_t max_area;
};
struct isis_iih_lan_header {
uint8_t circuit_type;
uint8_t source_id[SYSTEM_ID_LEN];
uint8_t holding_time[2];
uint8_t pdu_len[2];
uint8_t priority;
uint8_t lan_id[NODE_ID_LEN];
};
struct isis_iih_ptp_header {
uint8_t circuit_type;
uint8_t source_id[SYSTEM_ID_LEN];
uint8_t holding_time[2];
uint8_t pdu_len[2];
uint8_t circuit_id;
};
struct isis_lsp_header {
uint8_t pdu_len[2];
uint8_t remaining_lifetime[2];
uint8_t lsp_id[LSP_ID_LEN];
uint8_t sequence_number[4];
uint8_t checksum[2];
uint8_t typeblock;
};
struct isis_csnp_header {
uint8_t pdu_len[2];
uint8_t source_id[NODE_ID_LEN];
uint8_t start_lsp_id[LSP_ID_LEN];
uint8_t end_lsp_id[LSP_ID_LEN];
};
struct isis_psnp_header {
uint8_t pdu_len[2];
uint8_t source_id[NODE_ID_LEN];
};
struct isis_tlv_lsp {
uint8_t remaining_lifetime[2];
uint8_t lsp_id[LSP_ID_LEN];
uint8_t sequence_number[4];
uint8_t checksum[2];
};
#define ISIS_COMMON_HEADER_SIZE (sizeof(struct isis_common_header))
#define ISIS_IIH_LAN_HEADER_SIZE (sizeof(struct isis_iih_lan_header))
#define ISIS_IIH_PTP_HEADER_SIZE (sizeof(struct isis_iih_ptp_header))
#define ISIS_LSP_HEADER_SIZE (sizeof(struct isis_lsp_header))
#define ISIS_CSNP_HEADER_SIZE (sizeof(struct isis_csnp_header))
#define ISIS_PSNP_HEADER_SIZE (sizeof(struct isis_psnp_header))
void
isoclns_print(netdissect_options *ndo, const uint8_t *p, u_int length)
{
if (!ND_TTEST(*p)) { /* enough bytes on the wire ? */
ND_PRINT((ndo, "|OSI"));
return;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p));
switch (*p) {
case NLPID_CLNP:
if (!clnp_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_ESIS:
esis_print(ndo, p, length);
return;
case NLPID_ISIS:
if (!isis_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_NULLNS:
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
break;
case NLPID_Q933:
q933_print(ndo, p + 1, length - 1);
break;
case NLPID_IP:
ip_print(ndo, p + 1, length - 1);
break;
case NLPID_IP6:
ip6_print(ndo, p + 1, length - 1);
break;
case NLPID_PPP:
ppp_print(ndo, p + 1, length - 1);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p));
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
if (length > 1)
print_unknown_data(ndo, p, "\n\t", length);
break;
}
}
#define CLNP_PDU_ER 1
#define CLNP_PDU_DT 28
#define CLNP_PDU_MD 29
#define CLNP_PDU_ERQ 30
#define CLNP_PDU_ERP 31
static const struct tok clnp_pdu_values[] = {
{ CLNP_PDU_ER, "Error Report"},
{ CLNP_PDU_MD, "MD"},
{ CLNP_PDU_DT, "Data"},
{ CLNP_PDU_ERQ, "Echo Request"},
{ CLNP_PDU_ERP, "Echo Response"},
{ 0, NULL }
};
struct clnp_header_t {
uint8_t nlpid;
uint8_t length_indicator;
uint8_t version;
uint8_t lifetime; /* units of 500ms */
uint8_t type;
uint8_t segment_length[2];
uint8_t cksum[2];
};
struct clnp_segment_header_t {
uint8_t data_unit_id[2];
uint8_t segment_offset[2];
uint8_t total_length[2];
};
/*
* clnp_print
* Decode CLNP packets. Return 0 on error.
*/
static int
clnp_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr,*source_address,*dest_address;
u_int li,tlen,nsap_offset,source_address_length,dest_address_length, clnp_pdu_type, clnp_flags;
const struct clnp_header_t *clnp_header;
const struct clnp_segment_header_t *clnp_segment_header;
uint8_t rfd_error_major,rfd_error_minor;
clnp_header = (const struct clnp_header_t *) pptr;
ND_TCHECK(*clnp_header);
li = clnp_header->length_indicator;
optr = pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "CLNP"));
/*
* Sanity checking of the header.
*/
if (clnp_header->version != CLNP_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", clnp_header->version));
return (0);
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return (0);
}
if (li < sizeof(struct clnp_header_t)) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return (0);
}
/* FIXME further header sanity checking */
clnp_pdu_type = clnp_header->type & CLNP_PDU_TYPE_MASK;
clnp_flags = clnp_header->type & CLNP_FLAG_MASK;
pptr += sizeof(struct clnp_header_t);
li -= sizeof(struct clnp_header_t);
if (li < 1) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK(*pptr);
dest_address_length = *pptr;
pptr += 1;
li -= 1;
if (li < dest_address_length) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK2(*pptr, dest_address_length);
dest_address = pptr;
pptr += dest_address_length;
li -= dest_address_length;
if (li < 1) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK(*pptr);
source_address_length = *pptr;
pptr += 1;
li -= 1;
if (li < source_address_length) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK2(*pptr, source_address_length);
source_address = pptr;
pptr += source_address_length;
li -= source_address_length;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s > %s, %s, length %u",
ndo->ndo_eflag ? "" : ", ",
isonsap_string(ndo, source_address, source_address_length),
isonsap_string(ndo, dest_address, dest_address_length),
tok2str(clnp_pdu_values,"unknown (%u)",clnp_pdu_type),
length));
return (1);
}
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s PDU, hlen: %u, v: %u, lifetime: %u.%us, Segment PDU length: %u, checksum: 0x%04x",
tok2str(clnp_pdu_values, "unknown (%u)",clnp_pdu_type),
clnp_header->length_indicator,
clnp_header->version,
clnp_header->lifetime/2,
(clnp_header->lifetime%2)*5,
EXTRACT_16BITS(clnp_header->segment_length),
EXTRACT_16BITS(clnp_header->cksum)));
osi_print_cksum(ndo, optr, EXTRACT_16BITS(clnp_header->cksum), 7,
clnp_header->length_indicator);
ND_PRINT((ndo, "\n\tFlags [%s]",
bittok2str(clnp_flag_values, "none", clnp_flags)));
ND_PRINT((ndo, "\n\tsource address (length %u): %s\n\tdest address (length %u): %s",
source_address_length,
isonsap_string(ndo, source_address, source_address_length),
dest_address_length,
isonsap_string(ndo, dest_address, dest_address_length)));
if (clnp_flags & CLNP_SEGMENT_PART) {
if (li < sizeof(const struct clnp_segment_header_t)) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header, addresses, and segment part"));
return (0);
}
clnp_segment_header = (const struct clnp_segment_header_t *) pptr;
ND_TCHECK(*clnp_segment_header);
ND_PRINT((ndo, "\n\tData Unit ID: 0x%04x, Segment Offset: %u, Total PDU Length: %u",
EXTRACT_16BITS(clnp_segment_header->data_unit_id),
EXTRACT_16BITS(clnp_segment_header->segment_offset),
EXTRACT_16BITS(clnp_segment_header->total_length)));
pptr+=sizeof(const struct clnp_segment_header_t);
li-=sizeof(const struct clnp_segment_header_t);
}
/* now walk the options */
while (li >= 2) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return (0);
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return (0);
}
ND_TCHECK2(*pptr, opli);
li -= opli;
tptr = pptr;
tlen = opli;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(clnp_option_values,"Unknown",op),
op,
opli));
/*
* We've already checked that the entire option is present
* in the captured packet with the ND_TCHECK2() call.
* Therefore, we don't need to do ND_TCHECK()/ND_TCHECK2()
* checks.
* We do, however, need to check tlen, to make sure we
* don't run past the end of the option.
*/
switch (op) {
case CLNP_OPTION_ROUTE_RECORDING: /* those two options share the format */
case CLNP_OPTION_SOURCE_ROUTING:
if (tlen < 2) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "%s %s",
tok2str(clnp_option_sr_rr_values,"Unknown",*tptr),
tok2str(clnp_option_sr_rr_string_values, "Unknown Option %u", op)));
nsap_offset=*(tptr+1);
if (nsap_offset == 0) {
ND_PRINT((ndo, " Bad NSAP offset (0)"));
break;
}
nsap_offset-=1; /* offset to nsap list */
if (nsap_offset > tlen) {
ND_PRINT((ndo, " Bad NSAP offset (past end of option)"));
break;
}
tptr+=nsap_offset;
tlen-=nsap_offset;
while (tlen > 0) {
source_address_length=*tptr;
if (tlen < source_address_length+1) {
ND_PRINT((ndo, "\n\t NSAP address goes past end of option"));
break;
}
if (source_address_length > 0) {
source_address=(tptr+1);
ND_TCHECK2(*source_address, source_address_length);
ND_PRINT((ndo, "\n\t NSAP address (length %u): %s",
source_address_length,
isonsap_string(ndo, source_address, source_address_length)));
}
tlen-=source_address_length+1;
}
break;
case CLNP_OPTION_PRIORITY:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "0x%1x", *tptr&0x0f));
break;
case CLNP_OPTION_QOS_MAINTENANCE:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "\n\t Format Code: %s",
tok2str(clnp_option_scope_values, "Reserved", *tptr&CLNP_OPTION_SCOPE_MASK)));
if ((*tptr&CLNP_OPTION_SCOPE_MASK) == CLNP_OPTION_SCOPE_GLOBAL)
ND_PRINT((ndo, "\n\t QoS Flags [%s]",
bittok2str(clnp_option_qos_global_values,
"none",
*tptr&CLNP_OPTION_OPTION_QOS_MASK)));
break;
case CLNP_OPTION_SECURITY:
if (tlen < 2) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "\n\t Format Code: %s, Security-Level %u",
tok2str(clnp_option_scope_values,"Reserved",*tptr&CLNP_OPTION_SCOPE_MASK),
*(tptr+1)));
break;
case CLNP_OPTION_DISCARD_REASON:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
rfd_error_major = (*tptr&0xf0) >> 4;
rfd_error_minor = *tptr&0x0f;
ND_PRINT((ndo, "\n\t Class: %s Error (0x%01x), %s (0x%01x)",
tok2str(clnp_option_rfd_class_values,"Unknown",rfd_error_major),
rfd_error_major,
tok2str(clnp_option_rfd_error_class[rfd_error_major],"Unknown",rfd_error_minor),
rfd_error_minor));
break;
case CLNP_OPTION_PADDING:
ND_PRINT((ndo, "padding data"));
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
switch (clnp_pdu_type) {
case CLNP_PDU_ER: /* fall through */
case CLNP_PDU_ERP:
ND_TCHECK(*pptr);
if (*(pptr) == NLPID_CLNP) {
ND_PRINT((ndo, "\n\t-----original packet-----\n\t"));
/* FIXME recursion protection */
clnp_print(ndo, pptr, length - clnp_header->length_indicator);
break;
}
case CLNP_PDU_DT:
case CLNP_PDU_MD:
case CLNP_PDU_ERQ:
default:
/* dump the PDU specific data */
if (length-(pptr-optr) > 0) {
ND_PRINT((ndo, "\n\t undecoded non-header data, length %u", length-clnp_header->length_indicator));
print_unknown_data(ndo, pptr, "\n\t ", length - (pptr - optr));
}
}
return (1);
trunc:
ND_PRINT((ndo, "[|clnp]"));
return (1);
}
#define ESIS_PDU_REDIRECT 6
#define ESIS_PDU_ESH 2
#define ESIS_PDU_ISH 4
static const struct tok esis_pdu_values[] = {
{ ESIS_PDU_REDIRECT, "redirect"},
{ ESIS_PDU_ESH, "ESH"},
{ ESIS_PDU_ISH, "ISH"},
{ 0, NULL }
};
struct esis_header_t {
uint8_t nlpid;
uint8_t length_indicator;
uint8_t version;
uint8_t reserved;
uint8_t type;
uint8_t holdtime[2];
uint8_t cksum[2];
};
static void
esis_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr;
u_int li,esis_pdu_type,source_address_length, source_address_number;
const struct esis_header_t *esis_header;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "ES-IS"));
if (length <= 2) {
ND_PRINT((ndo, ndo->ndo_qflag ? "bad pkt!" : "no header at all!"));
return;
}
esis_header = (const struct esis_header_t *) pptr;
ND_TCHECK(*esis_header);
li = esis_header->length_indicator;
optr = pptr;
/*
* Sanity checking of the header.
*/
if (esis_header->nlpid != NLPID_ESIS) {
ND_PRINT((ndo, " nlpid 0x%02x packet not supported", esis_header->nlpid));
return;
}
if (esis_header->version != ESIS_VERSION) {
ND_PRINT((ndo, " version %d packet not supported", esis_header->version));
return;
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return;
}
if (li < sizeof(struct esis_header_t) + 2) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return;
}
esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s, length %u",
ndo->ndo_eflag ? "" : ", ",
tok2str(esis_pdu_values,"unknown type (%u)",esis_pdu_type),
length));
return;
} else
ND_PRINT((ndo, "%slength %u\n\t%s (%u)",
ndo->ndo_eflag ? "" : ", ",
length,
tok2str(esis_pdu_values,"unknown type: %u", esis_pdu_type),
esis_pdu_type));
ND_PRINT((ndo, ", v: %u%s", esis_header->version, esis_header->version == ESIS_VERSION ? "" : "unsupported" ));
ND_PRINT((ndo, ", checksum: 0x%04x", EXTRACT_16BITS(esis_header->cksum)));
osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li);
ND_PRINT((ndo, ", holding time: %us, length indicator: %u",
EXTRACT_16BITS(esis_header->holdtime), li));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, optr, "\n\t", sizeof(struct esis_header_t));
pptr += sizeof(struct esis_header_t);
li -= sizeof(struct esis_header_t);
switch (esis_pdu_type) {
case ESIS_PDU_REDIRECT: {
const uint8_t *dst, *snpa, *neta;
u_int dstl, snpal, netal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dstl = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, dstl);
if (li < dstl) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dst = pptr;
pptr += dstl;
li -= dstl;
ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, dst, dstl)));
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpal = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, snpal);
if (li < snpal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpa = pptr;
pptr += snpal;
li -= snpal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
netal = *pptr;
pptr++;
ND_TCHECK2(*pptr, netal);
if (li < netal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
neta = pptr;
pptr += netal;
li -= netal;
if (netal == 0)
ND_PRINT((ndo, "\n\t %s", etheraddr_string(ndo, snpa)));
else
ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, neta, netal)));
break;
}
case ESIS_PDU_ESH:
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_number = *pptr;
pptr++;
li--;
ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number));
while (source_address_number > 0) {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s",
source_address_length,
isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
source_address_number--;
}
break;
case ESIS_PDU_ISH: {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
break;
}
default:
if (ndo->ndo_vflag <= 1) {
if (pptr < ndo->ndo_snapend)
print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr);
}
return;
}
/* now walk the options */
while (li != 0) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return;
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return;
}
li -= opli;
tptr = pptr;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(esis_option_values,"Unknown",op),
op,
opli));
switch (op) {
case ESIS_OPTION_ES_CONF_TIME:
if (opli == 2) {
ND_TCHECK2(*pptr, 2);
ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr)));
} else
ND_PRINT((ndo, "(bad length)"));
break;
case ESIS_OPTION_PROTOCOLS:
while (opli>0) {
ND_TCHECK(*pptr);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (opli>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
opli--;
}
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
case ESIS_OPTION_QOS_MAINTENANCE:
case ESIS_OPTION_SECURITY:
case ESIS_OPTION_PRIORITY:
case ESIS_OPTION_ADDRESS_MASK:
case ESIS_OPTION_SNPA_MASK:
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
trunc:
return;
}
static void
isis_print_mcid(netdissect_options *ndo,
const struct isis_spb_mcid *mcid)
{
int i;
ND_TCHECK(*mcid);
ND_PRINT((ndo, "ID: %d, Name: ", mcid->format_id));
if (fn_printzp(ndo, mcid->name, 32, ndo->ndo_snapend))
goto trunc;
ND_PRINT((ndo, "\n\t Lvl: %d", EXTRACT_16BITS(mcid->revision_lvl)));
ND_PRINT((ndo, ", Digest: "));
for(i=0;i<16;i++)
ND_PRINT((ndo, "%.2x ", mcid->digest[i]));
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static int
isis_print_mt_port_cap_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len;
const struct isis_subtlv_spb_mcid *subtlv_spb_mcid;
int i;
while (len > 2)
{
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
/*len -= TLV_TYPE_LEN_OFFSET;*/
len = len -2;
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_MCID:
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_MCID_MIN_LEN);
subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr;
ND_PRINT((ndo, "\n\t MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
ND_PRINT((ndo, "\n\t AUX-MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
tptr = tptr + sizeof(struct isis_subtlv_spb_mcid);
len = len - sizeof(struct isis_subtlv_spb_mcid);
break;
}
case ISIS_SUBTLV_SPB_DIGEST:
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_DIGEST_MIN_LEN);
ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d",
(*(tptr) >> 5), (((*tptr)>> 4) & 0x01),
((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03)));
tptr++;
ND_PRINT((ndo, "\n\t Digest: "));
for(i=1;i<=8; i++)
{
ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr)));
if (i%4 == 0 && i != 8)
ND_PRINT((ndo, "\n\t "));
tptr = tptr + 4;
}
len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_BVID:
{
ND_TCHECK2(*(tptr), stlv_len);
while (len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN)
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_BVID_MIN_LEN);
ND_PRINT((ndo, "\n\t ECT: %08x",
EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ",
(EXTRACT_16BITS (tptr) >> 4) ,
(EXTRACT_16BITS (tptr) >> 3) & 0x01,
(EXTRACT_16BITS (tptr) >> 2) & 0x01));
tptr = tptr + 2;
len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
}
break;
}
default:
break;
}
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
static int
isis_print_mt_capability_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len, tmp;
while (len > 2)
{
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
len = len - 2;
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_INSTANCE:
ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN);
ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr)));
tptr = tptr + 2;
ND_PRINT((ndo, "\n\t RES: %d",
EXTRACT_16BITS(tptr) >> 5));
ND_PRINT((ndo, ", V: %d",
(EXTRACT_16BITS(tptr) >> 4) & 0x0001));
ND_PRINT((ndo, ", SPSource-ID: %d",
(EXTRACT_32BITS(tptr) & 0x000fffff)));
tptr = tptr+4;
ND_PRINT((ndo, ", No of Trees: %x", *(tptr)));
tmp = *(tptr++);
len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;
while (tmp)
{
ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN);
ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d",
*(tptr) >> 7, (*(tptr) >> 6) & 0x01,
(*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f)));
tptr++;
ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr + 4;
ND_PRINT((ndo, ", BVID: %d, SPVID: %d",
(EXTRACT_24BITS(tptr) >> 12) & 0x000fff,
EXTRACT_24BITS(tptr) & 0x000fff));
tptr = tptr + 3;
len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;
tmp--;
}
break;
case ISIS_SUBTLV_SPBM_SI:
ND_TCHECK2(*tptr, 8);
ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr)));
tptr = tptr+2;
ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12,
(EXTRACT_16BITS(tptr)) & 0x0fff));
tptr = tptr+2;
len = len - 8;
stlv_len = stlv_len - 8;
while (stlv_len >= 4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d",
(EXTRACT_32BITS(tptr) >> 31),
(EXTRACT_32BITS(tptr) >> 30) & 0x01,
(EXTRACT_32BITS(tptr) >> 24) & 0x03f,
(EXTRACT_32BITS(tptr)) & 0x0ffffff));
tptr = tptr + 4;
len = len - 4;
stlv_len = stlv_len - 4;
}
break;
default:
break;
}
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
/* shared routine for printing system, node and lsp-ids */
static char *
isis_print_id(const uint8_t *cp, int id_len)
{
int i;
static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")];
char *pos = id;
for (i = 1; i <= SYSTEM_ID_LEN; i++) {
snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++);
pos += strlen(pos);
if (i == 2 || i == 4)
*pos++ = '.';
}
if (id_len >= NODE_ID_LEN) {
snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++);
pos += strlen(pos);
}
if (id_len == LSP_ID_LEN)
snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp);
return (id);
}
/* print the 4-byte metric block which is common found in the old-style TLVs */
static int
isis_print_metric_block(netdissect_options *ndo,
const struct isis_metric_block *isis_metric_block)
{
ND_PRINT((ndo, ", Default Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_default),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_delay))
ND_PRINT((ndo, "\n\t\t Delay Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_delay),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_expense))
ND_PRINT((ndo, "\n\t\t Expense Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_expense),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_error))
ND_PRINT((ndo, "\n\t\t Error Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_error),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_error) ? "External" : "Internal"));
return(1); /* everything is ok */
}
static int
isis_print_tlv_ip_reach(netdissect_options *ndo,
const uint8_t *cp, const char *ident, int length)
{
int prefix_len;
const struct isis_tlv_ip_reach *tlv_ip_reach;
tlv_ip_reach = (const struct isis_tlv_ip_reach *)cp;
while (length > 0) {
if ((size_t)length < sizeof(*tlv_ip_reach)) {
ND_PRINT((ndo, "short IPv4 Reachability (%d vs %lu)",
length,
(unsigned long)sizeof(*tlv_ip_reach)));
return (0);
}
if (!ND_TTEST(*tlv_ip_reach))
return (0);
prefix_len = mask2plen(EXTRACT_32BITS(tlv_ip_reach->mask));
if (prefix_len == -1)
ND_PRINT((ndo, "%sIPv4 prefix: %s mask %s",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
ipaddr_string(ndo, (tlv_ip_reach->mask))));
else
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
prefix_len));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u, %s",
ISIS_LSP_TLV_METRIC_UPDOWN(tlv_ip_reach->isis_metric_block.metric_default) ? "down" : "up",
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_default),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_delay))
ND_PRINT((ndo, "%s Delay Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_delay),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_expense))
ND_PRINT((ndo, "%s Expense Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_expense),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_error))
ND_PRINT((ndo, "%s Error Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_error),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_error) ? "External" : "Internal"));
length -= sizeof(struct isis_tlv_ip_reach);
tlv_ip_reach++;
}
return (1);
}
/*
* this is the common IP-REACH subTLV decoder it is called
* from various EXTD-IP REACH TLVs (135,235,236,237)
*/
static int
isis_print_ip_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int subt, int subl,
const char *ident)
{
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_ip_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr,subl);
switch(subt) {
case ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR: /* fall through */
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32:
while (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x (=%u)",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr)));
tptr+=4;
subl-=4;
}
break;
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64:
while (subl >= 8) {
ND_PRINT((ndo, ", 0x%08x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr+4)));
tptr+=8;
subl-=8;
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
ND_PRINT((ndo, "%s", ident));
ND_PRINT((ndo, "%s", tstr));
return(0);
}
/*
* this is the common IS-REACH subTLV decoder it is called
* from isis_print_ext_is_reach()
*/
static int
isis_print_is_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, u_int subt, u_int subl,
const char *ident)
{
u_int te_class,priority_level,gmpls_switch_cap;
union { /* int to float conversion buffer for several subTLVs */
float f;
uint32_t i;
} bw;
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr, subl);
switch(subt) {
case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID:
if (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr)));
if (subl == 8) /* rfc4205 */
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR:
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR:
if (subl >= sizeof(struct in_addr))
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW :
case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW:
if (subl >= 4) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW :
if (subl >= 32) {
for (te_class = 0; te_class < 8; te_class++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD:
ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)",
ident,
tok2str(diffserv_te_bc_values, "unknown", *tptr),
*tptr));
tptr++;
/* decode BCs until the subTLV ends */
for (te_class = 0; te_class < (subl-1)/4; te_class++) {
ND_TCHECK2(*tptr, 4);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC:
if (subl >= 3)
ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE:
if (subl == 2) {
ND_PRINT((ndo, ", [ %s ] (0x%04x)",
bittok2str(isis_subtlv_link_attribute_values,
"Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE:
if (subl >= 2) {
ND_PRINT((ndo, ", %s, Priority %u",
bittok2str(gmpls_link_prot_values, "none", *tptr),
*(tptr+1)));
}
break;
case ISIS_SUBTLV_SPB_METRIC:
if (subl >= 6) {
ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr)));
tptr=tptr+3;
ND_PRINT((ndo, ", P: %u", *(tptr)));
tptr++;
ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR:
if (subl >= 36) {
gmpls_switch_cap = *tptr;
ND_PRINT((ndo, "%s Interface Switching Capability:%s",
ident,
tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap)));
ND_PRINT((ndo, ", LSP Encoding: %s",
tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1))));
tptr+=4;
ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident));
for (priority_level = 0; priority_level < 8; priority_level++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s priority level %d: %.3f Mbps",
ident,
priority_level,
bw.f * 8 / 1000000));
tptr+=4;
}
subl-=36;
switch (gmpls_switch_cap) {
case GMPLS_PSC1:
case GMPLS_PSC2:
case GMPLS_PSC3:
case GMPLS_PSC4:
ND_TCHECK2(*tptr, 6);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4)));
break;
case GMPLS_TSC:
ND_TCHECK2(*tptr, 8);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Indication %s", ident,
tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4))));
break;
default:
/* there is some optional stuff left to decode but this is as of yet
not specified so just lets hexdump what is left */
if(subl>0){
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
}
}
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
return(0);
}
/*
* this is the common IS-REACH decoder it is called
* from various EXTD-IS REACH style TLVs (22,24,222)
*/
static int
isis_print_ext_is_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, int tlv_type)
{
char ident_buffer[20];
int subtlv_type,subtlv_len,subtlv_sum_len;
int proc_bytes = 0; /* how many bytes did we process ? */
if (!ND_TTEST2(*tptr, NODE_ID_LEN))
return(0);
ND_PRINT((ndo, "%sIS Neighbor: %s", ident, isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
if (tlv_type != ISIS_TLV_IS_ALIAS_ID) { /* the Alias TLV Metric field is implicit 0 */
if (!ND_TTEST2(*tptr, 3)) /* and is therefore skipped */
return(0);
ND_PRINT((ndo, ", Metric: %d", EXTRACT_24BITS(tptr)));
tptr+=3;
}
if (!ND_TTEST2(*tptr, 1))
return(0);
subtlv_sum_len=*(tptr++); /* read out subTLV length */
proc_bytes=NODE_ID_LEN+3+1;
ND_PRINT((ndo, ", %ssub-TLVs present",subtlv_sum_len ? "" : "no "));
if (subtlv_sum_len) {
ND_PRINT((ndo, " (%u)", subtlv_sum_len));
while (subtlv_sum_len>0) {
if (!ND_TTEST2(*tptr,2))
return(0);
subtlv_type=*(tptr++);
subtlv_len=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_is_reach_subtlv(ndo, tptr, subtlv_type, subtlv_len, ident_buffer))
return(0);
tptr+=subtlv_len;
subtlv_sum_len-=(subtlv_len+2);
proc_bytes+=(subtlv_len+2);
}
}
return(proc_bytes);
}
/*
* this is the common Multi Topology ID decoder
* it is called from various MT-TLVs (222,229,235,237)
*/
static int
isis_print_mtid(netdissect_options *ndo,
const uint8_t *tptr, const char *ident)
{
if (!ND_TTEST2(*tptr, 2))
return(0);
ND_PRINT((ndo, "%s%s",
ident,
tok2str(isis_mt_values,
"Reserved for IETF Consensus",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)))));
ND_PRINT((ndo, " Topology (0x%03x), Flags: [%s]",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)),
bittok2str(isis_mt_flag_values, "none",ISIS_MASK_MTFLAGS(EXTRACT_16BITS(tptr)))));
return(2);
}
/*
* this is the common extended IP reach decoder
* it is called from TLVs (135,235,236,237)
* we process the TLV and optional subTLVs and return
* the amount of processed bytes
*/
static int
isis_print_extd_ip_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, uint16_t afi)
{
char ident_buffer[20];
uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */
u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen;
if (!ND_TTEST2(*tptr, 4))
return (0);
metric = EXTRACT_32BITS(tptr);
processed=4;
tptr+=4;
if (afi == AF_INET) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */
return (0);
status_byte=*(tptr++);
bit_length = status_byte&0x3f;
if (bit_length > 32) {
ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed++;
} else if (afi == AF_INET6) {
if (!ND_TTEST2(*tptr, 2)) /* fetch status & prefix_len byte */
return (0);
status_byte=*(tptr++);
bit_length=*(tptr++);
if (bit_length > 128) {
ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed+=2;
} else
return (0); /* somebody is fooling us */
byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */
if (!ND_TTEST2(*tptr, byte_length))
return (0);
memset(prefix, 0, sizeof prefix); /* clear the copy buffer */
memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */
tptr+=byte_length;
processed+=byte_length;
if (afi == AF_INET)
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, prefix),
bit_length));
else if (afi == AF_INET6)
ND_PRINT((ndo, "%sIPv6 prefix: %s/%u",
ident,
ip6addr_string(ndo, prefix),
bit_length));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u",
ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up",
metric));
if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
ND_PRINT((ndo, ", sub-TLVs present"));
else if (afi == AF_INET6)
ND_PRINT((ndo, ", %s%s",
ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal",
ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : ""));
if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
|| (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte))
) {
/* assume that one prefix can hold more
than one subTLV - therefore the first byte must reflect
the aggregate bytecount of the subTLVs for this prefix
*/
if (!ND_TTEST2(*tptr, 1))
return (0);
sublen=*(tptr++);
processed+=sublen+1;
ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */
while (sublen>0) {
if (!ND_TTEST2(*tptr,2))
return (0);
subtlvtype=*(tptr++);
subtlvlen=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer))
return(0);
tptr+=subtlvlen;
sublen-=(subtlvlen+2);
}
}
return (processed);
}
/*
* Clear checksum and lifetime prior to signature verification.
*/
static void
isis_clear_checksum_lifetime(void *header)
{
struct isis_lsp_header *header_lsp = (struct isis_lsp_header *) header;
header_lsp->checksum[0] = 0;
header_lsp->checksum[1] = 0;
header_lsp->remaining_lifetime[0] = 0;
header_lsp->remaining_lifetime[1] = 0;
}
/*
* isis_print
* Decode IS-IS packets. Return 0 on error.
*/
static int
isis_print(netdissect_options *ndo,
const uint8_t *p, u_int length)
{
const struct isis_common_header *isis_header;
const struct isis_iih_lan_header *header_iih_lan;
const struct isis_iih_ptp_header *header_iih_ptp;
const struct isis_lsp_header *header_lsp;
const struct isis_csnp_header *header_csnp;
const struct isis_psnp_header *header_psnp;
const struct isis_tlv_lsp *tlv_lsp;
const struct isis_tlv_ptp_adj *tlv_ptp_adj;
const struct isis_tlv_is_reach *tlv_is_reach;
const struct isis_tlv_es_reach *tlv_es_reach;
uint8_t pdu_type, max_area, id_length, tlv_type, tlv_len, tmp, alen, lan_alen, prefix_len;
uint8_t ext_is_len, ext_ip_len, mt_len;
const uint8_t *optr, *pptr, *tptr;
u_short packet_len,pdu_len, key_id;
u_int i,vendor_id;
int sigcheck;
packet_len=length;
optr = p; /* initialize the _o_riginal pointer to the packet start -
need it for parsing the checksum TLV and authentication
TLV verification */
isis_header = (const struct isis_common_header *)p;
ND_TCHECK(*isis_header);
if (length < ISIS_COMMON_HEADER_SIZE)
goto trunc;
pptr = p+(ISIS_COMMON_HEADER_SIZE);
header_iih_lan = (const struct isis_iih_lan_header *)pptr;
header_iih_ptp = (const struct isis_iih_ptp_header *)pptr;
header_lsp = (const struct isis_lsp_header *)pptr;
header_csnp = (const struct isis_csnp_header *)pptr;
header_psnp = (const struct isis_psnp_header *)pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "IS-IS"));
/*
* Sanity checking of the header.
*/
if (isis_header->version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->version));
return (0);
}
if ((isis_header->id_length != SYSTEM_ID_LEN) && (isis_header->id_length != 0)) {
ND_PRINT((ndo, "system ID length of %d is not supported",
isis_header->id_length));
return (0);
}
if (isis_header->pdu_version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->pdu_version));
return (0);
}
if (length < isis_header->fixed_len) {
ND_PRINT((ndo, "fixed header length %u > packet length %u", isis_header->fixed_len, length));
return (0);
}
if (isis_header->fixed_len < ISIS_COMMON_HEADER_SIZE) {
ND_PRINT((ndo, "fixed header length %u < minimum header size %u", isis_header->fixed_len, (u_int)ISIS_COMMON_HEADER_SIZE));
return (0);
}
max_area = isis_header->max_area;
switch(max_area) {
case 0:
max_area = 3; /* silly shit */
break;
case 255:
ND_PRINT((ndo, "bad packet -- 255 areas"));
return (0);
default:
break;
}
id_length = isis_header->id_length;
switch(id_length) {
case 0:
id_length = 6; /* silly shit again */
break;
case 1: /* 1-8 are valid sys-ID lenghts */
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
break;
case 255:
id_length = 0; /* entirely useless */
break;
default:
break;
}
/* toss any non 6-byte sys-ID len PDUs */
if (id_length != 6 ) {
ND_PRINT((ndo, "bad packet -- illegal sys-ID length (%u)", id_length));
return (0);
}
pdu_type=isis_header->pdu_type;
/* in non-verbose mode print the basic PDU Type plus PDU specific brief information*/
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, "%s%s",
ndo->ndo_eflag ? "" : ", ",
tok2str(isis_pdu_values, "unknown PDU-Type %u", pdu_type)));
} else {
/* ok they seem to want to know everything - lets fully decode it */
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s, hlen: %u, v: %u, pdu-v: %u, sys-id-len: %u (%u), max-area: %u (%u)",
tok2str(isis_pdu_values,
"unknown, type %u",
pdu_type),
isis_header->fixed_len,
isis_header->version,
isis_header->pdu_version,
id_length,
isis_header->id_length,
max_area,
isis_header->max_area));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, optr, "\n\t", 8)) /* provide the _o_riginal pointer */
return (0); /* for optionally debugging the common header */
}
}
switch (pdu_type) {
case ISIS_PDU_L1_LAN_IIH:
case ISIS_PDU_L2_LAN_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_lan);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s",
isis_print_id(header_iih_lan->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", lan-id %s, prio %u",
isis_print_id(header_iih_lan->lan_id,NODE_ID_LEN),
header_iih_lan->priority));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_lan->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_lan->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_lan->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_lan->circuit_type)));
ND_PRINT((ndo, "\n\t lan-id: %s, Priority: %u, PDU length: %u",
isis_print_id(header_iih_lan->lan_id, NODE_ID_LEN),
(header_iih_lan->priority) & ISIS_LAN_PRIORITY_MASK,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_LAN_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
break;
case ISIS_PDU_PTP_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_ptp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_ptp->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_ptp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_ptp->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_ptp->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_ptp->circuit_type)));
ND_PRINT((ndo, "\n\t circuit-id: 0x%02x, PDU length: %u",
header_iih_ptp->circuit_id,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_PTP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
break;
case ISIS_PDU_L1_LSP:
case ISIS_PDU_L2_LSP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)ISIS_LSP_HEADER_SIZE));
return (0);
}
ND_TCHECK(*header_lsp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", lsp-id %s, seq 0x%08x, lifetime %5us",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_lsp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t lsp-id: %s, seq: 0x%08x, lifetime: %5us\n\t chksum: 0x%04x",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime),
EXTRACT_16BITS(header_lsp->checksum)));
osi_print_cksum(ndo, (const uint8_t *)header_lsp->lsp_id,
EXTRACT_16BITS(header_lsp->checksum),
12, length-12);
ND_PRINT((ndo, ", PDU length: %u, Flags: [ %s",
pdu_len,
ISIS_MASK_LSP_OL_BIT(header_lsp->typeblock) ? "Overload bit set, " : ""));
if (ISIS_MASK_LSP_ATT_BITS(header_lsp->typeblock)) {
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DEFAULT_BIT(header_lsp->typeblock) ? "default " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DELAY_BIT(header_lsp->typeblock) ? "delay " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_EXPENSE_BIT(header_lsp->typeblock) ? "expense " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_ERROR_BIT(header_lsp->typeblock) ? "error " : ""));
ND_PRINT((ndo, "ATT bit set, "));
}
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_PARTITION_BIT(header_lsp->typeblock) ? "P bit set, " : ""));
ND_PRINT((ndo, "%s ]", tok2str(isis_lsp_istype_values, "Unknown(0x%x)",
ISIS_MASK_LSP_ISTYPE_BITS(header_lsp->typeblock))));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_LSP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
break;
case ISIS_PDU_L1_CSNP:
case ISIS_PDU_L2_CSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_csnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_csnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_csnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_csnp->source_id, NODE_ID_LEN),
pdu_len));
ND_PRINT((ndo, "\n\t start lsp-id: %s",
isis_print_id(header_csnp->start_lsp_id, LSP_ID_LEN)));
ND_PRINT((ndo, "\n\t end lsp-id: %s",
isis_print_id(header_csnp->end_lsp_id, LSP_ID_LEN)));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_CSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
break;
case ISIS_PDU_L1_PSNP:
case ISIS_PDU_L2_PSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)) {
ND_PRINT((ndo, "- bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_psnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_psnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_psnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_psnp->source_id, NODE_ID_LEN),
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_PSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
break;
default:
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", length %u", length));
return (1);
}
(void)print_unknown_data(ndo, pptr, "\n\t ", length);
return (0);
}
/*
* Now print the TLV's.
*/
while (packet_len > 0) {
ND_TCHECK2(*pptr, 2);
if (packet_len < 2)
goto trunc;
tlv_type = *pptr++;
tlv_len = *pptr++;
tmp =tlv_len; /* copy temporary len & pointer to packet data */
tptr = pptr;
packet_len -= 2;
/* first lets see if we know the TLVs name*/
ND_PRINT((ndo, "\n\t %s TLV #%u, length: %u",
tok2str(isis_tlv_values,
"unknown",
tlv_type),
tlv_type,
tlv_len));
if (tlv_len == 0) /* something is invalid */
continue;
if (packet_len < tlv_len)
goto trunc;
/* now check if we have a decoder otherwise do a hexdump at the end*/
switch (tlv_type) {
case ISIS_TLV_AREA_ADDR:
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
while (tmp && alen < tmp) {
ND_TCHECK2(*tptr, alen);
ND_PRINT((ndo, "\n\t Area address (length: %u): %s",
alen,
isonsap_string(ndo, tptr, alen)));
tptr += alen;
tmp -= alen + 1;
if (tmp==0) /* if this is the last area address do not attemt a boundary check */
break;
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
}
break;
case ISIS_TLV_ISNEIGH:
while (tmp >= ETHER_ADDR_LEN) {
ND_TCHECK2(*tptr, ETHER_ADDR_LEN);
ND_PRINT((ndo, "\n\t SNPA: %s", isis_print_id(tptr, ETHER_ADDR_LEN)));
tmp -= ETHER_ADDR_LEN;
tptr += ETHER_ADDR_LEN;
}
break;
case ISIS_TLV_ISNEIGH_VARLEN:
if (!ND_TTEST2(*tptr, 1) || tmp < 3) /* min. TLV length */
goto trunctlv;
lan_alen = *tptr++; /* LAN address length */
if (lan_alen == 0) {
ND_PRINT((ndo, "\n\t LAN address length 0 bytes (invalid)"));
break;
}
tmp --;
ND_PRINT((ndo, "\n\t LAN address length %u bytes ", lan_alen));
while (tmp >= lan_alen) {
ND_TCHECK2(*tptr, lan_alen);
ND_PRINT((ndo, "\n\t\tIS Neighbor: %s", isis_print_id(tptr, lan_alen)));
tmp -= lan_alen;
tptr +=lan_alen;
}
break;
case ISIS_TLV_PADDING:
break;
case ISIS_TLV_MT_IS_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
while (tmp >= 2+NODE_ID_LEN+3+1) {
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_ALIAS_ID:
while (tmp >= NODE_ID_LEN+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_EXT_IS_REACH:
while (tmp >= NODE_ID_LEN+3+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_REACH:
ND_TCHECK2(*tptr,1); /* check if there is one byte left to read out the virtual flag */
ND_PRINT((ndo, "\n\t %s",
tok2str(isis_is_reach_virtual_values,
"bogus virtual flag 0x%02x",
*tptr++)));
tlv_is_reach = (const struct isis_tlv_is_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_is_reach)) {
ND_TCHECK(*tlv_is_reach);
ND_PRINT((ndo, "\n\t IS Neighbor: %s",
isis_print_id(tlv_is_reach->neighbor_nodeid, NODE_ID_LEN)));
isis_print_metric_block(ndo, &tlv_is_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_is_reach);
tlv_is_reach++;
}
break;
case ISIS_TLV_ESNEIGH:
tlv_es_reach = (const struct isis_tlv_es_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_es_reach)) {
ND_TCHECK(*tlv_es_reach);
ND_PRINT((ndo, "\n\t ES Neighbor: %s",
isis_print_id(tlv_es_reach->neighbor_sysid, SYSTEM_ID_LEN)));
isis_print_metric_block(ndo, &tlv_es_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_es_reach);
tlv_es_reach++;
}
break;
/* those two TLVs share the same format */
case ISIS_TLV_INT_IP_REACH:
case ISIS_TLV_EXT_IP_REACH:
if (!isis_print_tlv_ip_reach(ndo, pptr, "\n\t ", tlv_len))
return (1);
break;
case ISIS_TLV_EXTD_IP_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP6_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6ADDR:
while (tmp>=sizeof(struct in6_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in6_addr));
ND_PRINT((ndo, "\n\t IPv6 interface address: %s",
ip6addr_string(ndo, tptr)));
tptr += sizeof(struct in6_addr);
tmp -= sizeof(struct in6_addr);
}
break;
case ISIS_TLV_AUTH:
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t %s: ",
tok2str(isis_subtlv_auth_values,
"unknown Authentication type 0x%02x",
*tptr)));
switch (*tptr) {
case ISIS_SUBTLV_AUTH_SIMPLE:
if (fn_printzp(ndo, tptr + 1, tlv_len - 1, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_SUBTLV_AUTH_MD5:
for(i=1;i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
if (tlv_len != ISIS_SUBTLV_AUTH_MD5_LEN+1)
ND_PRINT((ndo, ", (invalid subTLV) "));
sigcheck = signature_verify(ndo, optr, length, tptr + 1,
isis_clear_checksum_lifetime,
header_lsp);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
break;
case ISIS_SUBTLV_AUTH_GENERIC:
ND_TCHECK2(*(tptr + 1), 2);
key_id = EXTRACT_16BITS((tptr+1));
ND_PRINT((ndo, "%u, password: ", key_id));
for(i=1 + sizeof(uint16_t);i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
break;
case ISIS_SUBTLV_AUTH_PRIVATE:
default:
if (!print_unknown_data(ndo, tptr + 1, "\n\t\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_PTP_ADJ:
tlv_ptp_adj = (const struct isis_tlv_ptp_adj *)tptr;
if(tmp>=1) {
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t Adjacency State: %s (%u)",
tok2str(isis_ptp_adjancey_values, "unknown", *tptr),
*tptr));
tmp--;
}
if(tmp>sizeof(tlv_ptp_adj->extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->extd_local_circuit_id)));
tmp-=sizeof(tlv_ptp_adj->extd_local_circuit_id);
}
if(tmp>=SYSTEM_ID_LEN) {
ND_TCHECK2(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t Neighbor System-ID: %s",
isis_print_id(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN)));
tmp-=SYSTEM_ID_LEN;
}
if(tmp>=sizeof(tlv_ptp_adj->neighbor_extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->neighbor_extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Neighbor Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->neighbor_extd_local_circuit_id)));
}
break;
case ISIS_TLV_PROTOCOLS:
ND_PRINT((ndo, "\n\t NLPID(s): "));
while (tmp>0) {
ND_TCHECK2(*(tptr), 1);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (tmp>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
tmp--;
}
break;
case ISIS_TLV_MT_PORT_CAP:
{
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t RES: %d, MTID(s): %d",
(EXTRACT_16BITS (tptr) >> 12),
(EXTRACT_16BITS (tptr) & 0x0fff)));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_port_cap_subtlv(ndo, tptr, tmp);
break;
}
case ISIS_TLV_MT_CAPABILITY:
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t O: %d, RES: %d, MTID(s): %d",
(EXTRACT_16BITS(tptr) >> 15) & 0x01,
(EXTRACT_16BITS(tptr) >> 12) & 0x07,
EXTRACT_16BITS(tptr) & 0x0fff));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_capability_subtlv(ndo, tptr, tmp);
break;
case ISIS_TLV_TE_ROUTER_ID:
ND_TCHECK2(*pptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t Traffic Engineering Router ID: %s", ipaddr_string(ndo, pptr)));
break;
case ISIS_TLV_IPADDR:
while (tmp>=sizeof(struct in_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr += sizeof(struct in_addr);
tmp -= sizeof(struct in_addr);
}
break;
case ISIS_TLV_HOSTNAME:
ND_PRINT((ndo, "\n\t Hostname: "));
if (fn_printzp(ndo, tptr, tmp, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_TLV_SHARED_RISK_GROUP:
if (tmp < NODE_ID_LEN)
break;
ND_TCHECK2(*tptr, NODE_ID_LEN);
ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
tmp-=(NODE_ID_LEN);
if (tmp < 1)
break;
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, ", Flags: [%s]", ISIS_MASK_TLV_SHARED_RISK_GROUP(*tptr++) ? "numbered" : "unnumbered"));
tmp--;
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 neighbor address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
while (tmp>=4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Link-ID: 0x%08x", EXTRACT_32BITS(tptr)));
tptr+=4;
tmp-=4;
}
break;
case ISIS_TLV_LSP:
tlv_lsp = (const struct isis_tlv_lsp *)tptr;
while(tmp>=sizeof(struct isis_tlv_lsp)) {
ND_TCHECK((tlv_lsp->lsp_id)[LSP_ID_LEN-1]);
ND_PRINT((ndo, "\n\t lsp-id: %s",
isis_print_id(tlv_lsp->lsp_id, LSP_ID_LEN)));
ND_TCHECK2(tlv_lsp->sequence_number, 4);
ND_PRINT((ndo, ", seq: 0x%08x", EXTRACT_32BITS(tlv_lsp->sequence_number)));
ND_TCHECK2(tlv_lsp->remaining_lifetime, 2);
ND_PRINT((ndo, ", lifetime: %5ds", EXTRACT_16BITS(tlv_lsp->remaining_lifetime)));
ND_TCHECK2(tlv_lsp->checksum, 2);
ND_PRINT((ndo, ", chksum: 0x%04x", EXTRACT_16BITS(tlv_lsp->checksum)));
tmp-=sizeof(struct isis_tlv_lsp);
tlv_lsp++;
}
break;
case ISIS_TLV_CHECKSUM:
if (tmp < ISIS_TLV_CHECKSUM_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_CHECKSUM_MINLEN);
ND_PRINT((ndo, "\n\t checksum: 0x%04x ", EXTRACT_16BITS(tptr)));
/* do not attempt to verify the checksum if it is zero
* most likely a HMAC-MD5 TLV is also present and
* to avoid conflicts the checksum TLV is zeroed.
* see rfc3358 for details
*/
osi_print_cksum(ndo, optr, EXTRACT_16BITS(tptr), tptr-optr,
length);
break;
case ISIS_TLV_POI:
if (tlv_len >= SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Purge Originator System-ID: %s",
isis_print_id(tptr + 1, SYSTEM_ID_LEN)));
}
if (tlv_len == 2 * SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, 2 * SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Received from System-ID: %s",
isis_print_id(tptr + SYSTEM_ID_LEN + 1, SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_MT_SUPPORTED:
if (tmp < ISIS_TLV_MT_SUPPORTED_MINLEN)
break;
while (tmp>1) {
/* length can only be a multiple of 2, otherwise there is
something broken -> so decode down until length is 1 */
if (tmp!=1) {
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
} else {
ND_PRINT((ndo, "\n\t invalid MT-ID"));
break;
}
}
break;
case ISIS_TLV_RESTART_SIGNALING:
/* first attempt to decode the flags */
if (tmp < ISIS_TLV_RESTART_SIGNALING_FLAGLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_FLAGLEN);
ND_PRINT((ndo, "\n\t Flags [%s]",
bittok2str(isis_restart_flag_values, "none", *tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
/* is there anything other than the flags field? */
if (tmp == 0)
break;
if (tmp < ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN);
ND_PRINT((ndo, ", Remaining holding time %us", EXTRACT_16BITS(tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
/* is there an additional sysid field present ?*/
if (tmp == SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, ", for %s", isis_print_id(tptr,SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_IDRP_INFO:
if (tmp < ISIS_TLV_IDRP_INFO_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IDRP_INFO_MINLEN);
ND_PRINT((ndo, "\n\t Inter-Domain Information Type: %s",
tok2str(isis_subtlv_idrp_values,
"Unknown (0x%02x)",
*tptr)));
switch (*tptr++) {
case ISIS_SUBTLV_IDRP_ASN:
ND_TCHECK2(*tptr, 2); /* fetch AS number */
ND_PRINT((ndo, "AS Number: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_SUBTLV_IDRP_LOCAL:
case ISIS_SUBTLV_IDRP_RES:
default:
if (!print_unknown_data(ndo, tptr, "\n\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_LSP_BUFFERSIZE:
if (tmp < ISIS_TLV_LSP_BUFFERSIZE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_LSP_BUFFERSIZE_MINLEN);
ND_PRINT((ndo, "\n\t LSP Buffersize: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_TLV_PART_DIS:
while (tmp >= SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t %s", isis_print_id(tptr, SYSTEM_ID_LEN)));
tptr+=SYSTEM_ID_LEN;
tmp-=SYSTEM_ID_LEN;
}
break;
case ISIS_TLV_PREFIX_NEIGH:
if (tmp < sizeof(struct isis_metric_block))
break;
ND_TCHECK2(*tptr, sizeof(struct isis_metric_block));
ND_PRINT((ndo, "\n\t Metric Block"));
isis_print_metric_block(ndo, (const struct isis_metric_block *)tptr);
tptr+=sizeof(struct isis_metric_block);
tmp-=sizeof(struct isis_metric_block);
while(tmp>0) {
ND_TCHECK2(*tptr, 1);
prefix_len=*tptr++; /* read out prefix length in semioctets*/
if (prefix_len < 2) {
ND_PRINT((ndo, "\n\t\tAddress: prefix length %u < 2", prefix_len));
break;
}
tmp--;
if (tmp < prefix_len/2)
break;
ND_TCHECK2(*tptr, prefix_len / 2);
ND_PRINT((ndo, "\n\t\tAddress: %s/%u",
isonsap_string(ndo, tptr, prefix_len / 2), prefix_len * 4));
tptr+=prefix_len/2;
tmp-=prefix_len/2;
}
break;
case ISIS_TLV_IIH_SEQNR:
if (tmp < ISIS_TLV_IIH_SEQNR_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IIH_SEQNR_MINLEN); /* check if four bytes are on the wire */
ND_PRINT((ndo, "\n\t Sequence number: %u", EXTRACT_32BITS(tptr)));
break;
case ISIS_TLV_VENDOR_PRIVATE:
if (tmp < ISIS_TLV_VENDOR_PRIVATE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_VENDOR_PRIVATE_MINLEN); /* check if enough byte for a full oui */
vendor_id = EXTRACT_24BITS(tptr);
ND_PRINT((ndo, "\n\t Vendor: %s (%u)",
tok2str(oui_values, "Unknown", vendor_id),
vendor_id));
tptr+=3;
tmp-=3;
if (tmp > 0) /* hexdump the rest */
if (!print_unknown_data(ndo, tptr, "\n\t\t", tmp))
return(0);
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case ISIS_TLV_DECNET_PHASE4:
case ISIS_TLV_LUCENT_PRIVATE:
case ISIS_TLV_IPAUTH:
case ISIS_TLV_NORTEL_PRIVATE1:
case ISIS_TLV_NORTEL_PRIVATE2:
default:
if (ndo->ndo_vflag <= 1) {
if (!print_unknown_data(ndo, pptr, "\n\t\t", tlv_len))
return(0);
}
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", tlv_len))
return(0);
}
pptr += tlv_len;
packet_len -= tlv_len;
}
if (packet_len != 0) {
ND_PRINT((ndo, "\n\t %u straggler bytes", packet_len));
}
return (1);
trunc:
ND_PRINT((ndo, "%s", tstr));
return (1);
trunctlv:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
static void
osi_print_cksum(netdissect_options *ndo, const uint8_t *pptr,
uint16_t checksum, int checksum_offset, u_int length)
{
uint16_t calculated_checksum;
/* do not attempt to verify the checksum if it is zero,
* if the offset is nonsense,
* or the base pointer is not sane
*/
if (!checksum
|| checksum_offset < 0
|| !ND_TTEST2(*(pptr + checksum_offset), 2)
|| (u_int)checksum_offset > length
|| !ND_TTEST2(*pptr, length)) {
ND_PRINT((ndo, " (unverified)"));
} else {
#if 0
printf("\nosi_print_cksum: %p %u %u\n", pptr, checksum_offset, length);
#endif
calculated_checksum = create_osi_cksum(pptr, checksum_offset, length);
if (checksum == calculated_checksum) {
ND_PRINT((ndo, " (correct)"));
} else {
ND_PRINT((ndo, " (incorrect should be 0x%04x)", calculated_checksum));
}
}
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2671_0 |
crossvul-cpp_data_good_210_1 | /*
* GPAC - Multimedia Framework C SDK
*
* Authors: Jean Le Feuvre
* Copyright (c) Telecom ParisTech 2000-2012
* All rights reserved
*
* This file is part of GPAC / ISO Media File Format sub-project
*
* GPAC is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* GPAC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <gpac/internal/isomedia_dev.h>
#ifndef GPAC_DISABLE_ISOM
void co64_del(GF_Box *s)
{
GF_ChunkLargeOffsetBox *ptr;
ptr = (GF_ChunkLargeOffsetBox *) s;
if (ptr == NULL) return;
if (ptr->offsets) gf_free(ptr->offsets);
gf_free(ptr);
}
GF_Err co64_Read(GF_Box *s,GF_BitStream *bs)
{
u32 entries;
GF_ChunkLargeOffsetBox *ptr = (GF_ChunkLargeOffsetBox *) s;
ptr->nb_entries = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4)
if (ptr->nb_entries > ptr->size / 8) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in co64\n", ptr->nb_entries));
return GF_ISOM_INVALID_FILE;
}
ptr->offsets = (u64 *) gf_malloc(ptr->nb_entries * sizeof(u64) );
if (ptr->offsets == NULL) return GF_OUT_OF_MEM;
ptr->alloc_size = ptr->nb_entries;
for (entries = 0; entries < ptr->nb_entries; entries++) {
ptr->offsets[entries] = gf_bs_read_u64(bs);
}
return GF_OK;
}
GF_Box *co64_New()
{
ISOM_DECL_BOX_ALLOC(GF_ChunkLargeOffsetBox, GF_ISOM_BOX_TYPE_CO64);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err co64_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_ChunkLargeOffsetBox *ptr = (GF_ChunkLargeOffsetBox *) s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->nb_entries);
for (i = 0; i < ptr->nb_entries; i++ ) {
gf_bs_write_u64(bs, ptr->offsets[i]);
}
return GF_OK;
}
GF_Err co64_Size(GF_Box *s)
{
GF_ChunkLargeOffsetBox *ptr = (GF_ChunkLargeOffsetBox *) s;
ptr->size += 4 + (8 * ptr->nb_entries);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void cprt_del(GF_Box *s)
{
GF_CopyrightBox *ptr = (GF_CopyrightBox *) s;
if (ptr == NULL) return;
if (ptr->notice)
gf_free(ptr->notice);
gf_free(ptr);
}
GF_Box *chpl_New()
{
ISOM_DECL_BOX_ALLOC(GF_ChapterListBox, GF_ISOM_BOX_TYPE_CHPL);
tmp->list = gf_list_new();
tmp->version = 1;
return (GF_Box *)tmp;
}
void chpl_del(GF_Box *s)
{
GF_ChapterListBox *ptr = (GF_ChapterListBox *) s;
if (ptr == NULL) return;
while (gf_list_count(ptr->list)) {
GF_ChapterEntry *ce = (GF_ChapterEntry *)gf_list_get(ptr->list, 0);
if (ce->name) gf_free(ce->name);
gf_free(ce);
gf_list_rem(ptr->list, 0);
}
gf_list_del(ptr->list);
gf_free(ptr);
}
/*this is using chpl format according to some NeroRecode samples*/
GF_Err chpl_Read(GF_Box *s,GF_BitStream *bs)
{
GF_ChapterEntry *ce;
u32 nb_chaps, len, i, count;
GF_ChapterListBox *ptr = (GF_ChapterListBox *)s;
/*reserved or ???*/
gf_bs_read_u32(bs);
nb_chaps = gf_bs_read_u8(bs);
count = 0;
while (nb_chaps) {
GF_SAFEALLOC(ce, GF_ChapterEntry);
if (!ce) return GF_OUT_OF_MEM;
ce->start_time = gf_bs_read_u64(bs);
len = gf_bs_read_u8(bs);
if (len) {
ce->name = (char *)gf_malloc(sizeof(char)*(len+1));
gf_bs_read_data(bs, ce->name, len);
ce->name[len] = 0;
} else {
ce->name = gf_strdup("");
}
for (i=0; i<count; i++) {
GF_ChapterEntry *ace = (GF_ChapterEntry *) gf_list_get(ptr->list, i);
if (ace->start_time >= ce->start_time) {
gf_list_insert(ptr->list, ce, i);
ce = NULL;
break;
}
}
if (ce) gf_list_add(ptr->list, ce);
count++;
nb_chaps--;
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err chpl_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 count, i;
GF_ChapterListBox *ptr = (GF_ChapterListBox *) s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
count = gf_list_count(ptr->list);
gf_bs_write_u32(bs, 0);
gf_bs_write_u8(bs, count);
for (i=0; i<count; i++) {
u32 len;
GF_ChapterEntry *ce = (GF_ChapterEntry *)gf_list_get(ptr->list, i);
gf_bs_write_u64(bs, ce->start_time);
if (ce->name) {
len = (u32) strlen(ce->name);
if (len>255) len = 255;
gf_bs_write_u8(bs, len);
gf_bs_write_data(bs, ce->name, len);
} else {
gf_bs_write_u8(bs, 0);
}
}
return GF_OK;
}
GF_Err chpl_Size(GF_Box *s)
{
u32 count, i;
GF_ChapterListBox *ptr = (GF_ChapterListBox *)s;
ptr->size += 5;
count = gf_list_count(ptr->list);
for (i=0; i<count; i++) {
GF_ChapterEntry *ce = (GF_ChapterEntry *)gf_list_get(ptr->list, i);
ptr->size += 9; /*64bit time stamp + 8bit str len*/
if (ce->name) ptr->size += strlen(ce->name);
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Err cprt_Read(GF_Box *s,GF_BitStream *bs)
{
GF_CopyrightBox *ptr = (GF_CopyrightBox *)s;
gf_bs_read_int(bs, 1);
//the spec is unclear here, just says "the value 0 is interpreted as undetermined"
ptr->packedLanguageCode[0] = gf_bs_read_int(bs, 5);
ptr->packedLanguageCode[1] = gf_bs_read_int(bs, 5);
ptr->packedLanguageCode[2] = gf_bs_read_int(bs, 5);
ISOM_DECREASE_SIZE(ptr, 2);
//but before or after compaction ?? We assume before
if (ptr->packedLanguageCode[0] || ptr->packedLanguageCode[1] || ptr->packedLanguageCode[2]) {
ptr->packedLanguageCode[0] += 0x60;
ptr->packedLanguageCode[1] += 0x60;
ptr->packedLanguageCode[2] += 0x60;
} else {
ptr->packedLanguageCode[0] = 'u';
ptr->packedLanguageCode[1] = 'n';
ptr->packedLanguageCode[2] = 'd';
}
if (ptr->size) {
u32 bytesToRead = (u32) ptr->size;
ptr->notice = (char*)gf_malloc(bytesToRead * sizeof(char));
if (ptr->notice == NULL) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, ptr->notice, bytesToRead);
}
return GF_OK;
}
GF_Box *cprt_New()
{
ISOM_DECL_BOX_ALLOC(GF_CopyrightBox, GF_ISOM_BOX_TYPE_CPRT);
tmp->packedLanguageCode[0] = 'u';
tmp->packedLanguageCode[1] = 'n';
tmp->packedLanguageCode[2] = 'd';
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err cprt_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_CopyrightBox *ptr = (GF_CopyrightBox *) s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_int(bs, 0, 1);
if (ptr->packedLanguageCode[0]) {
gf_bs_write_int(bs, ptr->packedLanguageCode[0] - 0x60, 5);
gf_bs_write_int(bs, ptr->packedLanguageCode[1] - 0x60, 5);
gf_bs_write_int(bs, ptr->packedLanguageCode[2] - 0x60, 5);
} else {
gf_bs_write_int(bs, 0, 15);
}
if (ptr->notice) {
gf_bs_write_data(bs, ptr->notice, (u32) (strlen(ptr->notice) + 1) );
}
return GF_OK;
}
GF_Err cprt_Size(GF_Box *s)
{
GF_CopyrightBox *ptr = (GF_CopyrightBox *)s;
ptr->size += 2;
if (ptr->notice)
ptr->size += strlen(ptr->notice) + 1;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void kind_del(GF_Box *s)
{
GF_KindBox *ptr = (GF_KindBox *) s;
if (ptr == NULL) return;
if (ptr->schemeURI) gf_free(ptr->schemeURI);
if (ptr->value) gf_free(ptr->value);
gf_free(ptr);
}
GF_Err kind_Read(GF_Box *s,GF_BitStream *bs)
{
GF_KindBox *ptr = (GF_KindBox *)s;
if (ptr->size) {
u32 bytesToRead = (u32) ptr->size;
char *data;
u32 schemeURIlen;
data = (char*)gf_malloc(bytesToRead * sizeof(char));
if (data == NULL) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, data, bytesToRead);
/*safety check in case the string is not null-terminated*/
if (data[bytesToRead-1]) {
char *str = (char*)gf_malloc((u32) bytesToRead + 1);
memcpy(str, data, (u32) bytesToRead);
str[ptr->size] = 0;
gf_free(data);
data = str;
bytesToRead++;
}
ptr->schemeURI = gf_strdup(data);
schemeURIlen = (u32) strlen(data);
if (bytesToRead > schemeURIlen+1) {
/* read the value */
char *data_value = data + schemeURIlen +1;
ptr->value = gf_strdup(data_value);
}
gf_free(data);
}
return GF_OK;
}
GF_Box *kind_New()
{
ISOM_DECL_BOX_ALLOC(GF_KindBox, GF_ISOM_BOX_TYPE_KIND);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err kind_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_KindBox *ptr = (GF_KindBox *) s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_data(bs, ptr->schemeURI, (u32) (strlen(ptr->schemeURI) + 1 ));
if (ptr->value) {
gf_bs_write_data(bs, ptr->value, (u32) (strlen(ptr->value) + 1) );
}
return GF_OK;
}
GF_Err kind_Size(GF_Box *s)
{
GF_KindBox *ptr = (GF_KindBox *)s;
ptr->size += strlen(ptr->schemeURI) + 1;
if (ptr->value) {
ptr->size += strlen(ptr->value) + 1;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void ctts_del(GF_Box *s)
{
GF_CompositionOffsetBox *ptr = (GF_CompositionOffsetBox *)s;
if (ptr->entries) gf_free(ptr->entries);
gf_free(ptr);
}
GF_Err ctts_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i;
u32 sampleCount;
GF_CompositionOffsetBox *ptr = (GF_CompositionOffsetBox *)s;
ptr->nb_entries = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
if (ptr->nb_entries > ptr->size / 8) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in ctts\n", ptr->nb_entries));
return GF_ISOM_INVALID_FILE;
}
ptr->alloc_size = ptr->nb_entries;
ptr->entries = (GF_DttsEntry *)gf_malloc(sizeof(GF_DttsEntry)*ptr->alloc_size);
if (!ptr->entries) return GF_OUT_OF_MEM;
sampleCount = 0;
for (i=0; i<ptr->nb_entries; i++) {
ptr->entries[i].sampleCount = gf_bs_read_u32(bs);
if (ptr->version)
ptr->entries[i].decodingOffset = gf_bs_read_int(bs, 32);
else
ptr->entries[i].decodingOffset = (s32) gf_bs_read_u32(bs);
sampleCount += ptr->entries[i].sampleCount;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
ptr->w_LastSampleNumber = sampleCount;
#endif
return GF_OK;
}
GF_Box *ctts_New()
{
ISOM_DECL_BOX_ALLOC(GF_CompositionOffsetBox, GF_ISOM_BOX_TYPE_CTTS);
return (GF_Box *) tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err ctts_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_CompositionOffsetBox *ptr = (GF_CompositionOffsetBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->nb_entries);
for (i=0; i<ptr->nb_entries; i++ ) {
gf_bs_write_u32(bs, ptr->entries[i].sampleCount);
if (ptr->version) {
gf_bs_write_int(bs, ptr->entries[i].decodingOffset, 32);
} else {
gf_bs_write_u32(bs, (u32) ptr->entries[i].decodingOffset);
}
}
return GF_OK;
}
GF_Err ctts_Size(GF_Box *s)
{
GF_CompositionOffsetBox *ptr = (GF_CompositionOffsetBox *) s;
ptr->size += 4 + (8 * ptr->nb_entries);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void cslg_del(GF_Box *s)
{
GF_CompositionToDecodeBox *ptr = (GF_CompositionToDecodeBox *)s;
if (ptr == NULL) return;
gf_free(ptr);
return;
}
GF_Err cslg_Read(GF_Box *s, GF_BitStream *bs)
{
GF_CompositionToDecodeBox *ptr = (GF_CompositionToDecodeBox *)s;
ptr->compositionToDTSShift = gf_bs_read_int(bs, 32);
ptr->leastDecodeToDisplayDelta = gf_bs_read_int(bs, 32);
ptr->greatestDecodeToDisplayDelta = gf_bs_read_int(bs, 32);
ptr->compositionStartTime = gf_bs_read_int(bs, 32);
ptr->compositionEndTime = gf_bs_read_int(bs, 32);
return GF_OK;
}
GF_Box *cslg_New()
{
ISOM_DECL_BOX_ALLOC(GF_CompositionToDecodeBox, GF_ISOM_BOX_TYPE_CSLG);
return (GF_Box *) tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err cslg_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_CompositionToDecodeBox *ptr = (GF_CompositionToDecodeBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_int(bs, ptr->compositionToDTSShift, 32);
gf_bs_write_int(bs, ptr->leastDecodeToDisplayDelta, 32);
gf_bs_write_int(bs, ptr->greatestDecodeToDisplayDelta, 32);
gf_bs_write_int(bs, ptr->compositionStartTime, 32);
gf_bs_write_int(bs, ptr->compositionEndTime, 32);
return GF_OK;
}
GF_Err cslg_Size(GF_Box *s)
{
GF_CompositionToDecodeBox *ptr = (GF_CompositionToDecodeBox *)s;
ptr->size += 20;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void ccst_del(GF_Box *s)
{
GF_CodingConstraintsBox *ptr = (GF_CodingConstraintsBox *)s;
if (ptr) gf_free(ptr);
return;
}
GF_Err ccst_Read(GF_Box *s, GF_BitStream *bs)
{
GF_CodingConstraintsBox *ptr = (GF_CodingConstraintsBox *)s;
ISOM_DECREASE_SIZE(ptr, 4);
ptr->all_ref_pics_intra = gf_bs_read_int(bs, 1);
ptr->intra_pred_used = gf_bs_read_int(bs, 1);
ptr->max_ref_per_pic = gf_bs_read_int(bs, 4);
ptr->reserved = gf_bs_read_int(bs, 26);
return GF_OK;
}
GF_Box *ccst_New()
{
ISOM_DECL_BOX_ALLOC(GF_CodingConstraintsBox, GF_ISOM_BOX_TYPE_CCST);
return (GF_Box *) tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err ccst_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_CodingConstraintsBox *ptr = (GF_CodingConstraintsBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_int(bs, ptr->all_ref_pics_intra, 1);
gf_bs_write_int(bs, ptr->intra_pred_used, 1);
gf_bs_write_int(bs, ptr->max_ref_per_pic, 4);
gf_bs_write_int(bs, 0, 26);
return GF_OK;
}
GF_Err ccst_Size(GF_Box *s)
{
GF_CodingConstraintsBox *ptr = (GF_CodingConstraintsBox *)s;
ptr->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void url_del(GF_Box *s)
{
GF_DataEntryURLBox *ptr = (GF_DataEntryURLBox *)s;
if (ptr == NULL) return;
if (ptr->location) gf_free(ptr->location);
gf_free(ptr);
return;
}
GF_Err url_Read(GF_Box *s, GF_BitStream *bs)
{
GF_DataEntryURLBox *ptr = (GF_DataEntryURLBox *)s;
if (ptr->size) {
ptr->location = (char*)gf_malloc((u32) ptr->size);
if (! ptr->location) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, ptr->location, (u32)ptr->size);
}
return GF_OK;
}
GF_Box *url_New()
{
ISOM_DECL_BOX_ALLOC(GF_DataEntryURLBox, GF_ISOM_BOX_TYPE_URL);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err url_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_DataEntryURLBox *ptr = (GF_DataEntryURLBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
//the flag set indicates we have a string (WE HAVE TO for URLs)
if ( !(ptr->flags & 1)) {
if (ptr->location) {
gf_bs_write_data(bs, ptr->location, (u32)strlen(ptr->location) + 1);
}
}
return GF_OK;
}
GF_Err url_Size(GF_Box *s)
{
GF_DataEntryURLBox *ptr = (GF_DataEntryURLBox *)s;
if ( !(ptr->flags & 1)) {
if (ptr->location) ptr->size += 1 + strlen(ptr->location);
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void urn_del(GF_Box *s)
{
GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s;
if (ptr == NULL) return;
if (ptr->location) gf_free(ptr->location);
if (ptr->nameURN) gf_free(ptr->nameURN);
gf_free(ptr);
}
GF_Err urn_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i, to_read;
char *tmpName;
GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s;
if (! ptr->size ) return GF_OK;
//here we have to handle that in a clever way
to_read = (u32) ptr->size;
tmpName = (char*)gf_malloc(sizeof(char) * to_read);
if (!tmpName) return GF_OUT_OF_MEM;
//get the data
gf_bs_read_data(bs, tmpName, to_read);
//then get the break
i = 0;
while ( (i < to_read) && (tmpName[i] != 0) ) {
i++;
}
//check the data is consistent
if (i == to_read) {
gf_free(tmpName);
return GF_ISOM_INVALID_FILE;
}
//no NULL char, URL is not specified
if (i == to_read - 1) {
ptr->nameURN = tmpName;
ptr->location = NULL;
return GF_OK;
}
//OK, this has both URN and URL
ptr->nameURN = (char*)gf_malloc(sizeof(char) * (i+1));
if (!ptr->nameURN) {
gf_free(tmpName);
return GF_OUT_OF_MEM;
}
ptr->location = (char*)gf_malloc(sizeof(char) * (to_read - i - 1));
if (!ptr->location) {
gf_free(tmpName);
gf_free(ptr->nameURN);
ptr->nameURN = NULL;
return GF_OUT_OF_MEM;
}
memcpy(ptr->nameURN, tmpName, i + 1);
memcpy(ptr->location, tmpName + i + 1, (to_read - i - 1));
gf_free(tmpName);
return GF_OK;
}
GF_Box *urn_New()
{
ISOM_DECL_BOX_ALLOC(GF_DataEntryURNBox, GF_ISOM_BOX_TYPE_URN);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err urn_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
//the flag set indicates we have a string (WE HAVE TO for URLs)
if ( !(ptr->flags & 1)) {
//to check, the spec says: First name, then location
if (ptr->nameURN) {
gf_bs_write_data(bs, ptr->nameURN, (u32)strlen(ptr->nameURN) + 1);
}
if (ptr->location) {
gf_bs_write_data(bs, ptr->location, (u32)strlen(ptr->location) + 1);
}
}
return GF_OK;
}
GF_Err urn_Size(GF_Box *s)
{
GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s;
if ( !(ptr->flags & 1)) {
if (ptr->nameURN) ptr->size += 1 + strlen(ptr->nameURN);
if (ptr->location) ptr->size += 1 + strlen(ptr->location);
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void unkn_del(GF_Box *s)
{
GF_UnknownBox *ptr = (GF_UnknownBox *) s;
if (!s) return;
if (ptr->data) gf_free(ptr->data);
gf_free(ptr);
}
GF_Err unkn_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 bytesToRead, sub_size, sub_a;
GF_BitStream *sub_bs;
GF_UnknownBox *ptr = (GF_UnknownBox *)s;
if (ptr->size > 0xFFFFFFFF) return GF_ISOM_INVALID_FILE;
bytesToRead = (u32) (ptr->size);
if (!bytesToRead) return GF_OK;
if (bytesToRead>1000000) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Unknown box %s (0x%08X) with payload larger than 1 MBytes, ignoring\n", gf_4cc_to_str(ptr->type), ptr->type ));
gf_bs_skip_bytes(bs, ptr->dataSize);
return GF_OK;
}
ptr->data = (char*)gf_malloc(bytesToRead);
if (ptr->data == NULL ) return GF_OUT_OF_MEM;
ptr->dataSize = bytesToRead;
gf_bs_read_data(bs, ptr->data, ptr->dataSize);
//try to parse container boxes, check if next 8 bytes match a subbox
sub_bs = gf_bs_new(ptr->data, ptr->dataSize, GF_BITSTREAM_READ);
sub_size = gf_bs_read_u32(sub_bs);
sub_a = gf_bs_read_u8(sub_bs);
e = (sub_size && (sub_size <= ptr->dataSize)) ? GF_OK : GF_NOT_SUPPORTED;
if (! isalnum(sub_a)) e = GF_NOT_SUPPORTED;
sub_a = gf_bs_read_u8(sub_bs);
if (! isalnum(sub_a)) e = GF_NOT_SUPPORTED;
sub_a = gf_bs_read_u8(sub_bs);
if (! isalnum(sub_a)) e = GF_NOT_SUPPORTED;
sub_a = gf_bs_read_u8(sub_bs);
if (! isalnum(sub_a)) e = GF_NOT_SUPPORTED;
if (e == GF_OK) {
gf_bs_seek(sub_bs, 0);
e = gf_isom_box_array_read(s, sub_bs, gf_isom_box_add_default);
}
gf_bs_del(sub_bs);
if (e==GF_OK) {
gf_free(ptr->data);
ptr->data = NULL;
ptr->dataSize = 0;
} else if (s->other_boxes) {
gf_isom_box_array_del(s->other_boxes);
s->other_boxes=NULL;
}
return GF_OK;
}
GF_Box *unkn_New(u32 box_type)
{
ISOM_DECL_BOX_ALLOC(GF_UnknownBox, GF_ISOM_BOX_TYPE_UNKNOWN);
tmp->original_4cc = box_type;
return (GF_Box *) tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err unkn_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 type = s->type;
GF_UnknownBox *ptr = (GF_UnknownBox *)s;
if (!s) return GF_BAD_PARAM;
s->type = ptr->original_4cc;
e = gf_isom_box_write_header(s, bs);
s->type = type;
if (e) return e;
if (ptr->dataSize && ptr->data) {
gf_bs_write_data(bs, ptr->data, ptr->dataSize);
}
return GF_OK;
}
GF_Err unkn_Size(GF_Box *s)
{
GF_UnknownBox *ptr = (GF_UnknownBox *)s;
if (ptr->dataSize && ptr->data) {
ptr->size += ptr->dataSize;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void def_cont_box_del(GF_Box *s)
{
if (s) gf_free(s);
}
GF_Err def_cont_box_Read(GF_Box *s, GF_BitStream *bs)
{
return gf_isom_box_array_read(s, bs, gf_isom_box_add_default);
}
GF_Box *def_cont_box_New()
{
ISOM_DECL_BOX_ALLOC(GF_Box, 0);
return (GF_Box *) tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITEHintSa
GF_Err def_cont_box_Write(GF_Box *s, GF_BitStream *bs)
{
return gf_isom_box_write_header(s, bs);
}
GF_Err def_cont_box_Size(GF_Box *s)
{
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void uuid_del(GF_Box *s)
{
GF_UnknownUUIDBox *ptr = (GF_UnknownUUIDBox *) s;
if (!s) return;
if (ptr->data) gf_free(ptr->data);
gf_free(ptr);
}
GF_Err uuid_Read(GF_Box *s, GF_BitStream *bs)
{
u32 bytesToRead;
GF_UnknownUUIDBox *ptr = (GF_UnknownUUIDBox *)s;
if (ptr->size > 0xFFFFFFFF) return GF_ISOM_INVALID_FILE;
bytesToRead = (u32) (ptr->size);
if (bytesToRead) {
ptr->data = (char*)gf_malloc(bytesToRead);
if (ptr->data == NULL ) return GF_OUT_OF_MEM;
ptr->dataSize = bytesToRead;
gf_bs_read_data(bs, ptr->data, ptr->dataSize);
}
return GF_OK;
}
GF_Box *uuid_New()
{
ISOM_DECL_BOX_ALLOC(GF_UnknownUUIDBox, GF_ISOM_BOX_TYPE_UUID);
return (GF_Box *) tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err uuid_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_UnknownUUIDBox *ptr = (GF_UnknownUUIDBox*)s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
if (ptr->data) {
gf_bs_write_data(bs, ptr->data, ptr->dataSize);
}
return GF_OK;
}
GF_Err uuid_Size(GF_Box *s)
{
GF_UnknownUUIDBox*ptr = (GF_UnknownUUIDBox*)s;
ptr->size += ptr->dataSize;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void dinf_del(GF_Box *s)
{
GF_DataInformationBox *ptr = (GF_DataInformationBox *)s;
if (ptr == NULL) return;
gf_isom_box_del((GF_Box *)ptr->dref);
gf_free(ptr);
}
GF_Err dinf_AddBox(GF_Box *s, GF_Box *a)
{
GF_DataInformationBox *ptr = (GF_DataInformationBox *)s;
switch(a->type) {
case GF_ISOM_BOX_TYPE_DREF:
if (ptr->dref) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->dref = (GF_DataReferenceBox *)a;
return GF_OK;
default:
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err dinf_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e = gf_isom_box_array_read(s, bs, dinf_AddBox);
if (e) {
return e;
}
if (!((GF_DataInformationBox *)s)->dref) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing dref box in dinf\n"));
((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF);
}
return GF_OK;
}
GF_Box *dinf_New()
{
ISOM_DECL_BOX_ALLOC(GF_DataInformationBox, GF_ISOM_BOX_TYPE_DINF);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err dinf_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_DataInformationBox *ptr = (GF_DataInformationBox *)s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
if (ptr->dref) {
e = gf_isom_box_write((GF_Box *)ptr->dref, bs);
if (e) return e;
}
return GF_OK;
}
GF_Err dinf_Size(GF_Box *s)
{
GF_Err e;
GF_DataInformationBox *ptr = (GF_DataInformationBox *)s;
if (ptr->dref) {
e = gf_isom_box_size((GF_Box *) ptr->dref);
if (e) return e;
ptr->size += ptr->dref->size;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void dref_del(GF_Box *s)
{
GF_DataReferenceBox *ptr = (GF_DataReferenceBox *) s;
if (ptr == NULL) return;
gf_free(ptr);
}
GF_Err dref_AddDataEntry(GF_Box *ptr, GF_Box *entry)
{
if (entry->type==GF_ISOM_BOX_TYPE_ALIS) {
GF_DataEntryURLBox *urle = (GF_DataEntryURLBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_URL);
urle->flags = 1;
gf_isom_box_del(entry);
gf_isom_box_add_default(ptr, (GF_Box *)urle);
GF_LOG(GF_LOG_INFO, GF_LOG_CONTAINER, ("[iso file] Apple \'alis\' box found, not supported - converting to self-pointing \'url \' \n" ));
} else {
return gf_isom_box_add_default(ptr, entry);
}
return GF_OK;
}
GF_Err dref_Read(GF_Box *s, GF_BitStream *bs)
{
GF_DataReferenceBox *ptr = (GF_DataReferenceBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
return gf_isom_box_array_read(s, bs, dref_AddDataEntry);
}
GF_Box *dref_New()
{
ISOM_DECL_BOX_ALLOC(GF_DataReferenceBox, GF_ISOM_BOX_TYPE_DREF);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err dref_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 count;
GF_DataReferenceBox *ptr = (GF_DataReferenceBox *)s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
count = ptr->other_boxes ? gf_list_count(ptr->other_boxes) : 0;
gf_bs_write_u32(bs, count);
return GF_OK;
}
GF_Err dref_Size(GF_Box *s)
{
GF_DataReferenceBox *ptr = (GF_DataReferenceBox *)s;
if (!s) return GF_BAD_PARAM;
ptr->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void edts_del(GF_Box *s)
{
GF_EditBox *ptr = (GF_EditBox *) s;
gf_isom_box_del((GF_Box *)ptr->editList);
gf_free(ptr);
}
GF_Err edts_AddBox(GF_Box *s, GF_Box *a)
{
GF_EditBox *ptr = (GF_EditBox *)s;
if (a->type == GF_ISOM_BOX_TYPE_ELST) {
if (ptr->editList) return GF_BAD_PARAM;
ptr->editList = (GF_EditListBox *)a;
return GF_OK;
} else {
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err edts_Read(GF_Box *s, GF_BitStream *bs)
{
return gf_isom_box_array_read(s, bs, edts_AddBox);
}
GF_Box *edts_New()
{
ISOM_DECL_BOX_ALLOC(GF_EditBox, GF_ISOM_BOX_TYPE_EDTS);
return (GF_Box *) tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err edts_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_EditBox *ptr = (GF_EditBox *)s;
//here we have a trick: if editList is empty, skip the box
if (ptr->editList && gf_list_count(ptr->editList->entryList)) {
e = gf_isom_box_write_header(s, bs);
if (e) return e;
e = gf_isom_box_write((GF_Box *) ptr->editList, bs);
if (e) return e;
}
return GF_OK;
}
GF_Err edts_Size(GF_Box *s)
{
GF_Err e;
GF_EditBox *ptr = (GF_EditBox *)s;
//here we have a trick: if editList is empty, skip the box
if (!ptr->editList || ! gf_list_count(ptr->editList->entryList)) {
ptr->size = 0;
} else {
e = gf_isom_box_size((GF_Box *)ptr->editList);
if (e) return e;
ptr->size += ptr->editList->size;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void elst_del(GF_Box *s)
{
GF_EditListBox *ptr;
GF_EdtsEntry *p;
u32 nb_entries;
u32 i;
ptr = (GF_EditListBox *)s;
if (ptr == NULL) return;
nb_entries = gf_list_count(ptr->entryList);
for (i = 0; i < nb_entries; i++) {
p = (GF_EdtsEntry*)gf_list_get(ptr->entryList, i);
if (p) gf_free(p);
}
gf_list_del(ptr->entryList);
gf_free(ptr);
}
GF_Err elst_Read(GF_Box *s, GF_BitStream *bs)
{
u32 entries;
s32 tr;
u32 nb_entries;
GF_EdtsEntry *p;
GF_EditListBox *ptr = (GF_EditListBox *)s;
nb_entries = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
if (ptr->version == 1) {
if (nb_entries > ptr->size / 20) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in ctts\n", nb_entries));
return GF_ISOM_INVALID_FILE;
}
} else {
if (nb_entries > ptr->size / 12) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in ctts\n", nb_entries));
return GF_ISOM_INVALID_FILE;
}
}
for (entries = 0; entries < nb_entries; entries++) {
p = (GF_EdtsEntry *) gf_malloc(sizeof(GF_EdtsEntry));
if (!p) return GF_OUT_OF_MEM;
if (ptr->version == 1) {
p->segmentDuration = gf_bs_read_u64(bs);
p->mediaTime = (s64) gf_bs_read_u64(bs);
} else {
p->segmentDuration = gf_bs_read_u32(bs);
tr = gf_bs_read_u32(bs);
p->mediaTime = (s64) tr;
}
p->mediaRate = gf_bs_read_u16(bs);
gf_bs_read_u16(bs);
gf_list_add(ptr->entryList, p);
}
return GF_OK;
}
GF_Box *elst_New()
{
ISOM_DECL_BOX_ALLOC(GF_EditListBox, GF_ISOM_BOX_TYPE_ELST);
tmp->entryList = gf_list_new();
if (!tmp->entryList) {
gf_free(tmp);
return NULL;
}
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err elst_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
u32 nb_entries;
GF_EdtsEntry *p;
GF_EditListBox *ptr = (GF_EditListBox *)s;
if (!ptr) return GF_BAD_PARAM;
nb_entries = gf_list_count(ptr->entryList);
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, nb_entries);
for (i = 0; i < nb_entries; i++ ) {
p = (GF_EdtsEntry*)gf_list_get(ptr->entryList, i);
if (ptr->version == 1) {
gf_bs_write_u64(bs, p->segmentDuration);
gf_bs_write_u64(bs, p->mediaTime);
} else {
gf_bs_write_u32(bs, (u32) p->segmentDuration);
gf_bs_write_u32(bs, (s32) p->mediaTime);
}
gf_bs_write_u16(bs, p->mediaRate);
gf_bs_write_u16(bs, 0);
}
return GF_OK;
}
GF_Err elst_Size(GF_Box *s)
{
u32 durtimebytes;
u32 i, nb_entries;
GF_EditListBox *ptr = (GF_EditListBox *)s;
//entry count
ptr->size += 4;
nb_entries = gf_list_count(ptr->entryList);
ptr->version = 0;
for (i=0; i<nb_entries; i++) {
GF_EdtsEntry *p = (GF_EdtsEntry*)gf_list_get(ptr->entryList, i);
if ((p->segmentDuration>0xFFFFFFFF) || (p->mediaTime>0xFFFFFFFF)) {
ptr->version = 1;
break;
}
}
durtimebytes = (ptr->version == 1 ? 16 : 8) + 4;
ptr->size += (nb_entries * durtimebytes);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void esds_del(GF_Box *s)
{
GF_ESDBox *ptr = (GF_ESDBox *)s;
if (ptr == NULL) return;
if (ptr->desc) gf_odf_desc_del((GF_Descriptor *)ptr->desc);
gf_free(ptr);
}
GF_Err esds_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e=GF_OK;
u32 descSize;
char *enc_desc;
u32 SLIsPredefined(GF_SLConfig *sl);
GF_ESDBox *ptr = (GF_ESDBox *)s;
descSize = (u32) (ptr->size);
if (descSize) {
enc_desc = (char*)gf_malloc(sizeof(char) * descSize);
if (!enc_desc) return GF_OUT_OF_MEM;
//get the payload
gf_bs_read_data(bs, enc_desc, descSize);
//send it to the OD Codec
e = gf_odf_desc_read(enc_desc, descSize, (GF_Descriptor **) &ptr->desc);
//OK, free our desc
gf_free(enc_desc);
if (ptr->desc && (ptr->desc->tag!=GF_ODF_ESD_TAG) ) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid descriptor tag 0x%x in esds\n", ptr->desc->tag));
gf_odf_desc_del((GF_Descriptor*)ptr->desc);
ptr->desc=NULL;
return GF_ISOM_INVALID_FILE;
}
if (e) {
ptr->desc = NULL;
} else {
/*fix broken files*/
if (!ptr->desc->URLString) {
if (!ptr->desc->slConfig) {
ptr->desc->slConfig = (GF_SLConfig *) gf_odf_desc_new(GF_ODF_SLC_TAG);
ptr->desc->slConfig->predefined = SLPredef_MP4;
} else if (ptr->desc->slConfig->predefined != SLPredef_MP4) {
ptr->desc->slConfig->predefined = SLPredef_MP4;
gf_odf_slc_set_pref(ptr->desc->slConfig);
}
}
}
}
return e;
}
GF_Box *esds_New()
{
ISOM_DECL_BOX_ALLOC(GF_ESDBox, GF_ISOM_BOX_TYPE_ESDS);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err esds_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
char *enc_desc;
u32 descSize = 0;
GF_ESDBox *ptr = (GF_ESDBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
e = gf_odf_desc_write((GF_Descriptor *)ptr->desc, &enc_desc, &descSize);
if (e) return e;
gf_bs_write_data(bs, enc_desc, descSize);
//free our buffer
gf_free(enc_desc);
return GF_OK;
}
GF_Err esds_Size(GF_Box *s)
{
u32 descSize = 0;
GF_ESDBox *ptr = (GF_ESDBox *)s;
descSize = gf_odf_desc_size((GF_Descriptor *)ptr->desc);
ptr->size += descSize;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void free_del(GF_Box *s)
{
GF_FreeSpaceBox *ptr = (GF_FreeSpaceBox *)s;
if (ptr->data) gf_free(ptr->data);
gf_free(ptr);
}
GF_Err free_Read(GF_Box *s, GF_BitStream *bs)
{
u32 bytesToRead;
GF_FreeSpaceBox *ptr = (GF_FreeSpaceBox *)s;
if (ptr->size > 0xFFFFFFFF) return GF_IO_ERR;
bytesToRead = (u32) (ptr->size);
if (bytesToRead) {
ptr->data = (char*)gf_malloc(bytesToRead * sizeof(char));
gf_bs_read_data(bs, ptr->data, bytesToRead);
ptr->dataSize = bytesToRead;
}
return GF_OK;
}
GF_Box *free_New()
{
ISOM_DECL_BOX_ALLOC(GF_FreeSpaceBox, GF_ISOM_BOX_TYPE_FREE);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err free_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_FreeSpaceBox *ptr = (GF_FreeSpaceBox *)s;
if (ptr->original_4cc) {
u32 t = s->type;
s->type=ptr->original_4cc;
e = gf_isom_box_write_header(s, bs);
s->type=t;
} else {
e = gf_isom_box_write_header(s, bs);
}
if (e) return e;
if (ptr->dataSize) {
if (ptr->data) {
gf_bs_write_data(bs, ptr->data, ptr->dataSize);
} else {
u32 i = 0;
while (i<ptr->dataSize) {
gf_bs_write_u8(bs, 0);
i++;
}
}
}
return GF_OK;
}
GF_Err free_Size(GF_Box *s)
{
GF_FreeSpaceBox *ptr = (GF_FreeSpaceBox *)s;
ptr->size += ptr->dataSize;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void ftyp_del(GF_Box *s)
{
GF_FileTypeBox *ptr = (GF_FileTypeBox *) s;
if (ptr->altBrand) gf_free(ptr->altBrand);
gf_free(ptr);
}
GF_Box *ftyp_New()
{
ISOM_DECL_BOX_ALLOC(GF_FileTypeBox, GF_ISOM_BOX_TYPE_FTYP);
return (GF_Box *)tmp;
}
GF_Err ftyp_Read(GF_Box *s,GF_BitStream *bs)
{
u32 i;
GF_FileTypeBox *ptr = (GF_FileTypeBox *)s;
if (ptr->size < 8) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Found ftyp with size < 8, likely broken!\n"));
return GF_BAD_PARAM;
}
ptr->majorBrand = gf_bs_read_u32(bs);
ptr->minorVersion = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 8);
ptr->altCount = ( (u32) (ptr->size)) / 4;
if (!ptr->altCount) return GF_OK;
if (ptr->altCount * 4 != (u32) (ptr->size)) return GF_ISOM_INVALID_FILE;
ptr->altBrand = (u32*)gf_malloc(sizeof(u32)*ptr->altCount);
for (i = 0; i<ptr->altCount; i++) {
ptr->altBrand[i] = gf_bs_read_u32(bs);
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err ftyp_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_FileTypeBox *ptr = (GF_FileTypeBox *) s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->majorBrand);
gf_bs_write_u32(bs, ptr->minorVersion);
for (i=0; i<ptr->altCount; i++) {
gf_bs_write_u32(bs, ptr->altBrand[i]);
}
return GF_OK;
}
GF_Err ftyp_Size(GF_Box *s)
{
GF_FileTypeBox *ptr = (GF_FileTypeBox *)s;
ptr->size += 8 + ptr->altCount * 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void gnrm_del(GF_Box *s)
{
GF_GenericSampleEntryBox *ptr = (GF_GenericSampleEntryBox *)s;
gf_isom_sample_entry_predestroy((GF_SampleEntryBox *)ptr);
if (ptr->data) gf_free(ptr->data);
gf_free(ptr);
}
GF_Box *gnrm_New()
{
ISOM_DECL_BOX_ALLOC(GF_GenericSampleEntryBox, GF_ISOM_BOX_TYPE_GNRM);
gf_isom_sample_entry_init((GF_SampleEntryBox*)tmp);
return (GF_Box *)tmp;
}
//dummy
GF_Err gnrm_Read(GF_Box *s, GF_BitStream *bs)
{
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err gnrm_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_GenericSampleEntryBox *ptr = (GF_GenericSampleEntryBox *)s;
//carefull we are not writing the box type but the entry type so switch for write
ptr->type = ptr->EntryType;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
ptr->type = GF_ISOM_BOX_TYPE_GNRM;
gf_bs_write_data(bs, ptr->reserved, 6);
gf_bs_write_u16(bs, ptr->dataReferenceIndex);
gf_bs_write_data(bs, ptr->data, ptr->data_size);
return GF_OK;
}
GF_Err gnrm_Size(GF_Box *s)
{
GF_GenericSampleEntryBox *ptr = (GF_GenericSampleEntryBox *)s;
s->type = GF_ISOM_BOX_TYPE_GNRM;
ptr->size += 8+ptr->data_size;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void gnrv_del(GF_Box *s)
{
GF_GenericVisualSampleEntryBox *ptr = (GF_GenericVisualSampleEntryBox *)s;
gf_isom_sample_entry_predestroy((GF_SampleEntryBox *)ptr);
if (ptr->data) gf_free(ptr->data);
gf_free(ptr);
}
GF_Box *gnrv_New()
{
ISOM_DECL_BOX_ALLOC(GF_GenericVisualSampleEntryBox, GF_ISOM_BOX_TYPE_GNRV);
gf_isom_video_sample_entry_init((GF_VisualSampleEntryBox*) tmp);
return (GF_Box *)tmp;
}
//dummy
GF_Err gnrv_Read(GF_Box *s, GF_BitStream *bs)
{
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err gnrv_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_GenericVisualSampleEntryBox *ptr = (GF_GenericVisualSampleEntryBox *)s;
//carefull we are not writing the box type but the entry type so switch for write
ptr->type = ptr->EntryType;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
ptr->type = GF_ISOM_BOX_TYPE_GNRV;
gf_isom_video_sample_entry_write((GF_VisualSampleEntryBox *)ptr, bs);
gf_bs_write_data(bs, ptr->data, ptr->data_size);
return GF_OK;
}
GF_Err gnrv_Size(GF_Box *s)
{
GF_GenericVisualSampleEntryBox *ptr = (GF_GenericVisualSampleEntryBox *)s;
s->type = GF_ISOM_BOX_TYPE_GNRV;
gf_isom_video_sample_entry_size((GF_VisualSampleEntryBox *)s);
ptr->size += ptr->data_size;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void gnra_del(GF_Box *s)
{
GF_GenericAudioSampleEntryBox *ptr = (GF_GenericAudioSampleEntryBox *)s;
gf_isom_sample_entry_predestroy((GF_SampleEntryBox *)ptr);
if (ptr->data) gf_free(ptr->data);
gf_free(ptr);
}
GF_Box *gnra_New()
{
ISOM_DECL_BOX_ALLOC(GF_GenericAudioSampleEntryBox, GF_ISOM_BOX_TYPE_GNRA);
gf_isom_audio_sample_entry_init((GF_AudioSampleEntryBox*) tmp);
return (GF_Box *)tmp;
}
//dummy
GF_Err gnra_Read(GF_Box *s, GF_BitStream *bs)
{
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err gnra_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_GenericAudioSampleEntryBox *ptr = (GF_GenericAudioSampleEntryBox *)s;
//carefull we are not writing the box type but the entry type so switch for write
ptr->type = ptr->EntryType;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
ptr->type = GF_ISOM_BOX_TYPE_GNRA;
gf_isom_audio_sample_entry_write((GF_AudioSampleEntryBox *)ptr, bs);
if (ptr->data) {
gf_bs_write_data(bs, ptr->data, ptr->data_size);
}
return GF_OK;
}
GF_Err gnra_Size(GF_Box *s)
{
GF_GenericAudioSampleEntryBox *ptr = (GF_GenericAudioSampleEntryBox *)s;
s->type = GF_ISOM_BOX_TYPE_GNRA;
gf_isom_audio_sample_entry_size((GF_AudioSampleEntryBox *)s);
ptr->size += ptr->data_size;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void hdlr_del(GF_Box *s)
{
GF_HandlerBox *ptr = (GF_HandlerBox *)s;
if (ptr == NULL) return;
if (ptr->nameUTF8) gf_free(ptr->nameUTF8);
gf_free(ptr);
}
GF_Err hdlr_Read(GF_Box *s, GF_BitStream *bs)
{
GF_HandlerBox *ptr = (GF_HandlerBox *)s;
ptr->reserved1 = gf_bs_read_u32(bs);
ptr->handlerType = gf_bs_read_u32(bs);
gf_bs_read_data(bs, (char*)ptr->reserved2, 12);
ISOM_DECREASE_SIZE(ptr, 20);
if (ptr->size) {
size_t len;
ptr->nameUTF8 = (char*)gf_malloc((u32) ptr->size);
if (ptr->nameUTF8 == NULL) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, ptr->nameUTF8, (u32) ptr->size);
/*safety check in case the string is not null-terminated*/
if (ptr->nameUTF8[ptr->size-1]) {
char *str = (char*)gf_malloc((u32) ptr->size + 1);
memcpy(str, ptr->nameUTF8, (u32) ptr->size);
str[ptr->size] = 0;
gf_free(ptr->nameUTF8);
ptr->nameUTF8 = str;
}
//patch for old QT files
if (ptr->size > 1 && ptr->nameUTF8[0] == ptr->size-1) {
len = strlen(ptr->nameUTF8 + 1);
memmove(ptr->nameUTF8, ptr->nameUTF8+1, len );
ptr->nameUTF8[len] = 0;
ptr->store_counted_string = GF_TRUE;
}
}
return GF_OK;
}
GF_Box *hdlr_New()
{
ISOM_DECL_BOX_ALLOC(GF_HandlerBox, GF_ISOM_BOX_TYPE_HDLR);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err hdlr_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_HandlerBox *ptr = (GF_HandlerBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->reserved1);
gf_bs_write_u32(bs, ptr->handlerType);
gf_bs_write_data(bs, (char*)ptr->reserved2, 12);
if (ptr->nameUTF8) {
u32 len = (u32)strlen(ptr->nameUTF8);
if (ptr->store_counted_string) {
gf_bs_write_u8(bs, len);
gf_bs_write_data(bs, ptr->nameUTF8, len);
} else {
gf_bs_write_data(bs, ptr->nameUTF8, len);
gf_bs_write_u8(bs, 0);
}
} else {
gf_bs_write_u8(bs, 0);
}
return GF_OK;
}
GF_Err hdlr_Size(GF_Box *s)
{
GF_HandlerBox *ptr = (GF_HandlerBox *)s;
ptr->size += 20 + 1; //null term or counted string
if (ptr->nameUTF8) {
ptr->size += strlen(ptr->nameUTF8);
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void hinf_del(GF_Box *s)
{
GF_HintInfoBox *hinf = (GF_HintInfoBox *)s;
gf_free(hinf);
}
GF_Box *hinf_New()
{
ISOM_DECL_BOX_ALLOC(GF_HintInfoBox, GF_ISOM_BOX_TYPE_HINF);
tmp->other_boxes = gf_list_new();
return (GF_Box *)tmp;
}
GF_Err hinf_AddBox(GF_Box *s, GF_Box *a)
{
GF_MAXRBox *maxR;
GF_HintInfoBox *hinf = (GF_HintInfoBox *)s;
u32 i;
switch (a->type) {
case GF_ISOM_BOX_TYPE_MAXR:
i=0;
while ((maxR = (GF_MAXRBox *)gf_list_enum(hinf->other_boxes, &i))) {
if ((maxR->type==GF_ISOM_BOX_TYPE_MAXR) && (maxR->granularity == ((GF_MAXRBox *)a)->granularity))
return GF_ISOM_INVALID_FILE;
}
break;
}
return gf_isom_box_add_default(s, a);
}
GF_Err hinf_Read(GF_Box *s, GF_BitStream *bs)
{
return gf_isom_box_array_read(s, bs, hinf_AddBox);
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err hinf_Write(GF_Box *s, GF_BitStream *bs)
{
// GF_HintInfoBox *ptr = (GF_HintInfoBox *)s;
if (!s) return GF_BAD_PARAM;
return gf_isom_box_write_header(s, bs);
}
GF_Err hinf_Size(GF_Box *s)
{
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void hmhd_del(GF_Box *s)
{
GF_HintMediaHeaderBox *ptr = (GF_HintMediaHeaderBox *)s;
if (ptr == NULL) return;
gf_free(ptr);
}
GF_Err hmhd_Read(GF_Box *s,GF_BitStream *bs)
{
GF_HintMediaHeaderBox *ptr = (GF_HintMediaHeaderBox *)s;
ptr->maxPDUSize = gf_bs_read_u16(bs);
ptr->avgPDUSize = gf_bs_read_u16(bs);
ptr->maxBitrate = gf_bs_read_u32(bs);
ptr->avgBitrate = gf_bs_read_u32(bs);
ptr->slidingAverageBitrate = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *hmhd_New()
{
ISOM_DECL_BOX_ALLOC(GF_HintMediaHeaderBox, GF_ISOM_BOX_TYPE_HMHD);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err hmhd_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_HintMediaHeaderBox *ptr = (GF_HintMediaHeaderBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u16(bs, ptr->maxPDUSize);
gf_bs_write_u16(bs, ptr->avgPDUSize);
gf_bs_write_u32(bs, ptr->maxBitrate);
gf_bs_write_u32(bs, ptr->avgBitrate);
gf_bs_write_u32(bs, ptr->slidingAverageBitrate);
return GF_OK;
}
GF_Err hmhd_Size(GF_Box *s)
{
GF_HintMediaHeaderBox *ptr = (GF_HintMediaHeaderBox *)s;
ptr->size += 16;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *hnti_New()
{
ISOM_DECL_BOX_ALLOC(GF_HintTrackInfoBox, GF_ISOM_BOX_TYPE_HNTI);
return (GF_Box *)tmp;
}
void hnti_del(GF_Box *a)
{
gf_free(a);
}
GF_Err hnti_AddBox(GF_Box *s, GF_Box *a)
{
GF_HintTrackInfoBox *hnti = (GF_HintTrackInfoBox *)s;
if (!hnti || !a) return GF_BAD_PARAM;
switch (a->type) {
//this is the value for GF_RTPBox - same as HintSampleEntry for RTP !!!
case GF_ISOM_BOX_TYPE_RTP:
case GF_ISOM_BOX_TYPE_SDP:
if (hnti->SDP) return GF_BAD_PARAM;
hnti->SDP = a;
break;
default:
break;
}
return gf_isom_box_add_default(s, a);
}
GF_Err hnti_Read(GF_Box *s, GF_BitStream *bs)
{
return gf_isom_box_array_read_ex(s, bs, hnti_AddBox, s->type);
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err hnti_Write(GF_Box *s, GF_BitStream *bs)
{
return gf_isom_box_write_header(s, bs);
}
GF_Err hnti_Size(GF_Box *s)
{
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
GF_SDPBox
**********************************************************/
void sdp_del(GF_Box *s)
{
GF_SDPBox *ptr = (GF_SDPBox *)s;
if (ptr->sdpText) gf_free(ptr->sdpText);
gf_free(ptr);
}
GF_Err sdp_Read(GF_Box *s, GF_BitStream *bs)
{
u32 length;
GF_SDPBox *ptr = (GF_SDPBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
length = (u32) (ptr->size);
//sdp text has no delimiter !!!
ptr->sdpText = (char*)gf_malloc(sizeof(char) * (length+1));
if (!ptr->sdpText) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, ptr->sdpText, length);
ptr->sdpText[length] = 0;
return GF_OK;
}
GF_Box *sdp_New()
{
ISOM_DECL_BOX_ALLOC(GF_SDPBox, GF_ISOM_BOX_TYPE_SDP);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err sdp_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_SDPBox *ptr = (GF_SDPBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
//don't write the NULL char!!!
gf_bs_write_data(bs, ptr->sdpText, (u32) strlen(ptr->sdpText));
return GF_OK;
}
GF_Err sdp_Size(GF_Box *s)
{
GF_SDPBox *ptr = (GF_SDPBox *)s;
//don't count the NULL char!!!
ptr->size += strlen(ptr->sdpText);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void rtp_hnti_del(GF_Box *s)
{
GF_RTPBox *ptr = (GF_RTPBox *)s;
if (ptr->sdpText) gf_free(ptr->sdpText);
gf_free(ptr);
}
GF_Err rtp_hnti_Read(GF_Box *s, GF_BitStream *bs)
{
u32 length;
GF_RTPBox *ptr = (GF_RTPBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
ISOM_DECREASE_SIZE(ptr, 4)
ptr->subType = gf_bs_read_u32(bs);
length = (u32) (ptr->size);
//sdp text has no delimiter !!!
ptr->sdpText = (char*)gf_malloc(sizeof(char) * (length+1));
if (!ptr->sdpText) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, ptr->sdpText, length);
ptr->sdpText[length] = 0;
return GF_OK;
}
GF_Box *rtp_hnti_New()
{
ISOM_DECL_BOX_ALLOC(GF_RTPBox, GF_ISOM_BOX_TYPE_RTP);
tmp->subType = GF_ISOM_BOX_TYPE_SDP;
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err rtp_hnti_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_RTPBox *ptr = (GF_RTPBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->subType);
//don't write the NULL char!!!
gf_bs_write_data(bs, ptr->sdpText, (u32) strlen(ptr->sdpText));
return GF_OK;
}
GF_Err rtp_hnti_Size(GF_Box *s)
{
GF_RTPBox *ptr = (GF_RTPBox *)s;
ptr->size += 4 + strlen(ptr->sdpText);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
TRPY GF_Box
**********************************************************/
void trpy_del(GF_Box *s)
{
gf_free((GF_TRPYBox *)s);
}
GF_Err trpy_Read(GF_Box *s, GF_BitStream *bs)
{
GF_TRPYBox *ptr = (GF_TRPYBox *)s;
ptr->nbBytes = gf_bs_read_u64(bs);
return GF_OK;
}
GF_Box *trpy_New()
{
ISOM_DECL_BOX_ALLOC(GF_TRPYBox, GF_ISOM_BOX_TYPE_TRPY);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err trpy_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TRPYBox *ptr = (GF_TRPYBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u64(bs, ptr->nbBytes);
return GF_OK;
}
GF_Err trpy_Size(GF_Box *s)
{
s->size += 8;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
TOTL GF_Box
**********************************************************/
void totl_del(GF_Box *s)
{
gf_free((GF_TRPYBox *)s);
}
GF_Err totl_Read(GF_Box *s, GF_BitStream *bs)
{
GF_TOTLBox *ptr = (GF_TOTLBox *)s;
ptr->nbBytes = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *totl_New()
{
ISOM_DECL_BOX_ALLOC(GF_TOTLBox, GF_ISOM_BOX_TYPE_TOTL);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err totl_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TOTLBox *ptr = (GF_TOTLBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->nbBytes);
return GF_OK;
}
GF_Err totl_Size(GF_Box *s)
{
s->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
NUMP GF_Box
**********************************************************/
void nump_del(GF_Box *s)
{
gf_free((GF_NUMPBox *)s);
}
GF_Err nump_Read(GF_Box *s, GF_BitStream *bs)
{
GF_NUMPBox *ptr = (GF_NUMPBox *)s;
ptr->nbPackets = gf_bs_read_u64(bs);
return GF_OK;
}
GF_Box *nump_New()
{
ISOM_DECL_BOX_ALLOC(GF_NUMPBox, GF_ISOM_BOX_TYPE_NUMP);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err nump_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_NUMPBox *ptr = (GF_NUMPBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u64(bs, ptr->nbPackets);
return GF_OK;
}
GF_Err nump_Size(GF_Box *s)
{
s->size += 8;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
NPCK GF_Box
**********************************************************/
void npck_del(GF_Box *s)
{
gf_free((GF_NPCKBox *)s);
}
GF_Err npck_Read(GF_Box *s, GF_BitStream *bs)
{
GF_NPCKBox *ptr = (GF_NPCKBox *)s;
ptr->nbPackets = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *npck_New()
{
ISOM_DECL_BOX_ALLOC(GF_NPCKBox, GF_ISOM_BOX_TYPE_NPCK);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err npck_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_NPCKBox *ptr = (GF_NPCKBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->nbPackets);
return GF_OK;
}
GF_Err npck_Size(GF_Box *s)
{
s->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
TPYL GF_Box
**********************************************************/
void tpyl_del(GF_Box *s)
{
gf_free((GF_NTYLBox *)s);
}
GF_Err tpyl_Read(GF_Box *s, GF_BitStream *bs)
{
GF_NTYLBox *ptr = (GF_NTYLBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
ptr->nbBytes = gf_bs_read_u64(bs);
return GF_OK;
}
GF_Box *tpyl_New()
{
ISOM_DECL_BOX_ALLOC(GF_NTYLBox, GF_ISOM_BOX_TYPE_TPYL);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err tpyl_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_NTYLBox *ptr = (GF_NTYLBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u64(bs, ptr->nbBytes);
return GF_OK;
}
GF_Err tpyl_Size(GF_Box *s)
{
s->size += 8;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
TPAY GF_Box
**********************************************************/
void tpay_del(GF_Box *s)
{
gf_free((GF_TPAYBox *)s);
}
GF_Err tpay_Read(GF_Box *s, GF_BitStream *bs)
{
GF_TPAYBox *ptr = (GF_TPAYBox *)s;
ptr->nbBytes = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *tpay_New()
{
ISOM_DECL_BOX_ALLOC(GF_TPAYBox, GF_ISOM_BOX_TYPE_TPAY);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err tpay_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TPAYBox *ptr = (GF_TPAYBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->nbBytes);
return GF_OK;
}
GF_Err tpay_Size(GF_Box *s)
{
s->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
MAXR GF_Box
**********************************************************/
void maxr_del(GF_Box *s)
{
gf_free((GF_MAXRBox *)s);
}
GF_Err maxr_Read(GF_Box *s, GF_BitStream *bs)
{
GF_MAXRBox *ptr = (GF_MAXRBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
ptr->granularity = gf_bs_read_u32(bs);
ptr->maxDataRate = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *maxr_New()
{
ISOM_DECL_BOX_ALLOC(GF_MAXRBox, GF_ISOM_BOX_TYPE_MAXR);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err maxr_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_MAXRBox *ptr = (GF_MAXRBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->granularity);
gf_bs_write_u32(bs, ptr->maxDataRate);
return GF_OK;
}
GF_Err maxr_Size(GF_Box *s)
{
s->size += 8;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
DMED GF_Box
**********************************************************/
void dmed_del(GF_Box *s)
{
gf_free((GF_DMEDBox *)s);
}
GF_Err dmed_Read(GF_Box *s, GF_BitStream *bs)
{
GF_DMEDBox *ptr = (GF_DMEDBox *)s;
ptr->nbBytes = gf_bs_read_u64(bs);
return GF_OK;
}
GF_Box *dmed_New()
{
ISOM_DECL_BOX_ALLOC(GF_DMEDBox, GF_ISOM_BOX_TYPE_DMED);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err dmed_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_DMEDBox *ptr = (GF_DMEDBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u64(bs, ptr->nbBytes);
return GF_OK;
}
GF_Err dmed_Size(GF_Box *s)
{
s->size += 8;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
DIMM GF_Box
**********************************************************/
void dimm_del(GF_Box *s)
{
gf_free((GF_DIMMBox *)s);
}
GF_Err dimm_Read(GF_Box *s, GF_BitStream *bs)
{
GF_DIMMBox *ptr = (GF_DIMMBox *)s;
ptr->nbBytes = gf_bs_read_u64(bs);
return GF_OK;
}
GF_Box *dimm_New()
{
ISOM_DECL_BOX_ALLOC(GF_DIMMBox, GF_ISOM_BOX_TYPE_DIMM);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err dimm_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_DIMMBox *ptr = (GF_DIMMBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u64(bs, ptr->nbBytes);
return GF_OK;
}
GF_Err dimm_Size(GF_Box *s)
{
s->size += 8;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
DREP GF_Box
**********************************************************/
void drep_del(GF_Box *s)
{
gf_free((GF_DREPBox *)s);
}
GF_Err drep_Read(GF_Box *s, GF_BitStream *bs)
{
GF_DREPBox *ptr = (GF_DREPBox *)s;
ptr->nbBytes = gf_bs_read_u64(bs);
return GF_OK;
}
GF_Box *drep_New()
{
ISOM_DECL_BOX_ALLOC(GF_DREPBox, GF_ISOM_BOX_TYPE_DREP);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err drep_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_DREPBox *ptr = (GF_DREPBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u64(bs, ptr->nbBytes);
return GF_OK;
}
GF_Err drep_Size(GF_Box *s)
{
s->size += 8;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
TMIN GF_Box
**********************************************************/
void tmin_del(GF_Box *s)
{
gf_free((GF_TMINBox *)s);
}
GF_Err tmin_Read(GF_Box *s, GF_BitStream *bs)
{
GF_TMINBox *ptr = (GF_TMINBox *)s;
ptr->minTime = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *tmin_New()
{
ISOM_DECL_BOX_ALLOC(GF_TMINBox, GF_ISOM_BOX_TYPE_TMIN);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err tmin_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TMINBox *ptr = (GF_TMINBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->minTime);
return GF_OK;
}
GF_Err tmin_Size(GF_Box *s)
{
s->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
TMAX GF_Box
**********************************************************/
void tmax_del(GF_Box *s)
{
gf_free((GF_TMAXBox *)s);
}
GF_Err tmax_Read(GF_Box *s, GF_BitStream *bs)
{
GF_TMAXBox *ptr = (GF_TMAXBox *)s;
ptr->maxTime = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *tmax_New()
{
ISOM_DECL_BOX_ALLOC(GF_TMAXBox, GF_ISOM_BOX_TYPE_TMAX);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err tmax_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TMAXBox *ptr = (GF_TMAXBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->maxTime);
return GF_OK;
}
GF_Err tmax_Size(GF_Box *s)
{
s->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
PMAX GF_Box
**********************************************************/
void pmax_del(GF_Box *s)
{
gf_free((GF_PMAXBox *)s);
}
GF_Err pmax_Read(GF_Box *s, GF_BitStream *bs)
{
GF_PMAXBox *ptr = (GF_PMAXBox *)s;
ptr->maxSize = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *pmax_New()
{
ISOM_DECL_BOX_ALLOC(GF_PMAXBox, GF_ISOM_BOX_TYPE_PMAX);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err pmax_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_PMAXBox *ptr = (GF_PMAXBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->maxSize);
return GF_OK;
}
GF_Err pmax_Size(GF_Box *s)
{
s->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
DMAX GF_Box
**********************************************************/
void dmax_del(GF_Box *s)
{
gf_free((GF_DMAXBox *)s);
}
GF_Err dmax_Read(GF_Box *s, GF_BitStream *bs)
{
GF_DMAXBox *ptr = (GF_DMAXBox *)s;
ptr->maxDur = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *dmax_New()
{
ISOM_DECL_BOX_ALLOC(GF_DMAXBox, GF_ISOM_BOX_TYPE_DMAX);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err dmax_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_DMAXBox *ptr = (GF_DMAXBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->maxDur);
return GF_OK;
}
GF_Err dmax_Size(GF_Box *s)
{
s->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
PAYT GF_Box
**********************************************************/
void payt_del(GF_Box *s)
{
GF_PAYTBox *payt = (GF_PAYTBox *)s;
if (payt->payloadString) gf_free(payt->payloadString);
gf_free(payt);
}
GF_Err payt_Read(GF_Box *s, GF_BitStream *bs)
{
u32 length;
GF_PAYTBox *ptr = (GF_PAYTBox *)s;
ptr->payloadCode = gf_bs_read_u32(bs);
length = gf_bs_read_u8(bs);
ptr->payloadString = (char*)gf_malloc(sizeof(char) * (length+1) );
if (! ptr->payloadString) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, ptr->payloadString, length);
ptr->payloadString[length] = 0;
ISOM_DECREASE_SIZE(ptr, (4+length+1) );
return GF_OK;
}
GF_Box *payt_New()
{
ISOM_DECL_BOX_ALLOC(GF_PAYTBox, GF_ISOM_BOX_TYPE_PAYT);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err payt_Write(GF_Box *s, GF_BitStream *bs)
{
u32 len;
GF_Err e;
GF_PAYTBox *ptr = (GF_PAYTBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->payloadCode);
len = (u32) strlen(ptr->payloadString);
gf_bs_write_u8(bs, len);
if (len) gf_bs_write_data(bs, ptr->payloadString, len);
return GF_OK;
}
GF_Err payt_Size(GF_Box *s)
{
GF_PAYTBox *ptr = (GF_PAYTBox *)s;
s->size += 4;
if (ptr->payloadString) ptr->size += strlen(ptr->payloadString) + 1;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/**********************************************************
PAYT GF_Box
**********************************************************/
void name_del(GF_Box *s)
{
GF_NameBox *name = (GF_NameBox *)s;
if (name->string) gf_free(name->string);
gf_free(name);
}
GF_Err name_Read(GF_Box *s, GF_BitStream *bs)
{
u32 length;
GF_NameBox *ptr = (GF_NameBox *)s;
length = (u32) (ptr->size);
ptr->string = (char*)gf_malloc(sizeof(char) * (length+1));
if (! ptr->string) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, ptr->string, length);
ptr->string[length] = 0;
return GF_OK;
}
GF_Box *name_New()
{
ISOM_DECL_BOX_ALLOC(GF_NameBox, GF_ISOM_BOX_TYPE_NAME);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err name_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_NameBox *ptr = (GF_NameBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
if (ptr->string) {
gf_bs_write_data(bs, ptr->string, (u32) strlen(ptr->string) + 1);
}
return GF_OK;
}
GF_Err name_Size(GF_Box *s)
{
GF_NameBox *ptr = (GF_NameBox *)s;
if (ptr->string) ptr->size += strlen(ptr->string) + 1;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void tssy_del(GF_Box *s)
{
gf_free(s);
}
GF_Err tssy_Read(GF_Box *s, GF_BitStream *bs)
{
GF_TimeStampSynchronyBox *ptr = (GF_TimeStampSynchronyBox *)s;
gf_bs_read_int(bs, 6);
ptr->timestamp_sync = gf_bs_read_int(bs, 2);
return GF_OK;
}
GF_Box *tssy_New()
{
ISOM_DECL_BOX_ALLOC(GF_TimeStampSynchronyBox, GF_ISOM_BOX_TYPE_TSSY);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err tssy_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TimeStampSynchronyBox *ptr = (GF_TimeStampSynchronyBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_int(bs, 0, 6);
gf_bs_write_int(bs, ptr->timestamp_sync, 2);
return GF_OK;
}
GF_Err tssy_Size(GF_Box *s)
{
s->size += 1;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void srpp_del(GF_Box *s)
{
GF_SRTPProcessBox *ptr = (GF_SRTPProcessBox *)s;
if (ptr->info) gf_isom_box_del((GF_Box*)ptr->info);
if (ptr->scheme_type) gf_isom_box_del((GF_Box*)ptr->scheme_type);
gf_free(s);
}
GF_Err srpp_AddBox(GF_Box *s, GF_Box *a)
{
GF_SRTPProcessBox *ptr = (GF_SRTPProcessBox *)s;
switch(a->type) {
case GF_ISOM_BOX_TYPE_SCHI:
if (ptr->info) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->info = (GF_SchemeInformationBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_SCHM:
if (ptr->scheme_type) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->scheme_type = (GF_SchemeTypeBox *)a;
return GF_OK;
}
return gf_isom_box_add_default(s, a);
}
GF_Err srpp_Read(GF_Box *s, GF_BitStream *bs)
{
GF_SRTPProcessBox *ptr = (GF_SRTPProcessBox *)s;
ISOM_DECREASE_SIZE(s, 16)
ptr->encryption_algorithm_rtp = gf_bs_read_u32(bs);
ptr->encryption_algorithm_rtcp = gf_bs_read_u32(bs);
ptr->integrity_algorithm_rtp = gf_bs_read_u32(bs);
ptr->integrity_algorithm_rtp = gf_bs_read_u32(bs);
return gf_isom_box_array_read(s, bs, gf_isom_box_add_default);
}
GF_Box *srpp_New()
{
ISOM_DECL_BOX_ALLOC(GF_SRTPProcessBox, GF_ISOM_BOX_TYPE_SRPP);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err srpp_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_SRTPProcessBox *ptr = (GF_SRTPProcessBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->encryption_algorithm_rtp);
gf_bs_write_u32(bs, ptr->encryption_algorithm_rtcp);
gf_bs_write_u32(bs, ptr->integrity_algorithm_rtp);
gf_bs_write_u32(bs, ptr->integrity_algorithm_rtcp);
if (ptr->info) {
e = gf_isom_box_write((GF_Box*)ptr->info, bs);
if (e) return e;
}
if (ptr->scheme_type) {
e = gf_isom_box_write((GF_Box*)ptr->scheme_type, bs);
if (e) return e;
}
return GF_OK;
}
GF_Err srpp_Size(GF_Box *s)
{
GF_Err e;
GF_SRTPProcessBox *ptr = (GF_SRTPProcessBox *)s;
s->size += 16;
if (ptr->info) {
e = gf_isom_box_size((GF_Box*)ptr->info);
if (e) return e;
ptr->size += ptr->info->size;
}
if (ptr->scheme_type) {
e = gf_isom_box_size((GF_Box*)ptr->scheme_type);
if (e) return e;
ptr->size += ptr->scheme_type->size;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void rssr_del(GF_Box *s)
{
gf_free(s);
}
GF_Err rssr_Read(GF_Box *s, GF_BitStream *bs)
{
GF_ReceivedSsrcBox *ptr = (GF_ReceivedSsrcBox *)s;
ptr->ssrc = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *rssr_New()
{
ISOM_DECL_BOX_ALLOC(GF_ReceivedSsrcBox, GF_ISOM_BOX_TYPE_RSSR);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err rssr_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_ReceivedSsrcBox *ptr = (GF_ReceivedSsrcBox *)s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->ssrc);
return GF_OK;
}
GF_Err rssr_Size(GF_Box *s)
{
s->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void iods_del(GF_Box *s)
{
GF_ObjectDescriptorBox *ptr = (GF_ObjectDescriptorBox *)s;
if (ptr == NULL) return;
if (ptr->descriptor) gf_odf_desc_del(ptr->descriptor);
gf_free(ptr);
}
GF_Err iods_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 descSize;
char *desc;
GF_ObjectDescriptorBox *ptr = (GF_ObjectDescriptorBox *)s;
//use the OD codec...
descSize = (u32) (ptr->size);
desc = (char*)gf_malloc(sizeof(char) * descSize);
gf_bs_read_data(bs, desc, descSize);
e = gf_odf_desc_read(desc, descSize, &ptr->descriptor);
//OK, free our desc
gf_free(desc);
return e;
}
GF_Box *iods_New()
{
ISOM_DECL_BOX_ALLOC(GF_ObjectDescriptorBox, GF_ISOM_BOX_TYPE_IODS);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err iods_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 descSize;
char *desc;
GF_ObjectDescriptorBox *ptr = (GF_ObjectDescriptorBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
//call our OD codec
e = gf_odf_desc_write(ptr->descriptor, &desc, &descSize);
if (e) return e;
gf_bs_write_data(bs, desc, descSize);
//and free our stuff maybe!!
gf_free(desc);
return GF_OK;
}
GF_Err iods_Size(GF_Box *s)
{
GF_ObjectDescriptorBox *ptr = (GF_ObjectDescriptorBox *)s;
ptr->size += gf_odf_desc_size(ptr->descriptor);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void mdat_del(GF_Box *s)
{
GF_MediaDataBox *ptr = (GF_MediaDataBox *)s;
if (!s) return;
if (ptr->data) gf_free(ptr->data);
gf_free(ptr);
}
GF_Err mdat_Read(GF_Box *s, GF_BitStream *bs)
{
GF_MediaDataBox *ptr = (GF_MediaDataBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
ptr->dataSize = s->size;
ptr->bsOffset = gf_bs_get_position(bs);
//then skip these bytes
gf_bs_skip_bytes(bs, ptr->dataSize);
return GF_OK;
}
GF_Box *mdat_New()
{
ISOM_DECL_BOX_ALLOC(GF_MediaDataBox, GF_ISOM_BOX_TYPE_MDAT);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err mdat_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_MediaDataBox *ptr = (GF_MediaDataBox *)s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
//make sure we have some data ...
//if not, we handle that independantly (edit files)
if (ptr->data) {
gf_bs_write_data(bs, ptr->data, (u32) ptr->dataSize);
}
return GF_OK;
}
GF_Err mdat_Size(GF_Box *s)
{
GF_MediaDataBox *ptr = (GF_MediaDataBox *)s;
ptr->size += ptr->dataSize;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void mdhd_del(GF_Box *s)
{
GF_MediaHeaderBox *ptr = (GF_MediaHeaderBox *)s;
if (ptr == NULL) return;
gf_free(ptr);
}
GF_Err mdhd_Read(GF_Box *s, GF_BitStream *bs)
{
GF_MediaHeaderBox *ptr = (GF_MediaHeaderBox *)s;
if (ptr->version == 1) {
ptr->creationTime = gf_bs_read_u64(bs);
ptr->modificationTime = gf_bs_read_u64(bs);
ptr->timeScale = gf_bs_read_u32(bs);
ptr->duration = gf_bs_read_u64(bs);
} else {
ptr->creationTime = gf_bs_read_u32(bs);
ptr->modificationTime = gf_bs_read_u32(bs);
ptr->timeScale = gf_bs_read_u32(bs);
ptr->duration = gf_bs_read_u32(bs);
}
if (!ptr->timeScale) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Media header timescale is 0 - defaulting to 90000\n" ));
ptr->timeScale = 90000;
}
ptr->original_duration = ptr->duration;
//our padding bit
gf_bs_read_int(bs, 1);
//the spec is unclear here, just says "the value 0 is interpreted as undetermined"
ptr->packedLanguage[0] = gf_bs_read_int(bs, 5);
ptr->packedLanguage[1] = gf_bs_read_int(bs, 5);
ptr->packedLanguage[2] = gf_bs_read_int(bs, 5);
//but before or after compaction ?? We assume before
if (ptr->packedLanguage[0] || ptr->packedLanguage[1] || ptr->packedLanguage[2]) {
ptr->packedLanguage[0] += 0x60;
ptr->packedLanguage[1] += 0x60;
ptr->packedLanguage[2] += 0x60;
} else {
ptr->packedLanguage[0] = 'u';
ptr->packedLanguage[1] = 'n';
ptr->packedLanguage[2] = 'd';
}
ptr->reserved = gf_bs_read_u16(bs);
return GF_OK;
}
GF_Box *mdhd_New()
{
ISOM_DECL_BOX_ALLOC(GF_MediaHeaderBox, GF_ISOM_BOX_TYPE_MDHD);
tmp->packedLanguage[0] = 'u';
tmp->packedLanguage[1] = 'n';
tmp->packedLanguage[2] = 'd';
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err mdhd_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_MediaHeaderBox *ptr = (GF_MediaHeaderBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
if (ptr->version == 1) {
gf_bs_write_u64(bs, ptr->creationTime);
gf_bs_write_u64(bs, ptr->modificationTime);
gf_bs_write_u32(bs, ptr->timeScale);
gf_bs_write_u64(bs, ptr->duration);
} else {
gf_bs_write_u32(bs, (u32) ptr->creationTime);
gf_bs_write_u32(bs, (u32) ptr->modificationTime);
gf_bs_write_u32(bs, ptr->timeScale);
gf_bs_write_u32(bs, (u32) ptr->duration);
}
//SPECS: BIT(1) of padding
gf_bs_write_int(bs, 0, 1);
gf_bs_write_int(bs, ptr->packedLanguage[0] - 0x60, 5);
gf_bs_write_int(bs, ptr->packedLanguage[1] - 0x60, 5);
gf_bs_write_int(bs, ptr->packedLanguage[2] - 0x60, 5);
gf_bs_write_u16(bs, ptr->reserved);
return GF_OK;
}
GF_Err mdhd_Size(GF_Box *s)
{
GF_MediaHeaderBox *ptr = (GF_MediaHeaderBox *)s;
ptr->version = (ptr->duration>0xFFFFFFFF) ? 1 : 0;
ptr->size += 4;
ptr->size += (ptr->version == 1) ? 28 : 16;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void mdia_del(GF_Box *s)
{
GF_MediaBox *ptr = (GF_MediaBox *)s;
if (ptr == NULL) return;
if (ptr->mediaHeader) gf_isom_box_del((GF_Box *)ptr->mediaHeader);
if (ptr->information) gf_isom_box_del((GF_Box *)ptr->information);
if (ptr->handler) gf_isom_box_del((GF_Box *)ptr->handler);
gf_free(ptr);
}
GF_Err mdia_AddBox(GF_Box *s, GF_Box *a)
{
GF_MediaBox *ptr = (GF_MediaBox *)s;
switch(a->type) {
case GF_ISOM_BOX_TYPE_MDHD:
if (ptr->mediaHeader) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->mediaHeader = (GF_MediaHeaderBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_HDLR:
if (ptr->handler) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->handler = (GF_HandlerBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_MINF:
if (ptr->information) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->information = (GF_MediaInformationBox *)a;
return GF_OK;
default:
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err mdia_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e = gf_isom_box_array_read(s, bs, mdia_AddBox);
if (e) return e;
if (!((GF_MediaBox *)s)->information) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing MediaInformationBox\n"));
return GF_ISOM_INVALID_FILE;
}
if (!((GF_MediaBox *)s)->handler) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing HandlerBox\n"));
return GF_ISOM_INVALID_FILE;
}
if (!((GF_MediaBox *)s)->mediaHeader) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing MediaHeaderBox\n"));
return GF_ISOM_INVALID_FILE;
}
return GF_OK;
}
GF_Box *mdia_New()
{
ISOM_DECL_BOX_ALLOC(GF_MediaBox, GF_ISOM_BOX_TYPE_MDIA);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err mdia_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_MediaBox *ptr = (GF_MediaBox *)s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
//Header first
if (ptr->mediaHeader) {
e = gf_isom_box_write((GF_Box *) ptr->mediaHeader, bs);
if (e) return e;
}
//then handler
if (ptr->handler) {
e = gf_isom_box_write((GF_Box *) ptr->handler, bs);
if (e) return e;
}
if (ptr->information) {
e = gf_isom_box_write((GF_Box *) ptr->information, bs);
if (e) return e;
}
return GF_OK;
}
GF_Err mdia_Size(GF_Box *s)
{
GF_Err e;
GF_MediaBox *ptr = (GF_MediaBox *)s;
if (ptr->mediaHeader) {
e = gf_isom_box_size((GF_Box *) ptr->mediaHeader);
if (e) return e;
ptr->size += ptr->mediaHeader->size;
}
if (ptr->handler) {
e = gf_isom_box_size((GF_Box *) ptr->handler);
if (e) return e;
ptr->size += ptr->handler->size;
}
if (ptr->information) {
e = gf_isom_box_size((GF_Box *) ptr->information);
if (e) return e;
ptr->size += ptr->information->size;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void mfra_del(GF_Box *s)
{
GF_MovieFragmentRandomAccessBox *ptr = (GF_MovieFragmentRandomAccessBox *)s;
if (ptr == NULL) return;
if (ptr->mfro) gf_isom_box_del((GF_Box*)ptr->mfro);
gf_isom_box_array_del(ptr->tfra_list);
gf_free(ptr);
}
GF_Box *mfra_New()
{
ISOM_DECL_BOX_ALLOC(GF_MovieFragmentRandomAccessBox, GF_ISOM_BOX_TYPE_MFRA);
tmp->tfra_list = gf_list_new();
return (GF_Box *)tmp;
}
GF_Err mfra_AddBox(GF_Box *s, GF_Box *a)
{
GF_MovieFragmentRandomAccessBox *ptr = (GF_MovieFragmentRandomAccessBox *)s;
switch(a->type) {
case GF_ISOM_BOX_TYPE_TFRA:
return gf_list_add(ptr->tfra_list, a);
case GF_ISOM_BOX_TYPE_MFRO:
if (ptr->mfro) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->mfro = (GF_MovieFragmentRandomAccessOffsetBox *)a;
return GF_OK;
default:
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err mfra_Read(GF_Box *s, GF_BitStream *bs)
{
return gf_isom_box_array_read(s, bs, mfra_AddBox);
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err mfra_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_MovieFragmentRandomAccessBox *ptr = (GF_MovieFragmentRandomAccessBox *)s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
e = gf_isom_box_array_write(s, ptr->tfra_list, bs);
if (e) return e;
if (ptr->mfro) {
e = gf_isom_box_write((GF_Box *) ptr->mfro, bs);
if (e) return e;
}
return GF_OK;
}
GF_Err mfra_Size(GF_Box *s)
{
GF_Err e;
GF_MovieFragmentRandomAccessBox *ptr = (GF_MovieFragmentRandomAccessBox *)s;
if (ptr->mfro) {
e = gf_isom_box_size((GF_Box *)ptr->mfro);
if (e) return e;
ptr->size += ptr->mfro->size;
}
return gf_isom_box_array_size(s, ptr->tfra_list);
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void tfra_del(GF_Box *s)
{
GF_TrackFragmentRandomAccessBox *ptr = (GF_TrackFragmentRandomAccessBox *)s;
if (ptr == NULL) return;
if (ptr->entries) gf_free(ptr->entries);
gf_free(ptr);
}
GF_Box *tfra_New()
{
ISOM_DECL_BOX_ALLOC(GF_TrackFragmentRandomAccessBox, GF_ISOM_BOX_TYPE_TFRA);
return (GF_Box *)tmp;
}
GF_Err tfra_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i;
GF_RandomAccessEntry *p = 0;
GF_TrackFragmentRandomAccessBox *ptr = (GF_TrackFragmentRandomAccessBox *)s;
if (ptr->size<12) return GF_ISOM_INVALID_FILE;
ptr->track_id = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
if (gf_bs_read_int(bs, 26) !=0) return GF_ISOM_INVALID_FILE;
ptr->traf_bits = (gf_bs_read_int(bs, 2)+1)*8;
ptr->trun_bits = (gf_bs_read_int(bs, 2)+1)*8;
ptr->sample_bits = (gf_bs_read_int(bs, 2)+1)*8;
ISOM_DECREASE_SIZE(ptr, 4);
ptr->nb_entries = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
if (ptr->version==1) {
if (ptr->nb_entries > ptr->size / (16+(ptr->traf_bits+ptr->trun_bits+ptr->sample_bits)/8)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in traf\n", ptr->nb_entries));
return GF_ISOM_INVALID_FILE;
}
} else {
if (ptr->nb_entries > ptr->size / (8+(ptr->traf_bits+ptr->trun_bits+ptr->sample_bits)/8)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in traf\n", ptr->nb_entries));
return GF_ISOM_INVALID_FILE;
}
}
if (ptr->nb_entries)
{
p = (GF_RandomAccessEntry *) gf_malloc(sizeof(GF_RandomAccessEntry) * ptr->nb_entries);
if (!p) return GF_OUT_OF_MEM;
}
ptr->entries = p;
for (i=0; i<ptr->nb_entries; i++) {
memset(p, 0, sizeof(GF_RandomAccessEntry));
if (ptr->version==1) {
p->time = gf_bs_read_u64(bs);
p->moof_offset = gf_bs_read_u64(bs);
}
else
{
p->time = gf_bs_read_u32(bs);
p->moof_offset = gf_bs_read_u32(bs);
}
p->traf_number = gf_bs_read_int(bs, ptr->traf_bits);
p->trun_number = gf_bs_read_int(bs, ptr->trun_bits);
p->sample_number = gf_bs_read_int(bs, ptr->sample_bits);
++p;
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err tfra_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_TrackFragmentRandomAccessBox *ptr = (GF_TrackFragmentRandomAccessBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->track_id);
gf_bs_write_int(bs, 0, 26);
gf_bs_write_int(bs, ptr->traf_bits/8 - 1, 2);
gf_bs_write_int(bs, ptr->trun_bits/8 - 1, 2);
gf_bs_write_int(bs, ptr->sample_bits/8 - 1, 2);
gf_bs_write_u32(bs, ptr->nb_entries);
for (i=0; i<ptr->nb_entries; i++) {
GF_RandomAccessEntry *p = &ptr->entries[i];
if (ptr->version==1) {
gf_bs_write_u64(bs, p->time);
gf_bs_write_u64(bs, p->moof_offset);
} else {
gf_bs_write_u32(bs, (u32) p->time);
gf_bs_write_u32(bs, (u32) p->moof_offset);
}
gf_bs_write_int(bs, p->traf_number, ptr->traf_bits);
gf_bs_write_int(bs, p->trun_number, ptr->trun_bits);
gf_bs_write_int(bs, p->sample_number, ptr->sample_bits);
}
return GF_OK;
}
GF_Err tfra_Size(GF_Box *s)
{
GF_TrackFragmentRandomAccessBox *ptr = (GF_TrackFragmentRandomAccessBox *)s;
ptr->size += 12;
ptr->size += ptr->nb_entries * ( ((ptr->version==1) ? 16 : 8 ) + ptr->traf_bits/8 + ptr->trun_bits/8 + ptr->sample_bits/8);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void mfro_del(GF_Box *s)
{
GF_MovieFragmentRandomAccessOffsetBox *ptr = (GF_MovieFragmentRandomAccessOffsetBox *)s;
if (ptr == NULL) return;
gf_free(ptr);
}
GF_Box *mfro_New()
{
ISOM_DECL_BOX_ALLOC(GF_MovieFragmentRandomAccessOffsetBox, GF_ISOM_BOX_TYPE_MFRO);
return (GF_Box *)tmp;
}
GF_Err mfro_Read(GF_Box *s, GF_BitStream *bs)
{
GF_MovieFragmentRandomAccessOffsetBox *ptr = (GF_MovieFragmentRandomAccessOffsetBox *)s;
ptr->container_size = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err mfro_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_MovieFragmentRandomAccessOffsetBox *ptr = (GF_MovieFragmentRandomAccessOffsetBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->container_size);
return GF_OK;
}
GF_Err mfro_Size(GF_Box *s)
{
s->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void elng_del(GF_Box *s)
{
GF_ExtendedLanguageBox *ptr = (GF_ExtendedLanguageBox *)s;
if (ptr == NULL) return;
if (ptr->extended_language) gf_free(ptr->extended_language);
gf_free(ptr);
}
GF_Err elng_Read(GF_Box *s, GF_BitStream *bs)
{
GF_ExtendedLanguageBox *ptr = (GF_ExtendedLanguageBox *)s;
if (ptr->size) {
ptr->extended_language = (char*)gf_malloc((u32) ptr->size);
if (ptr->extended_language == NULL) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, ptr->extended_language, (u32) ptr->size);
/*safety check in case the string is not null-terminated*/
if (ptr->extended_language[ptr->size-1]) {
char *str = (char*)gf_malloc((u32) ptr->size + 1);
memcpy(str, ptr->extended_language, (u32) ptr->size);
str[ptr->size] = 0;
gf_free(ptr->extended_language);
ptr->extended_language = str;
}
}
return GF_OK;
}
GF_Box *elng_New()
{
ISOM_DECL_BOX_ALLOC(GF_MediaBox, GF_ISOM_BOX_TYPE_ELNG);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err elng_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_ExtendedLanguageBox *ptr = (GF_ExtendedLanguageBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
if (ptr->extended_language) {
gf_bs_write_data(bs, ptr->extended_language, (u32)(strlen(ptr->extended_language)+1));
}
return GF_OK;
}
GF_Err elng_Size(GF_Box *s)
{
GF_ExtendedLanguageBox *ptr = (GF_ExtendedLanguageBox *)s;
if (ptr->extended_language) {
ptr->size += strlen(ptr->extended_language)+1;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
void mfhd_del(GF_Box *s)
{
GF_MovieFragmentHeaderBox *ptr = (GF_MovieFragmentHeaderBox *)s;
if (ptr == NULL) return;
gf_free(ptr);
}
GF_Err mfhd_Read(GF_Box *s, GF_BitStream *bs)
{
GF_MovieFragmentHeaderBox *ptr = (GF_MovieFragmentHeaderBox *)s;
ptr->sequence_number = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *mfhd_New()
{
ISOM_DECL_BOX_ALLOC(GF_MovieFragmentHeaderBox, GF_ISOM_BOX_TYPE_MFHD);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err mfhd_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_MovieFragmentHeaderBox *ptr = (GF_MovieFragmentHeaderBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->sequence_number);
return GF_OK;
}
GF_Err mfhd_Size(GF_Box *s)
{
s->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/
void minf_del(GF_Box *s)
{
GF_MediaInformationBox *ptr = (GF_MediaInformationBox *)s;
if (ptr == NULL) return;
//if we have a Handler not self-contained, delete it (the self-contained belongs to the movie)
if (ptr->dataHandler) {
gf_isom_datamap_close(ptr);
}
if (ptr->InfoHeader) gf_isom_box_del((GF_Box *)ptr->InfoHeader);
if (ptr->dataInformation) gf_isom_box_del((GF_Box *)ptr->dataInformation);
if (ptr->sampleTable) gf_isom_box_del((GF_Box *)ptr->sampleTable);
gf_free(ptr);
}
GF_Err minf_AddBox(GF_Box *s, GF_Box *a)
{
GF_MediaInformationBox *ptr = (GF_MediaInformationBox *)s;
switch (a->type) {
case GF_ISOM_BOX_TYPE_NMHD:
case GF_ISOM_BOX_TYPE_STHD:
case GF_ISOM_BOX_TYPE_VMHD:
case GF_ISOM_BOX_TYPE_SMHD:
case GF_ISOM_BOX_TYPE_HMHD:
case GF_ISOM_BOX_TYPE_GMHD:
if (ptr->InfoHeader) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->InfoHeader = a;
return GF_OK;
case GF_ISOM_BOX_TYPE_DINF:
if (ptr->dataInformation) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->dataInformation = (GF_DataInformationBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_STBL:
if (ptr->sampleTable ) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->sampleTable = (GF_SampleTableBox *)a;
return GF_OK;
default:
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err minf_Read(GF_Box *s, GF_BitStream *bs)
{
GF_MediaInformationBox *ptr = (GF_MediaInformationBox *)s;
GF_Err e;
e = gf_isom_box_array_read(s, bs, minf_AddBox);
if (! ptr->dataInformation) {
GF_Box *dinf, *dref, *url;
Bool dump_mode = GF_FALSE;
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing DataInformationBox\n"));
//commented on purpose, we are still able to handle the file, we only throw an error but keep processing
// e = GF_ISOM_INVALID_FILE;
//add a dinf box to avoid any access to a null dinf
dinf = gf_isom_box_new(GF_ISOM_BOX_TYPE_DINF);
if (!dinf) return GF_OUT_OF_MEM;
if (ptr->InfoHeader && gf_list_find(ptr->other_boxes, ptr->InfoHeader)>=0) dump_mode = GF_TRUE;
if (ptr->sampleTable && gf_list_find(ptr->other_boxes, ptr->sampleTable)>=0) dump_mode = GF_TRUE;
ptr->dataInformation = (GF_DataInformationBox *)dinf;
dref = gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF);
if (!dref) return GF_OUT_OF_MEM;
e = dinf_AddBox(dinf, dref);
url = gf_isom_box_new(GF_ISOM_BOX_TYPE_URL);
if (!url) return GF_OUT_OF_MEM;
((GF_FullBox*)url)->flags = 1;
e = gf_isom_box_add_default(dref, url);
if (dump_mode) {
gf_list_add(ptr->other_boxes, ptr->dataInformation);
if (!dinf->other_boxes) dinf->other_boxes = gf_list_new();
gf_list_add(dinf->other_boxes, dref);
}
}
return e;
}
GF_Box *minf_New()
{
ISOM_DECL_BOX_ALLOC(GF_MediaInformationBox, GF_ISOM_BOX_TYPE_MINF);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err minf_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_MediaInformationBox *ptr = (GF_MediaInformationBox *)s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
//Header first
if (ptr->InfoHeader) {
e = gf_isom_box_write((GF_Box *) ptr->InfoHeader, bs);
if (e) return e;
}
//then dataInfo
if (ptr->dataInformation) {
e = gf_isom_box_write((GF_Box *) ptr->dataInformation, bs);
if (e) return e;
}
//then sampleTable
if (ptr->sampleTable) {
e = gf_isom_box_write((GF_Box *) ptr->sampleTable, bs);
if (e) return e;
}
return GF_OK;
}
GF_Err minf_Size(GF_Box *s)
{
GF_Err e;
GF_MediaInformationBox *ptr = (GF_MediaInformationBox *)s;
if (ptr->InfoHeader) {
e = gf_isom_box_size((GF_Box *) ptr->InfoHeader);
if (e) return e;
ptr->size += ptr->InfoHeader->size;
}
if (ptr->dataInformation) {
e = gf_isom_box_size((GF_Box *) ptr->dataInformation);
if (e) return e;
ptr->size += ptr->dataInformation->size;
}
if (ptr->sampleTable) {
e = gf_isom_box_size((GF_Box *) ptr->sampleTable);
if (e) return e;
ptr->size += ptr->sampleTable->size;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
void moof_del(GF_Box *s)
{
GF_MovieFragmentBox *ptr = (GF_MovieFragmentBox *)s;
if (ptr == NULL) return;
if (ptr->mfhd) gf_isom_box_del((GF_Box *) ptr->mfhd);
gf_isom_box_array_del(ptr->TrackList);
if (ptr->mdat) gf_free(ptr->mdat);
gf_free(ptr);
}
GF_Err moof_AddBox(GF_Box *s, GF_Box *a)
{
GF_MovieFragmentBox *ptr = (GF_MovieFragmentBox *)s;
switch (a->type) {
case GF_ISOM_BOX_TYPE_MFHD:
if (ptr->mfhd) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->mfhd = (GF_MovieFragmentHeaderBox *) a;
return GF_OK;
case GF_ISOM_BOX_TYPE_TRAF:
return gf_list_add(ptr->TrackList, a);
case GF_ISOM_BOX_TYPE_PSSH:
default:
return gf_isom_box_add_default(s, a);
}
}
GF_Err moof_Read(GF_Box *s, GF_BitStream *bs)
{
return gf_isom_box_array_read(s, bs, moof_AddBox);
}
GF_Box *moof_New()
{
ISOM_DECL_BOX_ALLOC(GF_MovieFragmentBox, GF_ISOM_BOX_TYPE_MOOF);
tmp->TrackList = gf_list_new();
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err moof_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_MovieFragmentBox *ptr = (GF_MovieFragmentBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
//Header First
if (ptr->mfhd) {
e = gf_isom_box_write((GF_Box *) ptr->mfhd, bs);
if (e) return e;
}
//then the track list
return gf_isom_box_array_write(s, ptr->TrackList, bs);
}
GF_Err moof_Size(GF_Box *s)
{
GF_Err e;
GF_MovieFragmentBox *ptr = (GF_MovieFragmentBox *)s;
if (ptr->mfhd) {
e = gf_isom_box_size((GF_Box *)ptr->mfhd);
if (e) return e;
ptr->size += ptr->mfhd->size;
}
return gf_isom_box_array_size(s, ptr->TrackList);
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/
void moov_del(GF_Box *s)
{
GF_MovieBox *ptr = (GF_MovieBox *)s;
if (ptr == NULL) return;
if (ptr->mvhd) gf_isom_box_del((GF_Box *)ptr->mvhd);
if (ptr->meta) gf_isom_box_del((GF_Box *)ptr->meta);
if (ptr->iods) gf_isom_box_del((GF_Box *)ptr->iods);
if (ptr->udta) gf_isom_box_del((GF_Box *)ptr->udta);
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
if (ptr->mvex) gf_isom_box_del((GF_Box *)ptr->mvex);
#endif
gf_isom_box_array_del(ptr->trackList);
gf_free(ptr);
}
GF_Err moov_AddBox(GF_Box *s, GF_Box *a)
{
GF_MovieBox *ptr = (GF_MovieBox *)s;
switch (a->type) {
case GF_ISOM_BOX_TYPE_IODS:
if (ptr->iods) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->iods = (GF_ObjectDescriptorBox *)a;
//if no IOD, delete the box
if (!ptr->iods->descriptor) {
ptr->iods = NULL;
gf_isom_box_del(a);
}
return GF_OK;
case GF_ISOM_BOX_TYPE_MVHD:
if (ptr->mvhd) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->mvhd = (GF_MovieHeaderBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_UDTA:
if (ptr->udta) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->udta = (GF_UserDataBox *)a;
return GF_OK;
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
case GF_ISOM_BOX_TYPE_MVEX:
if (ptr->mvex) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->mvex = (GF_MovieExtendsBox *)a;
ptr->mvex->mov = ptr->mov;
return GF_OK;
#endif
case GF_ISOM_BOX_TYPE_META:
if (ptr->meta) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->meta = (GF_MetaBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_TRAK:
//set our pointer to this obj
((GF_TrackBox *)a)->moov = ptr;
return gf_list_add(ptr->trackList, a);
case GF_ISOM_BOX_TYPE_PSSH:
default:
return gf_isom_box_add_default(s, a);
}
}
GF_Err moov_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
e = gf_isom_box_array_read(s, bs, moov_AddBox);
if (e) {
return e;
}
else {
if (!((GF_MovieBox *)s)->mvhd) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing MovieHeaderBox\n"));
return GF_ISOM_INVALID_FILE;
}
}
return e;
}
GF_Box *moov_New()
{
ISOM_DECL_BOX_ALLOC(GF_MovieBox, GF_ISOM_BOX_TYPE_MOOV);
tmp->trackList = gf_list_new();
if (!tmp->trackList) {
gf_free(tmp);
return NULL;
}
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err moov_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_MovieBox *ptr = (GF_MovieBox *)s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
if (ptr->mvhd) {
e = gf_isom_box_write((GF_Box *) ptr->mvhd, bs);
if (e) return e;
}
if (ptr->iods) {
e = gf_isom_box_write((GF_Box *) ptr->iods, bs);
if (e) return e;
}
if (ptr->meta) {
e = gf_isom_box_write((GF_Box *) ptr->meta, bs);
if (e) return e;
}
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
if (ptr->mvex) {
e = gf_isom_box_write((GF_Box *) ptr->mvex, bs);
if (e) return e;
}
#endif
e = gf_isom_box_array_write(s, ptr->trackList, bs);
if (e) return e;
if (ptr->udta) {
e = gf_isom_box_write((GF_Box *) ptr->udta, bs);
if (e) return e;
}
return GF_OK;
}
GF_Err moov_Size(GF_Box *s)
{
GF_Err e;
GF_MovieBox *ptr = (GF_MovieBox *)s;
if (ptr->mvhd) {
e = gf_isom_box_size((GF_Box *) ptr->mvhd);
if (e) return e;
ptr->size += ptr->mvhd->size;
}
if (ptr->iods) {
e = gf_isom_box_size((GF_Box *) ptr->iods);
if (e) return e;
ptr->size += ptr->iods->size;
}
if (ptr->udta) {
e = gf_isom_box_size((GF_Box *) ptr->udta);
if (e) return e;
ptr->size += ptr->udta->size;
}
if (ptr->meta) {
e = gf_isom_box_size((GF_Box *) ptr->meta);
if (e) return e;
ptr->size += ptr->meta->size;
}
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
if (ptr->mvex) {
e = gf_isom_box_size((GF_Box *) ptr->mvex);
if (e) return e;
ptr->size += ptr->mvex->size;
}
#endif
return gf_isom_box_array_size(s, ptr->trackList);
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void audio_sample_entry_del(GF_Box *s)
{
GF_MPEGAudioSampleEntryBox *ptr = (GF_MPEGAudioSampleEntryBox *)s;
if (ptr == NULL) return;
gf_isom_sample_entry_predestroy((GF_SampleEntryBox *)s);
if (ptr->esd) gf_isom_box_del((GF_Box *)ptr->esd);
if (ptr->slc) gf_odf_desc_del((GF_Descriptor *)ptr->slc);
if (ptr->cfg_ac3) gf_isom_box_del((GF_Box *)ptr->cfg_ac3);
if (ptr->cfg_3gpp) gf_isom_box_del((GF_Box *)ptr->cfg_3gpp);
gf_free(ptr);
}
GF_Err audio_sample_entry_AddBox(GF_Box *s, GF_Box *a)
{
GF_MPEGAudioSampleEntryBox *ptr = (GF_MPEGAudioSampleEntryBox *)s;
switch (a->type) {
case GF_ISOM_BOX_TYPE_ESDS:
if (ptr->esd) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->esd = (GF_ESDBox *)a;
break;
case GF_ISOM_BOX_TYPE_SINF:
gf_list_add(ptr->protections, a);
break;
case GF_ISOM_BOX_TYPE_DAMR:
case GF_ISOM_BOX_TYPE_DEVC:
case GF_ISOM_BOX_TYPE_DQCP:
case GF_ISOM_BOX_TYPE_DSMV:
ptr->cfg_3gpp = (GF_3GPPConfigBox *) a;
/*for 3GP config, remember sample entry type in config*/
ptr->cfg_3gpp->cfg.type = ptr->type;
break;
case GF_ISOM_BOX_TYPE_DAC3:
ptr->cfg_ac3 = (GF_AC3ConfigBox *) a;
break;
case GF_ISOM_BOX_TYPE_DEC3:
ptr->cfg_ac3 = (GF_AC3ConfigBox *) a;
break;
case GF_ISOM_BOX_TYPE_UNKNOWN:
if (ptr->esd) ERROR_ON_DUPLICATED_BOX(a, ptr)
/*HACK for QT files: get the esds box from the track*/
{
GF_UnknownBox *wave = (GF_UnknownBox *)a;
//wave subboxes may have been properly parsed
if ((wave->original_4cc == GF_ISOM_BOX_TYPE_WAVE) && gf_list_count(wave->other_boxes)) {
u32 i;
for (i =0; i<gf_list_count(wave->other_boxes); i++) {
GF_Box *inner_box = (GF_Box *)gf_list_get(wave->other_boxes, i);
if (inner_box->type == GF_ISOM_BOX_TYPE_ESDS) {
ptr->esd = (GF_ESDBox *)inner_box;
}
}
return gf_isom_box_add_default(s, a);
}
//unknown fomat, look for 'es' (esds) and try to parse box
else if (wave->data != NULL) {
u32 offset = 0;
while ((wave->data[offset + 4] != 'e') && (wave->data[offset + 5] != 's')) {
offset++;
if (offset == wave->dataSize) break;
}
if (offset < wave->dataSize) {
GF_Box *a;
GF_Err e;
GF_BitStream *bs = gf_bs_new(wave->data + offset, wave->dataSize - offset, GF_BITSTREAM_READ);
e = gf_isom_box_parse(&a, bs);
gf_bs_del(bs);
if (e) return e;
ptr->esd = (GF_ESDBox *)a;
gf_isom_box_add_for_dump_mode((GF_Box *)ptr, a);
}
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Cannot process box %s!\n", gf_4cc_to_str(wave->original_4cc)));
return gf_isom_box_add_default(s, a);
}
gf_isom_box_del(a);
return GF_ISOM_INVALID_MEDIA;
}
break;
default:
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err audio_sample_entry_Read(GF_Box *s, GF_BitStream *bs)
{
GF_MPEGAudioSampleEntryBox *ptr;
char *data;
u32 i, size;
GF_Err e;
u64 pos;
e = gf_isom_audio_sample_entry_read((GF_AudioSampleEntryBox*)s, bs);
if (e) return e;
pos = gf_bs_get_position(bs);
size = (u32) s->size;
e = gf_isom_box_array_read(s, bs, audio_sample_entry_AddBox);
if (!e) return GF_OK;
if (size<8) return GF_ISOM_INVALID_FILE;
/*hack for some weird files (possibly recorded with live.com tools, needs further investigations)*/
ptr = (GF_MPEGAudioSampleEntryBox *)s;
gf_bs_seek(bs, pos);
data = (char*)gf_malloc(sizeof(char) * size);
gf_bs_read_data(bs, data, size);
for (i=0; i<size-8; i++) {
if (GF_4CC(data[i+4], data[i+5], data[i+6], data[i+7]) == GF_ISOM_BOX_TYPE_ESDS) {
GF_BitStream *mybs = gf_bs_new(data + i, size - i, GF_BITSTREAM_READ);
e = gf_isom_box_parse((GF_Box **)&ptr->esd, mybs);
gf_bs_del(mybs);
break;
}
}
gf_free(data);
return e;
}
GF_Box *audio_sample_entry_New()
{
ISOM_DECL_BOX_ALLOC(GF_MPEGAudioSampleEntryBox, GF_ISOM_BOX_TYPE_MP4A);
gf_isom_audio_sample_entry_init((GF_AudioSampleEntryBox*)tmp);
return (GF_Box *)tmp;
}
GF_Box *enca_New()
{
ISOM_DECL_BOX_ALLOC(GF_MPEGAudioSampleEntryBox, GF_ISOM_BOX_TYPE_ENCA);
gf_isom_audio_sample_entry_init((GF_AudioSampleEntryBox*)tmp);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err audio_sample_entry_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_MPEGAudioSampleEntryBox *ptr = (GF_MPEGAudioSampleEntryBox *)s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_isom_audio_sample_entry_write((GF_AudioSampleEntryBox*)s, bs);
if (ptr->esd) {
e = gf_isom_box_write((GF_Box *)ptr->esd, bs);
if (e) return e;
}
if (ptr->cfg_3gpp) {
e = gf_isom_box_write((GF_Box *)ptr->cfg_3gpp, bs);
if (e) return e;
}
if (ptr->cfg_ac3) {
e = gf_isom_box_write((GF_Box *)ptr->cfg_ac3, bs);
if (e) return e;
}
return gf_isom_box_array_write(s, ptr->protections, bs);
}
GF_Err audio_sample_entry_Size(GF_Box *s)
{
GF_Err e;
GF_MPEGAudioSampleEntryBox *ptr = (GF_MPEGAudioSampleEntryBox *)s;
gf_isom_audio_sample_entry_size((GF_AudioSampleEntryBox*)s);
if (ptr->esd) {
e = gf_isom_box_size((GF_Box *)ptr->esd);
if (e) return e;
ptr->size += ptr->esd->size;
}
if (ptr->cfg_3gpp) {
e = gf_isom_box_size((GF_Box *)ptr->cfg_3gpp);
if (e) return e;
ptr->size += ptr->cfg_3gpp->size;
}
if (ptr->cfg_ac3) {
e = gf_isom_box_size((GF_Box *)ptr->cfg_ac3);
if (e) return e;
ptr->size += ptr->cfg_ac3->size;
}
return gf_isom_box_array_size(s, ptr->protections);
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void mp4s_del(GF_Box *s)
{
GF_MPEGSampleEntryBox *ptr = (GF_MPEGSampleEntryBox *)s;
if (ptr == NULL) return;
gf_isom_sample_entry_predestroy((GF_SampleEntryBox *)s);
if (ptr->esd) gf_isom_box_del((GF_Box *)ptr->esd);
if (ptr->slc) gf_odf_desc_del((GF_Descriptor *)ptr->slc);
gf_free(ptr);
}
GF_Err mp4s_AddBox(GF_Box *s, GF_Box *a)
{
GF_MPEGSampleEntryBox *ptr = (GF_MPEGSampleEntryBox *)s;
switch (a->type) {
case GF_ISOM_BOX_TYPE_ESDS:
if (ptr->esd) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->esd = (GF_ESDBox *)a;
break;
case GF_ISOM_BOX_TYPE_SINF:
gf_list_add(ptr->protections, a);
break;
default:
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err mp4s_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_MPEGSampleEntryBox *ptr = (GF_MPEGSampleEntryBox *)s;
e = gf_isom_base_sample_entry_read((GF_SampleEntryBox *)ptr, bs);
if (e) return e;
ISOM_DECREASE_SIZE(ptr, 8);
return gf_isom_box_array_read(s, bs, mp4s_AddBox);
}
GF_Box *mp4s_New()
{
ISOM_DECL_BOX_ALLOC(GF_MPEGSampleEntryBox, GF_ISOM_BOX_TYPE_MP4S);
gf_isom_sample_entry_init((GF_SampleEntryBox*)tmp);
return (GF_Box *)tmp;
}
GF_Box *encs_New()
{
ISOM_DECL_BOX_ALLOC(GF_MPEGSampleEntryBox, GF_ISOM_BOX_TYPE_ENCS);
gf_isom_sample_entry_init((GF_SampleEntryBox*)tmp);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err mp4s_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_MPEGSampleEntryBox *ptr = (GF_MPEGSampleEntryBox *)s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_data(bs, ptr->reserved, 6);
gf_bs_write_u16(bs, ptr->dataReferenceIndex);
e = gf_isom_box_write((GF_Box *)ptr->esd, bs);
if (e) return e;
return gf_isom_box_array_write(s, ptr->protections, bs);
}
GF_Err mp4s_Size(GF_Box *s)
{
GF_Err e;
GF_MPEGSampleEntryBox *ptr = (GF_MPEGSampleEntryBox *)s;
ptr->size += 8;
e = gf_isom_box_size((GF_Box *)ptr->esd);
if (e) return e;
ptr->size += ptr->esd->size;
return gf_isom_box_array_size(s, ptr->protections);
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void video_sample_entry_del(GF_Box *s)
{
GF_MPEGVisualSampleEntryBox *ptr = (GF_MPEGVisualSampleEntryBox *)s;
if (ptr == NULL) return;
gf_isom_sample_entry_predestroy((GF_SampleEntryBox *)s);
if (ptr->esd) gf_isom_box_del((GF_Box *)ptr->esd);
if (ptr->slc) gf_odf_desc_del((GF_Descriptor *)ptr->slc);
/*for publishing*/
if (ptr->emul_esd) gf_odf_desc_del((GF_Descriptor *)ptr->emul_esd);
if (ptr->avc_config) gf_isom_box_del((GF_Box *) ptr->avc_config);
if (ptr->svc_config) gf_isom_box_del((GF_Box *) ptr->svc_config);
if (ptr->mvc_config) gf_isom_box_del((GF_Box *) ptr->mvc_config);
if (ptr->hevc_config) gf_isom_box_del((GF_Box *) ptr->hevc_config);
if (ptr->lhvc_config) gf_isom_box_del((GF_Box *) ptr->lhvc_config);
if (ptr->cfg_3gpp) gf_isom_box_del((GF_Box *)ptr->cfg_3gpp);
if (ptr->descr) gf_isom_box_del((GF_Box *) ptr->descr);
if (ptr->ipod_ext) gf_isom_box_del((GF_Box *)ptr->ipod_ext);
if (ptr->pasp) gf_isom_box_del((GF_Box *)ptr->pasp);
if (ptr->clap) gf_isom_box_del((GF_Box *)ptr->clap);
if (ptr->rinf) gf_isom_box_del((GF_Box *)ptr->rinf);
if (ptr->rvcc) gf_isom_box_del((GF_Box *)ptr->rvcc);
gf_free(ptr);
}
GF_Err video_sample_entry_AddBox(GF_Box *s, GF_Box *a)
{
GF_MPEGVisualSampleEntryBox *ptr = (GF_MPEGVisualSampleEntryBox *)s;
switch (a->type) {
case GF_ISOM_BOX_TYPE_ESDS:
if (ptr->esd) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->esd = (GF_ESDBox *)a;
break;
case GF_ISOM_BOX_TYPE_SINF:
gf_list_add(ptr->protections, a);
break;
case GF_ISOM_BOX_TYPE_RINF:
if (ptr->rinf) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->rinf = (GF_RestrictedSchemeInfoBox *) a;
break;
case GF_ISOM_BOX_TYPE_AVCC:
if (ptr->avc_config) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->avc_config = (GF_AVCConfigurationBox *)a;
break;
case GF_ISOM_BOX_TYPE_HVCC:
if (ptr->hevc_config) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->hevc_config = (GF_HEVCConfigurationBox *)a;
break;
case GF_ISOM_BOX_TYPE_SVCC:
if (ptr->svc_config) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->svc_config = (GF_AVCConfigurationBox *)a;
break;
case GF_ISOM_BOX_TYPE_MVCC:
if (ptr->mvc_config) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->mvc_config = (GF_AVCConfigurationBox *)a;
break;
case GF_ISOM_BOX_TYPE_LHVC:
if (ptr->lhvc_config) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->lhvc_config = (GF_HEVCConfigurationBox *)a;
break;
case GF_ISOM_BOX_TYPE_M4DS:
if (ptr->descr) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->descr = (GF_MPEG4ExtensionDescriptorsBox *)a;
break;
case GF_ISOM_BOX_TYPE_UUID:
if (! memcmp(((GF_UnknownUUIDBox*)a)->uuid, GF_ISOM_IPOD_EXT, 16)) {
if (ptr->ipod_ext) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->ipod_ext = (GF_UnknownUUIDBox *)a;
} else {
return gf_isom_box_add_default(s, a);
}
break;
case GF_ISOM_BOX_TYPE_D263:
ptr->cfg_3gpp = (GF_3GPPConfigBox *)a;
/*for 3GP config, remember sample entry type in config*/
ptr->cfg_3gpp->cfg.type = ptr->type;
break;
break;
case GF_ISOM_BOX_TYPE_PASP:
if (ptr->pasp) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->pasp = (GF_PixelAspectRatioBox *)a;
break;
case GF_ISOM_BOX_TYPE_CLAP:
if (ptr->clap) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->clap = (GF_CleanAppertureBox *)a;
break;
case GF_ISOM_BOX_TYPE_RVCC:
if (ptr->rvcc) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->rvcc = (GF_RVCConfigurationBox *)a;
break;
default:
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err video_sample_entry_Read(GF_Box *s, GF_BitStream *bs)
{
GF_MPEGVisualSampleEntryBox *mp4v = (GF_MPEGVisualSampleEntryBox*)s;
GF_Err e;
e = gf_isom_video_sample_entry_read((GF_VisualSampleEntryBox *)s, bs);
if (e) return e;
e = gf_isom_box_array_read(s, bs, video_sample_entry_AddBox);
if (e) return e;
/*this is an AVC sample desc*/
if (mp4v->avc_config || mp4v->svc_config || mp4v->mvc_config) AVC_RewriteESDescriptor(mp4v);
/*this is an HEVC sample desc*/
if (mp4v->hevc_config || mp4v->lhvc_config || (mp4v->type==GF_ISOM_BOX_TYPE_HVT1))
HEVC_RewriteESDescriptor(mp4v);
return GF_OK;
}
GF_Box *video_sample_entry_New()
{
GF_MPEGVisualSampleEntryBox *tmp;
GF_SAFEALLOC(tmp, GF_MPEGVisualSampleEntryBox);
if (tmp == NULL) return NULL;
gf_isom_video_sample_entry_init((GF_VisualSampleEntryBox *)tmp);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err video_sample_entry_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_MPEGVisualSampleEntryBox *ptr = (GF_MPEGVisualSampleEntryBox *)s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_isom_video_sample_entry_write((GF_VisualSampleEntryBox *)s, bs);
/*mp4v*/
if (ptr->esd) {
e = gf_isom_box_write((GF_Box *)ptr->esd, bs);
if (e) return e;
}
/*mp4v*/
else if (ptr->cfg_3gpp) {
e = gf_isom_box_write((GF_Box *)ptr->cfg_3gpp, bs);
if (e) return e;
}
/*avc or hevc*/
else {
if (ptr->avc_config && ptr->avc_config->config) {
e = gf_isom_box_write((GF_Box *) ptr->avc_config, bs);
if (e) return e;
}
if (ptr->hevc_config && ptr->hevc_config->config) {
e = gf_isom_box_write((GF_Box *) ptr->hevc_config, bs);
if (e) return e;
}
if (ptr->ipod_ext) {
e = gf_isom_box_write((GF_Box *) ptr->ipod_ext, bs);
if (e) return e;
}
if (ptr->descr) {
e = gf_isom_box_write((GF_Box *) ptr->descr, bs);
if (e) return e;
}
if (ptr->svc_config && ptr->svc_config->config) {
e = gf_isom_box_write((GF_Box *) ptr->svc_config, bs);
if (e) return e;
}
if (ptr->mvc_config && ptr->mvc_config->config) {
e = gf_isom_box_write((GF_Box *) ptr->mvc_config, bs);
if (e) return e;
}
if (ptr->lhvc_config && ptr->lhvc_config->config) {
e = gf_isom_box_write((GF_Box *) ptr->lhvc_config, bs);
if (e) return e;
}
}
if (ptr->pasp) {
e = gf_isom_box_write((GF_Box *)ptr->pasp, bs);
if (e) return e;
}
if (ptr->clap) {
e = gf_isom_box_write((GF_Box *)ptr->clap, bs);
if (e) return e;
}
if (ptr->rvcc) {
e = gf_isom_box_write((GF_Box *)ptr->rvcc, bs);
if (e) return e;
}
if (ptr->rinf) {
e = gf_isom_box_write((GF_Box *)ptr->rinf, bs);
if (e) return e;
}
return gf_isom_box_array_write(s, ptr->protections, bs);
}
GF_Err video_sample_entry_Size(GF_Box *s)
{
GF_Err e;
GF_MPEGVisualSampleEntryBox *ptr = (GF_MPEGVisualSampleEntryBox *)s;
gf_isom_video_sample_entry_size((GF_VisualSampleEntryBox *)s);
if (ptr->esd) {
e = gf_isom_box_size((GF_Box *)ptr->esd);
if (e) return e;
ptr->size += ptr->esd->size;
} else if (ptr->cfg_3gpp) {
e = gf_isom_box_size((GF_Box *)ptr->cfg_3gpp);
if (e) return e;
ptr->size += ptr->cfg_3gpp->size;
} else {
if (!ptr->avc_config && !ptr->svc_config && !ptr->hevc_config && !ptr->lhvc_config && (ptr->type!=GF_ISOM_BOX_TYPE_HVT1) ) {
return GF_ISOM_INVALID_FILE;
}
if (ptr->hevc_config && ptr->hevc_config->config) {
e = gf_isom_box_size((GF_Box *)ptr->hevc_config);
if (e) return e;
ptr->size += ptr->hevc_config->size;
}
if (ptr->avc_config && ptr->avc_config->config) {
e = gf_isom_box_size((GF_Box *) ptr->avc_config);
if (e) return e;
ptr->size += ptr->avc_config->size;
}
if (ptr->svc_config && ptr->svc_config->config) {
e = gf_isom_box_size((GF_Box *) ptr->svc_config);
if (e) return e;
ptr->size += ptr->svc_config->size;
}
if (ptr->mvc_config && ptr->mvc_config->config) {
e = gf_isom_box_size((GF_Box *) ptr->mvc_config);
if (e) return e;
ptr->size += ptr->mvc_config->size;
}
if (ptr->lhvc_config && ptr->lhvc_config->config) {
e = gf_isom_box_size((GF_Box *) ptr->lhvc_config);
if (e) return e;
ptr->size += ptr->lhvc_config->size;
}
if (ptr->ipod_ext) {
e = gf_isom_box_size((GF_Box *) ptr->ipod_ext);
if (e) return e;
ptr->size += ptr->ipod_ext->size;
}
if (ptr->descr) {
e = gf_isom_box_size((GF_Box *) ptr->descr);
if (e) return e;
ptr->size += ptr->descr->size;
}
}
if (ptr->pasp) {
e = gf_isom_box_size((GF_Box *)ptr->pasp);
if (e) return e;
ptr->size += ptr->pasp->size;
}
if (ptr->clap) {
e = gf_isom_box_size((GF_Box *)ptr->clap);
if (e) return e;
ptr->size += ptr->clap->size;
}
if (ptr->rvcc) {
e = gf_isom_box_size((GF_Box *)ptr->rvcc);
if (e) return e;
ptr->size += ptr->rvcc->size;
}
if (ptr->rinf) {
e = gf_isom_box_size((GF_Box *)ptr->rinf);
if (e) return e;
ptr->size += ptr->rinf->size;
}
return gf_isom_box_array_size(s, ptr->protections);
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
void mvex_del(GF_Box *s)
{
GF_MovieExtendsBox *ptr = (GF_MovieExtendsBox *)s;
if (ptr == NULL) return;
if (ptr->mehd) gf_isom_box_del((GF_Box*)ptr->mehd);
gf_isom_box_array_del(ptr->TrackExList);
gf_isom_box_array_del(ptr->TrackExPropList);
gf_free(ptr);
}
GF_Err mvex_AddBox(GF_Box *s, GF_Box *a)
{
GF_MovieExtendsBox *ptr = (GF_MovieExtendsBox *)s;
switch (a->type) {
case GF_ISOM_BOX_TYPE_TREX:
return gf_list_add(ptr->TrackExList, a);
case GF_ISOM_BOX_TYPE_TREP:
return gf_list_add(ptr->TrackExPropList, a);
case GF_ISOM_BOX_TYPE_MEHD:
if (ptr->mehd) break;
ptr->mehd = (GF_MovieExtendsHeaderBox*)a;
return GF_OK;
default:
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err mvex_Read(GF_Box *s, GF_BitStream *bs)
{
return gf_isom_box_array_read(s, bs, mvex_AddBox);
}
GF_Box *mvex_New()
{
ISOM_DECL_BOX_ALLOC(GF_MovieExtendsBox, GF_ISOM_BOX_TYPE_MVEX);
tmp->TrackExList = gf_list_new();
if (!tmp->TrackExList) {
gf_free(tmp);
return NULL;
}
tmp->TrackExPropList = gf_list_new();
if (!tmp->TrackExPropList) {
gf_list_del(tmp->TrackExList);
gf_free(tmp);
return NULL;
}
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err mvex_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_MovieExtendsBox *ptr = (GF_MovieExtendsBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
if (ptr->mehd) {
e = gf_isom_box_write((GF_Box *)ptr->mehd, bs);
if (e) return e;
}
e = gf_isom_box_array_write(s, ptr->TrackExList, bs);
if (e) return e;
return gf_isom_box_array_write(s, ptr->TrackExPropList, bs);
}
GF_Err mvex_Size(GF_Box *s)
{
GF_Err e;
GF_MovieExtendsBox *ptr = (GF_MovieExtendsBox *)s;
if (ptr->mehd) {
e = gf_isom_box_size((GF_Box *)ptr->mehd);
if (e) return e;
ptr->size += ptr->mehd->size;
}
e = gf_isom_box_array_size(s, ptr->TrackExList);
if (e) return e;
return gf_isom_box_array_size(s, ptr->TrackExPropList);
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *mehd_New()
{
ISOM_DECL_BOX_ALLOC(GF_MovieExtendsHeaderBox, GF_ISOM_BOX_TYPE_MEHD);
return (GF_Box *)tmp;
}
void mehd_del(GF_Box *s)
{
gf_free(s);
}
GF_Err mehd_Read(GF_Box *s, GF_BitStream *bs)
{
GF_MovieExtendsHeaderBox *ptr = (GF_MovieExtendsHeaderBox *)s;
if (ptr->version==1) {
ptr->fragment_duration = gf_bs_read_u64(bs);
} else {
ptr->fragment_duration = (u64) gf_bs_read_u32(bs);
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err mehd_Write(GF_Box *s, GF_BitStream *bs)
{
GF_MovieExtendsHeaderBox *ptr = (GF_MovieExtendsHeaderBox *)s;
GF_Err e = gf_isom_full_box_write(s, bs);
if (e) return e;
if (ptr->version == 1) {
gf_bs_write_u64(bs, ptr->fragment_duration);
} else {
gf_bs_write_u32(bs, (u32) ptr->fragment_duration);
}
return GF_OK;
}
GF_Err mehd_Size(GF_Box *s)
{
GF_MovieExtendsHeaderBox *ptr = (GF_MovieExtendsHeaderBox *)s;
ptr->version = (ptr->fragment_duration>0xFFFFFFFF) ? 1 : 0;
s->size += (ptr->version == 1) ? 8 : 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/
void mvhd_del(GF_Box *s)
{
GF_MovieHeaderBox *ptr = (GF_MovieHeaderBox *)s;
if (ptr == NULL) return;
gf_free(ptr);
}
GF_Err mvhd_Read(GF_Box *s, GF_BitStream *bs)
{
GF_MovieHeaderBox *ptr = (GF_MovieHeaderBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
if (ptr->version == 1) {
ptr->creationTime = gf_bs_read_u64(bs);
ptr->modificationTime = gf_bs_read_u64(bs);
ptr->timeScale = gf_bs_read_u32(bs);
ptr->duration = gf_bs_read_u64(bs);
} else {
ptr->creationTime = gf_bs_read_u32(bs);
ptr->modificationTime = gf_bs_read_u32(bs);
ptr->timeScale = gf_bs_read_u32(bs);
ptr->duration = gf_bs_read_u32(bs);
}
if (!ptr->timeScale) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Movie header timescale is invalid (0) - defaulting to 600\n" ));
ptr->timeScale = 600;
}
ptr->preferredRate = gf_bs_read_u32(bs);
ptr->preferredVolume = gf_bs_read_u16(bs);
gf_bs_read_data(bs, ptr->reserved, 10);
ptr->matrixA = gf_bs_read_u32(bs);
ptr->matrixB = gf_bs_read_u32(bs);
ptr->matrixU = gf_bs_read_u32(bs);
ptr->matrixC = gf_bs_read_u32(bs);
ptr->matrixD = gf_bs_read_u32(bs);
ptr->matrixV = gf_bs_read_u32(bs);
ptr->matrixX = gf_bs_read_u32(bs);
ptr->matrixY = gf_bs_read_u32(bs);
ptr->matrixW = gf_bs_read_u32(bs);
ptr->previewTime = gf_bs_read_u32(bs);
ptr->previewDuration = gf_bs_read_u32(bs);
ptr->posterTime = gf_bs_read_u32(bs);
ptr->selectionTime = gf_bs_read_u32(bs);
ptr->selectionDuration = gf_bs_read_u32(bs);
ptr->currentTime = gf_bs_read_u32(bs);
ptr->nextTrackID = gf_bs_read_u32(bs);
ptr->original_duration = ptr->duration;
return GF_OK;
}
GF_Box *mvhd_New()
{
ISOM_DECL_BOX_ALLOC(GF_MovieHeaderBox, GF_ISOM_BOX_TYPE_MVHD);
tmp->preferredRate = (1<<16);
tmp->preferredVolume = (1<<8);
tmp->matrixA = (1<<16);
tmp->matrixD = (1<<16);
tmp->matrixW = (1<<30);
tmp->nextTrackID = 1;
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err mvhd_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_MovieHeaderBox *ptr = (GF_MovieHeaderBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
if (ptr->version == 1) {
gf_bs_write_u64(bs, ptr->creationTime);
gf_bs_write_u64(bs, ptr->modificationTime);
gf_bs_write_u32(bs, ptr->timeScale);
gf_bs_write_u64(bs, ptr->duration);
} else {
gf_bs_write_u32(bs, (u32) ptr->creationTime);
gf_bs_write_u32(bs, (u32) ptr->modificationTime);
gf_bs_write_u32(bs, ptr->timeScale);
gf_bs_write_u32(bs, (u32) ptr->duration);
}
gf_bs_write_u32(bs, ptr->preferredRate);
gf_bs_write_u16(bs, ptr->preferredVolume);
gf_bs_write_data(bs, ptr->reserved, 10);
gf_bs_write_u32(bs, ptr->matrixA);
gf_bs_write_u32(bs, ptr->matrixB);
gf_bs_write_u32(bs, ptr->matrixU);
gf_bs_write_u32(bs, ptr->matrixC);
gf_bs_write_u32(bs, ptr->matrixD);
gf_bs_write_u32(bs, ptr->matrixV);
gf_bs_write_u32(bs, ptr->matrixX);
gf_bs_write_u32(bs, ptr->matrixY);
gf_bs_write_u32(bs, ptr->matrixW);
gf_bs_write_u32(bs, ptr->previewTime);
gf_bs_write_u32(bs, ptr->previewDuration);
gf_bs_write_u32(bs, ptr->posterTime);
gf_bs_write_u32(bs, ptr->selectionTime);
gf_bs_write_u32(bs, ptr->selectionDuration);
gf_bs_write_u32(bs, ptr->currentTime);
gf_bs_write_u32(bs, ptr->nextTrackID);
return GF_OK;
}
GF_Err mvhd_Size(GF_Box *s)
{
GF_MovieHeaderBox *ptr = (GF_MovieHeaderBox *)s;
if (ptr->duration==(u64) -1) ptr->version = 0;
else ptr->version = (ptr->duration>0xFFFFFFFF) ? 1 : 0;
ptr->size += (ptr->version == 1) ? 28 : 16;
ptr->size += 80;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void nmhd_del(GF_Box *s)
{
GF_MPEGMediaHeaderBox *ptr = (GF_MPEGMediaHeaderBox *)s;
if (ptr == NULL) return;
gf_free(ptr);
}
GF_Err nmhd_Read(GF_Box *s, GF_BitStream *bs)
{
return GF_OK;
}
GF_Box *nmhd_New()
{
ISOM_DECL_BOX_ALLOC(GF_MPEGMediaHeaderBox, GF_ISOM_BOX_TYPE_NMHD);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err nmhd_Write(GF_Box *s, GF_BitStream *bs)
{
return gf_isom_full_box_write(s, bs);
}
GF_Err nmhd_Size(GF_Box *s)
{
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void padb_del(GF_Box *s)
{
GF_PaddingBitsBox *ptr = (GF_PaddingBitsBox *) s;
if (ptr == NULL) return;
if (ptr->padbits) gf_free(ptr->padbits);
gf_free(ptr);
}
GF_Err padb_Read(GF_Box *s,GF_BitStream *bs)
{
u32 i;
GF_PaddingBitsBox *ptr = (GF_PaddingBitsBox *)s;
ptr->SampleCount = gf_bs_read_u32(bs);
ptr->padbits = (u8 *)gf_malloc(sizeof(u8)*ptr->SampleCount);
for (i=0; i<ptr->SampleCount; i += 2) {
gf_bs_read_int(bs, 1);
if (i+1 < ptr->SampleCount) {
ptr->padbits[i+1] = gf_bs_read_int(bs, 3);
} else {
gf_bs_read_int(bs, 3);
}
gf_bs_read_int(bs, 1);
ptr->padbits[i] = gf_bs_read_int(bs, 3);
}
return GF_OK;
}
GF_Box *padb_New()
{
ISOM_DECL_BOX_ALLOC(GF_PaddingBitsBox, GF_ISOM_BOX_TYPE_PADB);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err padb_Write(GF_Box *s, GF_BitStream *bs)
{
u32 i;
GF_Err e;
GF_PaddingBitsBox *ptr = (GF_PaddingBitsBox *) s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_int(bs, ptr->SampleCount, 32);
for (i=0 ; i<ptr->SampleCount; i += 2) {
gf_bs_write_int(bs, 0, 1);
if (i+1 < ptr->SampleCount) {
gf_bs_write_int(bs, ptr->padbits[i+1], 3);
} else {
gf_bs_write_int(bs, 0, 3);
}
gf_bs_write_int(bs, 0, 1);
gf_bs_write_int(bs, ptr->padbits[i], 3);
}
return GF_OK;
}
GF_Err padb_Size(GF_Box *s)
{
GF_PaddingBitsBox *ptr = (GF_PaddingBitsBox *)s;
ptr->size += 4;
if (ptr->SampleCount) ptr->size += (ptr->SampleCount + 1) / 2;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void rely_del(GF_Box *s)
{
GF_RelyHintBox *rely = (GF_RelyHintBox *)s;
gf_free(rely);
}
GF_Err rely_Read(GF_Box *s, GF_BitStream *bs)
{
GF_RelyHintBox *ptr = (GF_RelyHintBox *)s;
ptr->reserved = gf_bs_read_int(bs, 6);
ptr->prefered = gf_bs_read_int(bs, 1);
ptr->required = gf_bs_read_int(bs, 1);
return GF_OK;
}
GF_Box *rely_New()
{
ISOM_DECL_BOX_ALLOC(GF_RelyHintBox, GF_ISOM_BOX_TYPE_RELY);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err rely_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_RelyHintBox *ptr = (GF_RelyHintBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_int(bs, ptr->reserved, 6);
gf_bs_write_int(bs, ptr->prefered, 1);
gf_bs_write_int(bs, ptr->required, 1);
return GF_OK;
}
GF_Err rely_Size(GF_Box *s)
{
s->size += 1;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void rtpo_del(GF_Box *s)
{
GF_RTPOBox *rtpo = (GF_RTPOBox *)s;
gf_free(rtpo);
}
GF_Err rtpo_Read(GF_Box *s, GF_BitStream *bs)
{
GF_RTPOBox *ptr = (GF_RTPOBox *)s;
ptr->timeOffset = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *rtpo_New()
{
ISOM_DECL_BOX_ALLOC(GF_RTPOBox, GF_ISOM_BOX_TYPE_RTPO);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err rtpo_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_RTPOBox *ptr = (GF_RTPOBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
//here we have no pb, just remembed that some entries will have to
//be 4-bytes aligned ...
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->timeOffset);
return GF_OK;
}
GF_Err rtpo_Size(GF_Box *s)
{
s->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void smhd_del(GF_Box *s)
{
GF_SoundMediaHeaderBox *ptr = (GF_SoundMediaHeaderBox *)s;
if (ptr == NULL ) return;
gf_free(ptr);
}
GF_Err smhd_Read(GF_Box *s, GF_BitStream *bs)
{
GF_SoundMediaHeaderBox *ptr = (GF_SoundMediaHeaderBox *)s;
ptr->balance = gf_bs_read_u16(bs);
ptr->reserved = gf_bs_read_u16(bs);
return GF_OK;
}
GF_Box *smhd_New()
{
ISOM_DECL_BOX_ALLOC(GF_SoundMediaHeaderBox, GF_ISOM_BOX_TYPE_SMHD);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err smhd_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_SoundMediaHeaderBox *ptr = (GF_SoundMediaHeaderBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u16(bs, ptr->balance);
gf_bs_write_u16(bs, ptr->reserved);
return GF_OK;
}
GF_Err smhd_Size(GF_Box *s)
{
GF_SoundMediaHeaderBox *ptr = (GF_SoundMediaHeaderBox *)s;
ptr->reserved = 0;
ptr->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void snro_del(GF_Box *s)
{
GF_SeqOffHintEntryBox *snro = (GF_SeqOffHintEntryBox *)s;
gf_free(snro);
}
GF_Err snro_Read(GF_Box *s, GF_BitStream *bs)
{
GF_SeqOffHintEntryBox *ptr = (GF_SeqOffHintEntryBox *)s;
ptr->SeqOffset = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *snro_New()
{
ISOM_DECL_BOX_ALLOC(GF_SeqOffHintEntryBox, GF_ISOM_BOX_TYPE_SNRO);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err snro_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_SeqOffHintEntryBox *ptr = (GF_SeqOffHintEntryBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->SeqOffset);
return GF_OK;
}
GF_Err snro_Size(GF_Box *s)
{
s->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#define WRITE_SAMPLE_FRAGMENTS 1
void stbl_del(GF_Box *s)
{
GF_SampleTableBox *ptr = (GF_SampleTableBox *)s;
if (ptr == NULL) return;
if (ptr->ChunkOffset) gf_isom_box_del(ptr->ChunkOffset);
if (ptr->CompositionOffset) gf_isom_box_del((GF_Box *) ptr->CompositionOffset);
if (ptr->CompositionToDecode) gf_isom_box_del((GF_Box *) ptr->CompositionToDecode);
if (ptr->DegradationPriority) gf_isom_box_del((GF_Box *) ptr->DegradationPriority);
if (ptr->SampleDescription) gf_isom_box_del((GF_Box *) ptr->SampleDescription);
if (ptr->SampleSize) gf_isom_box_del((GF_Box *) ptr->SampleSize);
if (ptr->SampleToChunk) gf_isom_box_del((GF_Box *) ptr->SampleToChunk);
if (ptr->ShadowSync) gf_isom_box_del((GF_Box *) ptr->ShadowSync);
if (ptr->SyncSample) gf_isom_box_del((GF_Box *) ptr->SyncSample);
if (ptr->TimeToSample) gf_isom_box_del((GF_Box *) ptr->TimeToSample);
if (ptr->SampleDep) gf_isom_box_del((GF_Box *) ptr->SampleDep);
if (ptr->PaddingBits) gf_isom_box_del((GF_Box *) ptr->PaddingBits);
if (ptr->Fragments) gf_isom_box_del((GF_Box *) ptr->Fragments);
if (ptr->sub_samples) gf_isom_box_array_del(ptr->sub_samples);
if (ptr->sampleGroups) gf_isom_box_array_del(ptr->sampleGroups);
if (ptr->sampleGroupsDescription) gf_isom_box_array_del(ptr->sampleGroupsDescription);
if (ptr->sai_sizes) gf_isom_box_array_del(ptr->sai_sizes);
if (ptr->sai_offsets) gf_isom_box_array_del(ptr->sai_offsets);
gf_free(ptr);
}
GF_Err stbl_AddBox(GF_Box *s, GF_Box *a)
{
GF_SampleTableBox *ptr = (GF_SampleTableBox *)s;
if (!a) return GF_OK;
switch (a->type) {
case GF_ISOM_BOX_TYPE_STTS:
if (ptr->TimeToSample) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->TimeToSample = (GF_TimeToSampleBox *)a;
break;
case GF_ISOM_BOX_TYPE_CTTS:
if (ptr->CompositionOffset) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->CompositionOffset = (GF_CompositionOffsetBox *)a;
break;
case GF_ISOM_BOX_TYPE_CSLG:
if (ptr->CompositionToDecode) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->CompositionToDecode = (GF_CompositionToDecodeBox *)a;
break;
case GF_ISOM_BOX_TYPE_STSS:
if (ptr->SyncSample) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->SyncSample = (GF_SyncSampleBox *)a;
break;
case GF_ISOM_BOX_TYPE_STSD:
if (ptr->SampleDescription) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->SampleDescription =(GF_SampleDescriptionBox *)a;
break;
case GF_ISOM_BOX_TYPE_STZ2:
case GF_ISOM_BOX_TYPE_STSZ:
if (ptr->SampleSize) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->SampleSize = (GF_SampleSizeBox *)a;
break;
case GF_ISOM_BOX_TYPE_STSC:
if (ptr->SampleToChunk) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->SampleToChunk = (GF_SampleToChunkBox *)a;
break;
case GF_ISOM_BOX_TYPE_PADB:
if (ptr->PaddingBits) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->PaddingBits = (GF_PaddingBitsBox *) a;
break;
//WARNING: AS THIS MAY CHANGE DYNAMICALLY DURING EDIT,
case GF_ISOM_BOX_TYPE_CO64:
case GF_ISOM_BOX_TYPE_STCO:
if (ptr->ChunkOffset) {
gf_isom_box_del(ptr->ChunkOffset);
}
ptr->ChunkOffset = a;
return GF_OK;
case GF_ISOM_BOX_TYPE_STSH:
if (ptr->ShadowSync) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->ShadowSync = (GF_ShadowSyncBox *)a;
break;
case GF_ISOM_BOX_TYPE_STDP:
if (ptr->DegradationPriority) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->DegradationPriority = (GF_DegradationPriorityBox *)a;
break;
case GF_ISOM_BOX_TYPE_SDTP:
if (ptr->SampleDep) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->SampleDep= (GF_SampleDependencyTypeBox *)a;
break;
case GF_ISOM_BOX_TYPE_STSF:
if (ptr->Fragments) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->Fragments = (GF_SampleFragmentBox *)a;
break;
case GF_ISOM_BOX_TYPE_SUBS:
if (!ptr->sub_samples) ptr->sub_samples = gf_list_new();
gf_list_add(ptr->sub_samples, a);
//check subsample box
{
GF_SubSampleInformationBox *subs = (GF_SubSampleInformationBox *)a;
GF_SubSampleInfoEntry *ent = gf_list_get(subs->Samples, 0);
if (ent->sample_delta==0) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] first entry in SubSample in track SampleTable has sample_delta of 0, should be one. Fixing\n"));
ent->sample_delta = 1;
}
}
break;
case GF_ISOM_BOX_TYPE_SBGP:
if (!ptr->sampleGroups) ptr->sampleGroups = gf_list_new();
gf_list_add(ptr->sampleGroups, a);
break;
case GF_ISOM_BOX_TYPE_SGPD:
if (!ptr->sampleGroupsDescription) ptr->sampleGroupsDescription = gf_list_new();
gf_list_add(ptr->sampleGroupsDescription, a);
break;
case GF_ISOM_BOX_TYPE_SAIZ:
if (!ptr->sai_sizes) ptr->sai_sizes = gf_list_new();
gf_list_add(ptr->sai_sizes, a);
break;
case GF_ISOM_BOX_TYPE_SAIO:
if (!ptr->sai_offsets) ptr->sai_offsets = gf_list_new();
gf_list_add(ptr->sai_offsets, a);
break;
default:
return gf_isom_box_add_default((GF_Box *)ptr, a);
}
return GF_OK;
}
GF_Err stbl_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
//we need to parse DegPrior in a special way
GF_SampleTableBox *ptr = (GF_SampleTableBox *)s;
e = gf_isom_box_array_read(s, bs, stbl_AddBox);
if (e) return e;
if (!ptr->SyncSample)
ptr->no_sync_found = 1;
ptr->nb_sgpd_in_stbl = gf_list_count(ptr->sampleGroupsDescription);
ptr->nb_other_boxes_in_stbl = gf_list_count(ptr->other_boxes);
return GF_OK;
}
GF_Box *stbl_New()
{
ISOM_DECL_BOX_ALLOC(GF_SampleTableBox, GF_ISOM_BOX_TYPE_STBL);
//maxSamplePer chunk is 10 by default
tmp->MaxSamplePerChunk = 10;
tmp->groupID = 1;
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err stbl_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_SampleTableBox *ptr = (GF_SampleTableBox *)s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
if (ptr->SampleDescription) {
e = gf_isom_box_write((GF_Box *) ptr->SampleDescription, bs);
if (e) return e;
}
if (ptr->TimeToSample) {
e = gf_isom_box_write((GF_Box *) ptr->TimeToSample, bs);
if (e) return e;
}
if (ptr->CompositionOffset) {
e = gf_isom_box_write((GF_Box *) ptr->CompositionOffset, bs);
if (e) return e;
}
if (ptr->CompositionToDecode) {
e = gf_isom_box_write((GF_Box *) ptr->CompositionToDecode, bs);
if (e) return e;
}
if (ptr->SyncSample) {
e = gf_isom_box_write((GF_Box *) ptr->SyncSample, bs);
if (e) return e;
}
if (ptr->ShadowSync) {
e = gf_isom_box_write((GF_Box *) ptr->ShadowSync, bs);
if (e) return e;
}
if (ptr->SampleToChunk) {
e = gf_isom_box_write((GF_Box *) ptr->SampleToChunk, bs);
if (e) return e;
}
if (ptr->SampleSize) {
e = gf_isom_box_write((GF_Box *) ptr->SampleSize, bs);
if (e) return e;
}
if (ptr->ChunkOffset) {
e = gf_isom_box_write(ptr->ChunkOffset, bs);
if (e) return e;
}
if (ptr->DegradationPriority) {
e = gf_isom_box_write((GF_Box *) ptr->DegradationPriority, bs);
if (e) return e;
}
if (ptr->SampleDep && ptr->SampleDep->sampleCount) {
e = gf_isom_box_write((GF_Box *) ptr->SampleDep, bs);
if (e) return e;
}
if (ptr->PaddingBits) {
e = gf_isom_box_write((GF_Box *) ptr->PaddingBits, bs);
if (e) return e;
}
if (ptr->sub_samples) {
e = gf_isom_box_array_write(s, ptr->sub_samples, bs);
if (e) return e;
}
if (ptr->sampleGroupsDescription) {
e = gf_isom_box_array_write(s, ptr->sampleGroupsDescription, bs);
if (e) return e;
}
if (ptr->sampleGroups) {
e = gf_isom_box_array_write(s, ptr->sampleGroups, bs);
if (e) return e;
}
if (ptr->sai_sizes) {
e = gf_isom_box_array_write(s, ptr->sai_sizes, bs);
if (e) return e;
}
if (ptr->sai_offsets) {
e = gf_isom_box_array_write(s, ptr->sai_offsets, bs);
if (e) return e;
}
#if WRITE_SAMPLE_FRAGMENTS
//sampleFragments
if (ptr->Fragments) {
e = gf_isom_box_write((GF_Box *) ptr->Fragments, bs);
if (e) return e;
}
#endif
return GF_OK;
}
GF_Err stbl_Size(GF_Box *s)
{
GF_Err e;
GF_SampleTableBox *ptr = (GF_SampleTableBox *)s;
//Mandatory boxs (but not internally :)
if (ptr->SampleDescription) {
e = gf_isom_box_size((GF_Box *) ptr->SampleDescription);
if (e) return e;
ptr->size += ptr->SampleDescription->size;
}
if (ptr->SampleSize) {
e = gf_isom_box_size((GF_Box *) ptr->SampleSize);
if (e) return e;
ptr->size += ptr->SampleSize->size;
}
if (ptr->SampleToChunk) {
e = gf_isom_box_size((GF_Box *) ptr->SampleToChunk);
if (e) return e;
ptr->size += ptr->SampleToChunk->size;
}
if (ptr->TimeToSample) {
e = gf_isom_box_size((GF_Box *) ptr->TimeToSample);
if (e) return e;
ptr->size += ptr->TimeToSample->size;
}
if (ptr->ChunkOffset) {
e = gf_isom_box_size(ptr->ChunkOffset);
if (e) return e;
ptr->size += ptr->ChunkOffset->size;
}
//optional boxs
if (ptr->CompositionOffset) {
e = gf_isom_box_size((GF_Box *) ptr->CompositionOffset);
if (e) return e;
ptr->size += ptr->CompositionOffset->size;
}
if (ptr->CompositionToDecode) {
e = gf_isom_box_size((GF_Box *) ptr->CompositionToDecode);
if (e) return e;
ptr->size += ptr->CompositionToDecode->size;
}
if (ptr->DegradationPriority) {
e = gf_isom_box_size((GF_Box *) ptr->DegradationPriority);
if (e) return e;
ptr->size += ptr->DegradationPriority->size;
}
if (ptr->ShadowSync) {
e = gf_isom_box_size((GF_Box *) ptr->ShadowSync);
if (e) return e;
ptr->size += ptr->ShadowSync->size;
}
if (ptr->SyncSample) {
e = gf_isom_box_size((GF_Box *) ptr->SyncSample);
if (e) return e;
ptr->size += ptr->SyncSample->size;
}
if (ptr->SampleDep && ptr->SampleDep->sampleCount) {
e = gf_isom_box_size((GF_Box *) ptr->SampleDep);
if (e) return e;
ptr->size += ptr->SampleDep->size;
}
//padb
if (ptr->PaddingBits) {
e = gf_isom_box_size((GF_Box *) ptr->PaddingBits);
if (e) return e;
ptr->size += ptr->PaddingBits->size;
}
#if WRITE_SAMPLE_FRAGMENTS
//sample fragments
if (ptr->Fragments) {
e = gf_isom_box_size((GF_Box *) ptr->Fragments);
if (e) return e;
ptr->size += ptr->Fragments->size;
}
#endif
if (ptr->sub_samples) {
e = gf_isom_box_array_size(s, ptr->sub_samples);
if (e) return e;
}
if (ptr->sampleGroups) {
e = gf_isom_box_array_size(s, ptr->sampleGroups);
if (e) return e;
}
if (ptr->sampleGroupsDescription) {
e = gf_isom_box_array_size(s, ptr->sampleGroupsDescription);
if (e) return e;
}
if (ptr->sai_sizes) {
e = gf_isom_box_array_size(s, ptr->sai_sizes);
if (e) return e;
}
if (ptr->sai_offsets) {
e = gf_isom_box_array_size(s, ptr->sai_offsets);
if (e) return e;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void stco_del(GF_Box *s)
{
GF_ChunkOffsetBox *ptr = (GF_ChunkOffsetBox *)s;
if (ptr == NULL) return;
if (ptr->offsets) gf_free(ptr->offsets);
gf_free(ptr);
}
GF_Err stco_Read(GF_Box *s, GF_BitStream *bs)
{
u32 entries;
GF_ChunkOffsetBox *ptr = (GF_ChunkOffsetBox *)s;
ptr->nb_entries = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
if (ptr->nb_entries > ptr->size / 4) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in stco\n", ptr->nb_entries));
return GF_ISOM_INVALID_FILE;
}
if (ptr->nb_entries) {
ptr->offsets = (u32 *) gf_malloc(ptr->nb_entries * sizeof(u32) );
if (ptr->offsets == NULL) return GF_OUT_OF_MEM;
ptr->alloc_size = ptr->nb_entries;
for (entries = 0; entries < ptr->nb_entries; entries++) {
ptr->offsets[entries] = gf_bs_read_u32(bs);
}
}
return GF_OK;
}
GF_Box *stco_New()
{
ISOM_DECL_BOX_ALLOC(GF_ChunkOffsetBox, GF_ISOM_BOX_TYPE_STCO);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err stco_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_ChunkOffsetBox *ptr = (GF_ChunkOffsetBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->nb_entries);
for (i = 0; i < ptr->nb_entries; i++) {
gf_bs_write_u32(bs, ptr->offsets[i]);
}
return GF_OK;
}
GF_Err stco_Size(GF_Box *s)
{
GF_ChunkOffsetBox *ptr = (GF_ChunkOffsetBox *)s;
ptr->size += 4 + (4 * ptr->nb_entries);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void stdp_del(GF_Box *s)
{
GF_DegradationPriorityBox *ptr = (GF_DegradationPriorityBox *)s;
if (ptr == NULL ) return;
if (ptr->priorities) gf_free(ptr->priorities);
gf_free(ptr);
}
//this is called through stbl_read...
GF_Err stdp_Read(GF_Box *s, GF_BitStream *bs)
{
u32 entry;
GF_DegradationPriorityBox *ptr = (GF_DegradationPriorityBox *)s;
/*out-of-order stdp, assume no padding at the end and take the entire remaining data for entries*/
if (!ptr->nb_entries) ptr->nb_entries = (u32) ptr->size / 2;
else if (ptr->nb_entries > ptr->size / 2) return GF_ISOM_INVALID_FILE;
ptr->priorities = (u16 *) gf_malloc(ptr->nb_entries * sizeof(u16));
if (ptr->priorities == NULL) return GF_OUT_OF_MEM;
for (entry = 0; entry < ptr->nb_entries; entry++) {
ptr->priorities[entry] = gf_bs_read_u16(bs);
}
ISOM_DECREASE_SIZE(ptr, (2*ptr->nb_entries) );
return GF_OK;
}
GF_Box *stdp_New()
{
ISOM_DECL_BOX_ALLOC(GF_DegradationPriorityBox, GF_ISOM_BOX_TYPE_STDP);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err stdp_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_DegradationPriorityBox *ptr = (GF_DegradationPriorityBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
for (i = 0; i < ptr->nb_entries; i++) {
gf_bs_write_u16(bs, ptr->priorities[i]);
}
return GF_OK;
}
GF_Err stdp_Size(GF_Box *s)
{
GF_DegradationPriorityBox *ptr = (GF_DegradationPriorityBox *)s;
ptr->size += (2 * ptr->nb_entries);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void stsc_del(GF_Box *s)
{
GF_SampleToChunkBox *ptr = (GF_SampleToChunkBox *)s;
if (ptr == NULL) return;
if (ptr->entries) gf_free(ptr->entries);
gf_free(ptr);
}
GF_Err stsc_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i;
GF_SampleToChunkBox *ptr = (GF_SampleToChunkBox *)s;
ptr->nb_entries = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
if (ptr->nb_entries > ptr->size / 12) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in stsc\n", ptr->nb_entries));
return GF_ISOM_INVALID_FILE;
}
ptr->alloc_size = ptr->nb_entries;
ptr->entries = gf_malloc(sizeof(GF_StscEntry)*ptr->alloc_size);
if (!ptr->entries) return GF_OUT_OF_MEM;
for (i = 0; i < ptr->nb_entries; i++) {
ptr->entries[i].firstChunk = gf_bs_read_u32(bs);
ptr->entries[i].samplesPerChunk = gf_bs_read_u32(bs);
ptr->entries[i].sampleDescriptionIndex = gf_bs_read_u32(bs);
ptr->entries[i].isEdited = 0;
ptr->entries[i].nextChunk = 0;
if (!ptr->entries[i].firstChunk) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] invalid first chunk 0 in stsc entry\n", ptr->nb_entries));
return GF_ISOM_INVALID_FILE;
}
//update the next chunk in the previous entry
if (i) ptr->entries[i-1].nextChunk = ptr->entries[i].firstChunk;
}
ptr->currentIndex = 0;
ptr->firstSampleInCurrentChunk = 0;
ptr->currentChunk = 0;
ptr->ghostNumber = 0;
return GF_OK;
}
GF_Box *stsc_New()
{
ISOM_DECL_BOX_ALLOC(GF_SampleToChunkBox, GF_ISOM_BOX_TYPE_STSC);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err stsc_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_SampleToChunkBox *ptr = (GF_SampleToChunkBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->nb_entries);
for (i=0; i<ptr->nb_entries; i++) {
gf_bs_write_u32(bs, ptr->entries[i].firstChunk);
gf_bs_write_u32(bs, ptr->entries[i].samplesPerChunk);
gf_bs_write_u32(bs, ptr->entries[i].sampleDescriptionIndex);
}
return GF_OK;
}
GF_Err stsc_Size(GF_Box *s)
{
GF_SampleToChunkBox *ptr = (GF_SampleToChunkBox *)s;
ptr->size += 4 + (12 * ptr->nb_entries);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void stsd_del(GF_Box *s)
{
GF_SampleDescriptionBox *ptr = (GF_SampleDescriptionBox *)s;
if (ptr == NULL) return;
gf_free(ptr);
}
GF_Err stsd_AddBox(GF_Box *s, GF_Box *a)
{
GF_UnknownBox *def;
GF_SampleDescriptionBox *ptr = (GF_SampleDescriptionBox *)s;
if (!a) return GF_OK;
switch (a->type) {
case GF_ISOM_BOX_TYPE_MP4S:
case GF_ISOM_BOX_TYPE_ENCS:
case GF_ISOM_BOX_TYPE_MP4A:
case GF_ISOM_BOX_TYPE_ENCA:
case GF_ISOM_BOX_TYPE_MP4V:
case GF_ISOM_BOX_TYPE_ENCV:
case GF_ISOM_BOX_TYPE_RESV:
case GF_ISOM_BOX_TYPE_GHNT:
case GF_ISOM_BOX_TYPE_RTP_STSD:
case GF_ISOM_BOX_TYPE_SRTP_STSD:
case GF_ISOM_BOX_TYPE_FDP_STSD:
case GF_ISOM_BOX_TYPE_RRTP_STSD:
case GF_ISOM_BOX_TYPE_RTCP_STSD:
case GF_ISOM_BOX_TYPE_AVC1:
case GF_ISOM_BOX_TYPE_AVC2:
case GF_ISOM_BOX_TYPE_AVC3:
case GF_ISOM_BOX_TYPE_AVC4:
case GF_ISOM_BOX_TYPE_SVC1:
case GF_ISOM_BOX_TYPE_MVC1:
case GF_ISOM_BOX_TYPE_HVC1:
case GF_ISOM_BOX_TYPE_HEV1:
case GF_ISOM_BOX_TYPE_HVC2:
case GF_ISOM_BOX_TYPE_HEV2:
case GF_ISOM_BOX_TYPE_HVT1:
case GF_ISOM_BOX_TYPE_LHV1:
case GF_ISOM_BOX_TYPE_LHE1:
case GF_ISOM_BOX_TYPE_TX3G:
case GF_ISOM_BOX_TYPE_TEXT:
case GF_ISOM_BOX_TYPE_ENCT:
case GF_ISOM_BOX_TYPE_METX:
case GF_ISOM_BOX_TYPE_METT:
case GF_ISOM_BOX_TYPE_STXT:
case GF_ISOM_BOX_TYPE_DIMS:
case GF_ISOM_BOX_TYPE_AC3:
case GF_ISOM_BOX_TYPE_EC3:
case GF_ISOM_BOX_TYPE_LSR1:
case GF_ISOM_BOX_TYPE_WVTT:
case GF_ISOM_BOX_TYPE_STPP:
case GF_ISOM_BOX_TYPE_SBTT:
case GF_ISOM_BOX_TYPE_ELNG:
case GF_ISOM_BOX_TYPE_MP3:
case GF_ISOM_BOX_TYPE_JPEG:
case GF_ISOM_BOX_TYPE_JP2K:
case GF_ISOM_BOX_TYPE_PNG:
case GF_ISOM_SUBTYPE_3GP_AMR:
case GF_ISOM_SUBTYPE_3GP_AMR_WB:
case GF_ISOM_SUBTYPE_3GP_EVRC:
case GF_ISOM_SUBTYPE_3GP_QCELP:
case GF_ISOM_SUBTYPE_3GP_SMV:
case GF_ISOM_SUBTYPE_3GP_H263:
return gf_isom_box_add_default((GF_Box*)ptr, a);
//unknown sample description: we need a specific box to handle the data ref index
//rather than a default box ...
case GF_ISOM_BOX_TYPE_UNKNOWN:
def = (GF_UnknownBox *)a;
/*we need at least 8 bytes for unknown sample entries*/
if (def->dataSize < 8) {
gf_isom_box_del(a);
return GF_OK;
}
return gf_isom_box_add_default((GF_Box*)ptr, a);
default:
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Cannot process box of type %s\n", gf_4cc_to_str(a->type)));
return GF_ISOM_INVALID_FILE;
}
}
GF_Err stsd_Read(GF_Box *s, GF_BitStream *bs)
{
gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(s, 4)
return gf_isom_box_array_read_ex(s, bs, stsd_AddBox, GF_ISOM_BOX_TYPE_STSD);
}
GF_Box *stsd_New()
{
ISOM_DECL_BOX_ALLOC(GF_SampleDescriptionBox, GF_ISOM_BOX_TYPE_STSD);
tmp->other_boxes = gf_list_new();
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err stsd_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 nb_entries;
GF_SampleDescriptionBox *ptr = (GF_SampleDescriptionBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
nb_entries = gf_list_count(ptr->other_boxes);
gf_bs_write_u32(bs, nb_entries);
return GF_OK;
}
GF_Err stsd_Size(GF_Box *s)
{
GF_SampleDescriptionBox *ptr = (GF_SampleDescriptionBox *)s;
ptr->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void stsf_del(GF_Box *s)
{
u32 nb_entries;
u32 i;
GF_StsfEntry *pe;
GF_SampleFragmentBox *ptr = (GF_SampleFragmentBox *)s;
if (ptr == NULL) return;
if (ptr->entryList) {
nb_entries = gf_list_count(ptr->entryList);
for ( i = 0; i < nb_entries; i++ ) {
pe = (GF_StsfEntry*)gf_list_get(ptr->entryList, i);
if (pe->fragmentSizes) gf_free(pe->fragmentSizes);
gf_free(pe);
}
gf_list_del(ptr->entryList);
}
gf_free(ptr);
}
GF_Err stsf_Read(GF_Box *s, GF_BitStream *bs)
{
u32 entries, i;
u32 nb_entries;
GF_StsfEntry *p;
GF_SampleFragmentBox *ptr = (GF_SampleFragmentBox *)s;
p = NULL;
if (!ptr) return GF_BAD_PARAM;
nb_entries = gf_bs_read_u32(bs);
p = NULL;
for ( entries = 0; entries < nb_entries; entries++ ) {
p = (GF_StsfEntry *) gf_malloc(sizeof(GF_StsfEntry));
if (!p) return GF_OUT_OF_MEM;
p->SampleNumber = gf_bs_read_u32(bs);
p->fragmentCount = gf_bs_read_u32(bs);
p->fragmentSizes = (u16*)gf_malloc(sizeof(GF_StsfEntry) * p->fragmentCount);
for (i=0; i<p->fragmentCount; i++) {
p->fragmentSizes[i] = gf_bs_read_u16(bs);
}
gf_list_add(ptr->entryList, p);
}
#ifndef GPAC_DISABLE_ISOM_WRITE
ptr->w_currentEntry = p;
ptr->w_currentEntryIndex = nb_entries-1;
#endif
return GF_OK;
}
GF_Box *stsf_New()
{
ISOM_DECL_BOX_ALLOC(GF_SampleFragmentBox, GF_ISOM_BOX_TYPE_STSF);
tmp->entryList = gf_list_new();
if (! tmp->entryList) {
gf_free(tmp);
return NULL;
}
return (GF_Box *) tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err stsf_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i, j;
u32 nb_entries;
GF_StsfEntry *p;
GF_SampleFragmentBox *ptr = (GF_SampleFragmentBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
nb_entries = gf_list_count(ptr->entryList);
gf_bs_write_u32(bs, nb_entries);
for ( i = 0; i < nb_entries; i++ ) {
p = (GF_StsfEntry*)gf_list_get(ptr->entryList, i);
gf_bs_write_u32(bs, p->SampleNumber);
gf_bs_write_u32(bs, p->fragmentCount);
for (j=0; j<p->fragmentCount; j++) {
gf_bs_write_u16(bs, p->fragmentSizes[j]);
}
}
return GF_OK;
}
GF_Err stsf_Size(GF_Box *s)
{
GF_StsfEntry *p;
u32 nb_entries, i;
GF_SampleFragmentBox *ptr = (GF_SampleFragmentBox *) s;
nb_entries = gf_list_count(ptr->entryList);
ptr->size += 4;
for (i=0; i<nb_entries; i++) {
p = (GF_StsfEntry *)gf_list_get(ptr->entryList, i);
ptr->size += 8 + 2*p->fragmentCount;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void stsh_del(GF_Box *s)
{
u32 i = 0;
GF_StshEntry *ent;
GF_ShadowSyncBox *ptr = (GF_ShadowSyncBox *)s;
if (ptr == NULL) return;
while ( (ent = (GF_StshEntry *)gf_list_enum(ptr->entries, &i)) ) {
gf_free(ent);
}
gf_list_del(ptr->entries);
gf_free(ptr);
}
GF_Err stsh_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 count, i;
GF_StshEntry *ent;
GF_ShadowSyncBox *ptr = (GF_ShadowSyncBox *)s;
count = gf_bs_read_u32(bs);
for (i = 0; i < count; i++) {
ent = (GF_StshEntry *) gf_malloc(sizeof(GF_StshEntry));
if (!ent) return GF_OUT_OF_MEM;
ent->shadowedSampleNumber = gf_bs_read_u32(bs);
ent->syncSampleNumber = gf_bs_read_u32(bs);
e = gf_list_add(ptr->entries, ent);
if (e) return e;
}
return GF_OK;
}
GF_Box *stsh_New()
{
ISOM_DECL_BOX_ALLOC(GF_ShadowSyncBox, GF_ISOM_BOX_TYPE_STSH);
tmp->entries = gf_list_new();
if (!tmp->entries) {
gf_free(tmp);
return NULL;
}
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err stsh_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_StshEntry *ent;
GF_ShadowSyncBox *ptr = (GF_ShadowSyncBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, gf_list_count(ptr->entries));
i=0;
while ((ent = (GF_StshEntry *)gf_list_enum(ptr->entries, &i))) {
gf_bs_write_u32(bs, ent->shadowedSampleNumber);
gf_bs_write_u32(bs, ent->syncSampleNumber);
}
return GF_OK;
}
GF_Err stsh_Size(GF_Box *s)
{
GF_ShadowSyncBox *ptr = (GF_ShadowSyncBox *)s;
ptr->size += 4 + (8 * gf_list_count(ptr->entries));
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void stss_del(GF_Box *s)
{
GF_SyncSampleBox *ptr = (GF_SyncSampleBox *)s;
if (ptr == NULL) return;
if (ptr->sampleNumbers) gf_free(ptr->sampleNumbers);
gf_free(ptr);
}
GF_Err stss_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i;
GF_SyncSampleBox *ptr = (GF_SyncSampleBox *)s;
ptr->nb_entries = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
if (ptr->nb_entries > ptr->size / 4) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in stss\n", ptr->nb_entries));
return GF_ISOM_INVALID_FILE;
}
ptr->alloc_size = ptr->nb_entries;
ptr->sampleNumbers = (u32 *) gf_malloc( ptr->alloc_size * sizeof(u32));
if (ptr->sampleNumbers == NULL) return GF_OUT_OF_MEM;
for (i = 0; i < ptr->nb_entries; i++) {
ptr->sampleNumbers[i] = gf_bs_read_u32(bs);
}
return GF_OK;
}
GF_Box *stss_New()
{
ISOM_DECL_BOX_ALLOC(GF_SyncSampleBox, GF_ISOM_BOX_TYPE_STSS);
return (GF_Box*)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err stss_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_SyncSampleBox *ptr = (GF_SyncSampleBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->nb_entries);
for (i = 0; i < ptr->nb_entries; i++) {
gf_bs_write_u32(bs, ptr->sampleNumbers[i]);
}
return GF_OK;
}
GF_Err stss_Size(GF_Box *s)
{
GF_SyncSampleBox *ptr = (GF_SyncSampleBox *)s;
ptr->size += 4 + (4 * ptr->nb_entries);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void stsz_del(GF_Box *s)
{
GF_SampleSizeBox *ptr = (GF_SampleSizeBox *)s;
if (ptr == NULL) return;
if (ptr->sizes) gf_free(ptr->sizes);
gf_free(ptr);
}
GF_Err stsz_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i, estSize;
GF_SampleSizeBox *ptr = (GF_SampleSizeBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
//support for CompactSizes
if (s->type == GF_ISOM_BOX_TYPE_STSZ) {
ptr->sampleSize = gf_bs_read_u32(bs);
ptr->sampleCount = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 8);
} else {
//24-reserved
gf_bs_read_int(bs, 24);
i = gf_bs_read_u8(bs);
ptr->sampleCount = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 8);
switch (i) {
case 4:
case 8:
case 16:
ptr->sampleSize = i;
break;
default:
//try to fix the file
//no samples, no parsing pb
if (!ptr->sampleCount) {
ptr->sampleSize = 16;
return GF_OK;
}
estSize = (u32) (ptr->size) / ptr->sampleCount;
if (!estSize && ((ptr->sampleCount+1)/2 == (ptr->size)) ) {
ptr->sampleSize = 4;
break;
} else if (estSize == 1 || estSize == 2) {
ptr->sampleSize = 8 * estSize;
} else {
return GF_ISOM_INVALID_FILE;
}
}
}
if (s->type == GF_ISOM_BOX_TYPE_STSZ) {
if (! ptr->sampleSize && ptr->sampleCount) {
if (ptr->sampleCount > ptr->size / 4) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in stsz\n", ptr->sampleCount));
return GF_ISOM_INVALID_FILE;
}
ptr->sizes = (u32 *) gf_malloc(ptr->sampleCount * sizeof(u32));
ptr->alloc_size = ptr->sampleCount;
if (! ptr->sizes) return GF_OUT_OF_MEM;
for (i = 0; i < ptr->sampleCount; i++) {
ptr->sizes[i] = gf_bs_read_u32(bs);
}
}
} else {
if (ptr->sampleSize==4) {
if (ptr->sampleCount / 2 > ptr->size) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in stsz\n", ptr->sampleCount));
return GF_ISOM_INVALID_FILE;
}
} else {
if (ptr->sampleCount > ptr->size / (ptr->sampleSize/8)) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in stsz\n", ptr->sampleCount));
return GF_ISOM_INVALID_FILE;
}
}
//note we could optimize the mem usage by keeping the table compact
//in memory. But that would complicate both caching and editing
//we therefore keep all sizes as u32 and uncompress the table
ptr->sizes = (u32 *) gf_malloc(ptr->sampleCount * sizeof(u32));
if (! ptr->sizes) return GF_OUT_OF_MEM;
ptr->alloc_size = ptr->sampleCount;
for (i = 0; i < ptr->sampleCount; ) {
switch (ptr->sampleSize) {
case 4:
ptr->sizes[i] = gf_bs_read_int(bs, 4);
if (i+1 < ptr->sampleCount) {
ptr->sizes[i+1] = gf_bs_read_int(bs, 4);
} else {
//0 padding in odd sample count
gf_bs_read_int(bs, 4);
}
i += 2;
break;
default:
ptr->sizes[i] = gf_bs_read_int(bs, ptr->sampleSize);
i += 1;
break;
}
}
}
return GF_OK;
}
GF_Box *stsz_New()
{
ISOM_DECL_BOX_ALLOC(GF_SampleSizeBox, 0);
//type is unknown here, can be regular or compact table
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err stsz_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_SampleSizeBox *ptr = (GF_SampleSizeBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
//in both versions this is still valid
if (ptr->type == GF_ISOM_BOX_TYPE_STSZ) {
gf_bs_write_u32(bs, ptr->sampleSize);
} else {
gf_bs_write_u24(bs, 0);
gf_bs_write_u8(bs, ptr->sampleSize);
}
gf_bs_write_u32(bs, ptr->sampleCount);
if (ptr->type == GF_ISOM_BOX_TYPE_STSZ) {
if (! ptr->sampleSize) {
for (i = 0; i < ptr->sampleCount; i++) {
gf_bs_write_u32(bs, ptr->sizes ? ptr->sizes[i] : 0);
}
}
} else {
for (i = 0; i < ptr->sampleCount; ) {
switch (ptr->sampleSize) {
case 4:
gf_bs_write_int(bs, ptr->sizes[i], 4);
if (i+1 < ptr->sampleCount) {
gf_bs_write_int(bs, ptr->sizes[i+1], 4);
} else {
//0 padding in odd sample count
gf_bs_write_int(bs, 0, 4);
}
i += 2;
break;
default:
gf_bs_write_int(bs, ptr->sizes[i], ptr->sampleSize);
i += 1;
break;
}
}
}
return GF_OK;
}
GF_Err stsz_Size(GF_Box *s)
{
u32 i, fieldSize, size;
GF_SampleSizeBox *ptr = (GF_SampleSizeBox *)s;
ptr->size += 8;
if (!ptr->sampleCount) return GF_OK;
//regular table
if (ptr->type == GF_ISOM_BOX_TYPE_STSZ) {
if (ptr->sampleSize) return GF_OK;
ptr->size += (4 * ptr->sampleCount);
return GF_OK;
}
fieldSize = 4;
size = ptr->sizes[0];
for (i=0; i < ptr->sampleCount; i++) {
if (ptr->sizes[i] <= 0xF) continue;
//switch to 8-bit table
else if (ptr->sizes[i] <= 0xFF) {
fieldSize = 8;
}
//switch to 16-bit table
else if (ptr->sizes[i] <= 0xFFFF) {
fieldSize = 16;
}
//switch to 32-bit table
else {
fieldSize = 32;
}
//check the size
if (size != ptr->sizes[i]) size = 0;
}
//if all samples are of the same size, switch to regular (more compact)
if (size) {
ptr->type = GF_ISOM_BOX_TYPE_STSZ;
ptr->sampleSize = size;
gf_free(ptr->sizes);
ptr->sizes = NULL;
}
if (fieldSize == 32) {
//oops, doesn't fit in a compact table
ptr->type = GF_ISOM_BOX_TYPE_STSZ;
ptr->size += (4 * ptr->sampleCount);
return GF_OK;
}
//make sure we are a compact table (no need to change the mem representation)
ptr->type = GF_ISOM_BOX_TYPE_STZ2;
ptr->sampleSize = fieldSize;
if (fieldSize == 4) {
//do not forget the 0 padding field for odd count
ptr->size += (ptr->sampleCount + 1) / 2;
} else {
ptr->size += (ptr->sampleCount) * (fieldSize/8);
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void stts_del(GF_Box *s)
{
GF_TimeToSampleBox *ptr = (GF_TimeToSampleBox *)s;
if (ptr->entries) gf_free(ptr->entries);
gf_free(ptr);
}
GF_Err stts_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i;
GF_TimeToSampleBox *ptr = (GF_TimeToSampleBox *)s;
#ifndef GPAC_DISABLE_ISOM_WRITE
ptr->w_LastDTS = 0;
#endif
ptr->nb_entries = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
if (ptr->nb_entries > ptr->size / 8) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in stts\n", ptr->nb_entries));
return GF_ISOM_INVALID_FILE;
}
ptr->alloc_size = ptr->nb_entries;
ptr->entries = gf_malloc(sizeof(GF_SttsEntry)*ptr->alloc_size);
if (!ptr->entries) return GF_OUT_OF_MEM;
for (i=0; i<ptr->nb_entries; i++) {
ptr->entries[i].sampleCount = gf_bs_read_u32(bs);
ptr->entries[i].sampleDelta = gf_bs_read_u32(bs);
#ifndef GPAC_DISABLE_ISOM_WRITE
ptr->w_currentSampleNum += ptr->entries[i].sampleCount;
ptr->w_LastDTS += (u64)ptr->entries[i].sampleCount * ptr->entries[i].sampleDelta;
#endif
if (!ptr->entries[i].sampleDelta) {
if ((i+1<ptr->nb_entries) ) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Found stts entry with sample_delta=0 - forbidden ! Fixing to 1\n" ));
ptr->entries[i].sampleDelta = 1;
} else if (ptr->entries[i].sampleCount>1) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] more than one stts entry at the end of the track with sample_delta=0 - forbidden ! Fixing to 1\n" ));
ptr->entries[i].sampleDelta = 1;
}
} else if ((s32) ptr->entries[i].sampleDelta < 0) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] stts entry %d has negative duration %d - forbidden ! Fixing to 1, sync may get lost (consider reimport raw media)\n", i, (s32) ptr->entries[i].sampleDelta ));
ptr->entries[i].sampleDelta = 1;
}
}
if (ptr->size<(ptr->nb_entries*8)) return GF_ISOM_INVALID_FILE;
ISOM_DECREASE_SIZE(ptr, ptr->nb_entries*8);
//remove the last sample delta.
#ifndef GPAC_DISABLE_ISOM_WRITE
if (ptr->nb_entries) ptr->w_LastDTS -= ptr->entries[ptr->nb_entries-1].sampleDelta;
#endif
return GF_OK;
}
GF_Box *stts_New()
{
ISOM_DECL_BOX_ALLOC(GF_TimeToSampleBox, GF_ISOM_BOX_TYPE_STTS);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err stts_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_TimeToSampleBox *ptr = (GF_TimeToSampleBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->nb_entries);
for (i=0; i<ptr->nb_entries; i++) {
gf_bs_write_u32(bs, ptr->entries[i].sampleCount);
gf_bs_write_u32(bs, ptr->entries[i].sampleDelta);
}
return GF_OK;
}
GF_Err stts_Size(GF_Box *s)
{
GF_TimeToSampleBox *ptr = (GF_TimeToSampleBox *)s;
ptr->size += 4 + (8 * ptr->nb_entries);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
void tfhd_del(GF_Box *s)
{
GF_TrackFragmentHeaderBox *ptr = (GF_TrackFragmentHeaderBox *)s;
if (ptr == NULL) return;
gf_free(ptr);
}
GF_Err tfhd_Read(GF_Box *s, GF_BitStream *bs)
{
GF_TrackFragmentHeaderBox *ptr = (GF_TrackFragmentHeaderBox *)s;
ptr->trackID = gf_bs_read_u32(bs);
//The rest depends on the flags
if (ptr->flags & GF_ISOM_TRAF_BASE_OFFSET) {
ptr->base_data_offset = gf_bs_read_u64(bs);
}
if (ptr->flags & GF_ISOM_TRAF_SAMPLE_DESC) {
ptr->sample_desc_index = gf_bs_read_u32(bs);
}
if (ptr->flags & GF_ISOM_TRAF_SAMPLE_DUR) {
ptr->def_sample_duration = gf_bs_read_u32(bs);
}
if (ptr->flags & GF_ISOM_TRAF_SAMPLE_SIZE) {
ptr->def_sample_size = gf_bs_read_u32(bs);
}
if (ptr->flags & GF_ISOM_TRAF_SAMPLE_FLAGS) {
ptr->def_sample_flags = gf_bs_read_u32(bs);
}
return GF_OK;
}
GF_Box *tfhd_New()
{
ISOM_DECL_BOX_ALLOC(GF_TrackFragmentHeaderBox, GF_ISOM_BOX_TYPE_TFHD);
//NO FLAGS SET BY DEFAULT
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err tfhd_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TrackFragmentHeaderBox *ptr = (GF_TrackFragmentHeaderBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->trackID);
//The rest depends on the flags
if (ptr->flags & GF_ISOM_TRAF_BASE_OFFSET) {
gf_bs_write_u64(bs, ptr->base_data_offset);
}
if (ptr->flags & GF_ISOM_TRAF_SAMPLE_DESC) {
gf_bs_write_u32(bs, ptr->sample_desc_index);
}
if (ptr->flags & GF_ISOM_TRAF_SAMPLE_DUR) {
gf_bs_write_u32(bs, ptr->def_sample_duration);
}
if (ptr->flags & GF_ISOM_TRAF_SAMPLE_SIZE) {
gf_bs_write_u32(bs, ptr->def_sample_size);
}
if (ptr->flags & GF_ISOM_TRAF_SAMPLE_FLAGS) {
gf_bs_write_u32(bs, ptr->def_sample_flags);
}
return GF_OK;
}
GF_Err tfhd_Size(GF_Box *s)
{
GF_TrackFragmentHeaderBox *ptr = (GF_TrackFragmentHeaderBox *)s;
ptr->size += 4;
//The rest depends on the flags
if (ptr->flags & GF_ISOM_TRAF_BASE_OFFSET) ptr->size += 8;
if (ptr->flags & GF_ISOM_TRAF_SAMPLE_DESC) ptr->size += 4;
if (ptr->flags & GF_ISOM_TRAF_SAMPLE_DUR) ptr->size += 4;
if (ptr->flags & GF_ISOM_TRAF_SAMPLE_SIZE) ptr->size += 4;
if (ptr->flags & GF_ISOM_TRAF_SAMPLE_FLAGS) ptr->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/
void tims_del(GF_Box *s)
{
GF_TSHintEntryBox *tims = (GF_TSHintEntryBox *)s;
gf_free(tims);
}
GF_Err tims_Read(GF_Box *s, GF_BitStream *bs)
{
GF_TSHintEntryBox *ptr = (GF_TSHintEntryBox *)s;
ptr->timeScale = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *tims_New()
{
ISOM_DECL_BOX_ALLOC(GF_TSHintEntryBox, GF_ISOM_BOX_TYPE_TIMS);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err tims_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TSHintEntryBox *ptr = (GF_TSHintEntryBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->timeScale);
return GF_OK;
}
GF_Err tims_Size(GF_Box *s)
{
s->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void tkhd_del(GF_Box *s)
{
GF_TrackHeaderBox *ptr = (GF_TrackHeaderBox *)s;
if (ptr == NULL) return;
gf_free(ptr);
return;
}
GF_Err tkhd_Read(GF_Box *s, GF_BitStream *bs)
{
GF_TrackHeaderBox *ptr = (GF_TrackHeaderBox *)s;
if (ptr->version == 1) {
ptr->creationTime = gf_bs_read_u64(bs);
ptr->modificationTime = gf_bs_read_u64(bs);
ptr->trackID = gf_bs_read_u32(bs);
ptr->reserved1 = gf_bs_read_u32(bs);
ptr->duration = gf_bs_read_u64(bs);
} else {
ptr->creationTime = gf_bs_read_u32(bs);
ptr->modificationTime = gf_bs_read_u32(bs);
ptr->trackID = gf_bs_read_u32(bs);
ptr->reserved1 = gf_bs_read_u32(bs);
ptr->duration = gf_bs_read_u32(bs);
}
ptr->reserved2[0] = gf_bs_read_u32(bs);
ptr->reserved2[1] = gf_bs_read_u32(bs);
ptr->layer = gf_bs_read_u16(bs);
ptr->alternate_group = gf_bs_read_u16(bs);
ptr->volume = gf_bs_read_u16(bs);
ptr->reserved3 = gf_bs_read_u16(bs);
ptr->matrix[0] = gf_bs_read_u32(bs);
ptr->matrix[1] = gf_bs_read_u32(bs);
ptr->matrix[2] = gf_bs_read_u32(bs);
ptr->matrix[3] = gf_bs_read_u32(bs);
ptr->matrix[4] = gf_bs_read_u32(bs);
ptr->matrix[5] = gf_bs_read_u32(bs);
ptr->matrix[6] = gf_bs_read_u32(bs);
ptr->matrix[7] = gf_bs_read_u32(bs);
ptr->matrix[8] = gf_bs_read_u32(bs);
ptr->width = gf_bs_read_u32(bs);
ptr->height = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *tkhd_New()
{
ISOM_DECL_BOX_ALLOC(GF_TrackHeaderBox, GF_ISOM_BOX_TYPE_TKHD);
tmp->matrix[0] = 0x00010000;
tmp->matrix[4] = 0x00010000;
tmp->matrix[8] = 0x40000000;
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err tkhd_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TrackHeaderBox *ptr = (GF_TrackHeaderBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
if (ptr->version == 1) {
gf_bs_write_u64(bs, ptr->creationTime);
gf_bs_write_u64(bs, ptr->modificationTime);
gf_bs_write_u32(bs, ptr->trackID);
gf_bs_write_u32(bs, ptr->reserved1);
gf_bs_write_u64(bs, ptr->duration);
} else {
gf_bs_write_u32(bs, (u32) ptr->creationTime);
gf_bs_write_u32(bs, (u32) ptr->modificationTime);
gf_bs_write_u32(bs, ptr->trackID);
gf_bs_write_u32(bs, ptr->reserved1);
gf_bs_write_u32(bs, (u32) ptr->duration);
}
gf_bs_write_u32(bs, ptr->reserved2[0]);
gf_bs_write_u32(bs, ptr->reserved2[1]);
gf_bs_write_u16(bs, ptr->layer);
gf_bs_write_u16(bs, ptr->alternate_group);
gf_bs_write_u16(bs, ptr->volume);
gf_bs_write_u16(bs, ptr->reserved3);
gf_bs_write_u32(bs, ptr->matrix[0]);
gf_bs_write_u32(bs, ptr->matrix[1]);
gf_bs_write_u32(bs, ptr->matrix[2]);
gf_bs_write_u32(bs, ptr->matrix[3]);
gf_bs_write_u32(bs, ptr->matrix[4]);
gf_bs_write_u32(bs, ptr->matrix[5]);
gf_bs_write_u32(bs, ptr->matrix[6]);
gf_bs_write_u32(bs, ptr->matrix[7]);
gf_bs_write_u32(bs, ptr->matrix[8]);
gf_bs_write_u32(bs, ptr->width);
gf_bs_write_u32(bs, ptr->height);
return GF_OK;
}
GF_Err tkhd_Size(GF_Box *s)
{
GF_TrackHeaderBox *ptr = (GF_TrackHeaderBox *)s;
if (ptr->duration==(u64) -1) ptr->version = 0;
else ptr->version = (ptr->duration>0xFFFFFFFF) ? 1 : 0;
ptr->size += (ptr->version == 1) ? 32 : 20;
ptr->size += 60;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
void traf_del(GF_Box *s)
{
GF_TrackFragmentBox *ptr = (GF_TrackFragmentBox *)s;
if (ptr == NULL) return;
if (ptr->tfhd) gf_isom_box_del((GF_Box *) ptr->tfhd);
if (ptr->sdtp) gf_isom_box_del((GF_Box *) ptr->sdtp);
if (ptr->sub_samples) gf_isom_box_array_del(ptr->sub_samples);
if (ptr->tfdt) gf_isom_box_del((GF_Box *) ptr->tfdt);
if (ptr->sample_encryption) gf_isom_box_del((GF_Box *) ptr->sample_encryption);
gf_isom_box_array_del(ptr->TrackRuns);
if (ptr->sampleGroups) gf_isom_box_array_del(ptr->sampleGroups);
if (ptr->sampleGroupsDescription) gf_isom_box_array_del(ptr->sampleGroupsDescription);
if (ptr->sai_sizes) gf_isom_box_array_del(ptr->sai_sizes);
if (ptr->sai_offsets) gf_isom_box_array_del(ptr->sai_offsets);
gf_free(ptr);
}
GF_Err traf_AddBox(GF_Box *s, GF_Box *a)
{
GF_TrackFragmentBox *ptr = (GF_TrackFragmentBox *)s;
switch (a->type) {
case GF_ISOM_BOX_TYPE_TFHD:
if (ptr->tfhd) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->tfhd = (GF_TrackFragmentHeaderBox *) a;
return GF_OK;
case GF_ISOM_BOX_TYPE_TRUN:
return gf_list_add(ptr->TrackRuns, a);
case GF_ISOM_BOX_TYPE_SDTP:
if (ptr->sdtp) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->sdtp = (GF_SampleDependencyTypeBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_TFDT:
if (ptr->tfdt) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->tfdt = (GF_TFBaseMediaDecodeTimeBox*) a;
return GF_OK;
case GF_ISOM_BOX_TYPE_SUBS:
if (!ptr->sub_samples) ptr->sub_samples = gf_list_new();
return gf_list_add(ptr->sub_samples, a);
case GF_ISOM_BOX_TYPE_SBGP:
if (!ptr->sampleGroups) ptr->sampleGroups = gf_list_new();
gf_list_add(ptr->sampleGroups, a);
return GF_OK;
case GF_ISOM_BOX_TYPE_SGPD:
if (!ptr->sampleGroupsDescription) ptr->sampleGroupsDescription = gf_list_new();
gf_list_add(ptr->sampleGroupsDescription, a);
return GF_OK;
case GF_ISOM_BOX_TYPE_SAIZ:
if (!ptr->sai_sizes) ptr->sai_sizes = gf_list_new();
gf_list_add(ptr->sai_sizes, a);
return GF_OK;
case GF_ISOM_BOX_TYPE_SAIO:
if (!ptr->sai_offsets) ptr->sai_offsets = gf_list_new();
gf_list_add(ptr->sai_offsets, a);
return GF_OK;
//we will throw an error if both PIFF_PSEC and SENC are found. Not such files seen yet
case GF_ISOM_BOX_TYPE_UUID:
if ( ((GF_UUIDBox *)a)->internal_4cc==GF_ISOM_BOX_UUID_PSEC) {
if (ptr->sample_encryption) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->sample_encryption = (GF_SampleEncryptionBox *)a;
ptr->sample_encryption->traf = ptr;
return GF_OK;
} else {
return gf_isom_box_add_default(s, a);
}
case GF_ISOM_BOX_TYPE_SENC:
if (ptr->sample_encryption) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->sample_encryption = (GF_SampleEncryptionBox *)a;
ptr->sample_encryption->traf = ptr;
return GF_OK;
default:
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err traf_Read(GF_Box *s, GF_BitStream *bs)
{
GF_TrackFragmentBox *ptr = (GF_TrackFragmentBox *)s;
GF_Err e = gf_isom_box_array_read(s, bs, traf_AddBox);
if (e) return e;
if (!ptr->tfhd) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing TrackFragmentHeaderBox \n"));
return GF_ISOM_INVALID_FILE;
}
return GF_OK;
}
GF_Box *traf_New()
{
ISOM_DECL_BOX_ALLOC(GF_TrackFragmentBox, GF_ISOM_BOX_TYPE_TRAF);
tmp->TrackRuns = gf_list_new();
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Box *tfxd_New()
{
ISOM_DECL_BOX_ALLOC(GF_MSSTimeExtBox, GF_ISOM_BOX_TYPE_UUID);
tmp->internal_4cc = GF_ISOM_BOX_UUID_TFXD;
return (GF_Box *)tmp;
}
void tfxd_del(GF_Box *s)
{
gf_free(s);
}
GF_Err tfxd_Read(GF_Box *s, GF_BitStream *bs)
{
GF_MSSTimeExtBox *ptr = (GF_MSSTimeExtBox *)s;
if (ptr->size<4) return GF_ISOM_INVALID_FILE;
ptr->version = gf_bs_read_u8(bs);
ptr->flags = gf_bs_read_u24(bs);
ISOM_DECREASE_SIZE(ptr, 4);
if (ptr->version == 0x01) {
ptr->absolute_time_in_track_timescale = gf_bs_read_u64(bs);
ptr->fragment_duration_in_track_timescale = gf_bs_read_u64(bs);
} else {
ptr->absolute_time_in_track_timescale = gf_bs_read_u32(bs);
ptr->fragment_duration_in_track_timescale = gf_bs_read_u32(bs);
}
return GF_OK;
}
GF_Err tfxd_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e = GF_OK;
GF_MSSTimeExtBox *uuid = (GF_MSSTimeExtBox*)s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u8(bs, 1);
gf_bs_write_u24(bs, 0);
gf_bs_write_u64(bs, uuid->absolute_time_in_track_timescale);
gf_bs_write_u64(bs, uuid->fragment_duration_in_track_timescale);
return GF_OK;
}
GF_Err tfxd_Size(GF_Box *s)
{
s->size += 20;
return GF_OK;
}
GF_Err traf_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TrackFragmentBox *ptr = (GF_TrackFragmentBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
//Header first
if (ptr->tfhd) {
e = gf_isom_box_write((GF_Box *) ptr->tfhd, bs);
if (e) return e;
}
if (ptr->sub_samples) {
e = gf_isom_box_array_write(s, ptr->sub_samples, bs);
if (e) return e;
}
if (ptr->tfdt) {
e = gf_isom_box_write((GF_Box *) ptr->tfdt, bs);
if (e) return e;
}
if (ptr->sdtp) {
e = gf_isom_box_write((GF_Box *) ptr->sdtp, bs);
if (e) return e;
}
if (ptr->sampleGroupsDescription) {
e = gf_isom_box_array_write(s, ptr->sampleGroupsDescription, bs);
if (e) return e;
}
if (ptr->sampleGroups) {
e = gf_isom_box_array_write(s, ptr->sampleGroups, bs);
if (e) return e;
}
if (ptr->sai_sizes) {
e = gf_isom_box_array_write(s, ptr->sai_sizes, bs);
if (e) return e;
}
if (ptr->sai_offsets) {
e = gf_isom_box_array_write(s, ptr->sai_offsets, bs);
if (e) return e;
}
e = gf_isom_box_array_write(s, ptr->TrackRuns, bs);
if (e) return e;
if (ptr->sample_encryption) {
e = gf_isom_box_write((GF_Box *) ptr->sample_encryption, bs);
if (e) return e;
}
//tfxd should be last ...
if (ptr->tfxd) {
e = gf_isom_box_write((GF_Box *) ptr->tfxd, bs);
if (e) return e;
}
return GF_OK;
}
GF_Err traf_Size(GF_Box *s)
{
GF_Err e;
GF_TrackFragmentBox *ptr = (GF_TrackFragmentBox *)s;
if (ptr->tfhd) {
e = gf_isom_box_size((GF_Box *) ptr->tfhd);
if (e) return e;
ptr->size += ptr->tfhd->size;
}
if (ptr->sub_samples) {
e = gf_isom_box_array_size(s, ptr->sub_samples);
if (e) return e;
}
if (ptr->sdtp) {
e = gf_isom_box_size((GF_Box *) ptr->sdtp);
if (e) return e;
ptr->size += ptr->sdtp->size;
}
if (ptr->tfdt) {
e = gf_isom_box_size((GF_Box *) ptr->tfdt);
if (e) return e;
ptr->size += ptr->tfdt->size;
}
if (ptr->sampleGroups) {
e = gf_isom_box_array_size(s, ptr->sampleGroups);
if (e) return e;
}
if (ptr->sampleGroupsDescription) {
e = gf_isom_box_array_size(s, ptr->sampleGroupsDescription);
if (e) return e;
}
if (ptr->sai_sizes) {
e = gf_isom_box_array_size(s, ptr->sai_sizes);
if (e) return e;
}
if (ptr->sai_offsets) {
e = gf_isom_box_array_size(s, ptr->sai_offsets);
if (e) return e;
}
if (ptr->sample_encryption) {
e = gf_isom_box_size((GF_Box *) ptr->sample_encryption);
if (e) return e;
ptr->size += ptr->sample_encryption->size;
}
if (ptr->tfxd) {
e = gf_isom_box_size((GF_Box *)ptr->tfxd);
if (e) return e;
s->size += ptr->tfxd->size;
}
return gf_isom_box_array_size(s, ptr->TrackRuns);
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/
void trak_del(GF_Box *s)
{
GF_TrackBox *ptr = (GF_TrackBox *) s;
if (ptr == NULL) return;
if (ptr->Header) gf_isom_box_del((GF_Box *)ptr->Header);
if (ptr->udta) gf_isom_box_del((GF_Box *)ptr->udta);
if (ptr->Media) gf_isom_box_del((GF_Box *)ptr->Media);
if (ptr->References) gf_isom_box_del((GF_Box *)ptr->References);
if (ptr->editBox) gf_isom_box_del((GF_Box *)ptr->editBox);
if (ptr->meta) gf_isom_box_del((GF_Box *)ptr->meta);
if (ptr->name) gf_free(ptr->name);
if (ptr->groups) gf_isom_box_del((GF_Box *)ptr->groups);
gf_free(ptr);
}
static void gf_isom_check_sample_desc(GF_TrackBox *trak)
{
GF_BitStream *bs;
GF_UnknownBox *a;
u32 i;
if (!trak->Media || !trak->Media->information) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Track with no media box !\n" ));
return;
}
if (!trak->Media->information->sampleTable) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Track with no sample table !\n" ));
trak->Media->information->sampleTable = (GF_SampleTableBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_STBL);
}
if (!trak->Media->information->sampleTable->SampleDescription) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Track with no sample description box !\n" ));
trak->Media->information->sampleTable->SampleDescription = (GF_SampleDescriptionBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_STSD);
return;
}
i=0;
while ((a = (GF_UnknownBox*)gf_list_enum(trak->Media->information->sampleTable->SampleDescription->other_boxes, &i))) {
switch (a->type) {
case GF_ISOM_BOX_TYPE_MP4S:
case GF_ISOM_BOX_TYPE_ENCS:
case GF_ISOM_BOX_TYPE_MP4A:
case GF_ISOM_BOX_TYPE_ENCA:
case GF_ISOM_BOX_TYPE_MP4V:
case GF_ISOM_BOX_TYPE_ENCV:
case GF_ISOM_BOX_TYPE_RESV:
case GF_ISOM_SUBTYPE_3GP_AMR:
case GF_ISOM_SUBTYPE_3GP_AMR_WB:
case GF_ISOM_SUBTYPE_3GP_EVRC:
case GF_ISOM_SUBTYPE_3GP_QCELP:
case GF_ISOM_SUBTYPE_3GP_SMV:
case GF_ISOM_SUBTYPE_3GP_H263:
case GF_ISOM_BOX_TYPE_GHNT:
case GF_ISOM_BOX_TYPE_RTP_STSD:
case GF_ISOM_BOX_TYPE_SRTP_STSD:
case GF_ISOM_BOX_TYPE_FDP_STSD:
case GF_ISOM_BOX_TYPE_RRTP_STSD:
case GF_ISOM_BOX_TYPE_RTCP_STSD:
case GF_ISOM_BOX_TYPE_METX:
case GF_ISOM_BOX_TYPE_METT:
case GF_ISOM_BOX_TYPE_STXT:
case GF_ISOM_BOX_TYPE_AVC1:
case GF_ISOM_BOX_TYPE_AVC2:
case GF_ISOM_BOX_TYPE_AVC3:
case GF_ISOM_BOX_TYPE_AVC4:
case GF_ISOM_BOX_TYPE_SVC1:
case GF_ISOM_BOX_TYPE_MVC1:
case GF_ISOM_BOX_TYPE_HVC1:
case GF_ISOM_BOX_TYPE_HEV1:
case GF_ISOM_BOX_TYPE_HVC2:
case GF_ISOM_BOX_TYPE_HEV2:
case GF_ISOM_BOX_TYPE_HVT1:
case GF_ISOM_BOX_TYPE_LHV1:
case GF_ISOM_BOX_TYPE_LHE1:
case GF_ISOM_BOX_TYPE_TX3G:
case GF_ISOM_BOX_TYPE_TEXT:
case GF_ISOM_BOX_TYPE_ENCT:
case GF_ISOM_BOX_TYPE_DIMS:
case GF_ISOM_BOX_TYPE_AC3:
case GF_ISOM_BOX_TYPE_EC3:
case GF_ISOM_BOX_TYPE_LSR1:
case GF_ISOM_BOX_TYPE_WVTT:
case GF_ISOM_BOX_TYPE_STPP:
case GF_ISOM_BOX_TYPE_SBTT:
case GF_ISOM_BOX_TYPE_MP3:
case GF_ISOM_BOX_TYPE_JPEG:
case GF_ISOM_BOX_TYPE_PNG:
case GF_ISOM_BOX_TYPE_JP2K:
continue;
case GF_ISOM_BOX_TYPE_UNKNOWN:
break;
default:
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Unexpected box %s in stsd!\n", gf_4cc_to_str(a->type)));
continue;
}
//we are sure to have an unknown box here
assert(a->type==GF_ISOM_BOX_TYPE_UNKNOWN);
if (!a->data || (a->dataSize<8) ) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] Sample description %s does not have at least 8 bytes!\n", gf_4cc_to_str(a->original_4cc) ));
continue;
}
else if (a->dataSize > a->size) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Sample description %s has wrong data size %d!\n", gf_4cc_to_str(a->original_4cc), a->dataSize));
continue;
}
/*only process visual or audio*/
switch (trak->Media->handler->handlerType) {
case GF_ISOM_MEDIA_VISUAL:
case GF_ISOM_MEDIA_AUXV:
case GF_ISOM_MEDIA_PICT:
{
GF_GenericVisualSampleEntryBox *genv;
/*remove entry*/
gf_list_rem(trak->Media->information->sampleTable->SampleDescription->other_boxes, i-1);
genv = (GF_GenericVisualSampleEntryBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_GNRV);
bs = gf_bs_new(a->data, a->dataSize, GF_BITSTREAM_READ);
genv->size = a->size-8;
gf_isom_video_sample_entry_read((GF_VisualSampleEntryBox *) genv, bs);
if (gf_bs_available(bs)) {
u64 pos = gf_bs_get_position(bs);
//try to parse as boxes
GF_Err e = gf_isom_box_array_read((GF_Box *) genv, bs, gf_isom_box_add_default);
if (e) {
gf_bs_seek(bs, pos);
genv->data_size = (u32) gf_bs_available(bs);
if (genv->data_size) {
genv->data = a->data;
a->data = NULL;
memmove(genv->data, genv->data + pos, genv->data_size);
}
} else {
genv->data_size = 0;
}
}
gf_bs_del(bs);
if (!genv->data_size && genv->data) {
gf_free(genv->data);
genv->data = NULL;
}
genv->size = 0;
genv->EntryType = a->original_4cc;
gf_isom_box_del((GF_Box *)a);
gf_list_insert(trak->Media->information->sampleTable->SampleDescription->other_boxes, genv, i-1);
}
break;
case GF_ISOM_MEDIA_AUDIO:
{
GF_GenericAudioSampleEntryBox *gena;
/*remove entry*/
gf_list_rem(trak->Media->information->sampleTable->SampleDescription->other_boxes, i-1);
gena = (GF_GenericAudioSampleEntryBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_GNRA);
gena->size = a->size-8;
bs = gf_bs_new(a->data, a->dataSize, GF_BITSTREAM_READ);
gf_isom_audio_sample_entry_read((GF_AudioSampleEntryBox *) gena, bs);
if (gf_bs_available(bs)) {
u64 pos = gf_bs_get_position(bs);
//try to parse as boxes
GF_Err e = gf_isom_box_array_read((GF_Box *) gena, bs, gf_isom_box_add_default);
if (e) {
gf_bs_seek(bs, pos);
gena->data_size = (u32) gf_bs_available(bs);
if (gena->data_size) {
gena->data = a->data;
a->data = NULL;
memmove(gena->data, gena->data + pos, gena->data_size);
}
} else {
gena->data_size = 0;
}
}
gf_bs_del(bs);
if (!gena->data_size && gena->data) {
gf_free(gena->data);
gena->data = NULL;
}
gena->size = 0;
gena->EntryType = a->original_4cc;
gf_isom_box_del((GF_Box *)a);
gf_list_insert(trak->Media->information->sampleTable->SampleDescription->other_boxes, gena, i-1);
}
break;
default:
{
GF_Err e;
GF_GenericSampleEntryBox *genm;
/*remove entry*/
gf_list_rem(trak->Media->information->sampleTable->SampleDescription->other_boxes, i-1);
genm = (GF_GenericSampleEntryBox *) gf_isom_box_new(GF_ISOM_BOX_TYPE_GNRM);
genm->size = a->size-8;
bs = gf_bs_new(a->data, a->dataSize, GF_BITSTREAM_READ);
e = gf_isom_base_sample_entry_read((GF_SampleEntryBox *)genm, bs);
if (e) return;
genm->size -= 8;
if (gf_bs_available(bs)) {
u64 pos = gf_bs_get_position(bs);
//try to parse as boxes
GF_Err e = gf_isom_box_array_read((GF_Box *) genm, bs, gf_isom_box_add_default);
if (e) {
gf_bs_seek(bs, pos);
genm->data_size = (u32) gf_bs_available(bs);
if (genm->data_size) {
genm->data = a->data;
a->data = NULL;
memmove(genm->data, genm->data + pos, genm->data_size);
}
} else {
genm->data_size = 0;
}
}
gf_bs_del(bs);
if (!genm->data_size && genm->data) {
gf_free(genm->data);
genm->data = NULL;
}
genm->size = 0;
genm->EntryType = a->original_4cc;
gf_isom_box_del((GF_Box *)a);
gf_list_insert(trak->Media->information->sampleTable->SampleDescription->other_boxes, genm, i-1);
}
break;
}
}
}
GF_Err trak_AddBox(GF_Box *s, GF_Box *a)
{
GF_TrackBox *ptr = (GF_TrackBox *)s;
if (!a) return GF_OK;
switch(a->type) {
case GF_ISOM_BOX_TYPE_TKHD:
if (ptr->Header) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->Header = (GF_TrackHeaderBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_EDTS:
if (ptr->editBox) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->editBox = (GF_EditBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_UDTA:
if (ptr->udta) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->udta = (GF_UserDataBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_META:
if (ptr->meta) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->meta = (GF_MetaBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_TREF:
if (ptr->References) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->References = (GF_TrackReferenceBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_MDIA:
if (ptr->Media) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->Media = (GF_MediaBox *)a;
((GF_MediaBox *)a)->mediaTrack = ptr;
return GF_OK;
case GF_ISOM_BOX_TYPE_TRGR:
if (ptr->groups) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->groups = (GF_TrackGroupBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_SENC:
ptr->sample_encryption = (GF_SampleEncryptionBox*)a;
return gf_isom_box_add_default((GF_Box *)ptr, a);
case GF_ISOM_BOX_TYPE_UUID:
if (((GF_UnknownUUIDBox *)a)->internal_4cc == GF_ISOM_BOX_UUID_PSEC) {
ptr->sample_encryption = (GF_SampleEncryptionBox*) a;
return gf_isom_box_add_default((GF_Box *)ptr, a);
}
default:
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err trak_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_TrackBox *ptr = (GF_TrackBox *)s;
e = gf_isom_box_array_read(s, bs, trak_AddBox);
if (e) return e;
gf_isom_check_sample_desc(ptr);
if (!ptr->Header) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing TrackHeaderBox\n"));
return GF_ISOM_INVALID_FILE;
}
if (!ptr->Media) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing MediaBox\n"));
return GF_ISOM_INVALID_FILE;
}
for (i=0; i<gf_list_count(ptr->Media->information->sampleTable->other_boxes); i++) {
GF_Box *a = gf_list_get(ptr->Media->information->sampleTable->other_boxes, i);
if ((a->type ==GF_ISOM_BOX_TYPE_UUID) && (((GF_UUIDBox *)a)->internal_4cc == GF_ISOM_BOX_UUID_PSEC)) {
ptr->sample_encryption = (struct __sample_encryption_box *) a;
break;
}
else if (a->type == GF_ISOM_BOX_TYPE_SENC) {
ptr->sample_encryption = (struct __sample_encryption_box *)a;
break;
}
}
return e;
}
GF_Box *trak_New()
{
ISOM_DECL_BOX_ALLOC(GF_TrackBox, GF_ISOM_BOX_TYPE_TRAK);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err trak_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TrackBox *ptr = (GF_TrackBox *)s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
if (ptr->Header) {
e = gf_isom_box_write((GF_Box *) ptr->Header, bs);
if (e) return e;
}
if (ptr->References) {
e = gf_isom_box_write((GF_Box *) ptr->References, bs);
if (e) return e;
}
if (ptr->editBox) {
e = gf_isom_box_write((GF_Box *) ptr->editBox, bs);
if (e) return e;
}
if (ptr->Media) {
e = gf_isom_box_write((GF_Box *) ptr->Media, bs);
if (e) return e;
}
if (ptr->meta) {
e = gf_isom_box_write((GF_Box *) ptr->meta, bs);
if (e) return e;
}
if (ptr->groups) {
e = gf_isom_box_write((GF_Box *) ptr->groups, bs);
if (e) return e;
}
if (ptr->udta) {
e = gf_isom_box_write((GF_Box *) ptr->udta, bs);
if (e) return e;
}
return GF_OK;
}
GF_Err trak_Size(GF_Box *s)
{
GF_Err e;
GF_TrackBox *ptr = (GF_TrackBox *)s;
if (ptr->Header) {
e = gf_isom_box_size((GF_Box *) ptr->Header);
if (e) return e;
ptr->size += ptr->Header->size;
}
if (ptr->udta) {
e = gf_isom_box_size((GF_Box *) ptr->udta);
if (e) return e;
ptr->size += ptr->udta->size;
}
if (ptr->References) {
e = gf_isom_box_size((GF_Box *) ptr->References);
if (e) return e;
ptr->size += ptr->References->size;
}
if (ptr->editBox) {
e = gf_isom_box_size((GF_Box *) ptr->editBox);
if (e) return e;
ptr->size += ptr->editBox->size;
}
if (ptr->Media) {
e = gf_isom_box_size((GF_Box *) ptr->Media);
if (e) return e;
ptr->size += ptr->Media->size;
}
if (ptr->meta) {
e = gf_isom_box_size((GF_Box *) ptr->meta);
if (e) return e;
ptr->size += ptr->meta->size;
}
if (ptr->groups) {
e = gf_isom_box_size((GF_Box *) ptr->groups);
if (e) return e;
ptr->size += ptr->groups->size;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void stri_del(GF_Box *s)
{
GF_SubTrackInformationBox *ptr = (GF_SubTrackInformationBox *)s;
if (ptr == NULL) return;
if (ptr->attribute_list) gf_free(ptr->attribute_list);
gf_free(ptr);
}
GF_Err stri_Read(GF_Box *s, GF_BitStream *bs)
{
size_t i;
GF_SubTrackInformationBox *ptr = (GF_SubTrackInformationBox *)s;
ptr->switch_group = gf_bs_read_u16(bs);
ptr->alternate_group = gf_bs_read_u16(bs);
ptr->sub_track_id = gf_bs_read_u32(bs);
ptr->size -= 8;
ptr->attribute_count = ptr->size / 4;
GF_SAFE_ALLOC_N(ptr->attribute_list, (size_t)ptr->attribute_count, u32);
if (!ptr->attribute_list) return GF_OUT_OF_MEM;
for (i = 0; i < ptr->attribute_count; i++) {
ptr->attribute_list[i] = gf_bs_read_u32(bs);
}
return GF_OK;
}
GF_Box *stri_New()
{
ISOM_DECL_BOX_ALLOC(GF_SubTrackInformationBox, GF_ISOM_BOX_TYPE_STRI);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err stri_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_SubTrackInformationBox *ptr = (GF_SubTrackInformationBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u16(bs, ptr->switch_group);
gf_bs_write_u16(bs, ptr->alternate_group);
gf_bs_write_u32(bs, ptr->sub_track_id);
for (i = 0; i < ptr->attribute_count; i++) {
gf_bs_write_u32(bs, ptr->attribute_list[i]);
}
return GF_OK;
}
GF_Err stri_Size(GF_Box *s)
{
GF_SubTrackInformationBox *ptr = (GF_SubTrackInformationBox *)s;
ptr->size += 8 + 4 * ptr->attribute_count;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void stsg_del(GF_Box *s)
{
GF_SubTrackSampleGroupBox *ptr = (GF_SubTrackSampleGroupBox *)s;
if (ptr == NULL) return;
if (ptr->group_description_index) gf_free(ptr->group_description_index);
gf_free(ptr);
}
GF_Err stsg_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i;
GF_SubTrackSampleGroupBox *ptr = (GF_SubTrackSampleGroupBox *)s;
ISOM_DECREASE_SIZE(s, 6);
ptr->grouping_type = gf_bs_read_u32(bs);
ptr->nb_groups = gf_bs_read_u16(bs);
ISOM_DECREASE_SIZE(s, ptr->nb_groups*4);
GF_SAFE_ALLOC_N(ptr->group_description_index, ptr->nb_groups, u32);
if (!ptr->group_description_index) return GF_OUT_OF_MEM;
for (i = 0; i < ptr->nb_groups; i++) {
ptr->group_description_index[i] = gf_bs_read_u32(bs);
}
return GF_OK;
}
GF_Box *stsg_New()
{
ISOM_DECL_BOX_ALLOC(GF_SubTrackSampleGroupBox, GF_ISOM_BOX_TYPE_STSG);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err stsg_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_SubTrackSampleGroupBox *ptr = (GF_SubTrackSampleGroupBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->grouping_type);
gf_bs_write_u16(bs, ptr->nb_groups);
for (i = 0; i < ptr->nb_groups; i++) {
gf_bs_write_u32(bs, ptr->group_description_index[i]);
}
return GF_OK;
}
GF_Err stsg_Size(GF_Box *s)
{
GF_SubTrackSampleGroupBox *ptr = (GF_SubTrackSampleGroupBox *)s;
ptr->size += 6 + 4 * ptr->nb_groups;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void strk_del(GF_Box *s)
{
GF_SubTrackBox *ptr = (GF_SubTrackBox *)s;
if (ptr == NULL) return;
if (ptr->info) gf_isom_box_del((GF_Box *)ptr->info);
gf_free(ptr);
}
GF_Err strk_AddBox(GF_Box *s, GF_Box *a)
{
GF_SubTrackBox *ptr = (GF_SubTrackBox *)s;
if (!a) return GF_OK;
switch (a->type) {
case GF_ISOM_BOX_TYPE_STRI:
if (ptr->info) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->info = (GF_SubTrackInformationBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_STRD:
if (ptr->strd) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->strd = a;
return GF_OK;
default:
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err strk_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_SubTrackBox *ptr = (GF_SubTrackBox *)s;
e = gf_isom_box_array_read(s, bs, strk_AddBox);
if (e) return e;
if (!ptr->info) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing SubTrackInformationBox\n"));
return GF_ISOM_INVALID_FILE;
}
return e;
}
GF_Box *strk_New()
{
ISOM_DECL_BOX_ALLOC(GF_SubTrackBox, GF_ISOM_BOX_TYPE_STRK);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err strk_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_SubTrackBox *ptr = (GF_SubTrackBox *)s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
if (ptr->info) {
e = gf_isom_box_write((GF_Box *)ptr->info, bs);
if (e) return e;
}
return GF_OK;
}
GF_Err strk_Size(GF_Box *s)
{
GF_Err e;
GF_SubTrackBox *ptr = (GF_SubTrackBox *)s;
if (ptr->info) {
e = gf_isom_box_size((GF_Box *)ptr->info);
if (e) return e;
ptr->size += ptr->info->size;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Err tref_AddBox(GF_Box *ptr, GF_Box *a)
{
return gf_isom_box_add_default(ptr, a);
}
void tref_del(GF_Box *s)
{
GF_TrackReferenceBox *ptr = (GF_TrackReferenceBox *)s;
if (ptr == NULL) return;
gf_free(ptr);
}
GF_Err tref_Read(GF_Box *s, GF_BitStream *bs)
{
return gf_isom_box_array_read_ex(s, bs, gf_isom_box_add_default, s->type);
}
GF_Box *tref_New()
{
ISOM_DECL_BOX_ALLOC(GF_TrackReferenceBox, GF_ISOM_BOX_TYPE_TREF);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err tref_Write(GF_Box *s, GF_BitStream *bs)
{
// GF_TrackReferenceBox *ptr = (GF_TrackReferenceBox *)s;
return gf_isom_box_write_header(s, bs);
}
GF_Err tref_Size(GF_Box *s)
{
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void reftype_del(GF_Box *s)
{
GF_TrackReferenceTypeBox *ptr = (GF_TrackReferenceTypeBox *)s;
if (!ptr) return;
if (ptr->trackIDs) gf_free(ptr->trackIDs);
gf_free(ptr);
}
GF_Err reftype_Read(GF_Box *s, GF_BitStream *bs)
{
u32 bytesToRead;
u32 i;
GF_TrackReferenceTypeBox *ptr = (GF_TrackReferenceTypeBox *)s;
bytesToRead = (u32) (ptr->size);
if (!bytesToRead) return GF_OK;
ptr->trackIDCount = (u32) (bytesToRead) / sizeof(u32);
ptr->trackIDs = (u32 *) gf_malloc(ptr->trackIDCount * sizeof(u32));
if (!ptr->trackIDs) return GF_OUT_OF_MEM;
for (i = 0; i < ptr->trackIDCount; i++) {
ptr->trackIDs[i] = gf_bs_read_u32(bs);
}
return GF_OK;
}
GF_Box *reftype_New()
{
ISOM_DECL_BOX_ALLOC(GF_TrackReferenceTypeBox, GF_ISOM_BOX_TYPE_REFT);
return (GF_Box *)tmp;
}
GF_Err reftype_AddRefTrack(GF_TrackReferenceTypeBox *ref, u32 trackID, u16 *outRefIndex)
{
u32 i;
if (!ref || !trackID) return GF_BAD_PARAM;
if (outRefIndex) *outRefIndex = 0;
//don't add a dep if already here !!
for (i = 0; i < ref->trackIDCount; i++) {
if (ref->trackIDs[i] == trackID) {
if (outRefIndex) *outRefIndex = i+1;
return GF_OK;
}
}
ref->trackIDs = (u32 *) gf_realloc(ref->trackIDs, (ref->trackIDCount + 1) * sizeof(u32) );
if (!ref->trackIDs) return GF_OUT_OF_MEM;
ref->trackIDs[ref->trackIDCount] = trackID;
ref->trackIDCount++;
if (outRefIndex) *outRefIndex = ref->trackIDCount;
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err reftype_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_TrackReferenceTypeBox *ptr = (GF_TrackReferenceTypeBox *)s;
ptr->type = ptr->reference_type;
if (!ptr->trackIDCount) return GF_OK;
e = gf_isom_box_write_header(s, bs);
ptr->type = GF_ISOM_BOX_TYPE_REFT;
if (e) return e;
for (i = 0; i < ptr->trackIDCount; i++) {
gf_bs_write_u32(bs, ptr->trackIDs[i]);
}
return GF_OK;
}
GF_Err reftype_Size(GF_Box *s)
{
GF_TrackReferenceTypeBox *ptr = (GF_TrackReferenceTypeBox *)s;
if (!ptr->trackIDCount)
ptr->size=0;
else
ptr->size += (ptr->trackIDCount * sizeof(u32));
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
void trex_del(GF_Box *s)
{
GF_TrackExtendsBox *ptr = (GF_TrackExtendsBox *)s;
if (ptr == NULL) return;
gf_free(ptr);
}
GF_Err trex_Read(GF_Box *s, GF_BitStream *bs)
{
GF_TrackExtendsBox *ptr = (GF_TrackExtendsBox *)s;
ptr->trackID = gf_bs_read_u32(bs);
ptr->def_sample_desc_index = gf_bs_read_u32(bs);
ptr->def_sample_duration = gf_bs_read_u32(bs);
ptr->def_sample_size = gf_bs_read_u32(bs);
ptr->def_sample_flags = gf_bs_read_u32(bs);
if (!ptr->def_sample_desc_index) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] TREX with default sample description set to 0, likely broken ! Fixing to 1\n" ));
ptr->def_sample_desc_index = 1;
}
return GF_OK;
}
GF_Box *trex_New()
{
ISOM_DECL_BOX_ALLOC(GF_TrackExtendsBox, GF_ISOM_BOX_TYPE_TREX);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err trex_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TrackExtendsBox *ptr = (GF_TrackExtendsBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->trackID);
gf_bs_write_u32(bs, ptr->def_sample_desc_index);
gf_bs_write_u32(bs, ptr->def_sample_duration);
gf_bs_write_u32(bs, ptr->def_sample_size);
gf_bs_write_u32(bs, ptr->def_sample_flags);
return GF_OK;
}
GF_Err trex_Size(GF_Box *s)
{
GF_TrackExtendsBox *ptr = (GF_TrackExtendsBox *)s;
ptr->size += 20;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void trep_del(GF_Box *s)
{
GF_TrackExtensionPropertiesBox *ptr = (GF_TrackExtensionPropertiesBox *)s;
if (ptr == NULL) return;
gf_free(ptr);
}
GF_Err trep_Read(GF_Box *s, GF_BitStream *bs)
{
GF_TrackExtensionPropertiesBox *ptr = (GF_TrackExtensionPropertiesBox *)s;
ptr->trackID = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
return gf_isom_box_array_read(s, bs, gf_isom_box_add_default);
}
GF_Box *trep_New()
{
ISOM_DECL_BOX_ALLOC(GF_TrackExtensionPropertiesBox, GF_ISOM_BOX_TYPE_TREP);
tmp->other_boxes = gf_list_new();
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err trep_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TrackExtensionPropertiesBox *ptr = (GF_TrackExtensionPropertiesBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->trackID);
return GF_OK;
}
GF_Err trep_Size(GF_Box *s)
{
GF_TrackExtensionPropertiesBox *ptr = (GF_TrackExtensionPropertiesBox *)s;
ptr->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
void trun_del(GF_Box *s)
{
GF_TrunEntry *p;
GF_TrackFragmentRunBox *ptr = (GF_TrackFragmentRunBox *)s;
if (ptr == NULL) return;
while (gf_list_count(ptr->entries)) {
p = (GF_TrunEntry*)gf_list_get(ptr->entries, 0);
gf_list_rem(ptr->entries, 0);
gf_free(p);
}
gf_list_del(ptr->entries);
if (ptr->cache) gf_bs_del(ptr->cache);
gf_free(ptr);
}
GF_Err trun_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i;
GF_TrunEntry *p;
GF_TrackFragmentRunBox *ptr = (GF_TrackFragmentRunBox *)s;
//check this is a good file
if ((ptr->flags & GF_ISOM_TRUN_FIRST_FLAG) && (ptr->flags & GF_ISOM_TRUN_FLAGS))
return GF_ISOM_INVALID_FILE;
ptr->sample_count = gf_bs_read_u32(bs);
//The rest depends on the flags
if (ptr->flags & GF_ISOM_TRUN_DATA_OFFSET) {
ptr->data_offset = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
}
if (ptr->flags & GF_ISOM_TRUN_FIRST_FLAG) {
ptr->first_sample_flags = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
}
//read each entry (even though nothing may be written)
for (i=0; i<ptr->sample_count; i++) {
u32 trun_size = 0;
p = (GF_TrunEntry *) gf_malloc(sizeof(GF_TrunEntry));
if (!p) return GF_OUT_OF_MEM;
memset(p, 0, sizeof(GF_TrunEntry));
if (ptr->flags & GF_ISOM_TRUN_DURATION) {
p->Duration = gf_bs_read_u32(bs);
trun_size += 4;
}
if (ptr->flags & GF_ISOM_TRUN_SIZE) {
p->size = gf_bs_read_u32(bs);
trun_size += 4;
}
//SHOULDN'T BE USED IF GF_ISOM_TRUN_FIRST_FLAG IS DEFINED
if (ptr->flags & GF_ISOM_TRUN_FLAGS) {
p->flags = gf_bs_read_u32(bs);
trun_size += 4;
}
if (ptr->flags & GF_ISOM_TRUN_CTS_OFFSET) {
if (ptr->version==0) {
p->CTS_Offset = (u32) gf_bs_read_u32(bs);
} else {
p->CTS_Offset = (s32) gf_bs_read_u32(bs);
}
}
gf_list_add(ptr->entries, p);
ISOM_DECREASE_SIZE(ptr, trun_size);
}
return GF_OK;
}
GF_Box *trun_New()
{
ISOM_DECL_BOX_ALLOC(GF_TrackFragmentRunBox, GF_ISOM_BOX_TYPE_TRUN);
tmp->entries = gf_list_new();
//NO FLAGS SET BY DEFAULT
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err trun_Write(GF_Box *s, GF_BitStream *bs)
{
GF_TrunEntry *p;
GF_Err e;
u32 i, count;
GF_TrackFragmentRunBox *ptr = (GF_TrackFragmentRunBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->sample_count);
//The rest depends on the flags
if (ptr->flags & GF_ISOM_TRUN_DATA_OFFSET) {
gf_bs_write_u32(bs, ptr->data_offset);
}
if (ptr->flags & GF_ISOM_TRUN_FIRST_FLAG) {
gf_bs_write_u32(bs, ptr->first_sample_flags);
}
//if nothing to do, this will be skipped automatically
count = gf_list_count(ptr->entries);
for (i=0; i<count; i++) {
p = (GF_TrunEntry*)gf_list_get(ptr->entries, i);
if (ptr->flags & GF_ISOM_TRUN_DURATION) {
gf_bs_write_u32(bs, p->Duration);
}
if (ptr->flags & GF_ISOM_TRUN_SIZE) {
gf_bs_write_u32(bs, p->size);
}
//SHOULDN'T BE USED IF GF_ISOM_TRUN_FIRST_FLAG IS DEFINED
if (ptr->flags & GF_ISOM_TRUN_FLAGS) {
gf_bs_write_u32(bs, p->flags);
}
if (ptr->flags & GF_ISOM_TRUN_CTS_OFFSET) {
if (ptr->version==0) {
gf_bs_write_u32(bs, p->CTS_Offset);
} else {
gf_bs_write_u32(bs, (u32) p->CTS_Offset);
}
}
}
return GF_OK;
}
GF_Err trun_Size(GF_Box *s)
{
u32 i, count;
GF_TrackFragmentRunBox *ptr = (GF_TrackFragmentRunBox *)s;
ptr->size += 4;
//The rest depends on the flags
if (ptr->flags & GF_ISOM_TRUN_DATA_OFFSET) ptr->size += 4;
if (ptr->flags & GF_ISOM_TRUN_FIRST_FLAG) ptr->size += 4;
//if nothing to do, this will be skipped automatically
count = gf_list_count(ptr->entries);
for (i=0; i<count; i++) {
if (ptr->flags & GF_ISOM_TRUN_DURATION) ptr->size += 4;
if (ptr->flags & GF_ISOM_TRUN_SIZE) ptr->size += 4;
//SHOULDN'T BE USED IF GF_ISOM_TRUN_FIRST_FLAG IS DEFINED
if (ptr->flags & GF_ISOM_TRUN_FLAGS) ptr->size += 4;
if (ptr->flags & GF_ISOM_TRUN_CTS_OFFSET) ptr->size += 4;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/
void tsro_del(GF_Box *s)
{
GF_TimeOffHintEntryBox *tsro = (GF_TimeOffHintEntryBox *)s;
gf_free(tsro);
}
GF_Err tsro_Read(GF_Box *s, GF_BitStream *bs)
{
GF_TimeOffHintEntryBox *ptr = (GF_TimeOffHintEntryBox *)s;
ptr->TimeOffset = gf_bs_read_u32(bs);
return GF_OK;
}
GF_Box *tsro_New()
{
ISOM_DECL_BOX_ALLOC(GF_TimeOffHintEntryBox, GF_ISOM_BOX_TYPE_TSRO);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err tsro_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TimeOffHintEntryBox *ptr = (GF_TimeOffHintEntryBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->TimeOffset);
return GF_OK;
}
GF_Err tsro_Size(GF_Box *s)
{
s->size += 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void udta_del(GF_Box *s)
{
u32 i;
GF_UserDataMap *map;
GF_UserDataBox *ptr = (GF_UserDataBox *)s;
if (ptr == NULL) return;
i=0;
while ((map = (GF_UserDataMap *)gf_list_enum(ptr->recordList, &i))) {
gf_isom_box_array_del(map->other_boxes);
gf_free(map);
}
gf_list_del(ptr->recordList);
gf_free(ptr);
}
GF_UserDataMap *udta_getEntry(GF_UserDataBox *ptr, u32 box_type, bin128 *uuid)
{
u32 i;
GF_UserDataMap *map;
if (ptr == NULL) return NULL;
i=0;
while ((map = (GF_UserDataMap *)gf_list_enum(ptr->recordList, &i))) {
if (map->boxType == box_type) {
if ((box_type != GF_ISOM_BOX_TYPE_UUID) || !uuid) return map;
if (!memcmp(map->uuid, *uuid, 16)) return map;
}
}
return NULL;
}
GF_Err udta_AddBox(GF_Box *s, GF_Box *a)
{
GF_Err e;
u32 box_type;
GF_UserDataMap *map;
GF_UserDataBox *ptr = (GF_UserDataBox *)s;
if (!ptr) return GF_BAD_PARAM;
if (!a) return GF_OK;
/* for unknown udta boxes, we reference them by their original box type */
box_type = a->type;
if (box_type == GF_ISOM_BOX_TYPE_UNKNOWN) {
GF_UnknownBox* unkn = (GF_UnknownBox *)a;
if (unkn)
box_type = unkn->original_4cc;
}
map = udta_getEntry(ptr, box_type, (a->type==GF_ISOM_BOX_TYPE_UUID) ? & ((GF_UUIDBox *)a)->uuid : NULL);
if (map == NULL) {
map = (GF_UserDataMap *) gf_malloc(sizeof(GF_UserDataMap));
if (map == NULL) return GF_OUT_OF_MEM;
memset(map, 0, sizeof(GF_UserDataMap));
map->boxType = box_type;
if (a->type == GF_ISOM_BOX_TYPE_UUID)
memcpy(map->uuid, ((GF_UUIDBox *)a)->uuid, 16);
map->other_boxes = gf_list_new();
if (!map->other_boxes) {
gf_free(map);
return GF_OUT_OF_MEM;
}
e = gf_list_add(ptr->recordList, map);
if (e) return e;
}
return gf_list_add(map->other_boxes, a);
}
GF_Err udta_Read(GF_Box *s, GF_BitStream *bs)
{
return gf_isom_box_array_read(s, bs, udta_AddBox);
}
GF_Box *udta_New()
{
ISOM_DECL_BOX_ALLOC(GF_UserDataBox, GF_ISOM_BOX_TYPE_UDTA);
tmp->recordList = gf_list_new();
if (!tmp->recordList) {
gf_free(tmp);
return NULL;
}
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err udta_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_UserDataMap *map;
GF_UserDataBox *ptr = (GF_UserDataBox *)s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
i=0;
while ((map = (GF_UserDataMap *)gf_list_enum(ptr->recordList, &i))) {
//warning: here we are not passing the actual "parent" of the list
//but the UDTA box. The parent itself is not an box, we don't care about it
e = gf_isom_box_array_write(s, map->other_boxes, bs);
if (e) return e;
}
return GF_OK;
}
GF_Err udta_Size(GF_Box *s)
{
GF_Err e;
u32 i;
GF_UserDataMap *map;
GF_UserDataBox *ptr = (GF_UserDataBox *)s;
i=0;
while ((map = (GF_UserDataMap *)gf_list_enum(ptr->recordList, &i))) {
//warning: here we are not passing the actual "parent" of the list
//but the UDTA box. The parent itself is not an box, we don't care about it
e = gf_isom_box_array_size(s, map->other_boxes);
if (e) return e;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void vmhd_del(GF_Box *s)
{
GF_VideoMediaHeaderBox *ptr = (GF_VideoMediaHeaderBox *)s;
if (ptr == NULL) return;
gf_free(ptr);
}
GF_Err vmhd_Read(GF_Box *s, GF_BitStream *bs)
{
GF_VideoMediaHeaderBox *ptr = (GF_VideoMediaHeaderBox *)s;
ptr->reserved = gf_bs_read_u64(bs);
return GF_OK;
}
GF_Box *vmhd_New()
{
ISOM_DECL_BOX_ALLOC(GF_VideoMediaHeaderBox, GF_ISOM_BOX_TYPE_VMHD);
tmp->flags = 1;
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err vmhd_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_VideoMediaHeaderBox *ptr = (GF_VideoMediaHeaderBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u64(bs, ptr->reserved);
return GF_OK;
}
GF_Err vmhd_Size(GF_Box *s)
{
GF_VideoMediaHeaderBox *ptr = (GF_VideoMediaHeaderBox *)s;
ptr->size += 8;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void void_del(GF_Box *s)
{
gf_free(s);
}
GF_Err void_Read(GF_Box *s, GF_BitStream *bs)
{
if (s->size) return GF_ISOM_INVALID_FILE;
return GF_OK;
}
GF_Box *void_New()
{
ISOM_DECL_BOX_ALLOC(GF_Box, GF_ISOM_BOX_TYPE_VOID);
return tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err void_Write(GF_Box *s, GF_BitStream *bs)
{
gf_bs_write_u32(bs, 0);
return GF_OK;
}
GF_Err void_Size(GF_Box *s)
{
s->size = 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *pdin_New()
{
ISOM_DECL_BOX_ALLOC(GF_ProgressiveDownloadBox, GF_ISOM_BOX_TYPE_PDIN);
tmp->flags = 1;
return (GF_Box *)tmp;
}
void pdin_del(GF_Box *s)
{
GF_ProgressiveDownloadBox *ptr = (GF_ProgressiveDownloadBox*)s;
if (ptr == NULL) return;
if (ptr->rates) gf_free(ptr->rates);
if (ptr->times) gf_free(ptr->times);
gf_free(ptr);
}
GF_Err pdin_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i;
GF_ProgressiveDownloadBox *ptr = (GF_ProgressiveDownloadBox*)s;
ptr->count = (u32) (ptr->size) / 8;
ptr->rates = (u32*)gf_malloc(sizeof(u32)*ptr->count);
ptr->times = (u32*)gf_malloc(sizeof(u32)*ptr->count);
for (i=0; i<ptr->count; i++) {
ptr->rates[i] = gf_bs_read_u32(bs);
ptr->times[i] = gf_bs_read_u32(bs);
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err pdin_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_ProgressiveDownloadBox *ptr = (GF_ProgressiveDownloadBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
for (i=0; i<ptr->count; i++) {
gf_bs_write_u32(bs, ptr->rates[i]);
gf_bs_write_u32(bs, ptr->times[i]);
}
return GF_OK;
}
GF_Err pdin_Size(GF_Box *s)
{
GF_ProgressiveDownloadBox *ptr = (GF_ProgressiveDownloadBox *)s;
ptr->size += 8*ptr->count;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *sdtp_New()
{
ISOM_DECL_BOX_ALLOC(GF_SampleDependencyTypeBox, GF_ISOM_BOX_TYPE_SDTP);
tmp->flags = 1;
return (GF_Box *)tmp;
}
void sdtp_del(GF_Box *s)
{
GF_SampleDependencyTypeBox *ptr = (GF_SampleDependencyTypeBox*)s;
if (ptr == NULL) return;
if (ptr->sample_info) gf_free(ptr->sample_info);
gf_free(ptr);
}
GF_Err sdtp_Read(GF_Box *s, GF_BitStream *bs)
{
GF_SampleDependencyTypeBox *ptr = (GF_SampleDependencyTypeBox*)s;
/*out-of-order sdtp, assume no padding at the end*/
if (!ptr->sampleCount) ptr->sampleCount = (u32) ptr->size;
else if (ptr->sampleCount > (u32) ptr->size) return GF_ISOM_INVALID_FILE;
ptr->sample_info = (u8 *) gf_malloc(sizeof(u8)*ptr->sampleCount);
gf_bs_read_data(bs, (char*)ptr->sample_info, ptr->sampleCount);
ISOM_DECREASE_SIZE(ptr, ptr->sampleCount);
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err sdtp_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_SampleDependencyTypeBox *ptr = (GF_SampleDependencyTypeBox *)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_data(bs, (char*)ptr->sample_info, ptr->sampleCount);
return GF_OK;
}
GF_Err sdtp_Size(GF_Box *s)
{
GF_SampleDependencyTypeBox *ptr = (GF_SampleDependencyTypeBox *)s;
ptr->size += ptr->sampleCount;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *pasp_New()
{
ISOM_DECL_BOX_ALLOC(GF_PixelAspectRatioBox, GF_ISOM_BOX_TYPE_PASP);
return (GF_Box *)tmp;
}
void pasp_del(GF_Box *s)
{
GF_PixelAspectRatioBox *ptr = (GF_PixelAspectRatioBox*)s;
if (ptr == NULL) return;
gf_free(ptr);
}
GF_Err pasp_Read(GF_Box *s, GF_BitStream *bs)
{
GF_PixelAspectRatioBox *ptr = (GF_PixelAspectRatioBox*)s;
ptr->hSpacing = gf_bs_read_u32(bs);
ptr->vSpacing = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 8);
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err pasp_Write(GF_Box *s, GF_BitStream *bs)
{
GF_PixelAspectRatioBox *ptr = (GF_PixelAspectRatioBox *)s;
GF_Err e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->hSpacing);
gf_bs_write_u32(bs, ptr->vSpacing);
return GF_OK;
}
GF_Err pasp_Size(GF_Box *s)
{
s->size += 8;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *clap_New()
{
ISOM_DECL_BOX_ALLOC(GF_CleanAppertureBox, GF_ISOM_BOX_TYPE_CLAP);
return (GF_Box *)tmp;
}
void clap_del(GF_Box *s)
{
GF_CleanAppertureBox *ptr = (GF_CleanAppertureBox*)s;
if (ptr == NULL) return;
gf_free(ptr);
}
GF_Err clap_Read(GF_Box *s, GF_BitStream *bs)
{
GF_CleanAppertureBox *ptr = (GF_CleanAppertureBox*)s;
ISOM_DECREASE_SIZE(ptr, 32);
ptr->cleanApertureWidthN = gf_bs_read_u32(bs);
ptr->cleanApertureWidthD = gf_bs_read_u32(bs);
ptr->cleanApertureHeightN = gf_bs_read_u32(bs);
ptr->cleanApertureHeightD = gf_bs_read_u32(bs);
ptr->horizOffN = gf_bs_read_u32(bs);
ptr->horizOffD = gf_bs_read_u32(bs);
ptr->vertOffN = gf_bs_read_u32(bs);
ptr->vertOffD = gf_bs_read_u32(bs);
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err clap_Write(GF_Box *s, GF_BitStream *bs)
{
GF_CleanAppertureBox *ptr = (GF_CleanAppertureBox *)s;
GF_Err e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->cleanApertureWidthN);
gf_bs_write_u32(bs, ptr->cleanApertureWidthD);
gf_bs_write_u32(bs, ptr->cleanApertureHeightN);
gf_bs_write_u32(bs, ptr->cleanApertureHeightD);
gf_bs_write_u32(bs, ptr->horizOffN);
gf_bs_write_u32(bs, ptr->horizOffD);
gf_bs_write_u32(bs, ptr->vertOffN);
gf_bs_write_u32(bs, ptr->vertOffD);
return GF_OK;
}
GF_Err clap_Size(GF_Box *s)
{
s->size += 32;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *metx_New()
{
//type is overridden by the box constructor
ISOM_DECL_BOX_ALLOC(GF_MetaDataSampleEntryBox, GF_ISOM_BOX_TYPE_METX);
gf_isom_sample_entry_init((GF_SampleEntryBox*)tmp);
return (GF_Box *)tmp;
}
void metx_del(GF_Box *s)
{
GF_MetaDataSampleEntryBox *ptr = (GF_MetaDataSampleEntryBox*)s;
if (ptr == NULL) return;
gf_isom_sample_entry_predestroy((GF_SampleEntryBox *)s);
if (ptr->content_encoding) gf_free(ptr->content_encoding);
if (ptr->xml_namespace) gf_free(ptr->xml_namespace);
if (ptr->xml_schema_loc) gf_free(ptr->xml_schema_loc);
if (ptr->mime_type) gf_free(ptr->mime_type);
if (ptr->config) gf_isom_box_del((GF_Box *)ptr->config);
gf_free(ptr);
}
GF_Err metx_AddBox(GF_Box *s, GF_Box *a)
{
GF_MetaDataSampleEntryBox *ptr = (GF_MetaDataSampleEntryBox *)s;
switch (a->type) {
case GF_ISOM_BOX_TYPE_SINF:
gf_list_add(ptr->protections, a);
break;
case GF_ISOM_BOX_TYPE_TXTC:
//we allow the config box on metx
if (ptr->config) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->config = (GF_TextConfigBox *)a;
break;
default:
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err metx_Read(GF_Box *s, GF_BitStream *bs)
{
u32 size, i;
GF_Err e;
char *str;
GF_MetaDataSampleEntryBox *ptr = (GF_MetaDataSampleEntryBox*)s;
e = gf_isom_base_sample_entry_read((GF_SampleEntryBox *)ptr, bs);
if (e) return e;
size = (u32) ptr->size - 8;
str = gf_malloc(sizeof(char)*size);
i=0;
while (size) {
str[i] = gf_bs_read_u8(bs);
size--;
if (!str[i])
break;
i++;
}
if (i) {
if (ptr->type==GF_ISOM_BOX_TYPE_STPP) {
ptr->xml_namespace = gf_strdup(str);
} else {
ptr->content_encoding = gf_strdup(str);
}
}
i=0;
while (size) {
str[i] = gf_bs_read_u8(bs);
size--;
if (!str[i])
break;
i++;
}
if ((ptr->type==GF_ISOM_BOX_TYPE_METX) || (ptr->type==GF_ISOM_BOX_TYPE_STPP)) {
if (i) {
if (ptr->type==GF_ISOM_BOX_TYPE_STPP) {
ptr->xml_schema_loc = gf_strdup(str);
} else {
ptr->xml_namespace = gf_strdup(str);
}
}
i=0;
while (size) {
str[i] = gf_bs_read_u8(bs);
size--;
if (!str[i])
break;
i++;
}
if (i) {
if (ptr->type==GF_ISOM_BOX_TYPE_STPP) {
ptr->mime_type = gf_strdup(str);
} else {
ptr->xml_schema_loc = gf_strdup(str);
}
}
}
//mett, sbtt, stxt, stpp
else {
if (i) ptr->mime_type = gf_strdup(str);
}
ptr->size = size;
gf_free(str);
return gf_isom_box_array_read(s, bs, metx_AddBox);
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err metx_Write(GF_Box *s, GF_BitStream *bs)
{
GF_MetaDataSampleEntryBox *ptr = (GF_MetaDataSampleEntryBox *)s;
GF_Err e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_data(bs, ptr->reserved, 6);
gf_bs_write_u16(bs, ptr->dataReferenceIndex);
if (ptr->type!=GF_ISOM_BOX_TYPE_STPP) {
if (ptr->content_encoding)
gf_bs_write_data(bs, ptr->content_encoding, (u32) strlen(ptr->content_encoding));
gf_bs_write_u8(bs, 0);
}
if ((ptr->type==GF_ISOM_BOX_TYPE_METX) || (ptr->type==GF_ISOM_BOX_TYPE_STPP)) {
if (ptr->xml_namespace)
gf_bs_write_data(bs, ptr->xml_namespace, (u32) strlen(ptr->xml_namespace));
gf_bs_write_u8(bs, 0);
if (ptr->xml_schema_loc)
gf_bs_write_data(bs, ptr->xml_schema_loc, (u32) strlen(ptr->xml_schema_loc));
gf_bs_write_u8(bs, 0);
if (ptr->type==GF_ISOM_BOX_TYPE_STPP) {
if (ptr->mime_type)
gf_bs_write_data(bs, ptr->mime_type, (u32) strlen(ptr->mime_type));
gf_bs_write_u8(bs, 0);
}
}
//mett, sbtt, stxt
else {
if (ptr->mime_type)
gf_bs_write_data(bs, ptr->mime_type, (u32) strlen(ptr->mime_type));
gf_bs_write_u8(bs, 0);
if (ptr->config) {
gf_isom_box_write((GF_Box *)ptr->config, bs);
}
}
return gf_isom_box_array_write(s, ptr->protections, bs);
}
GF_Err metx_Size(GF_Box *s)
{
GF_Err e;
GF_MetaDataSampleEntryBox *ptr = (GF_MetaDataSampleEntryBox *)s;
ptr->size += 8;
if (ptr->type!=GF_ISOM_BOX_TYPE_STPP) {
if (ptr->content_encoding)
ptr->size += strlen(ptr->content_encoding);
ptr->size++;
}
if ((ptr->type==GF_ISOM_BOX_TYPE_METX) || (ptr->type==GF_ISOM_BOX_TYPE_STPP)) {
if (ptr->xml_namespace)
ptr->size += strlen(ptr->xml_namespace);
ptr->size++;
if (ptr->xml_schema_loc)
ptr->size += strlen(ptr->xml_schema_loc);
ptr->size++;
if (ptr->type==GF_ISOM_BOX_TYPE_STPP) {
if (ptr->mime_type)
ptr->size += strlen(ptr->mime_type);
ptr->size++;
}
}
//mett, sbtt, stxt
else {
if (ptr->mime_type)
ptr->size += strlen(ptr->mime_type);
ptr->size++;
if (ptr->config) {
e = gf_isom_box_size((GF_Box *)ptr->config);
if (e) return e;
ptr->size += ptr->config->size;
}
}
return gf_isom_box_array_size(s, ptr->protections);
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
/* SimpleTextSampleEntry */
GF_Box *txtc_New()
{
ISOM_DECL_BOX_ALLOC(GF_TextConfigBox, GF_ISOM_BOX_TYPE_TXTC);
return (GF_Box *)tmp;
}
void txtc_del(GF_Box *s)
{
GF_TextConfigBox *ptr = (GF_TextConfigBox*)s;
if (ptr == NULL) return;
if (ptr->config) gf_free(ptr->config);
gf_free(ptr);
}
GF_Err txtc_Read(GF_Box *s, GF_BitStream *bs)
{
u32 size, i;
char *str;
GF_TextConfigBox *ptr = (GF_TextConfigBox*)s;
size = (u32) ptr->size;
str = (char *)gf_malloc(sizeof(char)*size);
i=0;
while (size) {
str[i] = gf_bs_read_u8(bs);
size--;
if (!str[i])
break;
i++;
}
if (i) ptr->config = gf_strdup(str);
gf_free(str);
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err txtc_Write(GF_Box *s, GF_BitStream *bs)
{
GF_TextConfigBox *ptr = (GF_TextConfigBox *)s;
GF_Err e = gf_isom_full_box_write(s, bs);
if (e) return e;
if (ptr->config)
gf_bs_write_data(bs, ptr->config, (u32) strlen(ptr->config));
gf_bs_write_u8(bs, 0);
return GF_OK;
}
GF_Err txtc_Size(GF_Box *s)
{
GF_TextConfigBox *ptr = (GF_TextConfigBox *)s;
if (ptr->config)
ptr->size += strlen(ptr->config);
ptr->size++;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *dac3_New()
{
ISOM_DECL_BOX_ALLOC(GF_AC3ConfigBox, GF_ISOM_BOX_TYPE_DAC3);
return (GF_Box *)tmp;
}
GF_Box *dec3_New()
{
ISOM_DECL_BOX_ALLOC(GF_AC3ConfigBox, GF_ISOM_BOX_TYPE_DAC3);
tmp->cfg.is_ec3 = 1;
return (GF_Box *)tmp;
}
void dac3_del(GF_Box *s)
{
GF_AC3ConfigBox *ptr = (GF_AC3ConfigBox *)s;
gf_free(ptr);
}
GF_Err dac3_Read(GF_Box *s, GF_BitStream *bs)
{
GF_AC3ConfigBox *ptr = (GF_AC3ConfigBox *)s;
if (ptr == NULL) return GF_BAD_PARAM;
if (ptr->cfg.is_ec3) {
u32 i;
ptr->cfg.brcode = gf_bs_read_int(bs, 13);
ptr->cfg.nb_streams = gf_bs_read_int(bs, 3) + 1;
for (i=0; i<ptr->cfg.nb_streams; i++) {
ptr->cfg.streams[i].fscod = gf_bs_read_int(bs, 2);
ptr->cfg.streams[i].bsid = gf_bs_read_int(bs, 5);
ptr->cfg.streams[i].bsmod = gf_bs_read_int(bs, 5);
ptr->cfg.streams[i].acmod = gf_bs_read_int(bs, 3);
ptr->cfg.streams[i].lfon = gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 3);
ptr->cfg.streams[i].nb_dep_sub = gf_bs_read_int(bs, 4);
if (ptr->cfg.streams[i].nb_dep_sub) {
ptr->cfg.streams[i].chan_loc = gf_bs_read_int(bs, 9);
} else {
gf_bs_read_int(bs, 1);
}
}
} else {
ptr->cfg.nb_streams = 1;
ptr->cfg.streams[0].fscod = gf_bs_read_int(bs, 2);
ptr->cfg.streams[0].bsid = gf_bs_read_int(bs, 5);
ptr->cfg.streams[0].bsmod = gf_bs_read_int(bs, 3);
ptr->cfg.streams[0].acmod = gf_bs_read_int(bs, 3);
ptr->cfg.streams[0].lfon = gf_bs_read_int(bs, 1);
ptr->cfg.brcode = gf_bs_read_int(bs, 5);
gf_bs_read_int(bs, 5);
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err dac3_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_AC3ConfigBox *ptr = (GF_AC3ConfigBox *)s;
if (ptr->cfg.is_ec3) s->type = GF_ISOM_BOX_TYPE_DEC3;
e = gf_isom_box_write_header(s, bs);
if (ptr->cfg.is_ec3) s->type = GF_ISOM_BOX_TYPE_DAC3;
if (e) return e;
if (ptr->cfg.is_ec3) {
u32 i;
gf_bs_write_int(bs, ptr->cfg.brcode, 13);
gf_bs_write_int(bs, ptr->cfg.nb_streams - 1, 3);
for (i=0; i<ptr->cfg.nb_streams; i++) {
gf_bs_write_int(bs, ptr->cfg.streams[i].fscod, 2);
gf_bs_write_int(bs, ptr->cfg.streams[i].bsid, 5);
gf_bs_write_int(bs, ptr->cfg.streams[i].bsmod, 5);
gf_bs_write_int(bs, ptr->cfg.streams[i].acmod, 3);
gf_bs_write_int(bs, ptr->cfg.streams[i].lfon, 1);
gf_bs_write_int(bs, 0, 3);
gf_bs_write_int(bs, ptr->cfg.streams[i].nb_dep_sub, 4);
if (ptr->cfg.streams[i].nb_dep_sub) {
gf_bs_write_int(bs, ptr->cfg.streams[i].chan_loc, 9);
} else {
gf_bs_write_int(bs, 0, 1);
}
}
} else {
gf_bs_write_int(bs, ptr->cfg.streams[0].fscod, 2);
gf_bs_write_int(bs, ptr->cfg.streams[0].bsid, 5);
gf_bs_write_int(bs, ptr->cfg.streams[0].bsmod, 3);
gf_bs_write_int(bs, ptr->cfg.streams[0].acmod, 3);
gf_bs_write_int(bs, ptr->cfg.streams[0].lfon, 1);
gf_bs_write_int(bs, ptr->cfg.brcode, 5);
gf_bs_write_int(bs, 0, 5);
}
return GF_OK;
}
GF_Err dac3_Size(GF_Box *s)
{
GF_AC3ConfigBox *ptr = (GF_AC3ConfigBox *)s;
if (ptr->cfg.is_ec3) {
u32 i;
s->size += 2;
for (i=0; i<ptr->cfg.nb_streams; i++) {
s->size += 3;
if (ptr->cfg.streams[i].nb_dep_sub)
s->size += 1;
}
} else {
s->size += 3;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void lsrc_del(GF_Box *s)
{
GF_LASERConfigurationBox *ptr = (GF_LASERConfigurationBox *)s;
if (ptr == NULL) return;
if (ptr->hdr) gf_free(ptr->hdr);
gf_free(ptr);
}
GF_Err lsrc_Read(GF_Box *s, GF_BitStream *bs)
{
GF_LASERConfigurationBox *ptr = (GF_LASERConfigurationBox *)s;
ptr->hdr_size = (u32) ptr->size;
ptr->hdr = gf_malloc(sizeof(char)*ptr->hdr_size);
gf_bs_read_data(bs, ptr->hdr, ptr->hdr_size);
return GF_OK;
}
GF_Box *lsrc_New()
{
ISOM_DECL_BOX_ALLOC(GF_LASERConfigurationBox, GF_ISOM_BOX_TYPE_LSRC);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err lsrc_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_LASERConfigurationBox *ptr = (GF_LASERConfigurationBox *)s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_data(bs, ptr->hdr, ptr->hdr_size);
return GF_OK;
}
GF_Err lsrc_Size(GF_Box *s)
{
GF_LASERConfigurationBox *ptr = (GF_LASERConfigurationBox *)s;
ptr->size += ptr->hdr_size;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void lsr1_del(GF_Box *s)
{
GF_LASeRSampleEntryBox *ptr = (GF_LASeRSampleEntryBox *)s;
if (ptr == NULL) return;
gf_isom_sample_entry_predestroy((GF_SampleEntryBox *)s);
if (ptr->slc) gf_odf_desc_del((GF_Descriptor *)ptr->slc);
if (ptr->lsr_config) gf_isom_box_del((GF_Box *) ptr->lsr_config);
if (ptr->descr) gf_isom_box_del((GF_Box *) ptr->descr);
gf_free(ptr);
}
GF_Err lsr1_AddBox(GF_Box *s, GF_Box *a)
{
GF_LASeRSampleEntryBox *ptr = (GF_LASeRSampleEntryBox *)s;
switch (a->type) {
case GF_ISOM_BOX_TYPE_LSRC:
if (ptr->lsr_config) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->lsr_config = (GF_LASERConfigurationBox *)a;
break;
case GF_ISOM_BOX_TYPE_M4DS:
if (ptr->descr) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->descr = (GF_MPEG4ExtensionDescriptorsBox *)a;
break;
default:
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err lsr1_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_LASeRSampleEntryBox *ptr = (GF_LASeRSampleEntryBox*)s;
e = gf_isom_base_sample_entry_read((GF_SampleEntryBox *)ptr, bs);
if (e) return e;
ISOM_DECREASE_SIZE(ptr, 8);
return gf_isom_box_array_read(s, bs, lsr1_AddBox);
}
GF_Box *lsr1_New()
{
ISOM_DECL_BOX_ALLOC(GF_LASeRSampleEntryBox, GF_ISOM_BOX_TYPE_LSR1);
gf_isom_sample_entry_init((GF_SampleEntryBox*)tmp);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err lsr1_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_LASeRSampleEntryBox *ptr = (GF_LASeRSampleEntryBox *)s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_data(bs, ptr->reserved, 6);
gf_bs_write_u16(bs, ptr->dataReferenceIndex);
if (ptr->lsr_config) {
e = gf_isom_box_write((GF_Box *)ptr->lsr_config, bs);
if (e) return e;
}
if (ptr->descr) {
e = gf_isom_box_write((GF_Box *)ptr->descr, bs);
if (e) return e;
}
return e;
}
GF_Err lsr1_Size(GF_Box *s)
{
GF_Err e;
GF_LASeRSampleEntryBox *ptr = (GF_LASeRSampleEntryBox *)s;
s->size += 8;
if (ptr->lsr_config) {
e = gf_isom_box_size((GF_Box *)ptr->lsr_config);
if (e) return e;
ptr->size += ptr->lsr_config->size;
}
if (ptr->descr) {
e = gf_isom_box_size((GF_Box *)ptr->descr);
if (e) return e;
ptr->size += ptr->descr->size;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void sidx_del(GF_Box *s)
{
GF_SegmentIndexBox *ptr = (GF_SegmentIndexBox *) s;
if (ptr == NULL) return;
if (ptr->refs) gf_free(ptr->refs);
gf_free(ptr);
}
GF_Err sidx_Read(GF_Box *s,GF_BitStream *bs)
{
u32 i;
GF_SegmentIndexBox *ptr = (GF_SegmentIndexBox*) s;
ptr->reference_ID = gf_bs_read_u32(bs);
ptr->timescale = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 8);
if (ptr->version==0) {
ptr->earliest_presentation_time = gf_bs_read_u32(bs);
ptr->first_offset = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 8);
} else {
ptr->earliest_presentation_time = gf_bs_read_u64(bs);
ptr->first_offset = gf_bs_read_u64(bs);
ISOM_DECREASE_SIZE(ptr, 16);
}
gf_bs_read_u16(bs); /* reserved */
ptr->nb_refs = gf_bs_read_u16(bs);
ISOM_DECREASE_SIZE(ptr, 4);
ptr->refs = gf_malloc(sizeof(GF_SIDXReference)*ptr->nb_refs);
for (i=0; i<ptr->nb_refs; i++) {
ptr->refs[i].reference_type = gf_bs_read_int(bs, 1);
ptr->refs[i].reference_size = gf_bs_read_int(bs, 31);
ptr->refs[i].subsegment_duration = gf_bs_read_u32(bs);
ptr->refs[i].starts_with_SAP = gf_bs_read_int(bs, 1);
ptr->refs[i].SAP_type = gf_bs_read_int(bs, 3);
ptr->refs[i].SAP_delta_time = gf_bs_read_int(bs, 28);
ISOM_DECREASE_SIZE(ptr, 12);
}
return GF_OK;
}
GF_Box *sidx_New()
{
ISOM_DECL_BOX_ALLOC(GF_SegmentIndexBox, GF_ISOM_BOX_TYPE_SIDX);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err sidx_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_SegmentIndexBox *ptr = (GF_SegmentIndexBox*) s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->reference_ID);
gf_bs_write_u32(bs, ptr->timescale);
if (ptr->version==0) {
gf_bs_write_u32(bs, (u32) ptr->earliest_presentation_time);
gf_bs_write_u32(bs, (u32) ptr->first_offset);
} else {
gf_bs_write_u64(bs, ptr->earliest_presentation_time);
gf_bs_write_u64(bs, ptr->first_offset);
}
gf_bs_write_u16(bs, 0);
gf_bs_write_u16(bs, ptr->nb_refs);
for (i=0; i<ptr->nb_refs; i++ ) {
gf_bs_write_int(bs, ptr->refs[i].reference_type, 1);
gf_bs_write_int(bs, ptr->refs[i].reference_size, 31);
gf_bs_write_u32(bs, ptr->refs[i].subsegment_duration);
gf_bs_write_int(bs, ptr->refs[i].starts_with_SAP, 1);
gf_bs_write_int(bs, ptr->refs[i].SAP_type, 3);
gf_bs_write_int(bs, ptr->refs[i].SAP_delta_time, 28);
}
return GF_OK;
}
GF_Err sidx_Size(GF_Box *s)
{
GF_SegmentIndexBox *ptr = (GF_SegmentIndexBox*) s;
ptr->size += 12;
if (ptr->version==0) {
ptr->size += 8;
} else {
ptr->size += 16;
}
ptr->size += ptr->nb_refs * 12;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void ssix_del(GF_Box *s)
{
u32 i;
GF_SubsegmentIndexBox *ptr = (GF_SubsegmentIndexBox *)s;
if (ptr == NULL) return;
if (ptr->subsegments) {
for (i = 0; i < ptr->subsegment_count; i++) {
GF_Subsegment *subsegment = &ptr->subsegments[i];
if (subsegment->levels) gf_free(subsegment->levels);
if (subsegment->range_sizes) gf_free(subsegment->range_sizes);
}
gf_free(ptr->subsegments);
}
gf_free(ptr);
}
GF_Err ssix_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i,j;
GF_SubsegmentIndexBox *ptr = (GF_SubsegmentIndexBox*)s;
if (ptr->size < 4) return GF_BAD_PARAM;
ptr->subsegment_count = gf_bs_read_u32(bs);
ptr->size -= 4;
ptr->subsegments = gf_malloc(ptr->subsegment_count*sizeof(GF_Subsegment));
for (i = 0; i < ptr->subsegment_count; i++) {
GF_Subsegment *subseg = &ptr->subsegments[i];
if (ptr->size < 4) return GF_BAD_PARAM;
subseg->range_count = gf_bs_read_u32(bs);
ptr->size -= 4;
if (ptr->size < subseg->range_count*4) return GF_BAD_PARAM;
subseg->levels = gf_malloc(sizeof(u8)*subseg->range_count);
subseg->range_sizes = gf_malloc(sizeof(u32)*subseg->range_count);
for (j = 0; j < subseg->range_count; j++) {
subseg->levels[j] = gf_bs_read_u8(bs);
subseg->range_sizes[j] = gf_bs_read_u24(bs);
ptr->size -= 4;
}
}
return GF_OK;
}
GF_Box *ssix_New()
{
ISOM_DECL_BOX_ALLOC(GF_SubsegmentIndexBox, GF_ISOM_BOX_TYPE_SSIX);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err ssix_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i, j;
GF_SubsegmentIndexBox *ptr = (GF_SubsegmentIndexBox*)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->subsegment_count);
for (i = 0; i<ptr->subsegment_count; i++) {
gf_bs_write_u32(bs, ptr->subsegments[i].range_count);
for (j = 0; j < ptr->subsegment_count; j++) {
gf_bs_write_u8(bs, ptr->subsegments[i].levels[j]);
gf_bs_write_u24(bs, ptr->subsegments[i].range_sizes[j]);
}
}
return GF_OK;
}
GF_Err ssix_Size(GF_Box *s)
{
u32 i;
GF_SubsegmentIndexBox *ptr = (GF_SubsegmentIndexBox*)s;
ptr->size += 4;
for (i = 0; i < ptr->subsegment_count; i++) {
ptr->size += 4 + 4 * ptr->subsegments[i].range_count;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void leva_del(GF_Box *s)
{
GF_LevelAssignmentBox *ptr = (GF_LevelAssignmentBox *)s;
if (ptr == NULL) return;
if (ptr->levels) gf_free(ptr->levels);
gf_free(ptr);
}
GF_Err leva_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i;
GF_LevelAssignmentBox *ptr = (GF_LevelAssignmentBox*)s;
if (ptr->size < 4) return GF_BAD_PARAM;
ptr->level_count = gf_bs_read_u8(bs);
ptr->size -= 4;
GF_SAFE_ALLOC_N(ptr->levels, ptr->level_count, GF_LevelAssignment);
for (i = 0; i < ptr->level_count; i++) {
GF_LevelAssignment *level = &ptr->levels[i];
u8 tmp;
if (ptr->size < 5) return GF_BAD_PARAM;
level->track_id = gf_bs_read_u32(bs);
tmp = gf_bs_read_u8(bs);
level->padding_flag = tmp >> 7;
level->type = tmp & 0x7F;
if (level->type == 0) {
level->grouping_type = gf_bs_read_u32(bs);
}
else if (level->type == 1) {
level->grouping_type = gf_bs_read_u32(bs);
level->grouping_type_parameter = gf_bs_read_u32(bs);
}
else if (level->type == 4) {
level->sub_track_id = gf_bs_read_u32(bs);
}
}
return GF_OK;
}
GF_Box *leva_New()
{
ISOM_DECL_BOX_ALLOC(GF_LevelAssignmentBox, GF_ISOM_BOX_TYPE_LEVA);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err leva_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_LevelAssignmentBox *ptr = (GF_LevelAssignmentBox*)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u8(bs, ptr->level_count);
for (i = 0; i<ptr->level_count; i++) {
gf_bs_write_u32(bs, ptr->levels[i].track_id);
gf_bs_write_u8(bs, ptr->levels[i].padding_flag << 7 | (ptr->levels[i].type & 0x7F));
if (ptr->levels[i].type == 0) {
gf_bs_write_u32(bs, ptr->levels[i].grouping_type);
}
else if (ptr->levels[i].type == 1) {
gf_bs_write_u32(bs, ptr->levels[i].grouping_type);
gf_bs_write_u32(bs, ptr->levels[i].grouping_type_parameter);
}
else if (ptr->levels[i].type == 4) {
gf_bs_write_u32(bs, ptr->levels[i].sub_track_id);
}
}
return GF_OK;
}
GF_Err leva_Size(GF_Box *s)
{
u32 i;
GF_LevelAssignmentBox *ptr = (GF_LevelAssignmentBox*)s;
ptr->size += 1;
for (i = 0; i < ptr->level_count; i++) {
ptr->size += 5;
if (ptr->levels[i].type == 0 || ptr->levels[i].type == 4) {
ptr->size += 4;
}
else if (ptr->levels[i].type == 1) {
ptr->size += 8;
}
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *pcrb_New()
{
ISOM_DECL_BOX_ALLOC(GF_PcrInfoBox, GF_ISOM_BOX_TYPE_PCRB);
return (GF_Box *)tmp;
}
void pcrb_del(GF_Box *s)
{
GF_PcrInfoBox *ptr = (GF_PcrInfoBox *) s;
if (ptr == NULL) return;
if (ptr->pcr_values) gf_free(ptr->pcr_values);
gf_free(ptr);
}
GF_Err pcrb_Read(GF_Box *s,GF_BitStream *bs)
{
u32 i;
GF_PcrInfoBox *ptr = (GF_PcrInfoBox*) s;
ptr->subsegment_count = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
ptr->pcr_values = gf_malloc(sizeof(u64)*ptr->subsegment_count);
for (i=0; i<ptr->subsegment_count; i++) {
u64 data1 = gf_bs_read_u32(bs);
u64 data2 = gf_bs_read_u16(bs);
ISOM_DECREASE_SIZE(ptr, 6);
ptr->pcr_values[i] = (data1 << 10) | (data2 >> 6);
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err pcrb_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_PcrInfoBox *ptr = (GF_PcrInfoBox*) s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->subsegment_count);
for (i=0; i<ptr->subsegment_count; i++ ) {
u32 data1 = (u32) (ptr->pcr_values[i] >> 10);
u16 data2 = (u16) (ptr->pcr_values[i] << 6);
gf_bs_write_u32(bs, data1);
gf_bs_write_u16(bs, data2);
}
return GF_OK;
}
GF_Err pcrb_Size(GF_Box *s)
{
GF_PcrInfoBox *ptr = (GF_PcrInfoBox*) s;
ptr->size += 4;
ptr->size += ptr->subsegment_count * 6;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *subs_New()
{
ISOM_DECL_BOX_ALLOC(GF_SubSampleInformationBox, GF_ISOM_BOX_TYPE_SUBS);
tmp->Samples = gf_list_new();
return (GF_Box *)tmp;
}
void subs_del(GF_Box *s)
{
GF_SubSampleInformationBox *ptr = (GF_SubSampleInformationBox *)s;
if (ptr == NULL) return;
while (gf_list_count(ptr->Samples)) {
GF_SubSampleInfoEntry *pSamp;
pSamp = (GF_SubSampleInfoEntry*)gf_list_get(ptr->Samples, 0);
while (gf_list_count(pSamp->SubSamples)) {
GF_SubSampleEntry *pSubSamp;
pSubSamp = (GF_SubSampleEntry*) gf_list_get(pSamp->SubSamples, 0);
gf_free(pSubSamp);
gf_list_rem(pSamp->SubSamples, 0);
}
gf_list_del(pSamp->SubSamples);
gf_free(pSamp);
gf_list_rem(ptr->Samples, 0);
}
gf_list_del(ptr->Samples);
gf_free(ptr);
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err subs_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i, j, entry_count;
u16 subsample_count;
GF_SubSampleInfoEntry *pSamp;
GF_SubSampleEntry *pSubSamp;
GF_SubSampleInformationBox *ptr = (GF_SubSampleInformationBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
entry_count = gf_list_count(ptr->Samples);
gf_bs_write_u32(bs, entry_count);
for (i=0; i<entry_count; i++) {
pSamp = (GF_SubSampleInfoEntry*) gf_list_get(ptr->Samples, i);
subsample_count = gf_list_count(pSamp->SubSamples);
gf_bs_write_u32(bs, pSamp->sample_delta);
gf_bs_write_u16(bs, subsample_count);
for (j=0; j<subsample_count; j++) {
pSubSamp = (GF_SubSampleEntry*) gf_list_get(pSamp->SubSamples, j);
if (ptr->version == 1) {
gf_bs_write_u32(bs, pSubSamp->subsample_size);
} else {
gf_bs_write_u16(bs, pSubSamp->subsample_size);
}
gf_bs_write_u8(bs, pSubSamp->subsample_priority);
gf_bs_write_u8(bs, pSubSamp->discardable);
gf_bs_write_u32(bs, pSubSamp->reserved);
}
}
return e;
}
GF_Err subs_Size(GF_Box *s)
{
GF_SubSampleInformationBox *ptr = (GF_SubSampleInformationBox *) s;
GF_SubSampleInfoEntry *pSamp;
u32 entry_count, i;
u16 subsample_count;
// add 4 byte for entry_count
ptr->size += 4;
entry_count = gf_list_count(ptr->Samples);
for (i=0; i<entry_count; i++) {
pSamp = (GF_SubSampleInfoEntry*) gf_list_get(ptr->Samples, i);
subsample_count = gf_list_count(pSamp->SubSamples);
// 4 byte for sample_delta, 2 byte for subsample_count
// and 6 + (4 or 2) bytes for each subsample
ptr->size += 4 + 2 + subsample_count * (6 + (ptr->version==1 ? 4 : 2));
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Err subs_Read(GF_Box *s, GF_BitStream *bs)
{
GF_SubSampleInformationBox *ptr = (GF_SubSampleInformationBox *)s;
u32 entry_count, i, j;
u16 subsample_count;
entry_count = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
for (i=0; i<entry_count; i++) {
u32 subs_size=0;
GF_SubSampleInfoEntry *pSamp = (GF_SubSampleInfoEntry*) gf_malloc(sizeof(GF_SubSampleInfoEntry));
if (!pSamp) return GF_OUT_OF_MEM;
memset(pSamp, 0, sizeof(GF_SubSampleInfoEntry));
pSamp->SubSamples = gf_list_new();
pSamp->sample_delta = gf_bs_read_u32(bs);
subsample_count = gf_bs_read_u16(bs);
subs_size=6;
for (j=0; j<subsample_count; j++) {
GF_SubSampleEntry *pSubSamp = (GF_SubSampleEntry*) gf_malloc(sizeof(GF_SubSampleEntry));
if (!pSubSamp) return GF_OUT_OF_MEM;
memset(pSubSamp, 0, sizeof(GF_SubSampleEntry));
if (ptr->version==1) {
pSubSamp->subsample_size = gf_bs_read_u32(bs);
subs_size+=4;
} else {
pSubSamp->subsample_size = gf_bs_read_u16(bs);
subs_size+=2;
}
pSubSamp->subsample_priority = gf_bs_read_u8(bs);
pSubSamp->discardable = gf_bs_read_u8(bs);
pSubSamp->reserved = gf_bs_read_u32(bs);
subs_size+=6;
gf_list_add(pSamp->SubSamples, pSubSamp);
}
gf_list_add(ptr->Samples, pSamp);
ISOM_DECREASE_SIZE(ptr, subs_size);
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
GF_Box *tfdt_New()
{
ISOM_DECL_BOX_ALLOC(GF_TFBaseMediaDecodeTimeBox, GF_ISOM_BOX_TYPE_TFDT);
return (GF_Box *)tmp;
}
void tfdt_del(GF_Box *s)
{
gf_free(s);
}
/*this is using chpl format according to some NeroRecode samples*/
GF_Err tfdt_Read(GF_Box *s,GF_BitStream *bs)
{
GF_TFBaseMediaDecodeTimeBox *ptr = (GF_TFBaseMediaDecodeTimeBox *)s;
if (ptr->version==1) {
ptr->baseMediaDecodeTime = gf_bs_read_u64(bs);
ISOM_DECREASE_SIZE(ptr, 8);
} else {
ptr->baseMediaDecodeTime = (u32) gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err tfdt_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TFBaseMediaDecodeTimeBox *ptr = (GF_TFBaseMediaDecodeTimeBox *) s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
if (ptr->version==1) {
gf_bs_write_u64(bs, ptr->baseMediaDecodeTime);
} else {
gf_bs_write_u32(bs, (u32) ptr->baseMediaDecodeTime);
}
return GF_OK;
}
GF_Err tfdt_Size(GF_Box *s)
{
GF_TFBaseMediaDecodeTimeBox *ptr = (GF_TFBaseMediaDecodeTimeBox *)s;
if (ptr->baseMediaDecodeTime<=0xFFFFFFFF) {
ptr->version = 0;
ptr->size += 4;
} else {
ptr->version = 1;
ptr->size += 8;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/
GF_Box *rvcc_New()
{
ISOM_DECL_BOX_ALLOC(GF_RVCConfigurationBox, GF_ISOM_BOX_TYPE_RVCC);
return (GF_Box *)tmp;
}
void rvcc_del(GF_Box *s)
{
gf_free(s);
}
GF_Err rvcc_Read(GF_Box *s,GF_BitStream *bs)
{
GF_RVCConfigurationBox *ptr = (GF_RVCConfigurationBox*)s;
ptr->predefined_rvc_config = gf_bs_read_u16(bs);
ISOM_DECREASE_SIZE(ptr, 2);
if (!ptr->predefined_rvc_config) {
ptr->rvc_meta_idx = gf_bs_read_u16(bs);
ISOM_DECREASE_SIZE(ptr, 2);
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err rvcc_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_RVCConfigurationBox *ptr = (GF_RVCConfigurationBox*) s;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
gf_bs_write_u16(bs, ptr->predefined_rvc_config);
if (!ptr->predefined_rvc_config) {
gf_bs_write_u16(bs, ptr->rvc_meta_idx);
}
return GF_OK;
}
GF_Err rvcc_Size(GF_Box *s)
{
GF_RVCConfigurationBox *ptr = (GF_RVCConfigurationBox *)s;
ptr->size += 2;
if (! ptr->predefined_rvc_config) ptr->size += 2;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *sbgp_New()
{
ISOM_DECL_BOX_ALLOC(GF_SampleGroupBox, GF_ISOM_BOX_TYPE_SBGP);
return (GF_Box *)tmp;
}
void sbgp_del(GF_Box *a)
{
GF_SampleGroupBox *p = (GF_SampleGroupBox *)a;
if (p->sample_entries) gf_free(p->sample_entries);
gf_free(p);
}
GF_Err sbgp_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i;
GF_SampleGroupBox *ptr = (GF_SampleGroupBox *)s;
ptr->grouping_type = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
if (ptr->version==1) {
ptr->grouping_type_parameter = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
}
ptr->entry_count = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
ptr->sample_entries = gf_malloc(sizeof(GF_SampleGroupEntry)*ptr->entry_count);
if (!ptr->sample_entries) return GF_IO_ERR;
for (i=0; i<ptr->entry_count; i++) {
ptr->sample_entries[i].sample_count = gf_bs_read_u32(bs);
ptr->sample_entries[i].group_description_index = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 8);
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err sbgp_Write(GF_Box *s, GF_BitStream *bs)
{
u32 i;
GF_Err e;
GF_SampleGroupBox *p = (GF_SampleGroupBox*)s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, p->grouping_type);
if (p->version==1)
gf_bs_write_u32(bs, p->grouping_type_parameter);
gf_bs_write_u32(bs, p->entry_count);
for (i = 0; i<p->entry_count; i++ ) {
gf_bs_write_u32(bs, p->sample_entries[i].sample_count);
gf_bs_write_u32(bs, p->sample_entries[i].group_description_index);
}
return GF_OK;
}
GF_Err sbgp_Size(GF_Box *s)
{
GF_SampleGroupBox *p = (GF_SampleGroupBox*)s;
p->size += 8;
if (p->grouping_type_parameter) p->version=1;
if (p->version==1) p->size += 4;
p->size += 8*p->entry_count;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
static void *sgpd_parse_entry(u32 grouping_type, GF_BitStream *bs, u32 entry_size, u32 *total_bytes)
{
Bool null_size_ok = GF_FALSE;
GF_DefaultSampleGroupDescriptionEntry *ptr;
switch (grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
case GF_ISOM_SAMPLE_GROUP_PROL:
{
GF_RollRecoveryEntry *ptr;
GF_SAFEALLOC(ptr, GF_RollRecoveryEntry);
if (!ptr) return NULL;
ptr->roll_distance = gf_bs_read_int(bs, 16);
*total_bytes = 2;
return ptr;
}
case GF_ISOM_SAMPLE_GROUP_RAP:
{
GF_VisualRandomAccessEntry *ptr;
GF_SAFEALLOC(ptr, GF_VisualRandomAccessEntry);
if (!ptr) return NULL;
ptr->num_leading_samples_known = gf_bs_read_int(bs, 1);
ptr->num_leading_samples = gf_bs_read_int(bs, 7);
*total_bytes = 1;
return ptr;
}
case GF_ISOM_SAMPLE_GROUP_SAP:
{
GF_SAPEntry *ptr;
GF_SAFEALLOC(ptr, GF_SAPEntry);
if (!ptr) return NULL;
ptr->dependent_flag = gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 3);
ptr->SAP_type = gf_bs_read_int(bs, 4);
*total_bytes = 1;
return ptr;
}
case GF_ISOM_SAMPLE_GROUP_SYNC:
{
GF_SYNCEntry *ptr;
GF_SAFEALLOC(ptr, GF_SYNCEntry);
if (!ptr) return NULL;
gf_bs_read_int(bs, 2);
ptr->NALU_type = gf_bs_read_int(bs, 6);
*total_bytes = 1;
return ptr;
}
case GF_ISOM_SAMPLE_GROUP_TELE:
{
GF_TemporalLevelEntry *ptr;
GF_SAFEALLOC(ptr, GF_TemporalLevelEntry);
if (!ptr) return NULL;
ptr->level_independently_decodable = gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 7);
*total_bytes = 1;
return ptr;
}
case GF_ISOM_SAMPLE_GROUP_SEIG:
{
GF_CENCSampleEncryptionGroupEntry *ptr;
GF_SAFEALLOC(ptr, GF_CENCSampleEncryptionGroupEntry);
if (!ptr) return NULL;
gf_bs_read_u8(bs); //reserved
ptr->crypt_byte_block = gf_bs_read_int(bs, 4);
ptr->skip_byte_block = gf_bs_read_int(bs, 4);
ptr->IsProtected = gf_bs_read_u8(bs);
ptr->Per_Sample_IV_size = gf_bs_read_u8(bs);
gf_bs_read_data(bs, (char *)ptr->KID, 16);
*total_bytes = 20;
if ((ptr->IsProtected == 1) && !ptr->Per_Sample_IV_size) {
ptr->constant_IV_size = gf_bs_read_u8(bs);
assert((ptr->constant_IV_size == 8) || (ptr->constant_IV_size == 16));
gf_bs_read_data(bs, (char *)ptr->constant_IV, ptr->constant_IV_size);
*total_bytes += 1 + ptr->constant_IV_size;
}
if (!entry_size) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] seig sample group does not indicate entry size, deprecated in spec\n"));
}
return ptr;
}
case GF_ISOM_SAMPLE_GROUP_OINF:
{
GF_OperatingPointsInformation *ptr = gf_isom_oinf_new_entry();
u32 s = (u32) gf_bs_get_position(bs);
gf_isom_oinf_read_entry(ptr, bs);
*total_bytes = (u32) gf_bs_get_position(bs) - s;
if (!entry_size) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] oinf sample group does not indicate entry size, deprecated in spec\n"));
}
return ptr;
}
case GF_ISOM_SAMPLE_GROUP_LINF:
{
GF_LHVCLayerInformation *ptr = gf_isom_linf_new_entry();
u32 s = (u32) gf_bs_get_position(bs);
gf_isom_linf_read_entry(ptr, bs);
*total_bytes = (u32) gf_bs_get_position(bs) - s;
if (!entry_size) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] linf sample group does not indicate entry size, deprecated in spec\n"));
}
return ptr;
}
case GF_ISOM_SAMPLE_GROUP_TRIF:
if (! entry_size) {
u32 flags = gf_bs_peek_bits(bs, 24, 0);
if (flags & 0x10000) entry_size=3;
else {
if (flags & 0x80000) entry_size=7;
else entry_size=11;
//have dependency list
if (flags & 0x200000) {
u32 nb_entries = gf_bs_peek_bits(bs, 16, entry_size);
entry_size += 2 + 2*nb_entries;
}
}
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] trif sample group does not indicate entry size, deprecated in spec\n"));
}
break;
case GF_ISOM_SAMPLE_GROUP_NALM:
if (! entry_size) {
u64 start = gf_bs_get_position(bs);
Bool rle, large_size;
u32 entry_count;
gf_bs_read_int(bs, 6);
large_size = gf_bs_read_int(bs, 1);
rle = gf_bs_read_int(bs, 1);
entry_count = gf_bs_read_int(bs, large_size ? 16 : 8);
gf_bs_seek(bs, start);
entry_size = 1 + large_size ? 2 : 1;
entry_size += entry_count * 2;
if (rle) entry_size += entry_count * (large_size ? 2 : 1);
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] nalm sample group does not indicate entry size, deprecated in spec\n"));
}
break;
case GF_ISOM_SAMPLE_GROUP_TSAS:
case GF_ISOM_SAMPLE_GROUP_STSA:
null_size_ok = GF_TRUE;
break;
//TODO, add support for these ones ?
case GF_ISOM_SAMPLE_GROUP_TSCL:
entry_size = 20;
break;
case GF_ISOM_SAMPLE_GROUP_LBLI:
entry_size = 2;
break;
default:
break;
}
if (!entry_size && !null_size_ok) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] %s sample group does not indicate entry size and is not implemented, cannot parse!\n", gf_4cc_to_str( grouping_type) ));
return NULL;
}
GF_SAFEALLOC(ptr, GF_DefaultSampleGroupDescriptionEntry);
if (!ptr) return NULL;
if (entry_size) {
ptr->length = entry_size;
ptr->data = (u8 *) gf_malloc(sizeof(u8)*ptr->length);
gf_bs_read_data(bs, (char *) ptr->data, ptr->length);
*total_bytes = entry_size;
}
return ptr;
}
static void sgpd_del_entry(u32 grouping_type, void *entry)
{
switch (grouping_type) {
case GF_ISOM_SAMPLE_GROUP_SYNC:
case GF_ISOM_SAMPLE_GROUP_ROLL:
case GF_ISOM_SAMPLE_GROUP_PROL:
case GF_ISOM_SAMPLE_GROUP_RAP:
case GF_ISOM_SAMPLE_GROUP_SEIG:
case GF_ISOM_SAMPLE_GROUP_TELE:
case GF_ISOM_SAMPLE_GROUP_SAP:
gf_free(entry);
return;
case GF_ISOM_SAMPLE_GROUP_OINF:
gf_isom_oinf_del_entry(entry);
return;
case GF_ISOM_SAMPLE_GROUP_LINF:
gf_isom_linf_del_entry(entry);
return;
default:
{
GF_DefaultSampleGroupDescriptionEntry *ptr = (GF_DefaultSampleGroupDescriptionEntry *)entry;
if (ptr->data) gf_free(ptr->data);
gf_free(ptr);
}
}
}
void sgpd_write_entry(u32 grouping_type, void *entry, GF_BitStream *bs)
{
switch (grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
case GF_ISOM_SAMPLE_GROUP_PROL:
gf_bs_write_int(bs, ((GF_RollRecoveryEntry*)entry)->roll_distance, 16);
return;
case GF_ISOM_SAMPLE_GROUP_RAP:
gf_bs_write_int(bs, ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known, 1);
gf_bs_write_int(bs, ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples, 7);
return;
case GF_ISOM_SAMPLE_GROUP_SAP:
gf_bs_write_int(bs, ((GF_SAPEntry*)entry)->dependent_flag, 1);
gf_bs_write_int(bs, 0, 3);
gf_bs_write_int(bs, ((GF_SAPEntry*)entry)->SAP_type, 4);
return;
case GF_ISOM_SAMPLE_GROUP_SYNC:
gf_bs_write_int(bs, 0, 2);
gf_bs_write_int(bs, ((GF_SYNCEntry*)entry)->NALU_type, 6);
return;
case GF_ISOM_SAMPLE_GROUP_TELE:
gf_bs_write_int(bs, ((GF_TemporalLevelEntry*)entry)->level_independently_decodable, 1);
gf_bs_write_int(bs, 0, 7);
return;
case GF_ISOM_SAMPLE_GROUP_SEIG:
gf_bs_write_u8(bs, 0x0);
gf_bs_write_int(bs, ((GF_CENCSampleEncryptionGroupEntry*)entry)->crypt_byte_block, 4);
gf_bs_write_int(bs, ((GF_CENCSampleEncryptionGroupEntry*)entry)->skip_byte_block, 4);
gf_bs_write_u8(bs, ((GF_CENCSampleEncryptionGroupEntry *)entry)->IsProtected);
gf_bs_write_u8(bs, ((GF_CENCSampleEncryptionGroupEntry *)entry)->Per_Sample_IV_size);
gf_bs_write_data(bs, (char *)((GF_CENCSampleEncryptionGroupEntry *)entry)->KID, 16);
if ((((GF_CENCSampleEncryptionGroupEntry *)entry)->IsProtected == 1) && !((GF_CENCSampleEncryptionGroupEntry *)entry)->Per_Sample_IV_size) {
gf_bs_write_u8(bs, ((GF_CENCSampleEncryptionGroupEntry *)entry)->constant_IV_size);
gf_bs_write_data(bs, (char *)((GF_CENCSampleEncryptionGroupEntry *)entry)->constant_IV, ((GF_CENCSampleEncryptionGroupEntry *)entry)->constant_IV_size);
}
return;
case GF_ISOM_SAMPLE_GROUP_OINF:
gf_isom_oinf_write_entry(entry, bs);
return;
case GF_ISOM_SAMPLE_GROUP_LINF:
gf_isom_linf_write_entry(entry, bs);
return;
default:
{
GF_DefaultSampleGroupDescriptionEntry *ptr = (GF_DefaultSampleGroupDescriptionEntry *)entry;
if (ptr->length)
gf_bs_write_data(bs, (char *) ptr->data, ptr->length);
}
}
}
#ifndef GPAC_DISABLE_ISOM_WRITE
static u32 sgpd_size_entry(u32 grouping_type, void *entry)
{
switch (grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
case GF_ISOM_SAMPLE_GROUP_PROL:
return 2;
case GF_ISOM_SAMPLE_GROUP_TELE:
case GF_ISOM_SAMPLE_GROUP_RAP:
case GF_ISOM_SAMPLE_GROUP_SAP:
case GF_ISOM_SAMPLE_GROUP_SYNC:
return 1;
case GF_ISOM_SAMPLE_GROUP_TSCL:
return 20;
case GF_ISOM_SAMPLE_GROUP_LBLI:
return 2;
case GF_ISOM_SAMPLE_GROUP_TSAS:
case GF_ISOM_SAMPLE_GROUP_STSA:
return 0;
case GF_ISOM_SAMPLE_GROUP_SEIG:
return ((((GF_CENCSampleEncryptionGroupEntry *)entry)->IsProtected == 1) && !((GF_CENCSampleEncryptionGroupEntry *)entry)->Per_Sample_IV_size) ? 21 + ((GF_CENCSampleEncryptionGroupEntry *)entry)->constant_IV_size : 20;
case GF_ISOM_SAMPLE_GROUP_OINF:
return gf_isom_oinf_size_entry(entry);
case GF_ISOM_SAMPLE_GROUP_LINF:
return gf_isom_linf_size_entry(entry);
default:
return ((GF_DefaultSampleGroupDescriptionEntry *)entry)->length;
}
}
#endif
GF_Box *sgpd_New()
{
ISOM_DECL_BOX_ALLOC(GF_SampleGroupDescriptionBox, GF_ISOM_BOX_TYPE_SGPD);
/*version 0 is deprecated, use v1 by default*/
tmp->version = 1;
tmp->group_descriptions = gf_list_new();
return (GF_Box *)tmp;
}
void sgpd_del(GF_Box *a)
{
GF_SampleGroupDescriptionBox *p = (GF_SampleGroupDescriptionBox *)a;
while (gf_list_count(p->group_descriptions)) {
void *ptr = gf_list_last(p->group_descriptions);
sgpd_del_entry(p->grouping_type, ptr);
gf_list_rem_last(p->group_descriptions);
}
gf_list_del(p->group_descriptions);
gf_free(p);
}
GF_Err sgpd_Read(GF_Box *s, GF_BitStream *bs)
{
u32 entry_count;
GF_SampleGroupDescriptionBox *p = (GF_SampleGroupDescriptionBox *)s;
p->grouping_type = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(p, 4);
if (p->version>=1) {
p->default_length = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(p, 4);
}
if (p->version>=2) {
p->default_description_index = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(p, 4);
}
entry_count = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(p, 4);
if (entry_count>p->size)
return GF_ISOM_INVALID_FILE;
while (entry_count) {
void *ptr;
u32 parsed_bytes=0;
u32 size = p->default_length;
if ((p->version>=1) && !size) {
size = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(p, 4);
}
ptr = sgpd_parse_entry(p->grouping_type, bs, size, &parsed_bytes);
//don't return an error, just stop parsing so that we skip over the sgpd box
if (!ptr) return GF_OK;
ISOM_DECREASE_SIZE(p, parsed_bytes);
gf_list_add(p->group_descriptions, ptr);
entry_count--;
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err sgpd_Write(GF_Box *s, GF_BitStream *bs)
{
u32 i;
GF_SampleGroupDescriptionBox *p = (GF_SampleGroupDescriptionBox *)s;
GF_Err e;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, p->grouping_type);
if (p->version>=1) gf_bs_write_u32(bs, p->default_length);
if (p->version>=2) gf_bs_write_u32(bs, p->default_description_index);
gf_bs_write_u32(bs, gf_list_count(p->group_descriptions) );
for (i=0; i<gf_list_count(p->group_descriptions); i++) {
void *ptr = gf_list_get(p->group_descriptions, i);
if ((p->version >= 1) && !p->default_length) {
u32 size = sgpd_size_entry(p->grouping_type, ptr);
gf_bs_write_u32(bs, size);
}
sgpd_write_entry(p->grouping_type, ptr, bs);
}
return GF_OK;
}
GF_Err sgpd_Size(GF_Box *s)
{
u32 i;
GF_SampleGroupDescriptionBox *p = (GF_SampleGroupDescriptionBox *)s;
p->size += 8;
//we force all sample groups to version 1, v0 being deprecated
p->version=1;
p->size += 4;
if (p->version>=2) p->size += 4;
p->default_length = 0;
for (i=0; i<gf_list_count(p->group_descriptions); i++) {
void *ptr = gf_list_get(p->group_descriptions, i);
u32 size = sgpd_size_entry(p->grouping_type, ptr);
p->size += size;
if (!p->default_length) {
p->default_length = size;
} else if (p->default_length != size) {
p->default_length = 0;
}
}
if (p->version>=1) {
if (!p->default_length) p->size += gf_list_count(p->group_descriptions)*4;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void saiz_del(GF_Box *s)
{
GF_SampleAuxiliaryInfoSizeBox*ptr = (GF_SampleAuxiliaryInfoSizeBox*)s;
if (ptr == NULL) return;
if (ptr->sample_info_size) gf_free(ptr->sample_info_size);
gf_free(ptr);
}
GF_Err saiz_Read(GF_Box *s, GF_BitStream *bs)
{
GF_SampleAuxiliaryInfoSizeBox*ptr = (GF_SampleAuxiliaryInfoSizeBox*)s;
if (ptr->flags & 1) {
ptr->aux_info_type = gf_bs_read_u32(bs);
ptr->aux_info_type_parameter = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 8);
}
ptr->default_sample_info_size = gf_bs_read_u8(bs);
ptr->sample_count = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 5);
if (ptr->default_sample_info_size == 0) {
ptr->sample_info_size = gf_malloc(sizeof(u8)*ptr->sample_count);
gf_bs_read_data(bs, (char *) ptr->sample_info_size, ptr->sample_count);
ISOM_DECREASE_SIZE(ptr, ptr->sample_count);
}
return GF_OK;
}
GF_Box *saiz_New()
{
ISOM_DECL_BOX_ALLOC(GF_SampleAuxiliaryInfoSizeBox, GF_ISOM_BOX_TYPE_SAIZ);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err saiz_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_SampleAuxiliaryInfoSizeBox*ptr = (GF_SampleAuxiliaryInfoSizeBox*) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
if (ptr->flags & 1) {
gf_bs_write_u32(bs, ptr->aux_info_type);
gf_bs_write_u32(bs, ptr->aux_info_type_parameter);
}
gf_bs_write_u8(bs, ptr->default_sample_info_size);
gf_bs_write_u32(bs, ptr->sample_count);
if (!ptr->default_sample_info_size) {
gf_bs_write_data(bs, (char *) ptr->sample_info_size, ptr->sample_count);
}
return GF_OK;
}
GF_Err saiz_Size(GF_Box *s)
{
GF_SampleAuxiliaryInfoSizeBox *ptr = (GF_SampleAuxiliaryInfoSizeBox*)s;
if (ptr->aux_info_type || ptr->aux_info_type_parameter) {
ptr->flags |= 1;
}
if (ptr->flags & 1) ptr->size += 8;
ptr->size += 5;
if (ptr->default_sample_info_size==0) ptr->size += ptr->sample_count;
return GF_OK;
}
#endif //GPAC_DISABLE_ISOM_WRITE
void saio_del(GF_Box *s)
{
GF_SampleAuxiliaryInfoOffsetBox *ptr = (GF_SampleAuxiliaryInfoOffsetBox*)s;
if (ptr == NULL) return;
if (ptr->offsets) gf_free(ptr->offsets);
if (ptr->offsets_large) gf_free(ptr->offsets_large);
gf_free(ptr);
}
GF_Err saio_Read(GF_Box *s, GF_BitStream *bs)
{
GF_SampleAuxiliaryInfoOffsetBox *ptr = (GF_SampleAuxiliaryInfoOffsetBox *)s;
if (ptr->flags & 1) {
ptr->aux_info_type = gf_bs_read_u32(bs);
ptr->aux_info_type_parameter = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 8);
}
ptr->entry_count = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
if (ptr->entry_count) {
u32 i;
if (ptr->version==0) {
ptr->offsets = gf_malloc(sizeof(u32)*ptr->entry_count);
for (i=0; i<ptr->entry_count; i++)
ptr->offsets[i] = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4*ptr->entry_count);
} else {
ptr->offsets_large = gf_malloc(sizeof(u64)*ptr->entry_count);
for (i=0; i<ptr->entry_count; i++)
ptr->offsets_large[i] = gf_bs_read_u64(bs);
ISOM_DECREASE_SIZE(ptr, 8*ptr->entry_count);
}
}
return GF_OK;
}
GF_Box *saio_New()
{
ISOM_DECL_BOX_ALLOC(GF_SampleAuxiliaryInfoOffsetBox, GF_ISOM_BOX_TYPE_SAIO);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err saio_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_SampleAuxiliaryInfoOffsetBox *ptr = (GF_SampleAuxiliaryInfoOffsetBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
if (ptr->flags & 1) {
gf_bs_write_u32(bs, ptr->aux_info_type);
gf_bs_write_u32(bs, ptr->aux_info_type_parameter);
}
gf_bs_write_u32(bs, ptr->entry_count);
if (ptr->entry_count) {
u32 i;
//store position in bitstream before writing data - offsets can be NULL if a single offset is rewritten later on (cf senc_write)
ptr->offset_first_offset_field = gf_bs_get_position(bs);
if (ptr->version==0) {
if (!ptr->offsets) {
gf_bs_write_u32(bs, 0);
} else {
for (i=0; i<ptr->entry_count; i++)
gf_bs_write_u32(bs, ptr->offsets[i]);
}
} else {
if (!ptr->offsets_large) {
gf_bs_write_u64(bs, 0);
} else {
for (i=0; i<ptr->entry_count; i++)
gf_bs_write_u64(bs, ptr->offsets_large[i]);
}
}
}
return GF_OK;
}
GF_Err saio_Size(GF_Box *s)
{
GF_SampleAuxiliaryInfoOffsetBox *ptr = (GF_SampleAuxiliaryInfoOffsetBox*)s;
if (ptr->aux_info_type || ptr->aux_info_type_parameter) {
ptr->flags |= 1;
}
if (ptr->offsets_large) {
ptr->version = 1;
}
if (ptr->flags & 1) ptr->size += 8;
ptr->size += 4;
//a little optim here: in cenc, the saio always points to a single data block, only one entry is needed
switch (ptr->aux_info_type) {
case GF_ISOM_CENC_SCHEME:
case GF_ISOM_CBC_SCHEME:
case GF_ISOM_CENS_SCHEME:
case GF_ISOM_CBCS_SCHEME:
if (ptr->offsets_large) gf_free(ptr->offsets_large);
if (ptr->offsets) gf_free(ptr->offsets);
ptr->offsets_large = NULL;
ptr->offsets = NULL;
ptr->entry_count = 1;
break;
}
ptr->size += ((ptr->version==1) ? 8 : 4) * ptr->entry_count;
return GF_OK;
}
#endif //GPAC_DISABLE_ISOM_WRITE
void prft_del(GF_Box *s)
{
gf_free(s);
}
GF_Err prft_Read(GF_Box *s,GF_BitStream *bs)
{
GF_ProducerReferenceTimeBox *ptr = (GF_ProducerReferenceTimeBox *) s;
ptr->refTrackID = gf_bs_read_u32(bs);
ptr->ntp = gf_bs_read_u64(bs);
if (ptr->version==0) {
ptr->timestamp = gf_bs_read_u32(bs);
} else {
ptr->timestamp = gf_bs_read_u64(bs);
}
return GF_OK;
}
GF_Box *prft_New()
{
ISOM_DECL_BOX_ALLOC(GF_ProducerReferenceTimeBox, GF_ISOM_BOX_TYPE_PRFT);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err prft_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_ProducerReferenceTimeBox *ptr = (GF_ProducerReferenceTimeBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->refTrackID);
gf_bs_write_u64(bs, ptr->ntp);
if (ptr->version==0) {
gf_bs_write_u32(bs, (u32) ptr->timestamp);
} else {
gf_bs_write_u64(bs, ptr->timestamp);
}
return GF_OK;
}
GF_Err prft_Size(GF_Box *s)
{
GF_ProducerReferenceTimeBox *ptr = (GF_ProducerReferenceTimeBox*)s;
ptr->size += 4+8+ (ptr->version ? 8 : 4);
return GF_OK;
}
#endif //GPAC_DISABLE_ISOM_WRITE
GF_Box *trgr_New()
{
ISOM_DECL_BOX_ALLOC(GF_TrackGroupBox, GF_ISOM_BOX_TYPE_TRGR);
tmp->groups = gf_list_new();
if (!tmp->groups) {
gf_free(tmp);
return NULL;
}
return (GF_Box *)tmp;
}
void trgr_del(GF_Box *s)
{
GF_TrackGroupBox *ptr = (GF_TrackGroupBox *)s;
if (ptr == NULL) return;
gf_isom_box_array_del(ptr->groups);
gf_free(ptr);
}
GF_Err trgr_AddBox(GF_Box *s, GF_Box *a)
{
GF_TrackGroupBox *ptr = (GF_TrackGroupBox *)s;
return gf_list_add(ptr->groups, a);
}
GF_Err trgr_Read(GF_Box *s, GF_BitStream *bs)
{
return gf_isom_box_array_read_ex(s, bs, trgr_AddBox, s->type);
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err trgr_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TrackGroupBox *ptr = (GF_TrackGroupBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_box_write_header(s, bs);
if (e) return e;
return gf_isom_box_array_write(s, ptr->groups, bs);
}
GF_Err trgr_Size(GF_Box *s)
{
GF_TrackGroupBox *ptr = (GF_TrackGroupBox *)s;
return gf_isom_box_array_size(s, ptr->groups);
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *trgt_New()
{
ISOM_DECL_BOX_ALLOC(GF_TrackGroupTypeBox, GF_ISOM_BOX_TYPE_TRGT);
return (GF_Box *)tmp;
}
void trgt_del(GF_Box *s)
{
GF_TrackGroupTypeBox *ptr = (GF_TrackGroupTypeBox *)s;
if (ptr == NULL) return;
gf_free(ptr);
}
GF_Err trgt_Read(GF_Box *s, GF_BitStream *bs)
{
GF_TrackGroupTypeBox *ptr = (GF_TrackGroupTypeBox *)s;
ptr->track_group_id = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, 4);
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err trgt_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_TrackGroupTypeBox *ptr = (GF_TrackGroupTypeBox *) s;
if (!s) return GF_BAD_PARAM;
s->type = ptr->group_type;
e = gf_isom_full_box_write(s, bs);
s->type = GF_ISOM_BOX_TYPE_TRGT;
if (e) return e;
gf_bs_write_u32(bs, ptr->track_group_id);
return GF_OK;
}
GF_Err trgt_Size(GF_Box *s)
{
GF_TrackGroupBox *ptr = (GF_TrackGroupBox *)s;
ptr->size+= 4;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *stvi_New()
{
ISOM_DECL_BOX_ALLOC(GF_StereoVideoBox, GF_ISOM_BOX_TYPE_STVI);
return (GF_Box *)tmp;
}
void stvi_del(GF_Box *s)
{
GF_StereoVideoBox *ptr = (GF_StereoVideoBox *)s;
if (ptr == NULL) return;
if (ptr->stereo_indication_type) gf_free(ptr->stereo_indication_type);
gf_free(ptr);
}
GF_Err stvi_Read(GF_Box *s, GF_BitStream *bs)
{
GF_StereoVideoBox *ptr = (GF_StereoVideoBox *)s;
ISOM_DECREASE_SIZE(ptr, 12);
gf_bs_read_int(bs, 30);
ptr->single_view_allowed = gf_bs_read_int(bs, 2);
ptr->stereo_scheme = gf_bs_read_u32(bs);
ptr->sit_len = gf_bs_read_u32(bs);
ISOM_DECREASE_SIZE(ptr, ptr->sit_len);
ptr->stereo_indication_type = gf_malloc(sizeof(char)*ptr->sit_len);
gf_bs_read_data(bs, ptr->stereo_indication_type, ptr->sit_len);
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err stvi_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_StereoVideoBox *ptr = (GF_StereoVideoBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_int(bs, 0, 30);
gf_bs_write_int(bs, ptr->single_view_allowed, 2);
gf_bs_write_u32(bs, ptr->stereo_scheme);
gf_bs_write_u32(bs, ptr->sit_len);
gf_bs_write_data(bs, ptr->stereo_indication_type, ptr->sit_len);
return GF_OK;
}
GF_Err stvi_Size(GF_Box *s)
{
GF_StereoVideoBox *ptr = (GF_StereoVideoBox *)s;
ptr->size+= 12 + ptr->sit_len;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *fiin_New()
{
ISOM_DECL_BOX_ALLOC(FDItemInformationBox, GF_ISOM_BOX_TYPE_FIIN);
return (GF_Box *)tmp;
}
void fiin_del(GF_Box *s)
{
FDItemInformationBox *ptr = (FDItemInformationBox *)s;
if (ptr == NULL) return;
if (ptr->partition_entries) gf_isom_box_array_del(ptr->partition_entries);
if (ptr->session_info) gf_isom_box_del((GF_Box*)ptr->session_info);
if (ptr->group_id_to_name) gf_isom_box_del((GF_Box*)ptr->group_id_to_name);
gf_free(ptr);
}
GF_Err fiin_AddBox(GF_Box *s, GF_Box *a)
{
FDItemInformationBox *ptr = (FDItemInformationBox *)s;
switch(a->type) {
case GF_ISOM_BOX_TYPE_PAEN:
if (!ptr->partition_entries) ptr->partition_entries = gf_list_new();
return gf_list_add(ptr->partition_entries, a);
case GF_ISOM_BOX_TYPE_SEGR:
if (ptr->session_info) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->session_info = (FDSessionGroupBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_GITN:
if (ptr->group_id_to_name) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->group_id_to_name = (GroupIdToNameBox *)a;
return GF_OK;
default:
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err fiin_Read(GF_Box *s, GF_BitStream *bs)
{
FDItemInformationBox *ptr = (FDItemInformationBox *)s;
ISOM_DECREASE_SIZE(ptr, 2);
gf_bs_read_u16(bs);
return gf_isom_box_array_read(s, bs, fiin_AddBox);
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err fiin_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
FDItemInformationBox *ptr = (FDItemInformationBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u16(bs, gf_list_count(ptr->partition_entries) );
e = gf_isom_box_array_write(s, ptr->partition_entries, bs);
if (e) return e;
if (ptr->session_info) gf_isom_box_write((GF_Box*)ptr->session_info, bs);
if (ptr->group_id_to_name) gf_isom_box_write((GF_Box*)ptr->group_id_to_name, bs);
return GF_OK;
}
GF_Err fiin_Size(GF_Box *s)
{
GF_Err e;
FDItemInformationBox *ptr = (FDItemInformationBox *)s;
ptr->size+= 2;
if (ptr->partition_entries) {
e = gf_isom_box_array_size(s, ptr->partition_entries);
if (e) return e;
}
if (ptr->session_info) {
e = gf_isom_box_size((GF_Box *)ptr->session_info);
if (e) return e;
ptr->size += ptr->session_info->size;
}
if (ptr->group_id_to_name) {
e = gf_isom_box_size((GF_Box *) ptr->group_id_to_name);
if (e) return e;
ptr->size += ptr->group_id_to_name->size;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *paen_New()
{
ISOM_DECL_BOX_ALLOC(FDPartitionEntryBox, GF_ISOM_BOX_TYPE_PAEN);
return (GF_Box *)tmp;
}
void paen_del(GF_Box *s)
{
FDPartitionEntryBox *ptr = (FDPartitionEntryBox *)s;
if (ptr == NULL) return;
if (ptr->blocks_and_symbols) gf_isom_box_del((GF_Box*)ptr->blocks_and_symbols);
if (ptr->FEC_symbol_locations) gf_isom_box_del((GF_Box*)ptr->FEC_symbol_locations);
if (ptr->File_symbol_locations) gf_isom_box_del((GF_Box*)ptr->File_symbol_locations);
gf_free(ptr);
}
GF_Err paen_AddBox(GF_Box *s, GF_Box *a)
{
FDPartitionEntryBox *ptr = (FDPartitionEntryBox *)s;
switch(a->type) {
case GF_ISOM_BOX_TYPE_FPAR:
if (ptr->blocks_and_symbols) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->blocks_and_symbols = (FilePartitionBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_FECR:
if (ptr->FEC_symbol_locations) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->FEC_symbol_locations = (FECReservoirBox *)a;
return GF_OK;
case GF_ISOM_BOX_TYPE_FIRE:
if (ptr->File_symbol_locations) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->File_symbol_locations = (FileReservoirBox *)a;
return GF_OK;
default:
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err paen_Read(GF_Box *s, GF_BitStream *bs)
{
return gf_isom_box_array_read(s, bs, fiin_AddBox);
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err paen_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
FDPartitionEntryBox *ptr = (FDPartitionEntryBox *) s;
if (!s) return GF_BAD_PARAM;
if (ptr->blocks_and_symbols) {
e = gf_isom_box_write((GF_Box *)ptr->blocks_and_symbols, bs);
if (e) return e;
}
if (ptr->FEC_symbol_locations) {
e = gf_isom_box_write((GF_Box *)ptr->FEC_symbol_locations, bs);
if (e) return e;
}
if (ptr->File_symbol_locations) {
e = gf_isom_box_write((GF_Box *)ptr->File_symbol_locations, bs);
if (e) return e;
}
return GF_OK;
}
GF_Err paen_Size(GF_Box *s)
{
GF_Err e;
FDPartitionEntryBox *ptr = (FDPartitionEntryBox *)s;
if (ptr->blocks_and_symbols) {
e = gf_isom_box_size((GF_Box *)ptr->blocks_and_symbols);
if (e) return e;
ptr->size += ptr->blocks_and_symbols->size;
}
if (ptr->FEC_symbol_locations) {
e = gf_isom_box_size((GF_Box *) ptr->FEC_symbol_locations);
if (e) return e;
ptr->size += ptr->FEC_symbol_locations->size;
}
if (ptr->File_symbol_locations) {
e = gf_isom_box_size((GF_Box *) ptr->File_symbol_locations);
if (e) return e;
ptr->size += ptr->File_symbol_locations->size;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *fpar_New()
{
ISOM_DECL_BOX_ALLOC(FilePartitionBox, GF_ISOM_BOX_TYPE_FPAR);
return (GF_Box *)tmp;
}
void fpar_del(GF_Box *s)
{
FilePartitionBox *ptr = (FilePartitionBox *)s;
if (ptr == NULL) return;
if (ptr->scheme_specific_info) gf_free(ptr->scheme_specific_info);
if (ptr->entries) gf_free(ptr->entries);
gf_free(ptr);
}
GF_Err gf_isom_read_null_terminated_string(GF_Box *s, GF_BitStream *bs, u64 size, char **out_str)
{
u32 len=10;
u32 i=0;
*out_str = gf_malloc(sizeof(char)*len);
while (1) {
ISOM_DECREASE_SIZE(s, 1 );
(*out_str)[i] = gf_bs_read_u8(bs);
if (!(*out_str)[i]) break;
i++;
if (i==len) {
len += 10;
*out_str = gf_realloc(*out_str, sizeof(char)*len);
}
if (gf_bs_available(bs) == 0) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] missing null character in null terminated string\n"));
(*out_str)[i] = 0;
return GF_OK;
}
if (i >= size) {
GF_LOG(GF_LOG_WARNING, GF_LOG_CONTAINER, ("[iso file] string bigger than container, probably missing null character\n"));
(*out_str)[i] = 0;
return GF_OK;
}
}
return GF_OK;
}
GF_Err fpar_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i;
GF_Err e;
FilePartitionBox *ptr = (FilePartitionBox *)s;
ISOM_DECREASE_SIZE(ptr, ((ptr->version ? 4 : 2) + 12) );
ptr->itemID = gf_bs_read_int(bs, ptr->version ? 32 : 16);
ptr->packet_payload_size = gf_bs_read_u16(bs);
gf_bs_read_u8(bs);
ptr->FEC_encoding_ID = gf_bs_read_u8(bs);
ptr->FEC_instance_ID = gf_bs_read_u16(bs);
ptr->max_source_block_length = gf_bs_read_u16(bs);
ptr->encoding_symbol_length = gf_bs_read_u16(bs);
ptr->max_number_of_encoding_symbols = gf_bs_read_u16(bs);
e = gf_isom_read_null_terminated_string(s, bs, ptr->size, &ptr->scheme_specific_info);
if (e) return e;
ISOM_DECREASE_SIZE(ptr, (ptr->version ? 4 : 2) );
ptr->nb_entries = gf_bs_read_int(bs, ptr->version ? 32 : 16);
ISOM_DECREASE_SIZE(ptr, ptr->nb_entries * 6 );
GF_SAFE_ALLOC_N(ptr->entries, ptr->nb_entries, FilePartitionEntry);
for (i=0;i < ptr->nb_entries; i++) {
ptr->entries[i].block_count = gf_bs_read_u16(bs);
ptr->entries[i].block_size = gf_bs_read_u32(bs);
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err fpar_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
FilePartitionBox *ptr = (FilePartitionBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_int(bs, ptr->itemID, ptr->version ? 32 : 16);
gf_bs_write_u16(bs, ptr->packet_payload_size);
gf_bs_write_u8(bs, 0);
gf_bs_write_u8(bs, ptr->FEC_encoding_ID);
gf_bs_write_u16(bs, ptr->FEC_instance_ID);
gf_bs_write_u16(bs, ptr->max_source_block_length);
gf_bs_write_u16(bs, ptr->encoding_symbol_length);
gf_bs_write_u16(bs, ptr->max_number_of_encoding_symbols);
if (ptr->scheme_specific_info) {
gf_bs_write_data(bs, ptr->scheme_specific_info, (u32)strlen(ptr->scheme_specific_info) );
}
//null terminated string
gf_bs_write_u8(bs, 0);
gf_bs_write_int(bs, ptr->nb_entries, ptr->version ? 32 : 16);
for (i=0;i < ptr->nb_entries; i++) {
gf_bs_write_u16(bs, ptr->entries[i].block_count);
gf_bs_write_u32(bs, ptr->entries[i].block_size);
}
return GF_OK;
}
GF_Err fpar_Size(GF_Box *s)
{
FilePartitionBox *ptr = (FilePartitionBox *)s;
ptr->size+= 13 + ptr->version ? 8 : 4;
if (ptr->scheme_specific_info)
ptr->size += strlen(ptr->scheme_specific_info);
ptr->size+= ptr->nb_entries * 6;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *fecr_New()
{
ISOM_DECL_BOX_ALLOC(FECReservoirBox, GF_ISOM_BOX_TYPE_FECR);
return (GF_Box *)tmp;
}
void fecr_del(GF_Box *s)
{
FECReservoirBox *ptr = (FECReservoirBox *)s;
if (ptr == NULL) return;
if (ptr->entries) gf_free(ptr->entries);
gf_free(ptr);
}
GF_Err fecr_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i;
FECReservoirBox *ptr = (FECReservoirBox *)s;
ISOM_DECREASE_SIZE(ptr, (ptr->version ? 4 : 2) );
ptr->nb_entries = gf_bs_read_int(bs, ptr->version ? 32 : 16);
ISOM_DECREASE_SIZE(ptr, ptr->nb_entries * (ptr->version ? 8 : 6) );
GF_SAFE_ALLOC_N(ptr->entries, ptr->nb_entries, FECReservoirEntry);
for (i=0; i<ptr->nb_entries; i++) {
ptr->entries[i].item_id = gf_bs_read_int(bs, ptr->version ? 32 : 16);
ptr->entries[i].symbol_count = gf_bs_read_u32(bs);
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err fecr_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
FECReservoirBox *ptr = (FECReservoirBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_int(bs, ptr->nb_entries, ptr->version ? 32 : 16);
for (i=0; i<ptr->nb_entries; i++) {
gf_bs_write_int(bs, ptr->entries[i].item_id, ptr->version ? 32 : 16);
gf_bs_write_u32(bs, ptr->entries[i].symbol_count);
}
return GF_OK;
}
GF_Err fecr_Size(GF_Box *s)
{
FECReservoirBox *ptr = (FECReservoirBox *)s;
ptr->size += (ptr->version ? 4 : 2) + ptr->nb_entries * (ptr->version ? 8 : 6);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *segr_New()
{
ISOM_DECL_BOX_ALLOC(FDSessionGroupBox, GF_ISOM_BOX_TYPE_SEGR);
return (GF_Box *)tmp;
}
void segr_del(GF_Box *s)
{
u32 i;
FDSessionGroupBox *ptr = (FDSessionGroupBox *)s;
if (ptr == NULL) return;
for (i=0; i<ptr->num_session_groups; i++) {
if (ptr->session_groups[i].group_ids) gf_free(ptr->session_groups[i].group_ids);
if (ptr->session_groups[i].channels) gf_free(ptr->session_groups[i].channels);
}
if (ptr->session_groups) gf_free(ptr->session_groups);
gf_free(ptr);
}
GF_Err segr_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i, k;
FDSessionGroupBox *ptr = (FDSessionGroupBox *)s;
ISOM_DECREASE_SIZE(ptr, 2);
ptr->num_session_groups = gf_bs_read_u16(bs);
if (ptr->num_session_groups*3>ptr->size) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in segr\n", ptr->num_session_groups));
return GF_ISOM_INVALID_FILE;
}
GF_SAFE_ALLOC_N(ptr->session_groups, ptr->num_session_groups, SessionGroupEntry);
for (i=0; i<ptr->num_session_groups; i++) {
ptr->session_groups[i].nb_groups = gf_bs_read_u8(bs);
ISOM_DECREASE_SIZE(ptr, 1);
GF_SAFE_ALLOC_N(ptr->session_groups[i].group_ids, ptr->session_groups[i].nb_groups, u32);
for (k=0; k<ptr->session_groups[i].nb_groups; k++) {
ISOM_DECREASE_SIZE(ptr, 4);
ptr->session_groups[i].group_ids[k] = gf_bs_read_u32(bs);
}
ptr->session_groups[i].nb_channels = gf_bs_read_u16(bs);
GF_SAFE_ALLOC_N(ptr->session_groups[i].channels, ptr->session_groups[i].nb_channels, u32);
for (k=0; k<ptr->session_groups[i].nb_channels; k++) {
ISOM_DECREASE_SIZE(ptr, 4);
ptr->session_groups[i].channels[k] = gf_bs_read_u32(bs);
}
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err segr_Write(GF_Box *s, GF_BitStream *bs)
{
u32 i, k;
FDSessionGroupBox *ptr = (FDSessionGroupBox *) s;
if (!s) return GF_BAD_PARAM;
gf_bs_write_u16(bs, ptr->num_session_groups);
for (i=0; i<ptr->num_session_groups; i++) {
gf_bs_write_u8(bs, ptr->session_groups[i].nb_groups);
for (k=0; k<ptr->session_groups[i].nb_groups; k++) {
gf_bs_write_u32(bs, ptr->session_groups[i].group_ids[k]);
}
gf_bs_write_u16(bs, ptr->session_groups[i].nb_channels);
for (k=0; k<ptr->session_groups[i].nb_channels; k++) {
gf_bs_write_u32(bs, ptr->session_groups[i].channels[k]);
}
}
return GF_OK;
}
GF_Err segr_Size(GF_Box *s)
{
u32 i;
FDSessionGroupBox *ptr = (FDSessionGroupBox *)s;
ptr->size += 2;
for (i=0; i<ptr->num_session_groups; i++) {
ptr->size += 1 + 4*ptr->session_groups[i].nb_groups;
ptr->size += 2 + 4*ptr->session_groups[i].nb_channels;
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *gitn_New()
{
ISOM_DECL_BOX_ALLOC(GroupIdToNameBox, GF_ISOM_BOX_TYPE_GITN);
return (GF_Box *)tmp;
}
void gitn_del(GF_Box *s)
{
u32 i;
GroupIdToNameBox *ptr = (GroupIdToNameBox *)s;
if (ptr == NULL) return;
for (i=0; i<ptr->nb_entries; i++) {
if (ptr->entries[i].name) gf_free(ptr->entries[i].name);
}
if (ptr->entries) gf_free(ptr->entries);
gf_free(ptr);
}
GF_Err gitn_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i;
GF_Err e;
GroupIdToNameBox *ptr = (GroupIdToNameBox *)s;
ISOM_DECREASE_SIZE(ptr, 2);
ptr->nb_entries = gf_bs_read_u16(bs);
GF_SAFE_ALLOC_N(ptr->entries, ptr->nb_entries, GroupIdNameEntry);
for (i=0; i<ptr->nb_entries; i++) {
ISOM_DECREASE_SIZE(ptr, 4);
ptr->entries[i].group_id = gf_bs_read_u32(bs);
e = gf_isom_read_null_terminated_string(s, bs, ptr->size, &ptr->entries[i].name);
if (e) return e;
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err gitn_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GroupIdToNameBox *ptr = (GroupIdToNameBox *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u16(bs, ptr->nb_entries);
for (i=0; i<ptr->nb_entries; i++) {
gf_bs_write_u32(bs, ptr->entries[i].group_id);
if (ptr->entries[i].name) gf_bs_write_data(bs, ptr->entries[i].name, (u32)strlen(ptr->entries[i].name) );
gf_bs_write_u8(bs, 0);
}
return GF_OK;
}
GF_Err gitn_Size(GF_Box *s)
{
u32 i;
GroupIdToNameBox *ptr = (GroupIdToNameBox *)s;
ptr->size += 2;
for (i=0; i<ptr->nb_entries; i++) {
ptr->size += 5;
if (ptr->entries[i].name) ptr->size += strlen(ptr->entries[i].name);
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#ifndef GPAC_DISABLE_ISOM_HINTING
GF_Box *fdpa_New()
{
ISOM_DECL_BOX_ALLOC(GF_FDpacketBox, GF_ISOM_BOX_TYPE_FDPA);
return (GF_Box *)tmp;
}
void fdpa_del(GF_Box *s)
{
u32 i;
GF_FDpacketBox *ptr = (GF_FDpacketBox *)s;
if (ptr == NULL) return;
if (ptr->headers) {
for (i=0; i<ptr->header_ext_count; i++) {
if (ptr->headers[i].data) gf_free(ptr->headers[i].data);
}
gf_free(ptr->headers);
}
gf_free(ptr);
}
GF_Err fdpa_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i;
GF_FDpacketBox *ptr = (GF_FDpacketBox *)s;
ISOM_DECREASE_SIZE(ptr, 3);
ptr->info.sender_current_time_present = gf_bs_read_int(bs, 1);
ptr->info.expected_residual_time_present = gf_bs_read_int(bs, 1);
ptr->info.session_close_bit = gf_bs_read_int(bs, 1);
ptr->info.object_close_bit = gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 4);
ptr->info.transport_object_identifier = gf_bs_read_u16(bs);
ISOM_DECREASE_SIZE(ptr, 2);
ptr->header_ext_count = gf_bs_read_u16(bs);
if (ptr->header_ext_count*2>ptr->size) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Invalid number of entries %d in fdpa\n", ptr->header_ext_count));
return GF_ISOM_INVALID_FILE;
}
GF_SAFE_ALLOC_N(ptr->headers, ptr->header_ext_count, GF_LCTheaderExtension);
for (i=0; i<ptr->header_ext_count; i++) {
ptr->headers[i].header_extension_type = gf_bs_read_u8(bs);
ISOM_DECREASE_SIZE(ptr, 1);
if (ptr->headers[i].header_extension_type > 127) {
gf_bs_read_data(bs, (char *) ptr->headers[i].content, 3);
} else {
ISOM_DECREASE_SIZE(ptr, 1);
ptr->headers[i].data_length = gf_bs_read_u8(bs);
if (ptr->headers[i].data_length) {
ptr->headers[i].data_length = 4*ptr->headers[i].data_length - 2;
ptr->headers[i].data = gf_malloc(sizeof(char) * ptr->headers[i].data_length);
gf_bs_read_data(bs, ptr->headers[i].data, ptr->headers[i].data_length);
}
}
}
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err fdpa_Write(GF_Box *s, GF_BitStream *bs)
{
u32 i;
GF_FDpacketBox *ptr = (GF_FDpacketBox *) s;
if (!s) return GF_BAD_PARAM;
gf_bs_write_int(bs, ptr->info.sender_current_time_present, 1);
gf_bs_write_int(bs, ptr->info.expected_residual_time_present, 1);
gf_bs_write_int(bs, ptr->info.session_close_bit, 1);
gf_bs_write_int(bs, ptr->info.object_close_bit, 1);
gf_bs_write_int(bs, 0, 4);
ptr->info.transport_object_identifier = gf_bs_read_u16(bs);
gf_bs_write_u16(bs, ptr->header_ext_count);
for (i=0; i<ptr->header_ext_count; i++) {
gf_bs_write_u8(bs, ptr->headers[i].header_extension_type);
if (ptr->headers[i].header_extension_type > 127) {
gf_bs_write_data(bs, (const char *) ptr->headers[i].content, 3);
} else {
gf_bs_write_u8(bs, ptr->headers[i].data_length ? (ptr->headers[i].data_length+2)/4 : 0);
if (ptr->headers[i].data_length) {
gf_bs_write_data(bs, ptr->headers[i].data, ptr->headers[i].data_length);
}
}
}
return GF_OK;
}
GF_Err fdpa_Size(GF_Box *s)
{
u32 i;
GF_FDpacketBox *ptr = (GF_FDpacketBox *)s;
ptr->size += 5;
for (i=0; i<ptr->header_ext_count; i++) {
ptr->size += 1;
if (ptr->headers[i].header_extension_type > 127) {
ptr->size += 3;
} else {
ptr->size += 1 + ptr->headers[i].data_length;
}
}
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *extr_New()
{
ISOM_DECL_BOX_ALLOC(GF_ExtraDataBox, GF_ISOM_BOX_TYPE_EXTR);
return (GF_Box *)tmp;
}
void extr_del(GF_Box *s)
{
GF_ExtraDataBox *ptr = (GF_ExtraDataBox *)s;
if (ptr == NULL) return;
if (ptr->feci) gf_isom_box_del((GF_Box*)ptr->feci);
if (ptr->data) gf_free(ptr->data);
gf_free(ptr);
}
GF_Err extr_Read(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_ExtraDataBox *ptr = (GF_ExtraDataBox *)s;
e = gf_isom_box_parse((GF_Box**) &ptr->feci, bs);
if (e) return e;
if (ptr->feci->size>ptr->size) return GF_ISOM_INVALID_MEDIA;
ptr->data_length = (u32) (ptr->size - ptr->feci->size);
ptr->data = gf_malloc(sizeof(char)*ptr->data_length);
gf_bs_read_data(bs, ptr->data, ptr->data_length);
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err extr_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_ExtraDataBox *ptr = (GF_ExtraDataBox *) s;
if (!s) return GF_BAD_PARAM;
if (ptr->feci) {
e = gf_isom_box_write((GF_Box *)ptr->feci, bs);
if (e) return e;
}
gf_bs_write_data(bs, ptr->data, ptr->data_length);
return GF_OK;
}
GF_Err extr_Size(GF_Box *s)
{
GF_Err e;
GF_ExtraDataBox *ptr = (GF_ExtraDataBox *) s;
if (ptr->feci) {
e = gf_isom_box_size((GF_Box *)ptr->feci);
if (e) return e;
ptr->size += ptr->feci->size;
}
ptr->size += ptr->data_length;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
GF_Box *fdsa_New()
{
ISOM_DECL_BOX_ALLOC(GF_HintSample, GF_ISOM_BOX_TYPE_FDSA);
if (!tmp) return NULL;
tmp->packetTable = gf_list_new();
tmp->hint_subtype = GF_ISOM_BOX_TYPE_FDP_STSD;
return (GF_Box*)tmp;
}
void fdsa_del(GF_Box *s)
{
GF_HintSample *ptr = (GF_HintSample *)s;
gf_isom_box_array_del(ptr->packetTable);
if (ptr->extra_data) gf_isom_box_del((GF_Box*)ptr->extra_data);
gf_free(ptr);
}
GF_Err fdsa_AddBox(GF_Box *s, GF_Box *a)
{
GF_HintSample *ptr = (GF_HintSample *)s;
switch(a->type) {
case GF_ISOM_BOX_TYPE_FDPA:
gf_list_add(ptr->packetTable, a);
break;
case GF_ISOM_BOX_TYPE_EXTR:
if (ptr->extra_data) ERROR_ON_DUPLICATED_BOX(a, ptr)
ptr->extra_data = (GF_ExtraDataBox*)a;
break;
default:
return gf_isom_box_add_default(s, a);
}
return GF_OK;
}
GF_Err fdsa_Read(GF_Box *s, GF_BitStream *bs)
{
return gf_isom_box_array_read(s, bs, fdsa_AddBox);
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err fdsa_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_HintSample *ptr = (GF_HintSample *) s;
if (!s) return GF_BAD_PARAM;
e = gf_isom_box_array_write(s, ptr->packetTable, bs);
if (e) return e;
if (ptr->extra_data) {
e = gf_isom_box_write((GF_Box *)ptr->extra_data, bs);
if (e) return e;
}
return GF_OK;
}
GF_Err fdsa_Size(GF_Box *s)
{
GF_HintSample *ptr = (GF_HintSample*)s;
GF_Err e;
if (ptr->extra_data) {
e = gf_isom_box_size((GF_Box *)ptr->extra_data);
if (e) return e;
ptr->size += ptr->extra_data->size;
}
return gf_isom_box_array_size(s, ptr->packetTable);
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#endif /*GPAC_DISABLE_ISOM_HINTING*/
void trik_del(GF_Box *s)
{
GF_TrickPlayBox *ptr = (GF_TrickPlayBox *) s;
if (ptr == NULL) return;
if (ptr->entries) gf_free(ptr->entries);
gf_free(ptr);
}
GF_Err trik_Read(GF_Box *s,GF_BitStream *bs)
{
u32 i;
GF_TrickPlayBox *ptr = (GF_TrickPlayBox *) s;
ptr->entry_count = (u32) ptr->size;
ptr->entries = (GF_TrickPlayBoxEntry *) gf_malloc(ptr->entry_count * sizeof(GF_TrickPlayBoxEntry) );
if (ptr->entries == NULL) return GF_OUT_OF_MEM;
for (i=0; i< ptr->entry_count; i++) {
ptr->entries[i].pic_type = gf_bs_read_int(bs, 2);
ptr->entries[i].dependency_level = gf_bs_read_int(bs, 6);
}
return GF_OK;
}
GF_Box *trik_New()
{
ISOM_DECL_BOX_ALLOC(GF_TrickPlayBox, GF_ISOM_BOX_TYPE_TRIK);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err trik_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_TrickPlayBox *ptr = (GF_TrickPlayBox *) s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
for (i=0; i < ptr->entry_count; i++ ) {
gf_bs_write_int(bs, ptr->entries[i].pic_type, 2);
gf_bs_write_int(bs, ptr->entries[i].dependency_level, 6);
}
return GF_OK;
}
GF_Err trik_Size(GF_Box *s)
{
GF_TrickPlayBox *ptr = (GF_TrickPlayBox *) s;
ptr->size += 8 * ptr->entry_count;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void bloc_del(GF_Box *s)
{
gf_free(s);
}
GF_Err bloc_Read(GF_Box *s,GF_BitStream *bs)
{
GF_BaseLocationBox *ptr = (GF_BaseLocationBox *) s;
ISOM_DECREASE_SIZE(s, 256)
gf_bs_read_data(bs, (char *) ptr->baseLocation, 256);
ISOM_DECREASE_SIZE(s, 256)
gf_bs_read_data(bs, (char *) ptr->basePurlLocation, 256);
ISOM_DECREASE_SIZE(s, 512)
gf_bs_skip_bytes(bs, 512);
return GF_OK;
}
GF_Box *bloc_New()
{
ISOM_DECL_BOX_ALLOC(GF_BaseLocationBox, GF_ISOM_BOX_TYPE_TRIK);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err bloc_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
u32 i;
GF_BaseLocationBox *ptr = (GF_BaseLocationBox *) s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_data(bs, (const char *) ptr->baseLocation, 256);
gf_bs_write_data(bs, (const char *) ptr->basePurlLocation, 256);
for (i=0; i < 64; i++ ) {
gf_bs_write_u64(bs, 0);
}
return GF_OK;
}
GF_Err bloc_Size(GF_Box *s)
{
s->size += 1024;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
void ainf_del(GF_Box *s)
{
GF_AssetInformationBox *ptr = (GF_AssetInformationBox *) s;
if (ptr->APID) gf_free(ptr->APID);
gf_free(s);
}
GF_Err ainf_Read(GF_Box *s,GF_BitStream *bs)
{
GF_AssetInformationBox *ptr = (GF_AssetInformationBox *) s;
ISOM_DECREASE_SIZE(s, 4)
ptr->profile_version = gf_bs_read_u32(bs);
return gf_isom_read_null_terminated_string(s, bs, s->size, &ptr->APID);
}
GF_Box *ainf_New()
{
ISOM_DECL_BOX_ALLOC(GF_AssetInformationBox, GF_ISOM_BOX_TYPE_AINF);
return (GF_Box *)tmp;
}
#ifndef GPAC_DISABLE_ISOM_WRITE
GF_Err ainf_Write(GF_Box *s, GF_BitStream *bs)
{
GF_Err e;
GF_AssetInformationBox *ptr = (GF_AssetInformationBox *) s;
e = gf_isom_full_box_write(s, bs);
if (e) return e;
gf_bs_write_u32(bs, ptr->profile_version);
gf_bs_write_data(bs, ptr->APID, (u32) strlen(ptr->APID) + 1);
return GF_OK;
}
GF_Err ainf_Size(GF_Box *s)
{
GF_AssetInformationBox *ptr = (GF_AssetInformationBox *) s;
s->size += 4 + strlen(ptr->APID) + 1;
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_WRITE*/
#endif /*GPAC_DISABLE_ISOM*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_210_1 |
crossvul-cpp_data_bad_2572_0 | /*
* Monkey's Audio lossless audio decoder
* Copyright (c) 2007 Benjamin Zores <ben@geexbox.org>
* based upon libdemac from Dave Chapman.
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <inttypes.h>
#include "libavutil/avassert.h"
#include "libavutil/channel_layout.h"
#include "libavutil/opt.h"
#include "lossless_audiodsp.h"
#include "avcodec.h"
#include "bswapdsp.h"
#include "bytestream.h"
#include "internal.h"
#include "get_bits.h"
#include "unary.h"
/**
* @file
* Monkey's Audio lossless audio decoder
*/
#define MAX_CHANNELS 2
#define MAX_BYTESPERSAMPLE 3
#define APE_FRAMECODE_MONO_SILENCE 1
#define APE_FRAMECODE_STEREO_SILENCE 3
#define APE_FRAMECODE_PSEUDO_STEREO 4
#define HISTORY_SIZE 512
#define PREDICTOR_ORDER 8
/** Total size of all predictor histories */
#define PREDICTOR_SIZE 50
#define YDELAYA (18 + PREDICTOR_ORDER*4)
#define YDELAYB (18 + PREDICTOR_ORDER*3)
#define XDELAYA (18 + PREDICTOR_ORDER*2)
#define XDELAYB (18 + PREDICTOR_ORDER)
#define YADAPTCOEFFSA 18
#define XADAPTCOEFFSA 14
#define YADAPTCOEFFSB 10
#define XADAPTCOEFFSB 5
/**
* Possible compression levels
* @{
*/
enum APECompressionLevel {
COMPRESSION_LEVEL_FAST = 1000,
COMPRESSION_LEVEL_NORMAL = 2000,
COMPRESSION_LEVEL_HIGH = 3000,
COMPRESSION_LEVEL_EXTRA_HIGH = 4000,
COMPRESSION_LEVEL_INSANE = 5000
};
/** @} */
#define APE_FILTER_LEVELS 3
/** Filter orders depending on compression level */
static const uint16_t ape_filter_orders[5][APE_FILTER_LEVELS] = {
{ 0, 0, 0 },
{ 16, 0, 0 },
{ 64, 0, 0 },
{ 32, 256, 0 },
{ 16, 256, 1280 }
};
/** Filter fraction bits depending on compression level */
static const uint8_t ape_filter_fracbits[5][APE_FILTER_LEVELS] = {
{ 0, 0, 0 },
{ 11, 0, 0 },
{ 11, 0, 0 },
{ 10, 13, 0 },
{ 11, 13, 15 }
};
/** Filters applied to the decoded data */
typedef struct APEFilter {
int16_t *coeffs; ///< actual coefficients used in filtering
int16_t *adaptcoeffs; ///< adaptive filter coefficients used for correcting of actual filter coefficients
int16_t *historybuffer; ///< filter memory
int16_t *delay; ///< filtered values
int avg;
} APEFilter;
typedef struct APERice {
uint32_t k;
uint32_t ksum;
} APERice;
typedef struct APERangecoder {
uint32_t low; ///< low end of interval
uint32_t range; ///< length of interval
uint32_t help; ///< bytes_to_follow resp. intermediate value
unsigned int buffer; ///< buffer for input/output
} APERangecoder;
/** Filter histories */
typedef struct APEPredictor {
int32_t *buf;
int32_t lastA[2];
int32_t filterA[2];
int32_t filterB[2];
int32_t coeffsA[2][4]; ///< adaption coefficients
int32_t coeffsB[2][5]; ///< adaption coefficients
int32_t historybuffer[HISTORY_SIZE + PREDICTOR_SIZE];
unsigned int sample_pos;
} APEPredictor;
/** Decoder context */
typedef struct APEContext {
AVClass *class; ///< class for AVOptions
AVCodecContext *avctx;
BswapDSPContext bdsp;
LLAudDSPContext adsp;
int channels;
int samples; ///< samples left to decode in current frame
int bps;
int fileversion; ///< codec version, very important in decoding process
int compression_level; ///< compression levels
int fset; ///< which filter set to use (calculated from compression level)
int flags; ///< global decoder flags
uint32_t CRC; ///< frame CRC
int frameflags; ///< frame flags
APEPredictor predictor; ///< predictor used for final reconstruction
int32_t *decoded_buffer;
int decoded_size;
int32_t *decoded[MAX_CHANNELS]; ///< decoded data for each channel
int blocks_per_loop; ///< maximum number of samples to decode for each call
int16_t* filterbuf[APE_FILTER_LEVELS]; ///< filter memory
APERangecoder rc; ///< rangecoder used to decode actual values
APERice riceX; ///< rice code parameters for the second channel
APERice riceY; ///< rice code parameters for the first channel
APEFilter filters[APE_FILTER_LEVELS][2]; ///< filters used for reconstruction
GetBitContext gb;
uint8_t *data; ///< current frame data
uint8_t *data_end; ///< frame data end
int data_size; ///< frame data allocated size
const uint8_t *ptr; ///< current position in frame data
int error;
void (*entropy_decode_mono)(struct APEContext *ctx, int blockstodecode);
void (*entropy_decode_stereo)(struct APEContext *ctx, int blockstodecode);
void (*predictor_decode_mono)(struct APEContext *ctx, int count);
void (*predictor_decode_stereo)(struct APEContext *ctx, int count);
} APEContext;
static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
int32_t *decoded1, int count);
static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode);
static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode);
static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode);
static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode);
static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode);
static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode);
static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode);
static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode);
static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode);
static void predictor_decode_mono_3800(APEContext *ctx, int count);
static void predictor_decode_stereo_3800(APEContext *ctx, int count);
static void predictor_decode_mono_3930(APEContext *ctx, int count);
static void predictor_decode_stereo_3930(APEContext *ctx, int count);
static void predictor_decode_mono_3950(APEContext *ctx, int count);
static void predictor_decode_stereo_3950(APEContext *ctx, int count);
static av_cold int ape_decode_close(AVCodecContext *avctx)
{
APEContext *s = avctx->priv_data;
int i;
for (i = 0; i < APE_FILTER_LEVELS; i++)
av_freep(&s->filterbuf[i]);
av_freep(&s->decoded_buffer);
av_freep(&s->data);
s->decoded_size = s->data_size = 0;
return 0;
}
static av_cold int ape_decode_init(AVCodecContext *avctx)
{
APEContext *s = avctx->priv_data;
int i;
if (avctx->extradata_size != 6) {
av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");
return AVERROR(EINVAL);
}
if (avctx->channels > 2) {
av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");
return AVERROR(EINVAL);
}
s->bps = avctx->bits_per_coded_sample;
switch (s->bps) {
case 8:
avctx->sample_fmt = AV_SAMPLE_FMT_U8P;
break;
case 16:
avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
break;
case 24:
avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
break;
default:
avpriv_request_sample(avctx,
"%d bits per coded sample", s->bps);
return AVERROR_PATCHWELCOME;
}
s->avctx = avctx;
s->channels = avctx->channels;
s->fileversion = AV_RL16(avctx->extradata);
s->compression_level = AV_RL16(avctx->extradata + 2);
s->flags = AV_RL16(avctx->extradata + 4);
av_log(avctx, AV_LOG_VERBOSE, "Compression Level: %d - Flags: %d\n",
s->compression_level, s->flags);
if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE ||
!s->compression_level ||
(s->fileversion < 3930 && s->compression_level == COMPRESSION_LEVEL_INSANE)) {
av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n",
s->compression_level);
return AVERROR_INVALIDDATA;
}
s->fset = s->compression_level / 1000 - 1;
for (i = 0; i < APE_FILTER_LEVELS; i++) {
if (!ape_filter_orders[s->fset][i])
break;
FF_ALLOC_OR_GOTO(avctx, s->filterbuf[i],
(ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4,
filter_alloc_fail);
}
if (s->fileversion < 3860) {
s->entropy_decode_mono = entropy_decode_mono_0000;
s->entropy_decode_stereo = entropy_decode_stereo_0000;
} else if (s->fileversion < 3900) {
s->entropy_decode_mono = entropy_decode_mono_3860;
s->entropy_decode_stereo = entropy_decode_stereo_3860;
} else if (s->fileversion < 3930) {
s->entropy_decode_mono = entropy_decode_mono_3900;
s->entropy_decode_stereo = entropy_decode_stereo_3900;
} else if (s->fileversion < 3990) {
s->entropy_decode_mono = entropy_decode_mono_3900;
s->entropy_decode_stereo = entropy_decode_stereo_3930;
} else {
s->entropy_decode_mono = entropy_decode_mono_3990;
s->entropy_decode_stereo = entropy_decode_stereo_3990;
}
if (s->fileversion < 3930) {
s->predictor_decode_mono = predictor_decode_mono_3800;
s->predictor_decode_stereo = predictor_decode_stereo_3800;
} else if (s->fileversion < 3950) {
s->predictor_decode_mono = predictor_decode_mono_3930;
s->predictor_decode_stereo = predictor_decode_stereo_3930;
} else {
s->predictor_decode_mono = predictor_decode_mono_3950;
s->predictor_decode_stereo = predictor_decode_stereo_3950;
}
ff_bswapdsp_init(&s->bdsp);
ff_llauddsp_init(&s->adsp);
avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
return 0;
filter_alloc_fail:
ape_decode_close(avctx);
return AVERROR(ENOMEM);
}
/**
* @name APE range decoding functions
* @{
*/
#define CODE_BITS 32
#define TOP_VALUE ((unsigned int)1 << (CODE_BITS-1))
#define SHIFT_BITS (CODE_BITS - 9)
#define EXTRA_BITS ((CODE_BITS-2) % 8 + 1)
#define BOTTOM_VALUE (TOP_VALUE >> 8)
/** Start the decoder */
static inline void range_start_decoding(APEContext *ctx)
{
ctx->rc.buffer = bytestream_get_byte(&ctx->ptr);
ctx->rc.low = ctx->rc.buffer >> (8 - EXTRA_BITS);
ctx->rc.range = (uint32_t) 1 << EXTRA_BITS;
}
/** Perform normalization */
static inline void range_dec_normalize(APEContext *ctx)
{
while (ctx->rc.range <= BOTTOM_VALUE) {
ctx->rc.buffer <<= 8;
if(ctx->ptr < ctx->data_end) {
ctx->rc.buffer += *ctx->ptr;
ctx->ptr++;
} else {
ctx->error = 1;
}
ctx->rc.low = (ctx->rc.low << 8) | ((ctx->rc.buffer >> 1) & 0xFF);
ctx->rc.range <<= 8;
}
}
/**
* Calculate cumulative frequency for next symbol. Does NO update!
* @param ctx decoder context
* @param tot_f is the total frequency or (code_value)1<<shift
* @return the cumulative frequency
*/
static inline int range_decode_culfreq(APEContext *ctx, int tot_f)
{
range_dec_normalize(ctx);
ctx->rc.help = ctx->rc.range / tot_f;
return ctx->rc.low / ctx->rc.help;
}
/**
* Decode value with given size in bits
* @param ctx decoder context
* @param shift number of bits to decode
*/
static inline int range_decode_culshift(APEContext *ctx, int shift)
{
range_dec_normalize(ctx);
ctx->rc.help = ctx->rc.range >> shift;
return ctx->rc.low / ctx->rc.help;
}
/**
* Update decoding state
* @param ctx decoder context
* @param sy_f the interval length (frequency of the symbol)
* @param lt_f the lower end (frequency sum of < symbols)
*/
static inline void range_decode_update(APEContext *ctx, int sy_f, int lt_f)
{
ctx->rc.low -= ctx->rc.help * lt_f;
ctx->rc.range = ctx->rc.help * sy_f;
}
/** Decode n bits (n <= 16) without modelling */
static inline int range_decode_bits(APEContext *ctx, int n)
{
int sym = range_decode_culshift(ctx, n);
range_decode_update(ctx, 1, sym);
return sym;
}
#define MODEL_ELEMENTS 64
/**
* Fixed probabilities for symbols in Monkey Audio version 3.97
*/
static const uint16_t counts_3970[22] = {
0, 14824, 28224, 39348, 47855, 53994, 58171, 60926,
62682, 63786, 64463, 64878, 65126, 65276, 65365, 65419,
65450, 65469, 65480, 65487, 65491, 65493,
};
/**
* Probability ranges for symbols in Monkey Audio version 3.97
*/
static const uint16_t counts_diff_3970[21] = {
14824, 13400, 11124, 8507, 6139, 4177, 2755, 1756,
1104, 677, 415, 248, 150, 89, 54, 31,
19, 11, 7, 4, 2,
};
/**
* Fixed probabilities for symbols in Monkey Audio version 3.98
*/
static const uint16_t counts_3980[22] = {
0, 19578, 36160, 48417, 56323, 60899, 63265, 64435,
64971, 65232, 65351, 65416, 65447, 65466, 65476, 65482,
65485, 65488, 65490, 65491, 65492, 65493,
};
/**
* Probability ranges for symbols in Monkey Audio version 3.98
*/
static const uint16_t counts_diff_3980[21] = {
19578, 16582, 12257, 7906, 4576, 2366, 1170, 536,
261, 119, 65, 31, 19, 10, 6, 3,
3, 2, 1, 1, 1,
};
/**
* Decode symbol
* @param ctx decoder context
* @param counts probability range start position
* @param counts_diff probability range widths
*/
static inline int range_get_symbol(APEContext *ctx,
const uint16_t counts[],
const uint16_t counts_diff[])
{
int symbol, cf;
cf = range_decode_culshift(ctx, 16);
if(cf > 65492){
symbol= cf - 65535 + 63;
range_decode_update(ctx, 1, cf);
if(cf > 65535)
ctx->error=1;
return symbol;
}
/* figure out the symbol inefficiently; a binary search would be much better */
for (symbol = 0; counts[symbol + 1] <= cf; symbol++);
range_decode_update(ctx, counts_diff[symbol], counts[symbol]);
return symbol;
}
/** @} */ // group rangecoder
static inline void update_rice(APERice *rice, unsigned int x)
{
int lim = rice->k ? (1 << (rice->k + 4)) : 0;
rice->ksum += ((x + 1) / 2) - ((rice->ksum + 16) >> 5);
if (rice->ksum < lim)
rice->k--;
else if (rice->ksum >= (1 << (rice->k + 5)))
rice->k++;
}
static inline int get_rice_ook(GetBitContext *gb, int k)
{
unsigned int x;
x = get_unary(gb, 1, get_bits_left(gb));
if (k)
x = (x << k) | get_bits(gb, k);
return x;
}
static inline int ape_decode_value_3860(APEContext *ctx, GetBitContext *gb,
APERice *rice)
{
unsigned int x, overflow;
overflow = get_unary(gb, 1, get_bits_left(gb));
if (ctx->fileversion > 3880) {
while (overflow >= 16) {
overflow -= 16;
rice->k += 4;
}
}
if (!rice->k)
x = overflow;
else if(rice->k <= MIN_CACHE_BITS) {
x = (overflow << rice->k) + get_bits(gb, rice->k);
} else {
av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %"PRIu32"\n", rice->k);
return AVERROR_INVALIDDATA;
}
rice->ksum += x - (rice->ksum + 8 >> 4);
if (rice->ksum < (rice->k ? 1 << (rice->k + 4) : 0))
rice->k--;
else if (rice->ksum >= (1 << (rice->k + 5)) && rice->k < 24)
rice->k++;
/* Convert to signed */
return ((x >> 1) ^ ((x & 1) - 1)) + 1;
}
static inline int ape_decode_value_3900(APEContext *ctx, APERice *rice)
{
unsigned int x, overflow;
int tmpk;
overflow = range_get_symbol(ctx, counts_3970, counts_diff_3970);
if (overflow == (MODEL_ELEMENTS - 1)) {
tmpk = range_decode_bits(ctx, 5);
overflow = 0;
} else
tmpk = (rice->k < 1) ? 0 : rice->k - 1;
if (tmpk <= 16 || ctx->fileversion < 3910) {
if (tmpk > 23) {
av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
return AVERROR_INVALIDDATA;
}
x = range_decode_bits(ctx, tmpk);
} else if (tmpk <= 31) {
x = range_decode_bits(ctx, 16);
x |= (range_decode_bits(ctx, tmpk - 16) << 16);
} else {
av_log(ctx->avctx, AV_LOG_ERROR, "Too many bits: %d\n", tmpk);
return AVERROR_INVALIDDATA;
}
x += overflow << tmpk;
update_rice(rice, x);
/* Convert to signed */
return ((x >> 1) ^ ((x & 1) - 1)) + 1;
}
static inline int ape_decode_value_3990(APEContext *ctx, APERice *rice)
{
unsigned int x, overflow;
int base, pivot;
pivot = rice->ksum >> 5;
if (pivot == 0)
pivot = 1;
overflow = range_get_symbol(ctx, counts_3980, counts_diff_3980);
if (overflow == (MODEL_ELEMENTS - 1)) {
overflow = range_decode_bits(ctx, 16) << 16;
overflow |= range_decode_bits(ctx, 16);
}
if (pivot < 0x10000) {
base = range_decode_culfreq(ctx, pivot);
range_decode_update(ctx, 1, base);
} else {
int base_hi = pivot, base_lo;
int bbits = 0;
while (base_hi & ~0xFFFF) {
base_hi >>= 1;
bbits++;
}
base_hi = range_decode_culfreq(ctx, base_hi + 1);
range_decode_update(ctx, 1, base_hi);
base_lo = range_decode_culfreq(ctx, 1 << bbits);
range_decode_update(ctx, 1, base_lo);
base = (base_hi << bbits) + base_lo;
}
x = base + overflow * pivot;
update_rice(rice, x);
/* Convert to signed */
return ((x >> 1) ^ ((x & 1) - 1)) + 1;
}
static void decode_array_0000(APEContext *ctx, GetBitContext *gb,
int32_t *out, APERice *rice, int blockstodecode)
{
int i;
int ksummax, ksummin;
rice->ksum = 0;
for (i = 0; i < FFMIN(blockstodecode, 5); i++) {
out[i] = get_rice_ook(&ctx->gb, 10);
rice->ksum += out[i];
}
rice->k = av_log2(rice->ksum / 10) + 1;
if (rice->k >= 24)
return;
for (; i < FFMIN(blockstodecode, 64); i++) {
out[i] = get_rice_ook(&ctx->gb, rice->k);
rice->ksum += out[i];
rice->k = av_log2(rice->ksum / ((i + 1) * 2)) + 1;
if (rice->k >= 24)
return;
}
ksummax = 1 << rice->k + 7;
ksummin = rice->k ? (1 << rice->k + 6) : 0;
for (; i < blockstodecode; i++) {
out[i] = get_rice_ook(&ctx->gb, rice->k);
rice->ksum += out[i] - out[i - 64];
while (rice->ksum < ksummin) {
rice->k--;
ksummin = rice->k ? ksummin >> 1 : 0;
ksummax >>= 1;
}
while (rice->ksum >= ksummax) {
rice->k++;
if (rice->k > 24)
return;
ksummax <<= 1;
ksummin = ksummin ? ksummin << 1 : 128;
}
}
for (i = 0; i < blockstodecode; i++)
out[i] = ((out[i] >> 1) ^ ((out[i] & 1) - 1)) + 1;
}
static void entropy_decode_mono_0000(APEContext *ctx, int blockstodecode)
{
decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
blockstodecode);
}
static void entropy_decode_stereo_0000(APEContext *ctx, int blockstodecode)
{
decode_array_0000(ctx, &ctx->gb, ctx->decoded[0], &ctx->riceY,
blockstodecode);
decode_array_0000(ctx, &ctx->gb, ctx->decoded[1], &ctx->riceX,
blockstodecode);
}
static void entropy_decode_mono_3860(APEContext *ctx, int blockstodecode)
{
int32_t *decoded0 = ctx->decoded[0];
while (blockstodecode--)
*decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
}
static void entropy_decode_stereo_3860(APEContext *ctx, int blockstodecode)
{
int32_t *decoded0 = ctx->decoded[0];
int32_t *decoded1 = ctx->decoded[1];
int blocks = blockstodecode;
while (blockstodecode--)
*decoded0++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceY);
while (blocks--)
*decoded1++ = ape_decode_value_3860(ctx, &ctx->gb, &ctx->riceX);
}
static void entropy_decode_mono_3900(APEContext *ctx, int blockstodecode)
{
int32_t *decoded0 = ctx->decoded[0];
while (blockstodecode--)
*decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
}
static void entropy_decode_stereo_3900(APEContext *ctx, int blockstodecode)
{
int32_t *decoded0 = ctx->decoded[0];
int32_t *decoded1 = ctx->decoded[1];
int blocks = blockstodecode;
while (blockstodecode--)
*decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
range_dec_normalize(ctx);
// because of some implementation peculiarities we need to backpedal here
ctx->ptr -= 1;
range_start_decoding(ctx);
while (blocks--)
*decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
}
static void entropy_decode_stereo_3930(APEContext *ctx, int blockstodecode)
{
int32_t *decoded0 = ctx->decoded[0];
int32_t *decoded1 = ctx->decoded[1];
while (blockstodecode--) {
*decoded0++ = ape_decode_value_3900(ctx, &ctx->riceY);
*decoded1++ = ape_decode_value_3900(ctx, &ctx->riceX);
}
}
static void entropy_decode_mono_3990(APEContext *ctx, int blockstodecode)
{
int32_t *decoded0 = ctx->decoded[0];
while (blockstodecode--)
*decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
}
static void entropy_decode_stereo_3990(APEContext *ctx, int blockstodecode)
{
int32_t *decoded0 = ctx->decoded[0];
int32_t *decoded1 = ctx->decoded[1];
while (blockstodecode--) {
*decoded0++ = ape_decode_value_3990(ctx, &ctx->riceY);
*decoded1++ = ape_decode_value_3990(ctx, &ctx->riceX);
}
}
static int init_entropy_decoder(APEContext *ctx)
{
/* Read the CRC */
if (ctx->fileversion >= 3900) {
if (ctx->data_end - ctx->ptr < 6)
return AVERROR_INVALIDDATA;
ctx->CRC = bytestream_get_be32(&ctx->ptr);
} else {
ctx->CRC = get_bits_long(&ctx->gb, 32);
}
/* Read the frame flags if they exist */
ctx->frameflags = 0;
if ((ctx->fileversion > 3820) && (ctx->CRC & 0x80000000)) {
ctx->CRC &= ~0x80000000;
if (ctx->data_end - ctx->ptr < 6)
return AVERROR_INVALIDDATA;
ctx->frameflags = bytestream_get_be32(&ctx->ptr);
}
/* Initialize the rice structs */
ctx->riceX.k = 10;
ctx->riceX.ksum = (1 << ctx->riceX.k) * 16;
ctx->riceY.k = 10;
ctx->riceY.ksum = (1 << ctx->riceY.k) * 16;
if (ctx->fileversion >= 3900) {
/* The first 8 bits of input are ignored. */
ctx->ptr++;
range_start_decoding(ctx);
}
return 0;
}
static const int32_t initial_coeffs_fast_3320[1] = {
375,
};
static const int32_t initial_coeffs_a_3800[3] = {
64, 115, 64,
};
static const int32_t initial_coeffs_b_3800[2] = {
740, 0
};
static const int32_t initial_coeffs_3930[4] = {
360, 317, -109, 98
};
static void init_predictor_decoder(APEContext *ctx)
{
APEPredictor *p = &ctx->predictor;
/* Zero the history buffers */
memset(p->historybuffer, 0, PREDICTOR_SIZE * sizeof(*p->historybuffer));
p->buf = p->historybuffer;
/* Initialize and zero the coefficients */
if (ctx->fileversion < 3930) {
if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
memcpy(p->coeffsA[0], initial_coeffs_fast_3320,
sizeof(initial_coeffs_fast_3320));
memcpy(p->coeffsA[1], initial_coeffs_fast_3320,
sizeof(initial_coeffs_fast_3320));
} else {
memcpy(p->coeffsA[0], initial_coeffs_a_3800,
sizeof(initial_coeffs_a_3800));
memcpy(p->coeffsA[1], initial_coeffs_a_3800,
sizeof(initial_coeffs_a_3800));
}
} else {
memcpy(p->coeffsA[0], initial_coeffs_3930, sizeof(initial_coeffs_3930));
memcpy(p->coeffsA[1], initial_coeffs_3930, sizeof(initial_coeffs_3930));
}
memset(p->coeffsB, 0, sizeof(p->coeffsB));
if (ctx->fileversion < 3930) {
memcpy(p->coeffsB[0], initial_coeffs_b_3800,
sizeof(initial_coeffs_b_3800));
memcpy(p->coeffsB[1], initial_coeffs_b_3800,
sizeof(initial_coeffs_b_3800));
}
p->filterA[0] = p->filterA[1] = 0;
p->filterB[0] = p->filterB[1] = 0;
p->lastA[0] = p->lastA[1] = 0;
p->sample_pos = 0;
}
/** Get inverse sign of integer (-1 for positive, 1 for negative and 0 for zero) */
static inline int APESIGN(int32_t x) {
return (x < 0) - (x > 0);
}
static av_always_inline int filter_fast_3320(APEPredictor *p,
const int decoded, const int filter,
const int delayA)
{
int32_t predictionA;
p->buf[delayA] = p->lastA[filter];
if (p->sample_pos < 3) {
p->lastA[filter] = decoded;
p->filterA[filter] = decoded;
return decoded;
}
predictionA = p->buf[delayA] * 2 - p->buf[delayA - 1];
p->lastA[filter] = decoded + (predictionA * p->coeffsA[filter][0] >> 9);
if ((decoded ^ predictionA) > 0)
p->coeffsA[filter][0]++;
else
p->coeffsA[filter][0]--;
p->filterA[filter] += p->lastA[filter];
return p->filterA[filter];
}
static av_always_inline int filter_3800(APEPredictor *p,
const int decoded, const int filter,
const int delayA, const int delayB,
const int start, const int shift)
{
int32_t predictionA, predictionB, sign;
int32_t d0, d1, d2, d3, d4;
p->buf[delayA] = p->lastA[filter];
p->buf[delayB] = p->filterB[filter];
if (p->sample_pos < start) {
predictionA = decoded + p->filterA[filter];
p->lastA[filter] = decoded;
p->filterB[filter] = decoded;
p->filterA[filter] = predictionA;
return predictionA;
}
d2 = p->buf[delayA];
d1 = (p->buf[delayA] - p->buf[delayA - 1]) << 1;
d0 = p->buf[delayA] + ((p->buf[delayA - 2] - p->buf[delayA - 1]) << 3);
d3 = p->buf[delayB] * 2 - p->buf[delayB - 1];
d4 = p->buf[delayB];
predictionA = d0 * p->coeffsA[filter][0] +
d1 * p->coeffsA[filter][1] +
d2 * p->coeffsA[filter][2];
sign = APESIGN(decoded);
p->coeffsA[filter][0] += (((d0 >> 30) & 2) - 1) * sign;
p->coeffsA[filter][1] += (((d1 >> 28) & 8) - 4) * sign;
p->coeffsA[filter][2] += (((d2 >> 28) & 8) - 4) * sign;
predictionB = d3 * p->coeffsB[filter][0] -
d4 * p->coeffsB[filter][1];
p->lastA[filter] = decoded + (predictionA >> 11);
sign = APESIGN(p->lastA[filter]);
p->coeffsB[filter][0] += (((d3 >> 29) & 4) - 2) * sign;
p->coeffsB[filter][1] -= (((d4 >> 30) & 2) - 1) * sign;
p->filterB[filter] = p->lastA[filter] + (predictionB >> shift);
p->filterA[filter] = p->filterB[filter] + ((p->filterA[filter] * 31) >> 5);
return p->filterA[filter];
}
static void long_filter_high_3800(int32_t *buffer, int order, int shift, int length)
{
int i, j;
int32_t dotprod, sign;
int32_t coeffs[256], delay[256];
if (order >= length)
return;
memset(coeffs, 0, order * sizeof(*coeffs));
for (i = 0; i < order; i++)
delay[i] = buffer[i];
for (i = order; i < length; i++) {
dotprod = 0;
sign = APESIGN(buffer[i]);
for (j = 0; j < order; j++) {
dotprod += delay[j] * coeffs[j];
coeffs[j] += ((delay[j] >> 31) | 1) * sign;
}
buffer[i] -= dotprod >> shift;
for (j = 0; j < order - 1; j++)
delay[j] = delay[j + 1];
delay[order - 1] = buffer[i];
}
}
static void long_filter_ehigh_3830(int32_t *buffer, int length)
{
int i, j;
int32_t dotprod, sign;
int32_t coeffs[8] = { 0 }, delay[8] = { 0 };
for (i = 0; i < length; i++) {
dotprod = 0;
sign = APESIGN(buffer[i]);
for (j = 7; j >= 0; j--) {
dotprod += delay[j] * coeffs[j];
coeffs[j] += ((delay[j] >> 31) | 1) * sign;
}
for (j = 7; j > 0; j--)
delay[j] = delay[j - 1];
delay[0] = buffer[i];
buffer[i] -= dotprod >> 9;
}
}
static void predictor_decode_stereo_3800(APEContext *ctx, int count)
{
APEPredictor *p = &ctx->predictor;
int32_t *decoded0 = ctx->decoded[0];
int32_t *decoded1 = ctx->decoded[1];
int start = 4, shift = 10;
if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
start = 16;
long_filter_high_3800(decoded0, 16, 9, count);
long_filter_high_3800(decoded1, 16, 9, count);
} else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
int order = 128, shift2 = 11;
if (ctx->fileversion >= 3830) {
order <<= 1;
shift++;
shift2++;
long_filter_ehigh_3830(decoded0 + order, count - order);
long_filter_ehigh_3830(decoded1 + order, count - order);
}
start = order;
long_filter_high_3800(decoded0, order, shift2, count);
long_filter_high_3800(decoded1, order, shift2, count);
}
while (count--) {
int X = *decoded0, Y = *decoded1;
if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
*decoded0 = filter_fast_3320(p, Y, 0, YDELAYA);
decoded0++;
*decoded1 = filter_fast_3320(p, X, 1, XDELAYA);
decoded1++;
} else {
*decoded0 = filter_3800(p, Y, 0, YDELAYA, YDELAYB,
start, shift);
decoded0++;
*decoded1 = filter_3800(p, X, 1, XDELAYA, XDELAYB,
start, shift);
decoded1++;
}
/* Combined */
p->buf++;
p->sample_pos++;
/* Have we filled the history buffer? */
if (p->buf == p->historybuffer + HISTORY_SIZE) {
memmove(p->historybuffer, p->buf,
PREDICTOR_SIZE * sizeof(*p->historybuffer));
p->buf = p->historybuffer;
}
}
}
static void predictor_decode_mono_3800(APEContext *ctx, int count)
{
APEPredictor *p = &ctx->predictor;
int32_t *decoded0 = ctx->decoded[0];
int start = 4, shift = 10;
if (ctx->compression_level == COMPRESSION_LEVEL_HIGH) {
start = 16;
long_filter_high_3800(decoded0, 16, 9, count);
} else if (ctx->compression_level == COMPRESSION_LEVEL_EXTRA_HIGH) {
int order = 128, shift2 = 11;
if (ctx->fileversion >= 3830) {
order <<= 1;
shift++;
shift2++;
long_filter_ehigh_3830(decoded0 + order, count - order);
}
start = order;
long_filter_high_3800(decoded0, order, shift2, count);
}
while (count--) {
if (ctx->compression_level == COMPRESSION_LEVEL_FAST) {
*decoded0 = filter_fast_3320(p, *decoded0, 0, YDELAYA);
decoded0++;
} else {
*decoded0 = filter_3800(p, *decoded0, 0, YDELAYA, YDELAYB,
start, shift);
decoded0++;
}
/* Combined */
p->buf++;
p->sample_pos++;
/* Have we filled the history buffer? */
if (p->buf == p->historybuffer + HISTORY_SIZE) {
memmove(p->historybuffer, p->buf,
PREDICTOR_SIZE * sizeof(*p->historybuffer));
p->buf = p->historybuffer;
}
}
}
static av_always_inline int predictor_update_3930(APEPredictor *p,
const int decoded, const int filter,
const int delayA)
{
int32_t predictionA, sign;
int32_t d0, d1, d2, d3;
p->buf[delayA] = p->lastA[filter];
d0 = p->buf[delayA ];
d1 = p->buf[delayA ] - p->buf[delayA - 1];
d2 = p->buf[delayA - 1] - p->buf[delayA - 2];
d3 = p->buf[delayA - 2] - p->buf[delayA - 3];
predictionA = d0 * p->coeffsA[filter][0] +
d1 * p->coeffsA[filter][1] +
d2 * p->coeffsA[filter][2] +
d3 * p->coeffsA[filter][3];
p->lastA[filter] = decoded + (predictionA >> 9);
p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
sign = APESIGN(decoded);
p->coeffsA[filter][0] += ((d0 < 0) * 2 - 1) * sign;
p->coeffsA[filter][1] += ((d1 < 0) * 2 - 1) * sign;
p->coeffsA[filter][2] += ((d2 < 0) * 2 - 1) * sign;
p->coeffsA[filter][3] += ((d3 < 0) * 2 - 1) * sign;
return p->filterA[filter];
}
static void predictor_decode_stereo_3930(APEContext *ctx, int count)
{
APEPredictor *p = &ctx->predictor;
int32_t *decoded0 = ctx->decoded[0];
int32_t *decoded1 = ctx->decoded[1];
ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
while (count--) {
/* Predictor Y */
int Y = *decoded1, X = *decoded0;
*decoded0 = predictor_update_3930(p, Y, 0, YDELAYA);
decoded0++;
*decoded1 = predictor_update_3930(p, X, 1, XDELAYA);
decoded1++;
/* Combined */
p->buf++;
/* Have we filled the history buffer? */
if (p->buf == p->historybuffer + HISTORY_SIZE) {
memmove(p->historybuffer, p->buf,
PREDICTOR_SIZE * sizeof(*p->historybuffer));
p->buf = p->historybuffer;
}
}
}
static void predictor_decode_mono_3930(APEContext *ctx, int count)
{
APEPredictor *p = &ctx->predictor;
int32_t *decoded0 = ctx->decoded[0];
ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
while (count--) {
*decoded0 = predictor_update_3930(p, *decoded0, 0, YDELAYA);
decoded0++;
p->buf++;
/* Have we filled the history buffer? */
if (p->buf == p->historybuffer + HISTORY_SIZE) {
memmove(p->historybuffer, p->buf,
PREDICTOR_SIZE * sizeof(*p->historybuffer));
p->buf = p->historybuffer;
}
}
}
static av_always_inline int predictor_update_filter(APEPredictor *p,
const int decoded, const int filter,
const int delayA, const int delayB,
const int adaptA, const int adaptB)
{
int32_t predictionA, predictionB, sign;
p->buf[delayA] = p->lastA[filter];
p->buf[adaptA] = APESIGN(p->buf[delayA]);
p->buf[delayA - 1] = p->buf[delayA] - p->buf[delayA - 1];
p->buf[adaptA - 1] = APESIGN(p->buf[delayA - 1]);
predictionA = p->buf[delayA ] * p->coeffsA[filter][0] +
p->buf[delayA - 1] * p->coeffsA[filter][1] +
p->buf[delayA - 2] * p->coeffsA[filter][2] +
p->buf[delayA - 3] * p->coeffsA[filter][3];
/* Apply a scaled first-order filter compression */
p->buf[delayB] = p->filterA[filter ^ 1] - ((p->filterB[filter] * 31) >> 5);
p->buf[adaptB] = APESIGN(p->buf[delayB]);
p->buf[delayB - 1] = p->buf[delayB] - p->buf[delayB - 1];
p->buf[adaptB - 1] = APESIGN(p->buf[delayB - 1]);
p->filterB[filter] = p->filterA[filter ^ 1];
predictionB = p->buf[delayB ] * p->coeffsB[filter][0] +
p->buf[delayB - 1] * p->coeffsB[filter][1] +
p->buf[delayB - 2] * p->coeffsB[filter][2] +
p->buf[delayB - 3] * p->coeffsB[filter][3] +
p->buf[delayB - 4] * p->coeffsB[filter][4];
p->lastA[filter] = decoded + ((predictionA + (predictionB >> 1)) >> 10);
p->filterA[filter] = p->lastA[filter] + ((p->filterA[filter] * 31) >> 5);
sign = APESIGN(decoded);
p->coeffsA[filter][0] += p->buf[adaptA ] * sign;
p->coeffsA[filter][1] += p->buf[adaptA - 1] * sign;
p->coeffsA[filter][2] += p->buf[adaptA - 2] * sign;
p->coeffsA[filter][3] += p->buf[adaptA - 3] * sign;
p->coeffsB[filter][0] += p->buf[adaptB ] * sign;
p->coeffsB[filter][1] += p->buf[adaptB - 1] * sign;
p->coeffsB[filter][2] += p->buf[adaptB - 2] * sign;
p->coeffsB[filter][3] += p->buf[adaptB - 3] * sign;
p->coeffsB[filter][4] += p->buf[adaptB - 4] * sign;
return p->filterA[filter];
}
static void predictor_decode_stereo_3950(APEContext *ctx, int count)
{
APEPredictor *p = &ctx->predictor;
int32_t *decoded0 = ctx->decoded[0];
int32_t *decoded1 = ctx->decoded[1];
ape_apply_filters(ctx, ctx->decoded[0], ctx->decoded[1], count);
while (count--) {
/* Predictor Y */
*decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,
YADAPTCOEFFSA, YADAPTCOEFFSB);
decoded0++;
*decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,
XADAPTCOEFFSA, XADAPTCOEFFSB);
decoded1++;
/* Combined */
p->buf++;
/* Have we filled the history buffer? */
if (p->buf == p->historybuffer + HISTORY_SIZE) {
memmove(p->historybuffer, p->buf,
PREDICTOR_SIZE * sizeof(*p->historybuffer));
p->buf = p->historybuffer;
}
}
}
static void predictor_decode_mono_3950(APEContext *ctx, int count)
{
APEPredictor *p = &ctx->predictor;
int32_t *decoded0 = ctx->decoded[0];
int32_t predictionA, currentA, A, sign;
ape_apply_filters(ctx, ctx->decoded[0], NULL, count);
currentA = p->lastA[0];
while (count--) {
A = *decoded0;
p->buf[YDELAYA] = currentA;
p->buf[YDELAYA - 1] = p->buf[YDELAYA] - p->buf[YDELAYA - 1];
predictionA = p->buf[YDELAYA ] * p->coeffsA[0][0] +
p->buf[YDELAYA - 1] * p->coeffsA[0][1] +
p->buf[YDELAYA - 2] * p->coeffsA[0][2] +
p->buf[YDELAYA - 3] * p->coeffsA[0][3];
currentA = A + (predictionA >> 10);
p->buf[YADAPTCOEFFSA] = APESIGN(p->buf[YDELAYA ]);
p->buf[YADAPTCOEFFSA - 1] = APESIGN(p->buf[YDELAYA - 1]);
sign = APESIGN(A);
p->coeffsA[0][0] += p->buf[YADAPTCOEFFSA ] * sign;
p->coeffsA[0][1] += p->buf[YADAPTCOEFFSA - 1] * sign;
p->coeffsA[0][2] += p->buf[YADAPTCOEFFSA - 2] * sign;
p->coeffsA[0][3] += p->buf[YADAPTCOEFFSA - 3] * sign;
p->buf++;
/* Have we filled the history buffer? */
if (p->buf == p->historybuffer + HISTORY_SIZE) {
memmove(p->historybuffer, p->buf,
PREDICTOR_SIZE * sizeof(*p->historybuffer));
p->buf = p->historybuffer;
}
p->filterA[0] = currentA + ((p->filterA[0] * 31) >> 5);
*(decoded0++) = p->filterA[0];
}
p->lastA[0] = currentA;
}
static void do_init_filter(APEFilter *f, int16_t *buf, int order)
{
f->coeffs = buf;
f->historybuffer = buf + order;
f->delay = f->historybuffer + order * 2;
f->adaptcoeffs = f->historybuffer + order;
memset(f->historybuffer, 0, (order * 2) * sizeof(*f->historybuffer));
memset(f->coeffs, 0, order * sizeof(*f->coeffs));
f->avg = 0;
}
static void init_filter(APEContext *ctx, APEFilter *f, int16_t *buf, int order)
{
do_init_filter(&f[0], buf, order);
do_init_filter(&f[1], buf + order * 3 + HISTORY_SIZE, order);
}
static void do_apply_filter(APEContext *ctx, int version, APEFilter *f,
int32_t *data, int count, int order, int fracbits)
{
int res;
int absres;
while (count--) {
/* round fixedpoint scalar product */
res = ctx->adsp.scalarproduct_and_madd_int16(f->coeffs,
f->delay - order,
f->adaptcoeffs - order,
order, APESIGN(*data));
res = (res + (1 << (fracbits - 1))) >> fracbits;
res += *data;
*data++ = res;
/* Update the output history */
*f->delay++ = av_clip_int16(res);
if (version < 3980) {
/* Version ??? to < 3.98 files (untested) */
f->adaptcoeffs[0] = (res == 0) ? 0 : ((res >> 28) & 8) - 4;
f->adaptcoeffs[-4] >>= 1;
f->adaptcoeffs[-8] >>= 1;
} else {
/* Version 3.98 and later files */
/* Update the adaption coefficients */
absres = FFABS(res);
if (absres)
*f->adaptcoeffs = APESIGN(res) *
(8 << ((absres > f->avg * 3) + (absres > f->avg * 4 / 3)));
/* equivalent to the following code
if (absres <= f->avg * 4 / 3)
*f->adaptcoeffs = APESIGN(res) * 8;
else if (absres <= f->avg * 3)
*f->adaptcoeffs = APESIGN(res) * 16;
else
*f->adaptcoeffs = APESIGN(res) * 32;
*/
else
*f->adaptcoeffs = 0;
f->avg += (absres - f->avg) / 16;
f->adaptcoeffs[-1] >>= 1;
f->adaptcoeffs[-2] >>= 1;
f->adaptcoeffs[-8] >>= 1;
}
f->adaptcoeffs++;
/* Have we filled the history buffer? */
if (f->delay == f->historybuffer + HISTORY_SIZE + (order * 2)) {
memmove(f->historybuffer, f->delay - (order * 2),
(order * 2) * sizeof(*f->historybuffer));
f->delay = f->historybuffer + order * 2;
f->adaptcoeffs = f->historybuffer + order;
}
}
}
static void apply_filter(APEContext *ctx, APEFilter *f,
int32_t *data0, int32_t *data1,
int count, int order, int fracbits)
{
do_apply_filter(ctx, ctx->fileversion, &f[0], data0, count, order, fracbits);
if (data1)
do_apply_filter(ctx, ctx->fileversion, &f[1], data1, count, order, fracbits);
}
static void ape_apply_filters(APEContext *ctx, int32_t *decoded0,
int32_t *decoded1, int count)
{
int i;
for (i = 0; i < APE_FILTER_LEVELS; i++) {
if (!ape_filter_orders[ctx->fset][i])
break;
apply_filter(ctx, ctx->filters[i], decoded0, decoded1, count,
ape_filter_orders[ctx->fset][i],
ape_filter_fracbits[ctx->fset][i]);
}
}
static int init_frame_decoder(APEContext *ctx)
{
int i, ret;
if ((ret = init_entropy_decoder(ctx)) < 0)
return ret;
init_predictor_decoder(ctx);
for (i = 0; i < APE_FILTER_LEVELS; i++) {
if (!ape_filter_orders[ctx->fset][i])
break;
init_filter(ctx, ctx->filters[i], ctx->filterbuf[i],
ape_filter_orders[ctx->fset][i]);
}
return 0;
}
static void ape_unpack_mono(APEContext *ctx, int count)
{
if (ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) {
/* We are pure silence, so we're done. */
av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence mono\n");
return;
}
ctx->entropy_decode_mono(ctx, count);
/* Now apply the predictor decoding */
ctx->predictor_decode_mono(ctx, count);
/* Pseudo-stereo - just copy left channel to right channel */
if (ctx->channels == 2) {
memcpy(ctx->decoded[1], ctx->decoded[0], count * sizeof(*ctx->decoded[1]));
}
}
static void ape_unpack_stereo(APEContext *ctx, int count)
{
int32_t left, right;
int32_t *decoded0 = ctx->decoded[0];
int32_t *decoded1 = ctx->decoded[1];
if ((ctx->frameflags & APE_FRAMECODE_STEREO_SILENCE) == APE_FRAMECODE_STEREO_SILENCE) {
/* We are pure silence, so we're done. */
av_log(ctx->avctx, AV_LOG_DEBUG, "pure silence stereo\n");
return;
}
ctx->entropy_decode_stereo(ctx, count);
/* Now apply the predictor decoding */
ctx->predictor_decode_stereo(ctx, count);
/* Decorrelate and scale to output depth */
while (count--) {
left = *decoded1 - (*decoded0 / 2);
right = left + *decoded0;
*(decoded0++) = left;
*(decoded1++) = right;
}
}
static int ape_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
AVFrame *frame = data;
const uint8_t *buf = avpkt->data;
APEContext *s = avctx->priv_data;
uint8_t *sample8;
int16_t *sample16;
int32_t *sample24;
int i, ch, ret;
int blockstodecode;
/* this should never be negative, but bad things will happen if it is, so
check it just to make sure. */
av_assert0(s->samples >= 0);
if(!s->samples){
uint32_t nblocks, offset;
int buf_size;
if (!avpkt->size) {
*got_frame_ptr = 0;
return 0;
}
if (avpkt->size < 8) {
av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
return AVERROR_INVALIDDATA;
}
buf_size = avpkt->size & ~3;
if (buf_size != avpkt->size) {
av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
"extra bytes at the end will be skipped.\n");
}
if (s->fileversion < 3950) // previous versions overread two bytes
buf_size += 2;
av_fast_padded_malloc(&s->data, &s->data_size, buf_size);
if (!s->data)
return AVERROR(ENOMEM);
s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,
buf_size >> 2);
memset(s->data + (buf_size & ~3), 0, buf_size & 3);
s->ptr = s->data;
s->data_end = s->data + buf_size;
nblocks = bytestream_get_be32(&s->ptr);
offset = bytestream_get_be32(&s->ptr);
if (s->fileversion >= 3900) {
if (offset > 3) {
av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
s->data = NULL;
return AVERROR_INVALIDDATA;
}
if (s->data_end - s->ptr < offset) {
av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
return AVERROR_INVALIDDATA;
}
s->ptr += offset;
} else {
if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0)
return ret;
if (s->fileversion > 3800)
skip_bits_long(&s->gb, offset * 8);
else
skip_bits_long(&s->gb, offset);
}
if (!nblocks || nblocks > INT_MAX) {
av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n",
nblocks);
return AVERROR_INVALIDDATA;
}
/* Initialize the frame decoder */
if (init_frame_decoder(s) < 0) {
av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
return AVERROR_INVALIDDATA;
}
s->samples = nblocks;
}
if (!s->data) {
*got_frame_ptr = 0;
return avpkt->size;
}
blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
// for old files coefficients were not interleaved,
// so we need to decode all of them at once
if (s->fileversion < 3930)
blockstodecode = s->samples;
/* reallocate decoded sample buffer if needed */
av_fast_malloc(&s->decoded_buffer, &s->decoded_size,
2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));
if (!s->decoded_buffer)
return AVERROR(ENOMEM);
memset(s->decoded_buffer, 0, s->decoded_size);
s->decoded[0] = s->decoded_buffer;
s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
/* get output buffer */
frame->nb_samples = blockstodecode;
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
s->error=0;
if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
ape_unpack_mono(s, blockstodecode);
else
ape_unpack_stereo(s, blockstodecode);
emms_c();
if (s->error) {
s->samples=0;
av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
return AVERROR_INVALIDDATA;
}
switch (s->bps) {
case 8:
for (ch = 0; ch < s->channels; ch++) {
sample8 = (uint8_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
}
break;
case 16:
for (ch = 0; ch < s->channels; ch++) {
sample16 = (int16_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample16++ = s->decoded[ch][i];
}
break;
case 24:
for (ch = 0; ch < s->channels; ch++) {
sample24 = (int32_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample24++ = s->decoded[ch][i] << 8;
}
break;
}
s->samples -= blockstodecode;
*got_frame_ptr = 1;
return !s->samples ? avpkt->size : 0;
}
static void ape_flush(AVCodecContext *avctx)
{
APEContext *s = avctx->priv_data;
s->samples= 0;
}
#define OFFSET(x) offsetof(APEContext, x)
#define PAR (AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM)
static const AVOption options[] = {
{ "max_samples", "maximum number of samples decoded per call", OFFSET(blocks_per_loop), AV_OPT_TYPE_INT, { .i64 = 4608 }, 1, INT_MAX, PAR, "max_samples" },
{ "all", "no maximum. decode all samples for each packet at once", 0, AV_OPT_TYPE_CONST, { .i64 = INT_MAX }, INT_MIN, INT_MAX, PAR, "max_samples" },
{ NULL},
};
static const AVClass ape_decoder_class = {
.class_name = "APE decoder",
.item_name = av_default_item_name,
.option = options,
.version = LIBAVUTIL_VERSION_INT,
};
AVCodec ff_ape_decoder = {
.name = "ape",
.long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
.type = AVMEDIA_TYPE_AUDIO,
.id = AV_CODEC_ID_APE,
.priv_data_size = sizeof(APEContext),
.init = ape_decode_init,
.close = ape_decode_close,
.decode = ape_decode_frame,
.capabilities = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DELAY |
AV_CODEC_CAP_DR1,
.flush = ape_flush,
.sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_U8P,
AV_SAMPLE_FMT_S16P,
AV_SAMPLE_FMT_S32P,
AV_SAMPLE_FMT_NONE },
.priv_class = &ape_decoder_class,
};
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2572_0 |
crossvul-cpp_data_good_1018_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT IIIII FFFFF FFFFF %
% T I F F %
% T I FFF FFF %
% T I F F %
% T IIIII F F %
% %
% %
% Read/Write TIFF Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#ifdef __VMS
#define JPEG_SUPPORT 1
#endif
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/channel.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/constitute.h"
#include "magick/draw.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/memory-private.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/pixel-private.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantum.h"
#include "magick/quantum-private.h"
#include "magick/resize.h"
#include "magick/resource_.h"
#include "magick/semaphore.h"
#include "magick/splay-tree.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/thread_.h"
#include "magick/token.h"
#include "magick/utility.h"
#if defined(MAGICKCORE_TIFF_DELEGATE)
# if defined(MAGICKCORE_HAVE_TIFFCONF_H)
# include <tiffconf.h>
# endif
# include <tiff.h>
# include <tiffio.h>
# if !defined(COMPRESSION_ADOBE_DEFLATE)
# define COMPRESSION_ADOBE_DEFLATE 8
# endif
# if !defined(PREDICTOR_HORIZONTAL)
# define PREDICTOR_HORIZONTAL 2
# endif
# if !defined(TIFFTAG_COPYRIGHT)
# define TIFFTAG_COPYRIGHT 33432
# endif
# if !defined(TIFFTAG_OPIIMAGEID)
# define TIFFTAG_OPIIMAGEID 32781
# endif
# if defined(COMPRESSION_ZSTD) && defined(MAGICKCORE_ZSTD_DELEGATE)
# include <zstd.h>
# endif
#include "psd-private.h"
/*
Typedef declarations.
*/
typedef enum
{
ReadSingleSampleMethod,
ReadRGBAMethod,
ReadCMYKAMethod,
ReadYCCKMethod,
ReadStripMethod,
ReadTileMethod,
ReadGenericMethod
} TIFFMethodType;
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
typedef struct _ExifInfo
{
unsigned int
tag,
type,
variable_length;
const char
*property;
} ExifInfo;
static const ExifInfo
exif_info[] = {
{ EXIFTAG_EXPOSURETIME, TIFF_RATIONAL, 0, "exif:ExposureTime" },
{ EXIFTAG_FNUMBER, TIFF_RATIONAL, 0, "exif:FNumber" },
{ EXIFTAG_EXPOSUREPROGRAM, TIFF_SHORT, 0, "exif:ExposureProgram" },
{ EXIFTAG_SPECTRALSENSITIVITY, TIFF_ASCII, 0, "exif:SpectralSensitivity" },
{ EXIFTAG_ISOSPEEDRATINGS, TIFF_SHORT, 1, "exif:ISOSpeedRatings" },
{ EXIFTAG_OECF, TIFF_NOTYPE, 0, "exif:OptoelectricConversionFactor" },
{ EXIFTAG_EXIFVERSION, TIFF_NOTYPE, 0, "exif:ExifVersion" },
{ EXIFTAG_DATETIMEORIGINAL, TIFF_ASCII, 0, "exif:DateTimeOriginal" },
{ EXIFTAG_DATETIMEDIGITIZED, TIFF_ASCII, 0, "exif:DateTimeDigitized" },
{ EXIFTAG_COMPONENTSCONFIGURATION, TIFF_NOTYPE, 0, "exif:ComponentsConfiguration" },
{ EXIFTAG_COMPRESSEDBITSPERPIXEL, TIFF_RATIONAL, 0, "exif:CompressedBitsPerPixel" },
{ EXIFTAG_SHUTTERSPEEDVALUE, TIFF_SRATIONAL, 0, "exif:ShutterSpeedValue" },
{ EXIFTAG_APERTUREVALUE, TIFF_RATIONAL, 0, "exif:ApertureValue" },
{ EXIFTAG_BRIGHTNESSVALUE, TIFF_SRATIONAL, 0, "exif:BrightnessValue" },
{ EXIFTAG_EXPOSUREBIASVALUE, TIFF_SRATIONAL, 0, "exif:ExposureBiasValue" },
{ EXIFTAG_MAXAPERTUREVALUE, TIFF_RATIONAL, 0, "exif:MaxApertureValue" },
{ EXIFTAG_SUBJECTDISTANCE, TIFF_RATIONAL, 0, "exif:SubjectDistance" },
{ EXIFTAG_METERINGMODE, TIFF_SHORT, 0, "exif:MeteringMode" },
{ EXIFTAG_LIGHTSOURCE, TIFF_SHORT, 0, "exif:LightSource" },
{ EXIFTAG_FLASH, TIFF_SHORT, 0, "exif:Flash" },
{ EXIFTAG_FOCALLENGTH, TIFF_RATIONAL, 0, "exif:FocalLength" },
{ EXIFTAG_SUBJECTAREA, TIFF_NOTYPE, 0, "exif:SubjectArea" },
{ EXIFTAG_MAKERNOTE, TIFF_NOTYPE, 0, "exif:MakerNote" },
{ EXIFTAG_USERCOMMENT, TIFF_NOTYPE, 0, "exif:UserComment" },
{ EXIFTAG_SUBSECTIME, TIFF_ASCII, 0, "exif:SubSecTime" },
{ EXIFTAG_SUBSECTIMEORIGINAL, TIFF_ASCII, 0, "exif:SubSecTimeOriginal" },
{ EXIFTAG_SUBSECTIMEDIGITIZED, TIFF_ASCII, 0, "exif:SubSecTimeDigitized" },
{ EXIFTAG_FLASHPIXVERSION, TIFF_NOTYPE, 0, "exif:FlashpixVersion" },
{ EXIFTAG_PIXELXDIMENSION, TIFF_LONG, 0, "exif:PixelXDimension" },
{ EXIFTAG_PIXELYDIMENSION, TIFF_LONG, 0, "exif:PixelYDimension" },
{ EXIFTAG_RELATEDSOUNDFILE, TIFF_ASCII, 0, "exif:RelatedSoundFile" },
{ EXIFTAG_FLASHENERGY, TIFF_RATIONAL, 0, "exif:FlashEnergy" },
{ EXIFTAG_SPATIALFREQUENCYRESPONSE, TIFF_NOTYPE, 0, "exif:SpatialFrequencyResponse" },
{ EXIFTAG_FOCALPLANEXRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneXResolution" },
{ EXIFTAG_FOCALPLANEYRESOLUTION, TIFF_RATIONAL, 0, "exif:FocalPlaneYResolution" },
{ EXIFTAG_FOCALPLANERESOLUTIONUNIT, TIFF_SHORT, 0, "exif:FocalPlaneResolutionUnit" },
{ EXIFTAG_SUBJECTLOCATION, TIFF_SHORT, 0, "exif:SubjectLocation" },
{ EXIFTAG_EXPOSUREINDEX, TIFF_RATIONAL, 0, "exif:ExposureIndex" },
{ EXIFTAG_SENSINGMETHOD, TIFF_SHORT, 0, "exif:SensingMethod" },
{ EXIFTAG_FILESOURCE, TIFF_NOTYPE, 0, "exif:FileSource" },
{ EXIFTAG_SCENETYPE, TIFF_NOTYPE, 0, "exif:SceneType" },
{ EXIFTAG_CFAPATTERN, TIFF_NOTYPE, 0, "exif:CFAPattern" },
{ EXIFTAG_CUSTOMRENDERED, TIFF_SHORT, 0, "exif:CustomRendered" },
{ EXIFTAG_EXPOSUREMODE, TIFF_SHORT, 0, "exif:ExposureMode" },
{ EXIFTAG_WHITEBALANCE, TIFF_SHORT, 0, "exif:WhiteBalance" },
{ EXIFTAG_DIGITALZOOMRATIO, TIFF_RATIONAL, 0, "exif:DigitalZoomRatio" },
{ EXIFTAG_FOCALLENGTHIN35MMFILM, TIFF_SHORT, 0, "exif:FocalLengthIn35mmFilm" },
{ EXIFTAG_SCENECAPTURETYPE, TIFF_SHORT, 0, "exif:SceneCaptureType" },
{ EXIFTAG_GAINCONTROL, TIFF_RATIONAL, 0, "exif:GainControl" },
{ EXIFTAG_CONTRAST, TIFF_SHORT, 0, "exif:Contrast" },
{ EXIFTAG_SATURATION, TIFF_SHORT, 0, "exif:Saturation" },
{ EXIFTAG_SHARPNESS, TIFF_SHORT, 0, "exif:Sharpness" },
{ EXIFTAG_DEVICESETTINGDESCRIPTION, TIFF_NOTYPE, 0, "exif:DeviceSettingDescription" },
{ EXIFTAG_SUBJECTDISTANCERANGE, TIFF_SHORT, 0, "exif:SubjectDistanceRange" },
{ EXIFTAG_IMAGEUNIQUEID, TIFF_ASCII, 0, "exif:ImageUniqueID" },
{ 0, 0, 0, (char *) NULL }
};
#endif
/*
Global declarations.
*/
static MagickThreadKey
tiff_exception;
static SemaphoreInfo
*tiff_semaphore = (SemaphoreInfo *) NULL;
static TIFFErrorHandler
error_handler,
warning_handler;
static volatile MagickBooleanType
instantiate_key = MagickFalse;
/*
Forward declarations.
*/
static Image *
ReadTIFFImage(const ImageInfo *,ExceptionInfo *);
static MagickBooleanType
WriteGROUP4Image(const ImageInfo *,Image *),
WritePTIFImage(const ImageInfo *,Image *),
WriteTIFFImage(const ImageInfo *,Image *);
static void InitPSDInfo(Image *image,Image *layer,PSDInfo *info)
{
info->version=1;
info->columns=layer->columns;
info->rows=layer->rows;
info->mode=10; /* Set mode to a value that won't change the colorspace */
/* Assume that image has matte */
if (IsGrayImage(image,&image->exception) != MagickFalse)
info->channels=2U;
else
if (image->storage_class == PseudoClass)
{
info->mode=2;
info->channels=2U;
}
else
{
if (image->colorspace != CMYKColorspace)
info->channels=4U;
else
info->channels=5U;
}
if (image->matte == MagickFalse)
info->channels--;
info->min_channels=info->channels;
if (image->matte != MagickFalse)
info->min_channels--;
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s T I F F %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsTIFF() returns MagickTrue if the image format type, identified by the
% magick string, is TIFF.
%
% The format of the IsTIFF method is:
%
% MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsTIFF(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\115\115\000\052",4) == 0)
return(MagickTrue);
if (memcmp(magick,"\111\111\052\000",4) == 0)
return(MagickTrue);
#if defined(TIFF_VERSION_BIG)
if (length < 8)
return(MagickFalse);
if (memcmp(magick,"\115\115\000\053\000\010\000\000",8) == 0)
return(MagickTrue);
if (memcmp(magick,"\111\111\053\000\010\000\000\000",8) == 0)
return(MagickTrue);
#endif
return(MagickFalse);
}
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d G R O U P 4 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadGROUP4Image() reads a raw CCITT Group 4 image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadGROUP4Image method is:
%
% Image *ReadGROUP4Image(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline size_t WriteLSBLong(FILE *file,const unsigned int value)
{
unsigned char
buffer[4];
buffer[0]=(unsigned char) value;
buffer[1]=(unsigned char) (value >> 8);
buffer[2]=(unsigned char) (value >> 16);
buffer[3]=(unsigned char) (value >> 24);
return(fwrite(buffer,1,4,file));
}
static Image *ReadGROUP4Image(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MaxTextExtent];
FILE
*file;
Image
*image;
ImageInfo
*read_info;
int
c,
unique_file;
MagickBooleanType
status;
size_t
length;
ssize_t
offset,
strip_offset;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Write raw CCITT Group 4 wrapped as a TIFF image file.
*/
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
length=fwrite("\111\111\052\000\010\000\000\000\016\000",1,10,file);
if (length != 10)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
length=fwrite("\376\000\003\000\001\000\000\000\000\000\000\000",1,12,file);
length=fwrite("\000\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->columns);
length=fwrite("\001\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->rows);
length=fwrite("\002\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
length=fwrite("\003\001\003\000\001\000\000\000\004\000\000\000",1,12,file);
length=fwrite("\006\001\003\000\001\000\000\000\000\000\000\000",1,12,file);
length=fwrite("\021\001\003\000\001\000\000\000",1,8,file);
strip_offset=10+(12*14)+4+8;
length=WriteLSBLong(file,(unsigned int) strip_offset);
length=fwrite("\022\001\003\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(unsigned int) image_info->orientation);
length=fwrite("\025\001\003\000\001\000\000\000\001\000\000\000",1,12,file);
length=fwrite("\026\001\004\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,image->rows);
length=fwrite("\027\001\004\000\001\000\000\000\000\000\000\000",1,12,file);
offset=(ssize_t) ftell(file)-4;
length=fwrite("\032\001\005\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(unsigned int) (strip_offset-8));
length=fwrite("\033\001\005\000\001\000\000\000",1,8,file);
length=WriteLSBLong(file,(unsigned int) (strip_offset-8));
length=fwrite("\050\001\003\000\001\000\000\000\002\000\000\000",1,12,file);
length=fwrite("\000\000\000\000",1,4,file);
length=WriteLSBLong(file,(unsigned int) image->x_resolution);
length=WriteLSBLong(file,1);
status=MagickTrue;
for (length=0; (c=ReadBlobByte(image)) != EOF; length++)
if (fputc(c,file) != c)
status=MagickFalse;
offset=(ssize_t) fseek(file,(ssize_t) offset,SEEK_SET);
length=WriteLSBLong(file,(unsigned int) length);
if (ferror(file) != 0)
{
(void) fclose(file);
ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
}
(void) fclose(file);
(void) CloseBlob(image);
image=DestroyImage(image);
/*
Read TIFF image.
*/
read_info=CloneImageInfo((ImageInfo *) NULL);
(void) FormatLocaleString(read_info->filename,MaxTextExtent,"%s",filename);
image=ReadTIFFImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
{
(void) CopyMagickString(image->filename,image_info->filename,
MaxTextExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MaxTextExtent);
(void) CopyMagickString(image->magick,"GROUP4",MaxTextExtent);
}
(void) RelinquishUniqueFileResource(filename);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadTIFFImage() reads a Tagged image file and returns it. It allocates the
% memory necessary for the new Image structure and returns a pointer to the
% new image.
%
% The format of the ReadTIFFImage method is:
%
% Image *ReadTIFFImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline unsigned char ClampYCC(double value)
{
value=255.0-value;
if (value < 0.0)
return((unsigned char)0);
if (value > 255.0)
return((unsigned char)255);
return((unsigned char)(value));
}
static MagickBooleanType DecodeLabImage(Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
a,
b;
a=QuantumScale*GetPixela(q)+0.5;
if (a > 1.0)
a-=1.0;
b=QuantumScale*GetPixelb(q)+0.5;
if (b > 1.0)
b-=1.0;
SetPixela(q,QuantumRange*a);
SetPixelb(q,QuantumRange*b);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
{
status=MagickFalse;
break;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
static MagickBooleanType ReadProfile(Image *image,const char *name,
const unsigned char *datum,ssize_t length)
{
MagickBooleanType
status;
StringInfo
*profile;
if (length < 4)
return(MagickFalse);
profile=BlobToStringInfo(datum,(size_t) length);
if (profile == (StringInfo *) NULL)
ThrowBinaryImageException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=SetImageProfile(image,name,profile);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
ThrowBinaryImageException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
return(MagickTrue);
}
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int TIFFCloseBlob(thandle_t image)
{
(void) CloseBlob((Image *) image);
return(0);
}
static void TIFFErrors(const char *,const char *,va_list)
magick_attribute((__format__ (__printf__,2,0)));
static void TIFFErrors(const char *module,const char *format,va_list error)
{
char
message[MaxTextExtent];
ExceptionInfo
*exception;
#if defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsnprintf(message,MaxTextExtent-2,format,error);
#else
(void) vsprintf(message,format,error);
#endif
message[MaxTextExtent-2]='\0';
(void) ConcatenateMagickString(message,".",MaxTextExtent);
exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
if (exception != (ExceptionInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,message,
"`%s'",module);
}
static toff_t TIFFGetBlobSize(thandle_t image)
{
return((toff_t) GetBlobSize((Image *) image));
}
static void TIFFGetProfiles(TIFF *tiff,Image *image)
{
uint32
length;
unsigned char
*profile;
length=0;
#if defined(TIFFTAG_ICCPROFILE)
if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"icc",profile,(ssize_t) length);
#endif
#if defined(TIFFTAG_PHOTOSHOP)
if ((TIFFGetField(tiff,TIFFTAG_PHOTOSHOP,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"8bim",profile,(ssize_t) length);
#endif
#if defined(TIFFTAG_RICHTIFFIPTC)
if ((TIFFGetField(tiff,TIFFTAG_RICHTIFFIPTC,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
{
if (TIFFIsByteSwapped(tiff) != 0)
TIFFSwabArrayOfLong((uint32 *) profile,(size_t) length);
(void) ReadProfile(image,"iptc",profile,4L*length);
}
#endif
#if defined(TIFFTAG_XMLPACKET)
if ((TIFFGetField(tiff,TIFFTAG_XMLPACKET,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"xmp",profile,(ssize_t) length);
#endif
if ((TIFFGetField(tiff,34118,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length);
if ((TIFFGetField(tiff,37724,&length,&profile) == 1) &&
(profile != (unsigned char *) NULL))
(void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length);
}
static void TIFFGetProperties(TIFF *tiff,Image *image)
{
char
message[MaxTextExtent],
*text;
uint32
count,
type;
if ((TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:artist",text);
if ((TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:copyright",text);
if ((TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:timestamp",text);
if ((TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:document",text);
if ((TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:hostcomputer",text);
if ((TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"comment",text);
if ((TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:make",text);
if ((TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:model",text);
if ((TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) &&
(text != (char *) NULL))
{
if (count >= MaxTextExtent)
count=MaxTextExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:image-id",message);
}
if ((TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"label",text);
if ((TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) &&
(text != (char *) NULL))
(void) SetImageProperty(image,"tiff:software",text);
if ((TIFFGetField(tiff,33423,&count,&text) == 1) && (text != (char *) NULL))
{
if (count >= MaxTextExtent)
count=MaxTextExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:kodak-33423",message);
}
if ((TIFFGetField(tiff,36867,&count,&text) == 1) && (text != (char *) NULL))
{
if (count >= MaxTextExtent)
count=MaxTextExtent-1;
(void) CopyMagickString(message,text,count+1);
(void) SetImageProperty(image,"tiff:kodak-36867",message);
}
if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1)
switch (type)
{
case 0x01:
{
(void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE");
break;
}
case 0x02:
{
(void) SetImageProperty(image,"tiff:subfiletype","PAGE");
break;
}
case 0x04:
{
(void) SetImageProperty(image,"tiff:subfiletype","MASK");
break;
}
default:
break;
}
}
static void TIFFGetEXIFProperties(TIFF *tiff,Image *image)
{
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
char
value[MaxTextExtent];
register ssize_t
i;
tdir_t
directory;
#if defined(TIFF_VERSION_BIG)
uint64
#else
uint32
#endif
offset;
void
*sans[2] = { NULL, NULL };
/*
Read EXIF properties.
*/
offset=0;
if (TIFFGetField(tiff,TIFFTAG_EXIFIFD,&offset) != 1)
return;
directory=TIFFCurrentDirectory(tiff);
if (TIFFReadEXIFDirectory(tiff,offset) != 1)
{
TIFFSetDirectory(tiff,directory);
return;
}
for (i=0; exif_info[i].tag != 0; i++)
{
*value='\0';
switch (exif_info[i].type)
{
case TIFF_ASCII:
{
char
*ascii;
ascii=(char *) NULL;
if ((TIFFGetField(tiff,exif_info[i].tag,&ascii,sans) == 1) &&
(ascii != (char *) NULL) && (*ascii != '\0'))
(void) CopyMagickString(value,ascii,MaxTextExtent);
break;
}
case TIFF_SHORT:
{
if (exif_info[i].variable_length == 0)
{
uint16
shorty;
shorty=0;
if (TIFFGetField(tiff,exif_info[i].tag,&shorty,sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%d",shorty);
}
else
{
int
tiff_status;
uint16
*shorty;
uint16
shorty_num;
tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty,
sans);
if (tiff_status == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%d",
shorty_num != 0 ? shorty[0] : 0);
}
break;
}
case TIFF_LONG:
{
uint32
longy;
longy=0;
if (TIFFGetField(tiff,exif_info[i].tag,&longy,sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%d",longy);
break;
}
#if defined(TIFF_VERSION_BIG)
case TIFF_LONG8:
{
uint64
long8y;
long8y=0;
if (TIFFGetField(tiff,exif_info[i].tag,&long8y,sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double)
((MagickOffsetType) long8y));
break;
}
#endif
case TIFF_RATIONAL:
case TIFF_SRATIONAL:
case TIFF_FLOAT:
{
float
floaty;
floaty=0.0;
if (TIFFGetField(tiff,exif_info[i].tag,&floaty,sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%g",(double) floaty);
break;
}
case TIFF_DOUBLE:
{
double
doubley;
doubley=0.0;
if (TIFFGetField(tiff,exif_info[i].tag,&doubley,sans) == 1)
(void) FormatLocaleString(value,MaxTextExtent,"%g",doubley);
break;
}
default:
break;
}
if (*value != '\0')
(void) SetImageProperty(image,exif_info[i].property,value);
}
TIFFSetDirectory(tiff,directory);
#else
(void) tiff;
(void) image;
#endif
}
static int TIFFMapBlob(thandle_t image,tdata_t *base,toff_t *size)
{
*base=(tdata_t *) GetBlobStreamData((Image *) image);
if (*base != (tdata_t *) NULL)
*size=(toff_t) GetBlobSize((Image *) image);
if (*base != (tdata_t *) NULL)
return(1);
return(0);
}
static tsize_t TIFFReadBlob(thandle_t image,tdata_t data,tsize_t size)
{
tsize_t
count;
count=(tsize_t) ReadBlob((Image *) image,(size_t) size,
(unsigned char *) data);
return(count);
}
static int32 TIFFReadPixels(TIFF *tiff,const tsample_t sample,const ssize_t row,
tdata_t scanline)
{
int32
status;
status=TIFFReadScanline(tiff,scanline,(uint32) row,sample);
return(status);
}
static toff_t TIFFSeekBlob(thandle_t image,toff_t offset,int whence)
{
return((toff_t) SeekBlob((Image *) image,(MagickOffsetType) offset,whence));
}
static void TIFFUnmapBlob(thandle_t image,tdata_t base,toff_t size)
{
(void) image;
(void) base;
(void) size;
}
static void TIFFWarnings(const char *,const char *,va_list)
magick_attribute((__format__ (__printf__,2,0)));
static void TIFFWarnings(const char *module,const char *format,va_list warning)
{
char
message[MaxTextExtent];
ExceptionInfo
*exception;
#if defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsnprintf(message,MaxTextExtent,format,warning);
#else
(void) vsprintf(message,format,warning);
#endif
message[MaxTextExtent-2]='\0';
(void) ConcatenateMagickString(message,".",MaxTextExtent);
exception=(ExceptionInfo *) GetMagickThreadValue(tiff_exception);
if (exception != (ExceptionInfo *) NULL)
(void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
message,"`%s'",module);
}
static tsize_t TIFFWriteBlob(thandle_t image,tdata_t data,tsize_t size)
{
tsize_t
count;
count=(tsize_t) WriteBlob((Image *) image,(size_t) size,
(unsigned char *) data);
return(count);
}
static TIFFMethodType GetJPEGMethod(Image* image,TIFF *tiff,uint16 photometric,
uint16 bits_per_sample,uint16 samples_per_pixel)
{
#define BUFFER_SIZE 2048
MagickOffsetType
position,
offset;
register size_t
i;
TIFFMethodType
method;
#if defined(TIFF_VERSION_BIG)
uint64
#else
uint32
#endif
*value;
unsigned char
buffer[BUFFER_SIZE+32];
unsigned short
length;
/*
Only support 8 bit for now.
*/
if ((photometric != PHOTOMETRIC_SEPARATED) || (bits_per_sample != 8) ||
(samples_per_pixel != 4))
return(ReadGenericMethod);
/*
Search for Adobe APP14 JPEG marker.
*/
value=NULL;
if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value) || (value == NULL))
return(ReadRGBAMethod);
position=TellBlob(image);
offset=(MagickOffsetType) (value[0]);
if (SeekBlob(image,offset,SEEK_SET) != offset)
return(ReadRGBAMethod);
method=ReadRGBAMethod;
if (ReadBlob(image,BUFFER_SIZE,buffer) == BUFFER_SIZE)
{
for (i=0; i < BUFFER_SIZE; i++)
{
while (i < BUFFER_SIZE)
{
if (buffer[i++] == 255)
break;
}
while (i < BUFFER_SIZE)
{
if (buffer[++i] != 255)
break;
}
if (buffer[i++] == 216) /* JPEG_MARKER_SOI */
continue;
length=(unsigned short) (((unsigned int) (buffer[i] << 8) |
(unsigned int) buffer[i+1]) & 0xffff);
if (i+(size_t) length >= BUFFER_SIZE)
break;
if (buffer[i-1] == 238) /* JPEG_MARKER_APP0+14 */
{
if (length != 14)
break;
/* 0 == CMYK, 1 == YCbCr, 2 = YCCK */
if (buffer[i+13] == 2)
method=ReadYCCKMethod;
break;
}
i+=(size_t) length;
}
}
(void) SeekBlob(image,position,SEEK_SET);
return(method);
}
static void TIFFReadPhotoshopLayers(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
const char
*option;
const StringInfo
*profile;
Image
*layers;
ImageInfo
*clone_info;
PSDInfo
info;
register ssize_t
i;
if (GetImageListLength(image) != 1)
return;
if ((image_info->number_scenes == 1) && (image_info->scene == 0))
return;
option=GetImageOption(image_info,"tiff:ignore-layers");
if (option != (const char * ) NULL)
return;
profile=GetImageProfile(image,"tiff:37724");
if (profile == (const StringInfo *) NULL)
return;
for (i=0; i < (ssize_t) profile->length-8; i++)
{
if (LocaleNCompare((const char *) (profile->datum+i),
image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0)
continue;
i+=4;
if ((LocaleNCompare((const char *) (profile->datum+i),
image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) ||
(LocaleNCompare((const char *) (profile->datum+i),
image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) ||
(LocaleNCompare((const char *) (profile->datum+i),
image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) ||
(LocaleNCompare((const char *) (profile->datum+i),
image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0))
break;
}
i+=4;
if (i >= (ssize_t) (profile->length-8))
return;
layers=CloneImage(image,0,0,MagickTrue,exception);
(void) DeleteImageProfile(layers,"tiff:37724");
AttachBlob(layers->blob,profile->datum,profile->length);
SeekBlob(layers,(MagickOffsetType) i,SEEK_SET);
InitPSDInfo(image, layers, &info);
clone_info=CloneImageInfo(image_info);
clone_info->number_scenes=0;
(void) ReadPSDLayers(layers,clone_info,&info,MagickFalse,exception);
clone_info=DestroyImageInfo(clone_info);
/* we need to set the datum in case a realloc happend */
((StringInfo *) profile)->datum=GetBlobStreamData(layers);
InheritException(exception,&layers->exception);
DeleteImageFromList(&layers);
if (layers != (Image *) NULL)
{
SetImageArtifact(image,"tiff:has-layers","true");
AppendImageToList(&image,layers);
while (layers != (Image *) NULL)
{
SetImageArtifact(layers,"tiff:has-layers","true");
DetachBlob(layers->blob);
layers=GetNextImageInList(layers);
}
}
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static Image *ReadTIFFImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
#define ThrowTIFFException(severity,message) \
{ \
if (tiff_pixels != (unsigned char *) NULL) \
tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels); \
if (quantum_info != (QuantumInfo *) NULL) \
quantum_info=DestroyQuantumInfo(quantum_info); \
TIFFClose(tiff); \
ThrowReaderException(severity,message); \
}
const char
*option;
float
*chromaticity,
x_position,
y_position,
x_resolution,
y_resolution;
Image
*image;
int
tiff_status;
MagickBooleanType
more_frames,
status;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
number_pixels,
pad;
ssize_t
y;
TIFF
*tiff;
TIFFMethodType
method;
uint16
compress_tag,
bits_per_sample,
endian,
extra_samples,
interlace,
max_sample_value,
min_sample_value,
orientation,
pages,
photometric,
*sample_info,
sample_format,
samples_per_pixel,
units,
value;
uint32
height,
rows_per_strip,
width;
unsigned char
*tiff_pixels;
/*
Open image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) SetMagickThreadValue(tiff_exception,exception);
tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (exception->severity > ErrorException)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (image_info->number_scenes != 0)
{
/*
Generate blank images for subimage specification (e.g. image.tif[4].
We need to check the number of directores because it is possible that
the subimage(s) are stored in the photoshop profile.
*/
if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff))
{
for (i=0; i < (ssize_t) image_info->scene; i++)
{
status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
if (status == MagickFalse)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
TIFFClose(tiff);
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
}
}
}
more_frames=MagickTrue;
do
{
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
TIFFPrintDirectory(tiff,stdout,MagickFalse);
RestoreMSCWarning
photometric=PHOTOMETRIC_RGB;
if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) ||
(TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value) != 1) ||
(TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value) != 1))
{
TIFFClose(tiff);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (((sample_format != SAMPLEFORMAT_IEEEFP) || (bits_per_sample == 64)) &&
((bits_per_sample <= 0) || (bits_per_sample > 32)))
{
TIFFClose(tiff);
ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel");
}
if (sample_format == SAMPLEFORMAT_IEEEFP)
(void) SetImageProperty(image,"quantum:format","floating-point");
switch (photometric)
{
case PHOTOMETRIC_MINISBLACK:
{
(void) SetImageProperty(image,"tiff:photometric","min-is-black");
break;
}
case PHOTOMETRIC_MINISWHITE:
{
(void) SetImageProperty(image,"tiff:photometric","min-is-white");
break;
}
case PHOTOMETRIC_PALETTE:
{
(void) SetImageProperty(image,"tiff:photometric","palette");
break;
}
case PHOTOMETRIC_RGB:
{
(void) SetImageProperty(image,"tiff:photometric","RGB");
break;
}
case PHOTOMETRIC_CIELAB:
{
(void) SetImageProperty(image,"tiff:photometric","CIELAB");
break;
}
case PHOTOMETRIC_LOGL:
{
(void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)");
break;
}
case PHOTOMETRIC_LOGLUV:
{
(void) SetImageProperty(image,"tiff:photometric","LOGLUV");
break;
}
#if defined(PHOTOMETRIC_MASK)
case PHOTOMETRIC_MASK:
{
(void) SetImageProperty(image,"tiff:photometric","MASK");
break;
}
#endif
case PHOTOMETRIC_SEPARATED:
{
(void) SetImageProperty(image,"tiff:photometric","separated");
break;
}
case PHOTOMETRIC_YCBCR:
{
(void) SetImageProperty(image,"tiff:photometric","YCBCR");
break;
}
default:
{
(void) SetImageProperty(image,"tiff:photometric","unknown");
break;
}
}
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u",
(unsigned int) width,(unsigned int) height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u",
interlace);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Bits per sample: %u",bits_per_sample);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Min sample value: %u",min_sample_value);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Max sample value: %u",max_sample_value);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric "
"interpretation: %s",GetImageProperty(image,"tiff:photometric"));
}
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=(size_t) bits_per_sample;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g",
(double) image->depth);
image->endian=MSBEndian;
if (endian == FILLORDER_LSB2MSB)
image->endian=LSBEndian;
#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN)
if (TIFFIsBigEndian(tiff) == 0)
{
(void) SetImageProperty(image,"tiff:endian","lsb");
image->endian=LSBEndian;
}
else
{
(void) SetImageProperty(image,"tiff:endian","msb");
image->endian=MSBEndian;
}
#endif
if ((photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
SetImageColorspace(image,GRAYColorspace);
if (photometric == PHOTOMETRIC_SEPARATED)
SetImageColorspace(image,CMYKColorspace);
if (photometric == PHOTOMETRIC_CIELAB)
SetImageColorspace(image,LabColorspace);
TIFFGetProfiles(tiff,image);
TIFFGetProperties(tiff,image);
option=GetImageOption(image_info,"tiff:exif-properties");
if ((option == (const char *) NULL) ||
(IsMagickTrue(option) != MagickFalse))
TIFFGetEXIFProperties(tiff,image);
if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) &&
(TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1))
{
image->x_resolution=x_resolution;
image->y_resolution=y_resolution;
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_RESOLUTIONUNIT,&units) == 1)
{
if (units == RESUNIT_INCH)
image->units=PixelsPerInchResolution;
if (units == RESUNIT_CENTIMETER)
image->units=PixelsPerCentimeterResolution;
}
if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XPOSITION,&x_position) == 1) &&
(TIFFGetFieldDefaulted(tiff,TIFFTAG_YPOSITION,&y_position) == 1))
{
image->page.x=(ssize_t) ceil(x_position*image->x_resolution-0.5);
image->page.y=(ssize_t) ceil(y_position*image->y_resolution-0.5);
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_ORIENTATION,&orientation) == 1)
image->orientation=(OrientationType) orientation;
if (TIFFGetField(tiff,TIFFTAG_WHITEPOINT,&chromaticity) == 1)
{
if (chromaticity != (float *) NULL)
{
image->chromaticity.white_point.x=chromaticity[0];
image->chromaticity.white_point.y=chromaticity[1];
}
}
if (TIFFGetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,&chromaticity) == 1)
{
if (chromaticity != (float *) NULL)
{
image->chromaticity.red_primary.x=chromaticity[0];
image->chromaticity.red_primary.y=chromaticity[1];
image->chromaticity.green_primary.x=chromaticity[2];
image->chromaticity.green_primary.y=chromaticity[3];
image->chromaticity.blue_primary.x=chromaticity[4];
image->chromaticity.blue_primary.y=chromaticity[5];
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
TIFFClose(tiff);
ThrowReaderException(CoderError,"CompressNotSupported");
}
#endif
switch (compress_tag)
{
case COMPRESSION_NONE: image->compression=NoCompression; break;
case COMPRESSION_CCITTFAX3: image->compression=FaxCompression; break;
case COMPRESSION_CCITTFAX4: image->compression=Group4Compression; break;
case COMPRESSION_JPEG:
{
image->compression=JPEGCompression;
#if defined(JPEG_SUPPORT)
{
char
sampling_factor[MaxTextExtent];
int
tiff_status;
uint16
horizontal,
vertical;
tiff_status=TIFFGetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,&horizontal,
&vertical);
if (tiff_status == 1)
{
(void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d",
horizontal,vertical);
(void) SetImageProperty(image,"jpeg:sampling-factor",
sampling_factor);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Sampling Factors: %s",sampling_factor);
}
}
#endif
break;
}
case COMPRESSION_OJPEG: image->compression=JPEGCompression; break;
#if defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA: image->compression=LZMACompression; break;
#endif
case COMPRESSION_LZW: image->compression=LZWCompression; break;
case COMPRESSION_DEFLATE: image->compression=ZipCompression; break;
case COMPRESSION_ADOBE_DEFLATE: image->compression=ZipCompression; break;
#if defined(COMPRESSION_WEBP)
case COMPRESSION_WEBP: image->compression=WebPCompression; break;
#endif
#if defined(COMPRESSION_ZSTD)
case COMPRESSION_ZSTD: image->compression=ZstdCompression; break;
#endif
default: image->compression=RLECompression; break;
}
tiff_pixels=(unsigned char *) NULL;
quantum_info=(QuantumInfo *) NULL;
if ((photometric == PHOTOMETRIC_PALETTE) &&
(pow(2.0,1.0*bits_per_sample) <= MaxColormapSize))
{
size_t
colors;
colors=(size_t) GetQuantumRange(bits_per_sample)+1;
if (AcquireImageColormap(image,colors) == MagickFalse)
{
TIFFClose(tiff);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1)
image->scene=value;
if (image->storage_class == PseudoClass)
{
int
tiff_status;
size_t
range;
uint16
*blue_colormap,
*green_colormap,
*red_colormap;
/*
Initialize colormap.
*/
tiff_status=TIFFGetField(tiff,TIFFTAG_COLORMAP,&red_colormap,
&green_colormap,&blue_colormap);
if (tiff_status == 1)
{
if ((red_colormap != (uint16 *) NULL) &&
(green_colormap != (uint16 *) NULL) &&
(blue_colormap != (uint16 *) NULL))
{
range=255; /* might be old style 8-bit colormap */
for (i=0; i < (ssize_t) image->colors; i++)
if ((red_colormap[i] >= 256) || (green_colormap[i] >= 256) ||
(blue_colormap[i] >= 256))
{
range=65535;
break;
}
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ClampToQuantum(((double)
QuantumRange*red_colormap[i])/range);
image->colormap[i].green=ClampToQuantum(((double)
QuantumRange*green_colormap[i])/range);
image->colormap[i].blue=ClampToQuantum(((double)
QuantumRange*blue_colormap[i])/range);
}
}
}
}
if (image_info->ping != MagickFalse)
{
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
goto next_tiff_frame;
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
TIFFClose(tiff);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
status=ResetImagePixels(image,exception);
if (status == MagickFalse)
{
TIFFClose(tiff);
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate memory for the image and pixel buffer.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
if (sample_format == SAMPLEFORMAT_UINT)
status=SetQuantumFormat(image,quantum_info,UnsignedQuantumFormat);
if (sample_format == SAMPLEFORMAT_INT)
status=SetQuantumFormat(image,quantum_info,SignedQuantumFormat);
if (sample_format == SAMPLEFORMAT_IEEEFP)
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
status=MagickTrue;
switch (photometric)
{
case PHOTOMETRIC_MINISBLACK:
{
quantum_info->min_is_white=MagickFalse;
break;
}
case PHOTOMETRIC_MINISWHITE:
{
quantum_info->min_is_white=MagickTrue;
break;
}
default:
break;
}
tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_EXTRASAMPLES,&extra_samples,
&sample_info);
if (tiff_status == 1)
{
(void) SetImageProperty(image,"tiff:alpha","unspecified");
if (extra_samples == 0)
{
if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB))
image->matte=MagickTrue;
}
else
for (i=0; i < extra_samples; i++)
{
image->matte=MagickTrue;
if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA)
{
SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
(void) SetImageProperty(image,"tiff:alpha","associated");
}
else
if (sample_info[i] == EXTRASAMPLE_UNASSALPHA)
{
SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha);
(void) SetImageProperty(image,"tiff:alpha","unassociated");
}
}
}
if (image->matte != MagickFalse)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel);
method=ReadGenericMethod;
rows_per_strip=(uint32) image->rows;
if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1)
{
char
value[MaxTextExtent];
method=ReadStripMethod;
(void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int)
rows_per_strip);
(void) SetImageProperty(image,"tiff:rows-per-strip",value);
}
if (rows_per_strip > (uint32) image->rows)
rows_per_strip=(uint32) image->rows;
if ((samples_per_pixel >= 3) && (interlace == PLANARCONFIG_CONTIG))
if ((image->matte == MagickFalse) || (samples_per_pixel >= 4))
method=ReadRGBAMethod;
if ((samples_per_pixel >= 4) && (interlace == PLANARCONFIG_SEPARATE))
if ((image->matte == MagickFalse) || (samples_per_pixel >= 5))
method=ReadCMYKAMethod;
if ((photometric != PHOTOMETRIC_RGB) &&
(photometric != PHOTOMETRIC_CIELAB) &&
(photometric != PHOTOMETRIC_SEPARATED))
method=ReadGenericMethod;
if (image->storage_class == PseudoClass)
method=ReadSingleSampleMethod;
if ((photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
method=ReadSingleSampleMethod;
if ((photometric != PHOTOMETRIC_SEPARATED) &&
(interlace == PLANARCONFIG_SEPARATE) && (bits_per_sample < 64))
method=ReadGenericMethod;
if (image->compression == JPEGCompression)
method=GetJPEGMethod(image,tiff,photometric,bits_per_sample,
samples_per_pixel);
if (compress_tag == COMPRESSION_JBIG)
method=ReadStripMethod;
if (TIFFIsTiled(tiff) != MagickFalse)
method=ReadTileMethod;
quantum_info->endian=LSBEndian;
quantum_type=RGBQuantum;
if (TIFFScanlineSize(tiff) <= 0)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
if (((MagickSizeType) TIFFScanlineSize(tiff)) > (2*GetBlobSize(image)))
ThrowTIFFException(CorruptImageError,"InsufficientImageDataInFile");
number_pixels=MagickMax(TIFFScanlineSize(tiff),MagickMax((ssize_t)
image->columns*samples_per_pixel*pow(2.0,ceil(log(bits_per_sample)/
log(2.0))),image->columns*rows_per_strip)*sizeof(uint32));
tiff_pixels=(unsigned char *) AcquireMagickMemory(number_pixels);
if (tiff_pixels == (unsigned char *) NULL)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(tiff_pixels,0,number_pixels);
switch (method)
{
case ReadSingleSampleMethod:
{
/*
Convert TIFF image to PseudoClass MIFF image.
*/
quantum_type=IndexQuantum;
pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0);
if (image->matte != MagickFalse)
{
if (image->storage_class != PseudoClass)
{
quantum_type=samples_per_pixel == 1 ? AlphaQuantum :
GrayAlphaQuantum;
pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0);
}
else
{
quantum_type=IndexAlphaQuantum;
pad=(size_t) MagickMax((ssize_t) samples_per_pixel-2,0);
}
}
else
if (image->storage_class != PseudoClass)
{
quantum_type=GrayQuantum;
pad=(size_t) MagickMax((ssize_t) samples_per_pixel-1,0);
}
status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log(
bits_per_sample)/log(2))));
if (status == MagickFalse)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register PixelPacket
*magick_restrict q;
status=TIFFReadPixels(tiff,0,y,(char *) tiff_pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,tiff_pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadRGBAMethod:
{
/*
Convert TIFF image to DirectClass MIFF image.
*/
pad=(size_t) MagickMax((size_t) samples_per_pixel-3,0);
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
{
quantum_type=RGBAQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
}
if (image->colorspace == CMYKColorspace)
{
pad=(size_t) MagickMax((size_t) samples_per_pixel-4,0);
quantum_type=CMYKQuantum;
if (image->matte != MagickFalse)
{
quantum_type=CMYKAQuantum;
pad=(size_t) MagickMax((size_t) samples_per_pixel-5,0);
}
}
status=SetQuantumPad(image,quantum_info,pad*((bits_per_sample+7) >> 3));
if (status == MagickFalse)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register PixelPacket
*magick_restrict q;
status=TIFFReadPixels(tiff,0,y,(char *) tiff_pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,tiff_pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadCMYKAMethod:
{
/*
Convert TIFF image to DirectClass MIFF image.
*/
for (i=0; i < (ssize_t) samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
int
status;
status=TIFFReadPixels(tiff,(tsample_t) i,y,(char *) tiff_pixels);
if (status == -1)
break;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
if (image->colorspace != CMYKColorspace)
switch (i)
{
case 0: quantum_type=RedQuantum; break;
case 1: quantum_type=GreenQuantum; break;
case 2: quantum_type=BlueQuantum; break;
case 3: quantum_type=AlphaQuantum; break;
default: quantum_type=UndefinedQuantum; break;
}
else
switch (i)
{
case 0: quantum_type=CyanQuantum; break;
case 1: quantum_type=MagentaQuantum; break;
case 2: quantum_type=YellowQuantum; break;
case 3: quantum_type=BlackQuantum; break;
case 4: quantum_type=AlphaQuantum; break;
default: quantum_type=UndefinedQuantum; break;
}
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,tiff_pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadYCCKMethod:
{
for (y=0; y < (ssize_t) image->rows; y++)
{
int
status;
register IndexPacket
*indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
unsigned char
*p;
status=TIFFReadPixels(tiff,0,y,(char *) tiff_pixels);
if (status == -1)
break;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
p=tiff_pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+
(1.402*(double) *(p+2))-179.456)));
SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p-
(0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+
135.45984)));
SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+
(1.772*(double) *(p+1))-226.816)));
SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3)));
q++;
p+=4;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadStripMethod:
{
register uint32
*p;
/*
Convert stripped TIFF image to DirectClass MIFF image.
*/
(void) SetImageStorageClass(image,DirectClass);
i=0;
p=(uint32 *) NULL;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
if (i == 0)
{
if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) tiff_pixels) == 0)
break;
i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t)
image->rows-y);
}
i--;
p=((uint32 *) tiff_pixels)+image->columns*i;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
(TIFFGetR(*p))));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
(TIFFGetG(*p))));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
(TIFFGetB(*p))));
if (image->matte == MagickFalse)
SetPixelOpacity(q,OpaqueOpacity);
else
SetPixelOpacity(q,ScaleCharToQuantum((unsigned char)
(TIFFGetA(*p))));
p++;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case ReadTileMethod:
{
register uint32
*p;
uint32
*tile_pixels,
columns,
rows;
/*
Convert tiled TIFF image to DirectClass MIFF image.
*/
if ((TIFFGetField(tiff,TIFFTAG_TILEWIDTH,&columns) != 1) ||
(TIFFGetField(tiff,TIFFTAG_TILELENGTH,&rows) != 1))
ThrowTIFFException(CoderError,"ImageIsNotTiled");
if ((AcquireMagickResource(WidthResource,columns) == MagickFalse) ||
(AcquireMagickResource(HeightResource,rows) == MagickFalse))
ThrowTIFFException(ImageError,"WidthOrHeightExceedsLimit");
(void) SetImageStorageClass(image,DirectClass);
if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
tile_pixels=(uint32 *) AcquireQuantumMemory(columns,rows*
sizeof(*tile_pixels));
if (tile_pixels == (uint32 *) NULL)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y+=rows)
{
PixelPacket
*tile;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
size_t
columns_remaining,
rows_remaining;
rows_remaining=image->rows-y;
if ((ssize_t) (y+rows) < (ssize_t) image->rows)
rows_remaining=rows;
tile=QueueAuthenticPixels(image,0,y,image->columns,rows_remaining,
exception);
if (tile == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x+=columns)
{
size_t
column,
row;
if (TIFFReadRGBATile(tiff,(uint32) x,(uint32) y,tile_pixels) == 0)
break;
columns_remaining=image->columns-x;
if ((ssize_t) (x+columns) < (ssize_t) image->columns)
columns_remaining=columns;
p=tile_pixels+(rows-rows_remaining)*columns;
q=tile+(image->columns*(rows_remaining-1)+x);
for (row=rows_remaining; row > 0; row--)
{
if (image->matte != MagickFalse)
for (column=columns_remaining; column > 0; column--)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)));
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
TIFFGetA(*p)));
q++;
p++;
}
else
for (column=columns_remaining; column > 0; column--)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
TIFFGetR(*p)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
TIFFGetG(*p)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
TIFFGetB(*p)));
SetPixelOpacity(q,OpaqueOpacity);
q++;
p++;
}
p+=columns-columns_remaining;
q-=(image->columns+columns_remaining);
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
tile_pixels=(uint32 *) RelinquishMagickMemory(tile_pixels);
break;
}
case ReadGenericMethod:
default:
{
MemoryInfo
*pixel_info;
MagickSizeType
number_pixels;
register uint32
*p;
uint32
*pixels;
/*
Convert TIFF image to DirectClass MIFF image.
*/
(void) SetImageStorageClass(image,DirectClass);
number_pixels=(MagickSizeType) image->columns*image->rows;
if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowTIFFException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(uint32 *) GetVirtualMemoryBlob(pixel_info);
(void) TIFFReadRGBAImage(tiff,(uint32) image->columns,(uint32)
image->rows,(uint32 *) pixels,0);
/*
Convert image to DirectClass pixel packets.
*/
p=pixels+number_pixels-1;
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register PixelPacket
*magick_restrict q;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
q+=image->columns-1;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p)));
if (image->matte == MagickFalse)
SetPixelOpacity(q,OpaqueOpacity);
else
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p)));
p--;
q--;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
break;
}
}
tiff_pixels=(unsigned char *) RelinquishMagickMemory(tiff_pixels);
SetQuantumImageType(image,quantum_type);
next_tiff_frame:
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (photometric == PHOTOMETRIC_CIELAB)
DecodeLabImage(image,exception);
if ((photometric == PHOTOMETRIC_LOGL) ||
(photometric == PHOTOMETRIC_MINISBLACK) ||
(photometric == PHOTOMETRIC_MINISWHITE))
{
image->type=GrayscaleType;
if (bits_per_sample == 1)
image->type=BilevelType;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
more_frames=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse;
if (more_frames != MagickFalse)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,image->scene-1,
image->scene);
if (status == MagickFalse)
break;
}
} while ((status != MagickFalse) && (more_frames != MagickFalse));
TIFFClose(tiff);
TIFFReadPhotoshopLayers(image_info,image,exception);
if ((image_info->number_scenes != 0) &&
(image_info->scene >= GetImageListLength(image)))
status=MagickFalse;
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterTIFFImage() adds properties for the TIFF image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterTIFFImage method is:
%
% size_t RegisterTIFFImage(void)
%
*/
#if defined(MAGICKCORE_TIFF_DELEGATE)
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
static TIFFExtendProc
tag_extender = (TIFFExtendProc) NULL;
static void TIFFIgnoreTags(TIFF *tiff)
{
char
*q;
const char
*p,
*tags;
Image
*image;
register ssize_t
i;
size_t
count;
TIFFFieldInfo
*ignore;
if (TIFFGetReadProc(tiff) != TIFFReadBlob)
return;
image=(Image *)TIFFClientdata(tiff);
tags=GetImageArtifact(image,"tiff:ignore-tags");
if (tags == (const char *) NULL)
return;
count=0;
p=tags;
while (*p != '\0')
{
while ((isspace((int) ((unsigned char) *p)) != 0))
p++;
(void) strtol(p,&q,10);
if (p == q)
return;
p=q;
count++;
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
p++;
}
if (count == 0)
return;
i=0;
p=tags;
ignore=(TIFFFieldInfo *) AcquireQuantumMemory(count,sizeof(*ignore));
if (ignore == (TIFFFieldInfo *) NULL)
return;
/* This also sets field_bit to 0 (FIELD_IGNORE) */
memset(ignore,0,count*sizeof(*ignore));
while (*p != '\0')
{
while ((isspace((int) ((unsigned char) *p)) != 0))
p++;
ignore[i].field_tag=(ttag_t) strtol(p,&q,10);
p=q;
i++;
while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ','))
p++;
}
(void) TIFFMergeFieldInfo(tiff,ignore,(uint32) count);
ignore=(TIFFFieldInfo *) RelinquishMagickMemory(ignore);
}
static void TIFFTagExtender(TIFF *tiff)
{
static const TIFFFieldInfo
TIFFExtensions[] =
{
{ 37724, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
(char *) "PhotoshopLayerData" },
{ 34118, -3, -3, TIFF_UNDEFINED, FIELD_CUSTOM, 1, 1,
(char *) "Microscope" }
};
TIFFMergeFieldInfo(tiff,TIFFExtensions,sizeof(TIFFExtensions)/
sizeof(*TIFFExtensions));
if (tag_extender != (TIFFExtendProc) NULL)
(*tag_extender)(tiff);
TIFFIgnoreTags(tiff);
}
#endif
#endif
ModuleExport size_t RegisterTIFFImage(void)
{
#define TIFFDescription "Tagged Image File Format"
char
version[MaxTextExtent];
MagickInfo
*entry;
#if defined(MAGICKCORE_TIFF_DELEGATE)
if (tiff_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&tiff_semaphore);
LockSemaphoreInfo(tiff_semaphore);
if (instantiate_key == MagickFalse)
{
if (CreateMagickThreadKey(&tiff_exception,NULL) == MagickFalse)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
error_handler=TIFFSetErrorHandler(TIFFErrors);
warning_handler=TIFFSetWarningHandler(TIFFWarnings);
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
if (tag_extender == (TIFFExtendProc) NULL)
tag_extender=TIFFSetTagExtender(TIFFTagExtender);
#endif
instantiate_key=MagickTrue;
}
UnlockSemaphoreInfo(tiff_semaphore);
#endif
*version='\0';
#if defined(TIFF_VERSION)
(void) FormatLocaleString(version,MaxTextExtent,"%d",TIFF_VERSION);
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
{
const char
*p;
register ssize_t
i;
p=TIFFGetVersion();
for (i=0; (i < (MaxTextExtent-1)) && (*p != 0) && (*p != '\n'); i++)
version[i]=(*p++);
version[i]='\0';
}
#endif
entry=SetMagickInfo("GROUP4");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadGROUP4Image;
entry->encoder=(EncodeImageHandler *) WriteGROUP4Image;
#endif
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->adjoin=MagickFalse;
entry->format_type=ImplicitFormatType;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Raw CCITT Group4");
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PTIF");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WritePTIFImage;
#endif
entry->endian_support=MagickTrue;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Pyramid encoded TIFF");
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TIF");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->endian_support=MagickTrue;
entry->seekable_stream=MagickTrue;
entry->stealth=MagickTrue;
entry->description=ConstantString(TIFFDescription);
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TIFF");
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->magick=(IsImageFormatHandler *) IsTIFF;
entry->endian_support=MagickTrue;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString(TIFFDescription);
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("TIFF64");
#if defined(TIFF_VERSION_BIG)
entry->decoder=(DecodeImageHandler *) ReadTIFFImage;
entry->encoder=(EncodeImageHandler *) WriteTIFFImage;
#endif
entry->adjoin=MagickFalse;
entry->endian_support=MagickTrue;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Tagged Image File Format (64-bit)");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/tiff");
entry->module=ConstantString("TIFF");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterTIFFImage() removes format registrations made by the TIFF module
% from the list of supported formats.
%
% The format of the UnregisterTIFFImage method is:
%
% UnregisterTIFFImage(void)
%
*/
ModuleExport void UnregisterTIFFImage(void)
{
(void) UnregisterMagickInfo("TIFF64");
(void) UnregisterMagickInfo("TIFF");
(void) UnregisterMagickInfo("TIF");
(void) UnregisterMagickInfo("PTIF");
#if defined(MAGICKCORE_TIFF_DELEGATE)
if (tiff_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&tiff_semaphore);
LockSemaphoreInfo(tiff_semaphore);
if (instantiate_key != MagickFalse)
{
if (DeleteMagickThreadKey(tiff_exception) == MagickFalse)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
#if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER)
if (tag_extender == (TIFFExtendProc) NULL)
(void) TIFFSetTagExtender(tag_extender);
#endif
(void) TIFFSetWarningHandler(warning_handler);
(void) TIFFSetErrorHandler(error_handler);
instantiate_key=MagickFalse;
}
UnlockSemaphoreInfo(tiff_semaphore);
DestroySemaphoreInfo(&tiff_semaphore);
#endif
}
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e G R O U P 4 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteGROUP4Image() writes an image in the raw CCITT Group 4 image format.
%
% The format of the WriteGROUP4Image method is:
%
% MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info,
Image *image)
{
char
filename[MaxTextExtent];
FILE
*file;
Image
*huffman_image;
ImageInfo
*write_info;
int
unique_file;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count;
TIFF
*tiff;
toff_t
*byte_count,
strip_size;
unsigned char
*buffer;
/*
Write image as CCITT Group4 TIFF image to a temporary file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
huffman_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (huffman_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
huffman_image->endian=MSBEndian;
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
{
ThrowFileException(&image->exception,FileOpenError,
"UnableToCreateTemporaryFile",filename);
return(MagickFalse);
}
(void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s",
filename);
(void) SetImageType(huffman_image,BilevelType);
write_info=CloneImageInfo((ImageInfo *) NULL);
SetImageInfoFile(write_info,file);
(void) SetImageDepth(image,1);
(void) SetImageType(image,BilevelType);
write_info->compression=Group4Compression;
write_info->type=BilevelType;
status=WriteTIFFImage(write_info,huffman_image);
(void) fflush(file);
write_info=DestroyImageInfo(write_info);
if (status == MagickFalse)
{
InheritException(&image->exception,&huffman_image->exception);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
return(MagickFalse);
}
tiff=TIFFOpen(filename,"rb");
if (tiff == (TIFF *) NULL)
{
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile",
image_info->filename);
return(MagickFalse);
}
/*
Allocate raw strip buffer.
*/
if (TIFFGetField(tiff,TIFFTAG_STRIPBYTECOUNTS,&byte_count) != 1)
{
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
return(MagickFalse);
}
strip_size=byte_count[0];
for (i=1; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
if (byte_count[i] > strip_size)
strip_size=byte_count[i];
buffer=(unsigned char *) AcquireQuantumMemory((size_t) strip_size,
sizeof(*buffer));
if (buffer == (unsigned char *) NULL)
{
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
ThrowBinaryImageException(ResourceLimitError,"MemoryAllocationFailed",
image_info->filename);
}
/*
Compress runlength encoded to 2D Huffman pixels.
*/
for (i=0; i < (ssize_t) TIFFNumberOfStrips(tiff); i++)
{
count=(ssize_t) TIFFReadRawStrip(tiff,(uint32) i,buffer,strip_size);
if (WriteBlob(image,(size_t) count,buffer) != count)
status=MagickFalse;
}
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
TIFFClose(tiff);
huffman_image=DestroyImage(huffman_image);
(void) fclose(file);
(void) RelinquishUniqueFileResource(filename);
(void) CloseBlob(image);
return(status);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e P T I F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WritePTIFImage() writes an image in the pyrimid-encoded Tagged image file
% format.
%
% The format of the WritePTIFImage method is:
%
% MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WritePTIFImage(const ImageInfo *image_info,
Image *image)
{
ExceptionInfo
*exception;
Image
*images,
*next,
*pyramid_image;
ImageInfo
*write_info;
MagickBooleanType
status;
PointInfo
resolution;
size_t
columns,
rows;
/*
Create pyramid-encoded TIFF image.
*/
exception=(&image->exception);
images=NewImageList();
for (next=image; next != (Image *) NULL; next=GetNextImageInList(next))
{
Image
*clone_image;
clone_image=CloneImage(next,0,0,MagickFalse,exception);
if (clone_image == (Image *) NULL)
break;
clone_image->previous=NewImageList();
clone_image->next=NewImageList();
(void) SetImageProperty(clone_image,"tiff:subfiletype","none");
AppendImageToList(&images,clone_image);
columns=next->columns;
rows=next->rows;
resolution.x=next->x_resolution;
resolution.y=next->y_resolution;
while ((columns > 64) && (rows > 64))
{
columns/=2;
rows/=2;
resolution.x/=2.0;
resolution.y/=2.0;
pyramid_image=ResizeImage(next,columns,rows,image->filter,image->blur,
exception);
if (pyramid_image == (Image *) NULL)
break;
DestroyBlob(pyramid_image);
pyramid_image->blob=ReferenceBlob(next->blob);
pyramid_image->x_resolution=resolution.x;
pyramid_image->y_resolution=resolution.y;
(void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE");
AppendImageToList(&images,pyramid_image);
}
}
status=MagickFalse;
if (images != (Image *) NULL)
{
/*
Write pyramid-encoded TIFF image.
*/
images=GetFirstImageInList(images);
write_info=CloneImageInfo(image_info);
write_info->adjoin=MagickTrue;
status=WriteTIFFImage(write_info,images);
images=DestroyImageList(images);
write_info=DestroyImageInfo(write_info);
}
return(status);
}
#endif
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% W r i t e T I F F I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteTIFFImage() writes an image in the Tagged image file format.
%
% The format of the WriteTIFFImage method is:
%
% MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: The image.
%
*/
typedef struct _TIFFInfo
{
RectangleInfo
tile_geometry;
unsigned char
*scanline,
*scanlines,
*pixels;
} TIFFInfo;
static void DestroyTIFFInfo(TIFFInfo *tiff_info)
{
assert(tiff_info != (TIFFInfo *) NULL);
if (tiff_info->scanlines != (unsigned char *) NULL)
tiff_info->scanlines=(unsigned char *) RelinquishMagickMemory(
tiff_info->scanlines);
if (tiff_info->pixels != (unsigned char *) NULL)
tiff_info->pixels=(unsigned char *) RelinquishMagickMemory(
tiff_info->pixels);
}
static MagickBooleanType EncodeLabImage(Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
status;
ssize_t
y;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
break;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
a,
b;
a=QuantumScale*GetPixela(q)-0.5;
if (a < 0.0)
a+=1.0;
b=QuantumScale*GetPixelb(q)-0.5;
if (b < 0.0)
b+=1.0;
SetPixela(q,QuantumRange*a);
SetPixelb(q,QuantumRange*b);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
{
status=MagickFalse;
break;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
static MagickBooleanType GetTIFFInfo(const ImageInfo *image_info,TIFF *tiff,
TIFFInfo *tiff_info)
{
const char
*option;
MagickStatusType
flags;
uint32
tile_columns,
tile_rows;
assert(tiff_info != (TIFFInfo *) NULL);
(void) memset(tiff_info,0,sizeof(*tiff_info));
option=GetImageOption(image_info,"tiff:tile-geometry");
if (option == (const char *) NULL)
{
uint32
rows_per_strip;
option=GetImageOption(image_info,"tiff:rows-per-strip");
if (option != (const char *) NULL)
rows_per_strip=(size_t) strtol(option,(char **) NULL,10);
else
if (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&rows_per_strip) == 0)
rows_per_strip=0; /* use default */
rows_per_strip=TIFFDefaultStripSize(tiff,rows_per_strip);
(void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip);
return(MagickTrue);
}
flags=ParseAbsoluteGeometry(option,&tiff_info->tile_geometry);
if ((flags & HeightValue) == 0)
tiff_info->tile_geometry.height=tiff_info->tile_geometry.width;
tile_columns=(uint32) tiff_info->tile_geometry.width;
tile_rows=(uint32) tiff_info->tile_geometry.height;
TIFFDefaultTileSize(tiff,&tile_columns,&tile_rows);
(void) TIFFSetField(tiff,TIFFTAG_TILEWIDTH,tile_columns);
(void) TIFFSetField(tiff,TIFFTAG_TILELENGTH,tile_rows);
tiff_info->tile_geometry.width=tile_columns;
tiff_info->tile_geometry.height=tile_rows;
if ((TIFFScanlineSize(tiff) <= 0) || (TIFFTileSize(tiff) <= 0))
{
DestroyTIFFInfo(tiff_info);
return(MagickFalse);
}
tiff_info->scanlines=(unsigned char *) AcquireQuantumMemory((size_t)
tile_rows*TIFFScanlineSize(tiff),sizeof(*tiff_info->scanlines));
tiff_info->pixels=(unsigned char *) AcquireQuantumMemory((size_t)
tile_rows*TIFFTileSize(tiff),sizeof(*tiff_info->scanlines));
if ((tiff_info->scanlines == (unsigned char *) NULL) ||
(tiff_info->pixels == (unsigned char *) NULL))
{
DestroyTIFFInfo(tiff_info);
return(MagickFalse);
}
return(MagickTrue);
}
static int32 TIFFWritePixels(TIFF *tiff,TIFFInfo *tiff_info,ssize_t row,
tsample_t sample,Image *image)
{
int32
status;
register ssize_t
i;
register unsigned char
*p,
*q;
size_t
number_tiles,
tile_width;
ssize_t
bytes_per_pixel,
j,
k,
l;
if (TIFFIsTiled(tiff) == 0)
return(TIFFWriteScanline(tiff,tiff_info->scanline,(uint32) row,sample));
/*
Fill scanlines to tile height.
*/
i=(ssize_t) (row % tiff_info->tile_geometry.height)*TIFFScanlineSize(tiff);
(void) memcpy(tiff_info->scanlines+i,(char *) tiff_info->scanline,
(size_t) TIFFScanlineSize(tiff));
if (((size_t) (row % tiff_info->tile_geometry.height) !=
(tiff_info->tile_geometry.height-1)) &&
(row != (ssize_t) (image->rows-1)))
return(0);
/*
Write tile to TIFF image.
*/
status=0;
bytes_per_pixel=TIFFTileSize(tiff)/(ssize_t) (tiff_info->tile_geometry.height*
tiff_info->tile_geometry.width);
number_tiles=(image->columns+tiff_info->tile_geometry.width)/
tiff_info->tile_geometry.width;
for (i=0; i < (ssize_t) number_tiles; i++)
{
tile_width=(i == (ssize_t) (number_tiles-1)) ? image->columns-(i*
tiff_info->tile_geometry.width) : tiff_info->tile_geometry.width;
for (j=0; j < (ssize_t) ((row % tiff_info->tile_geometry.height)+1); j++)
for (k=0; k < (ssize_t) tile_width; k++)
{
if (bytes_per_pixel == 0)
{
p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
tiff_info->tile_geometry.width+k)/8);
q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k/8);
*q++=(*p++);
continue;
}
p=tiff_info->scanlines+(j*TIFFScanlineSize(tiff)+(i*
tiff_info->tile_geometry.width+k)*bytes_per_pixel);
q=tiff_info->pixels+(j*TIFFTileRowSize(tiff)+k*bytes_per_pixel);
for (l=0; l < bytes_per_pixel; l++)
*q++=(*p++);
}
if ((i*tiff_info->tile_geometry.width) != image->columns)
status=TIFFWriteTile(tiff,tiff_info->pixels,(uint32) (i*
tiff_info->tile_geometry.width),(uint32) ((row/
tiff_info->tile_geometry.height)*tiff_info->tile_geometry.height),0,
sample);
if (status < 0)
break;
}
return(status);
}
static void TIFFSetProfiles(TIFF *tiff,Image *image)
{
const char
*name;
const StringInfo
*profile;
if (image->profiles == (void *) NULL)
return;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (GetStringInfoLength(profile) == 0)
{
name=GetNextImageProfile(image);
continue;
}
#if defined(TIFFTAG_XMLPACKET)
if (LocaleCompare(name,"xmp") == 0)
(void) TIFFSetField(tiff,TIFFTAG_XMLPACKET,(uint32) GetStringInfoLength(
profile),GetStringInfoDatum(profile));
#endif
#if defined(TIFFTAG_ICCPROFILE)
if (LocaleCompare(name,"icc") == 0)
(void) TIFFSetField(tiff,TIFFTAG_ICCPROFILE,(uint32) GetStringInfoLength(
profile),GetStringInfoDatum(profile));
#endif
if (LocaleCompare(name,"iptc") == 0)
{
size_t
length;
StringInfo
*iptc_profile;
iptc_profile=CloneStringInfo(profile);
length=GetStringInfoLength(profile)+4-(GetStringInfoLength(profile) &
0x03);
SetStringInfoLength(iptc_profile,length);
if (TIFFIsByteSwapped(tiff))
TIFFSwabArrayOfLong((uint32 *) GetStringInfoDatum(iptc_profile),
(unsigned long) (length/4));
(void) TIFFSetField(tiff,TIFFTAG_RICHTIFFIPTC,(uint32)
GetStringInfoLength(iptc_profile)/4,GetStringInfoDatum(iptc_profile));
iptc_profile=DestroyStringInfo(iptc_profile);
}
#if defined(TIFFTAG_PHOTOSHOP)
if (LocaleCompare(name,"8bim") == 0)
(void) TIFFSetField(tiff,TIFFTAG_PHOTOSHOP,(uint32)
GetStringInfoLength(profile),GetStringInfoDatum(profile));
#endif
if (LocaleCompare(name,"tiff:37724") == 0)
(void) TIFFSetField(tiff,37724,(uint32) GetStringInfoLength(profile),
GetStringInfoDatum(profile));
if (LocaleCompare(name,"tiff:34118") == 0)
(void) TIFFSetField(tiff,34118,(uint32) GetStringInfoLength(profile),
GetStringInfoDatum(profile));
name=GetNextImageProfile(image);
}
}
static void TIFFSetProperties(TIFF *tiff,const ImageInfo *image_info,
Image *image)
{
const char
*value;
value=GetImageArtifact(image,"tiff:document");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_DOCUMENTNAME,value);
value=GetImageArtifact(image,"tiff:hostcomputer");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_HOSTCOMPUTER,value);
value=GetImageArtifact(image,"tiff:artist");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_ARTIST,value);
value=GetImageArtifact(image,"tiff:timestamp");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_DATETIME,value);
value=GetImageArtifact(image,"tiff:make");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_MAKE,value);
value=GetImageArtifact(image,"tiff:model");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_MODEL,value);
value=GetImageArtifact(image,"tiff:software");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_SOFTWARE,value);
value=GetImageArtifact(image,"tiff:copyright");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_COPYRIGHT,value);
value=GetImageArtifact(image,"kodak-33423");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,33423,value);
value=GetImageArtifact(image,"kodak-36867");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,36867,value);
value=GetImageProperty(image,"label");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value);
value=GetImageProperty(image,"comment");
if (value != (const char *) NULL)
(void) TIFFSetField(tiff,TIFFTAG_IMAGEDESCRIPTION,value);
value=GetImageArtifact(image,"tiff:subfiletype");
if (value != (const char *) NULL)
{
if (LocaleCompare(value,"REDUCEDIMAGE") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
else
if (LocaleCompare(value,"PAGE") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
else
if (LocaleCompare(value,"MASK") == 0)
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_MASK);
}
else
{
uint16
page,
pages;
page=(uint16) image->scene;
pages=(uint16) GetImageListLength(image);
if ((image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
}
static void TIFFSetEXIFProperties(TIFF *tiff,Image *image)
{
#if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY)
const char
*value;
register ssize_t
i;
uint32
offset;
/*
Write EXIF properties.
*/
offset=0;
(void) TIFFSetField(tiff,TIFFTAG_SUBIFD,1,&offset);
for (i=0; exif_info[i].tag != 0; i++)
{
value=GetImageProperty(image,exif_info[i].property);
if (value == (const char *) NULL)
continue;
switch (exif_info[i].type)
{
case TIFF_ASCII:
{
(void) TIFFSetField(tiff,exif_info[i].tag,value);
break;
}
case TIFF_SHORT:
{
uint16
field;
field=(uint16) StringToLong(value);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
case TIFF_LONG:
{
uint16
field;
field=(uint16) StringToLong(value);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
case TIFF_RATIONAL:
case TIFF_SRATIONAL:
{
float
field;
field=StringToDouble(value,(char **) NULL);
(void) TIFFSetField(tiff,exif_info[i].tag,field);
break;
}
default:
break;
}
}
/* (void) TIFFSetField(tiff,TIFFTAG_EXIFIFD,offset); */
#else
(void) tiff;
(void) image;
#endif
}
static MagickBooleanType WriteTIFFImage(const ImageInfo *image_info,
Image *image)
{
const char
*mode,
*option;
CompressionType
compression;
EndianType
endian_type;
MagickBooleanType
debug,
status;
MagickOffsetType
scene;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register ssize_t
i;
size_t
imageListLength;
ssize_t
y;
TIFF
*tiff;
TIFFInfo
tiff_info;
uint16
bits_per_sample,
compress_tag,
endian,
photometric,
predictor;
unsigned char
*pixels;
/*
Open TIFF file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) SetMagickThreadValue(tiff_exception,&image->exception);
endian_type=UndefinedEndian;
option=GetImageOption(image_info,"tiff:endian");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian_type=MSBEndian;
if (LocaleNCompare(option,"lsb",3) == 0)
endian_type=LSBEndian;;
}
switch (endian_type)
{
case LSBEndian: mode="wl"; break;
case MSBEndian: mode="wb"; break;
default: mode="w"; break;
}
#if defined(TIFF_VERSION_BIG)
if (LocaleCompare(image_info->magick,"TIFF64") == 0)
switch (endian_type)
{
case LSBEndian: mode="wl8"; break;
case MSBEndian: mode="wb8"; break;
default: mode="w8"; break;
}
#endif
tiff=TIFFClientOpen(image->filename,mode,(thandle_t) image,TIFFReadBlob,
TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob,
TIFFUnmapBlob);
if (tiff == (TIFF *) NULL)
return(MagickFalse);
if (image->exception.severity > ErrorException)
{
TIFFClose(tiff);
return(MagickFalse);
}
(void) DeleteImageProfile(image,"tiff:37724");
scene=0;
debug=IsEventLogging();
(void) debug;
imageListLength=GetImageListLength(image);
do
{
/*
Initialize TIFF fields.
*/
if ((image_info->type != UndefinedType) &&
(image_info->type != OptimizeType))
(void) SetImageType(image,image_info->type);
compression=UndefinedCompression;
if (image->compression != JPEGCompression)
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
switch (compression)
{
case FaxCompression:
case Group4Compression:
{
(void) SetImageType(image,BilevelType);
(void) SetImageDepth(image,1);
break;
}
case JPEGCompression:
{
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
break;
}
default:
break;
}
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if ((image->storage_class != PseudoClass) && (image->depth >= 32) &&
(quantum_info->format == UndefinedQuantumFormat) &&
(IsHighDynamicRangeImage(image,&image->exception) != MagickFalse))
{
status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat);
if (status == MagickFalse)
{
quantum_info=DestroyQuantumInfo(quantum_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if ((LocaleCompare(image_info->magick,"PTIF") == 0) &&
(GetPreviousImageInList(image) != (Image *) NULL))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_REDUCEDIMAGE);
if ((image->columns != (uint32) image->columns) ||
(image->rows != (uint32) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
(void) TIFFSetField(tiff,TIFFTAG_IMAGELENGTH,(uint32) image->rows);
(void) TIFFSetField(tiff,TIFFTAG_IMAGEWIDTH,(uint32) image->columns);
switch (compression)
{
case FaxCompression:
{
compress_tag=COMPRESSION_CCITTFAX3;
option=GetImageOption(image_info,"quantum:polarity");
if (option == (const char *) NULL)
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
case Group4Compression:
{
compress_tag=COMPRESSION_CCITTFAX4;
option=GetImageOption(image_info,"quantum:polarity");
if (option == (const char *) NULL)
SetQuantumMinIsWhite(quantum_info,MagickTrue);
break;
}
#if defined(COMPRESSION_JBIG)
case JBIG1Compression:
{
compress_tag=COMPRESSION_JBIG;
break;
}
#endif
case JPEGCompression:
{
compress_tag=COMPRESSION_JPEG;
break;
}
#if defined(COMPRESSION_LZMA)
case LZMACompression:
{
compress_tag=COMPRESSION_LZMA;
break;
}
#endif
case LZWCompression:
{
compress_tag=COMPRESSION_LZW;
break;
}
case RLECompression:
{
compress_tag=COMPRESSION_PACKBITS;
break;
}
#if defined(COMPRESSION_WEBP)
case WebPCompression:
{
compress_tag=COMPRESSION_WEBP;
break;
}
#endif
case ZipCompression:
{
compress_tag=COMPRESSION_ADOBE_DEFLATE;
break;
}
#if defined(COMPRESSION_ZSTD)
case ZstdCompression:
{
compress_tag=COMPRESSION_ZSTD;
break;
}
#endif
case NoCompression:
default:
{
compress_tag=COMPRESSION_NONE;
break;
}
}
#if defined(MAGICKCORE_HAVE_TIFFISCODECCONFIGURED) || (TIFFLIB_VERSION > 20040919)
if ((compress_tag != COMPRESSION_NONE) &&
(TIFFIsCODECConfigured(compress_tag) == 0))
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
}
#else
switch (compress_tag)
{
#if defined(CCITT_SUPPORT)
case COMPRESSION_CCITTFAX3:
case COMPRESSION_CCITTFAX4:
#endif
#if defined(YCBCR_SUPPORT) && defined(JPEG_SUPPORT)
case COMPRESSION_JPEG:
#endif
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
#endif
#if defined(LZW_SUPPORT)
case COMPRESSION_LZW:
#endif
#if defined(PACKBITS_SUPPORT)
case COMPRESSION_PACKBITS:
#endif
#if defined(ZIP_SUPPORT)
case COMPRESSION_ADOBE_DEFLATE:
#endif
case COMPRESSION_NONE:
break;
default:
{
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic(
MagickCompressOptions,(ssize_t) compression));
compress_tag=COMPRESSION_NONE;
break;
}
}
#endif
if (image->colorspace == CMYKColorspace)
{
photometric=PHOTOMETRIC_SEPARATED;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,4);
(void) TIFFSetField(tiff,TIFFTAG_INKSET,INKSET_CMYK);
}
else
{
/*
Full color TIFF raster.
*/
if (image->colorspace == LabColorspace)
{
photometric=PHOTOMETRIC_CIELAB;
EncodeLabImage(image,&image->exception);
}
else
if (image->colorspace == YCbCrColorspace)
{
photometric=PHOTOMETRIC_YCBCR;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1);
(void) SetImageStorageClass(image,DirectClass);
(void) SetImageDepth(image,8);
}
else
photometric=PHOTOMETRIC_RGB;
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3);
if ((image_info->type != TrueColorType) &&
(image_info->type != TrueColorMatteType))
{
if ((image_info->type != PaletteType) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
photometric=(uint16) (quantum_info->min_is_white !=
MagickFalse ? PHOTOMETRIC_MINISWHITE :
PHOTOMETRIC_MINISBLACK);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
if ((image->depth == 1) && (image->matte == MagickFalse))
SetImageMonochrome(image,&image->exception);
}
else
if (image->storage_class == PseudoClass)
{
size_t
depth;
/*
Colormapped TIFF raster.
*/
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,1);
photometric=PHOTOMETRIC_PALETTE;
depth=1;
while ((GetQuantumRange(depth)+1) < image->colors)
depth<<=1;
status=SetQuantumDepth(image,quantum_info,depth);
if (status == MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian);
if ((compress_tag == COMPRESSION_CCITTFAX3) ||
(compress_tag == COMPRESSION_CCITTFAX4))
{
if ((photometric != PHOTOMETRIC_MINISWHITE) &&
(photometric != PHOTOMETRIC_MINISBLACK))
{
compress_tag=COMPRESSION_NONE;
endian=FILLORDER_MSB2LSB;
}
}
option=GetImageOption(image_info,"tiff:fill-order");
if (option != (const char *) NULL)
{
if (LocaleNCompare(option,"msb",3) == 0)
endian=FILLORDER_MSB2LSB;
if (LocaleNCompare(option,"lsb",3) == 0)
endian=FILLORDER_LSB2MSB;
}
(void) TIFFSetField(tiff,TIFFTAG_COMPRESSION,compress_tag);
(void) TIFFSetField(tiff,TIFFTAG_FILLORDER,endian);
(void) TIFFSetField(tiff,TIFFTAG_BITSPERSAMPLE,quantum_info->depth);
if (image->matte != MagickFalse)
{
uint16
extra_samples,
sample_info[1],
samples_per_pixel;
/*
TIFF has a matte channel.
*/
extra_samples=1;
sample_info[0]=EXTRASAMPLE_UNASSALPHA;
option=GetImageOption(image_info,"tiff:alpha");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"associated") == 0)
sample_info[0]=EXTRASAMPLE_ASSOCALPHA;
else
if (LocaleCompare(option,"unspecified") == 0)
sample_info[0]=EXTRASAMPLE_UNSPECIFIED;
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,
&samples_per_pixel);
(void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,samples_per_pixel+1);
(void) TIFFSetField(tiff,TIFFTAG_EXTRASAMPLES,extra_samples,
&sample_info);
if (sample_info[0] == EXTRASAMPLE_ASSOCALPHA)
SetQuantumAlphaType(quantum_info,AssociatedQuantumAlpha);
}
(void) TIFFSetField(tiff,TIFFTAG_PHOTOMETRIC,photometric);
switch (quantum_info->format)
{
case FloatingPointQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_IEEEFP);
(void) TIFFSetField(tiff,TIFFTAG_SMINSAMPLEVALUE,quantum_info->minimum);
(void) TIFFSetField(tiff,TIFFTAG_SMAXSAMPLEVALUE,quantum_info->maximum);
break;
}
case SignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_INT);
break;
}
case UnsignedQuantumFormat:
{
(void) TIFFSetField(tiff,TIFFTAG_SAMPLEFORMAT,SAMPLEFORMAT_UINT);
break;
}
default:
break;
}
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG);
if (photometric == PHOTOMETRIC_RGB)
if ((image_info->interlace == PlaneInterlace) ||
(image_info->interlace == PartitionInterlace))
(void) TIFFSetField(tiff,TIFFTAG_PLANARCONFIG,PLANARCONFIG_SEPARATE);
predictor=0;
switch (compress_tag)
{
case COMPRESSION_JPEG:
{
#if defined(JPEG_SUPPORT)
if (image_info->quality != UndefinedCompressionQuality)
(void) TIFFSetField(tiff,TIFFTAG_JPEGQUALITY,image_info->quality);
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RAW);
if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
{
const char
*value;
(void) TIFFSetField(tiff,TIFFTAG_JPEGCOLORMODE,JPEGCOLORMODE_RGB);
if (image->colorspace == YCbCrColorspace)
{
const char
*sampling_factor;
GeometryInfo
geometry_info;
MagickStatusType
flags;
sampling_factor=(const char *) NULL;
value=GetImageProperty(image,"jpeg:sampling-factor");
if (value != (char *) NULL)
{
sampling_factor=value;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Input sampling-factors=%s",sampling_factor);
}
if (image_info->sampling_factor != (char *) NULL)
sampling_factor=image_info->sampling_factor;
if (sampling_factor != (const char *) NULL)
{
flags=ParseGeometry(sampling_factor,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=geometry_info.rho;
(void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,(uint16)
geometry_info.rho,(uint16) geometry_info.sigma);
}
}
}
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (bits_per_sample == 12)
(void) TIFFSetField(tiff,TIFFTAG_JPEGTABLESMODE,JPEGTABLESMODE_QUANT);
#endif
break;
}
case COMPRESSION_ADOBE_DEFLATE:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_ZIPQUALITY,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
case COMPRESSION_CCITTFAX3:
{
/*
Byte-aligned EOL.
*/
(void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4);
break;
}
case COMPRESSION_CCITTFAX4:
break;
#if defined(LZMA_SUPPORT) && defined(COMPRESSION_LZMA)
case COMPRESSION_LZMA:
{
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_LZMAPRESET,(long) (
image_info->quality == UndefinedCompressionQuality ? 7 :
MagickMin((ssize_t) image_info->quality/10,9)));
break;
}
#endif
case COMPRESSION_LZW:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
break;
}
#if defined(WEBP_SUPPORT) && defined(COMPRESSION_WEBP)
case COMPRESSION_WEBP:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_WEBP_LEVEL,mage_info->quality);
if (image_info->quality >= 100)
(void) TIFFSetField(tiff,TIFFTAG_WEBP_LOSSLESS,1);
break;
}
#endif
#if defined(ZSTD_SUPPORT) && defined(COMPRESSION_ZSTD)
case COMPRESSION_ZSTD:
{
(void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,
&bits_per_sample);
if (((photometric == PHOTOMETRIC_RGB) ||
(photometric == PHOTOMETRIC_SEPARATED) ||
(photometric == PHOTOMETRIC_MINISBLACK)) &&
((bits_per_sample == 8) || (bits_per_sample == 16)))
predictor=PREDICTOR_HORIZONTAL;
(void) TIFFSetField(tiff,TIFFTAG_ZSTD_LEVEL,22*image_info->quality/
100.0);
break;
}
#endif
default:
break;
}
option=GetImageOption(image_info,"tiff:predictor");
if (option != (const char * ) NULL)
predictor=(size_t) strtol(option,(char **) NULL,10);
if (predictor != 0)
(void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,predictor);
if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0))
{
unsigned short
units;
/*
Set image resolution.
*/
units=RESUNIT_NONE;
if (image->units == PixelsPerInchResolution)
units=RESUNIT_INCH;
if (image->units == PixelsPerCentimeterResolution)
units=RESUNIT_CENTIMETER;
(void) TIFFSetField(tiff,TIFFTAG_RESOLUTIONUNIT,(uint16) units);
(void) TIFFSetField(tiff,TIFFTAG_XRESOLUTION,image->x_resolution);
(void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution);
if ((image->page.x < 0) || (image->page.y < 0))
(void) ThrowMagickException(&image->exception,GetMagickModule(),
CoderError,"TIFF: negative image positions unsupported","%s",
image->filename);
if ((image->page.x > 0) && (image->x_resolution > 0.0))
{
/*
Set horizontal image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/
image->x_resolution);
}
if ((image->page.y > 0) && (image->y_resolution > 0.0))
{
/*
Set vertical image position.
*/
(void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/
image->y_resolution);
}
}
if (image->chromaticity.white_point.x != 0.0)
{
float
chromaticity[6];
/*
Set image chromaticity.
*/
chromaticity[0]=(float) image->chromaticity.red_primary.x;
chromaticity[1]=(float) image->chromaticity.red_primary.y;
chromaticity[2]=(float) image->chromaticity.green_primary.x;
chromaticity[3]=(float) image->chromaticity.green_primary.y;
chromaticity[4]=(float) image->chromaticity.blue_primary.x;
chromaticity[5]=(float) image->chromaticity.blue_primary.y;
(void) TIFFSetField(tiff,TIFFTAG_PRIMARYCHROMATICITIES,chromaticity);
chromaticity[0]=(float) image->chromaticity.white_point.x;
chromaticity[1]=(float) image->chromaticity.white_point.y;
(void) TIFFSetField(tiff,TIFFTAG_WHITEPOINT,chromaticity);
}
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (imageListLength > 1))
{
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
if (image->scene != 0)
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene,
imageListLength);
}
if (image->orientation != UndefinedOrientation)
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation);
else
(void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT);
(void) TIFFSetProfiles(tiff,image);
{
uint16
page,
pages;
page=(uint16) scene;
pages=(uint16) imageListLength;
if ((LocaleCompare(image_info->magick,"PTIF") != 0) &&
(image_info->adjoin != MagickFalse) && (pages > 1))
(void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE);
(void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages);
}
(void) TIFFSetProperties(tiff,image_info,image);
DisableMSCWarning(4127)
if (0)
RestoreMSCWarning
(void) TIFFSetEXIFProperties(tiff,image);
/*
Write image scanlines.
*/
if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
quantum_info->endian=LSBEndian;
pixels=GetQuantumPixels(quantum_info);
tiff_info.scanline=GetQuantumPixels(quantum_info);
switch (photometric)
{
case PHOTOMETRIC_CIELAB:
case PHOTOMETRIC_YCBCR:
case PHOTOMETRIC_RGB:
{
/*
RGB TIFF image.
*/
switch (image_info->interlace)
{
case NoInterlace:
default:
{
quantum_type=RGBQuantum;
if (image->matte != MagickFalse)
quantum_type=RGBAQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PlaneInterlace:
case PartitionInterlace:
{
/*
Plane interlacing: RRRRRR...GGGGGG...BBBBBB...
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,RedQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,100,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,GreenQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,1,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,200,400);
if (status == MagickFalse)
break;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,BlueQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,2,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,300,400);
if (status == MagickFalse)
break;
}
if (image->matte != MagickFalse)
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,
&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,AlphaQuantum,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,3,image) == -1)
break;
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,400,400);
if (status == MagickFalse)
break;
}
break;
}
}
break;
}
case PHOTOMETRIC_SEPARATED:
{
/*
CMYK TIFF image.
*/
quantum_type=CMYKQuantum;
if (image->matte != MagickFalse)
quantum_type=CMYKAQuantum;
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
case PHOTOMETRIC_PALETTE:
{
uint16
*blue,
*green,
*red;
/*
Colormapped TIFF image.
*/
red=(uint16 *) AcquireQuantumMemory(65536,sizeof(*red));
green=(uint16 *) AcquireQuantumMemory(65536,sizeof(*green));
blue=(uint16 *) AcquireQuantumMemory(65536,sizeof(*blue));
if ((red == (uint16 *) NULL) || (green == (uint16 *) NULL) ||
(blue == (uint16 *) NULL))
{
if (red != (uint16 *) NULL)
red=(uint16 *) RelinquishMagickMemory(red);
if (green != (uint16 *) NULL)
green=(uint16 *) RelinquishMagickMemory(green);
if (blue != (uint16 *) NULL)
blue=(uint16 *) RelinquishMagickMemory(blue);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Initialize TIFF colormap.
*/
(void) memset(red,0,65536*sizeof(*red));
(void) memset(green,0,65536*sizeof(*green));
(void) memset(blue,0,65536*sizeof(*blue));
for (i=0; i < (ssize_t) image->colors; i++)
{
red[i]=ScaleQuantumToShort(image->colormap[i].red);
green[i]=ScaleQuantumToShort(image->colormap[i].green);
blue[i]=ScaleQuantumToShort(image->colormap[i].blue);
}
(void) TIFFSetField(tiff,TIFFTAG_COLORMAP,red,green,blue);
red=(uint16 *) RelinquishMagickMemory(red);
green=(uint16 *) RelinquishMagickMemory(green);
blue=(uint16 *) RelinquishMagickMemory(blue);
}
default:
{
/*
Convert PseudoClass packets to contiguous grayscale scanlines.
*/
quantum_type=IndexQuantum;
if (image->matte != MagickFalse)
{
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayAlphaQuantum;
else
quantum_type=IndexAlphaQuantum;
}
else
if (photometric != PHOTOMETRIC_PALETTE)
quantum_type=GrayQuantum;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
(void) ExportQuantumPixels(image,(const CacheView *) NULL,
quantum_info,quantum_type,pixels,&image->exception);
if (TIFFWritePixels(tiff,&tiff_info,y,0,image) == -1)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
break;
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
if (image->colorspace == LabColorspace)
DecodeLabImage(image,&image->exception);
DestroyTIFFInfo(&tiff_info);
DisableMSCWarning(4127)
if (0 && (image_info->verbose != MagickFalse))
RestoreMSCWarning
TIFFPrintDirectory(tiff,stdout,MagickFalse);
if (TIFFWriteDirectory(tiff) == 0)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
if (image == (Image *) NULL)
break;
status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
TIFFClose(tiff);
return(status);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1018_0 |
crossvul-cpp_data_bad_2713_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997
* 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: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IP printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ip.h"
#include "ipproto.h"
static const char tstr[] = "[|ip]";
static const struct tok ip_option_values[] = {
{ IPOPT_EOL, "EOL" },
{ IPOPT_NOP, "NOP" },
{ IPOPT_TS, "timestamp" },
{ IPOPT_SECURITY, "security" },
{ IPOPT_RR, "RR" },
{ IPOPT_SSRR, "SSRR" },
{ IPOPT_LSRR, "LSRR" },
{ IPOPT_RA, "RA" },
{ IPOPT_RFC1393, "traceroute" },
{ 0, NULL }
};
/*
* print the recorded route in an IP RR, LSRR or SSRR option.
*/
static int
ip_printroute(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int ptr;
register u_int len;
if (length < 3) {
ND_PRINT((ndo, " [bad length %u]", length));
return (0);
}
if ((length + 1) & 3)
ND_PRINT((ndo, " [bad length %u]", length));
ND_TCHECK(cp[2]);
ptr = cp[2] - 1;
if (ptr < 3 || ((ptr + 1) & 3) || ptr > length + 1)
ND_PRINT((ndo, " [bad ptr %u]", cp[2]));
for (len = 3; len < length; len += 4) {
ND_TCHECK2(cp[len], 4);
ND_PRINT((ndo, " %s", ipaddr_string(ndo, &cp[len])));
if (ptr > len)
ND_PRINT((ndo, ","));
}
return (0);
trunc:
return (-1);
}
/*
* If source-routing is present and valid, return the final destination.
* Otherwise, return IP destination.
*
* This is used for UDP and TCP pseudo-header in the checksum
* calculation.
*/
static uint32_t
ip_finddst(netdissect_options *ndo,
const struct ip *ip)
{
int length;
int len;
const u_char *cp;
uint32_t retval;
cp = (const u_char *)(ip + 1);
length = (IP_HL(ip) << 2) - sizeof(struct ip);
for (; length > 0; cp += len, length -= len) {
int tt;
ND_TCHECK(*cp);
tt = *cp;
if (tt == IPOPT_EOL)
break;
else if (tt == IPOPT_NOP)
len = 1;
else {
ND_TCHECK(cp[1]);
len = cp[1];
if (len < 2)
break;
}
ND_TCHECK2(*cp, len);
switch (tt) {
case IPOPT_SSRR:
case IPOPT_LSRR:
if (len < 7)
break;
UNALIGNED_MEMCPY(&retval, cp + len - 4, 4);
return retval;
}
}
trunc:
UNALIGNED_MEMCPY(&retval, &ip->ip_dst, sizeof(uint32_t));
return retval;
}
/*
* Compute a V4-style checksum by building a pseudoheader.
*/
int
nextproto4_cksum(netdissect_options *ndo,
const struct ip *ip, const uint8_t *data,
u_int len, u_int covlen, u_int next_proto)
{
struct phdr {
uint32_t src;
uint32_t dst;
u_char mbz;
u_char proto;
uint16_t len;
} ph;
struct cksum_vec vec[2];
/* pseudo-header.. */
ph.len = htons((uint16_t)len);
ph.mbz = 0;
ph.proto = next_proto;
UNALIGNED_MEMCPY(&ph.src, &ip->ip_src, sizeof(uint32_t));
if (IP_HL(ip) == 5)
UNALIGNED_MEMCPY(&ph.dst, &ip->ip_dst, sizeof(uint32_t));
else
ph.dst = ip_finddst(ndo, ip);
vec[0].ptr = (const uint8_t *)(void *)&ph;
vec[0].len = sizeof(ph);
vec[1].ptr = data;
vec[1].len = covlen;
return (in_cksum(vec, 2));
}
static void
ip_printts(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int ptr;
register u_int len;
int hoplen;
const char *type;
if (length < 4) {
ND_PRINT((ndo, "[bad length %u]", length));
return;
}
ND_PRINT((ndo, " TS{"));
hoplen = ((cp[3]&0xF) != IPOPT_TS_TSONLY) ? 8 : 4;
if ((length - 4) & (hoplen-1))
ND_PRINT((ndo, "[bad length %u]", length));
ptr = cp[2] - 1;
len = 0;
if (ptr < 4 || ((ptr - 4) & (hoplen-1)) || ptr > length + 1)
ND_PRINT((ndo, "[bad ptr %u]", cp[2]));
switch (cp[3]&0xF) {
case IPOPT_TS_TSONLY:
ND_PRINT((ndo, "TSONLY"));
break;
case IPOPT_TS_TSANDADDR:
ND_PRINT((ndo, "TS+ADDR"));
break;
/*
* prespecified should really be 3, but some ones might send 2
* instead, and the IPOPT_TS_PRESPEC constant can apparently
* have both values, so we have to hard-code it here.
*/
case 2:
ND_PRINT((ndo, "PRESPEC2.0"));
break;
case 3: /* IPOPT_TS_PRESPEC */
ND_PRINT((ndo, "PRESPEC"));
break;
default:
ND_PRINT((ndo, "[bad ts type %d]", cp[3]&0xF));
goto done;
}
type = " ";
for (len = 4; len < length; len += hoplen) {
if (ptr == len)
type = " ^ ";
ND_PRINT((ndo, "%s%d@%s", type, EXTRACT_32BITS(&cp[len+hoplen-4]),
hoplen!=8 ? "" : ipaddr_string(ndo, &cp[len])));
type = " ";
}
done:
ND_PRINT((ndo, "%s", ptr == len ? " ^ " : ""));
if (cp[3]>>4)
ND_PRINT((ndo, " [%d hops not recorded]} ", cp[3]>>4));
else
ND_PRINT((ndo, "}"));
}
/*
* print IP options.
*/
static void
ip_optprint(netdissect_options *ndo,
register const u_char *cp, u_int length)
{
register u_int option_len;
const char *sep = "";
for (; length > 0; cp += option_len, length -= option_len) {
u_int option_code;
ND_PRINT((ndo, "%s", sep));
sep = ",";
ND_TCHECK(*cp);
option_code = *cp;
ND_PRINT((ndo, "%s",
tok2str(ip_option_values,"unknown %u",option_code)));
if (option_code == IPOPT_NOP ||
option_code == IPOPT_EOL)
option_len = 1;
else {
ND_TCHECK(cp[1]);
option_len = cp[1];
if (option_len < 2) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
}
if (option_len > length) {
ND_PRINT((ndo, " [bad length %u]", option_len));
return;
}
ND_TCHECK2(*cp, option_len);
switch (option_code) {
case IPOPT_EOL:
return;
case IPOPT_TS:
ip_printts(ndo, cp, option_len);
break;
case IPOPT_RR: /* fall through */
case IPOPT_SSRR:
case IPOPT_LSRR:
if (ip_printroute(ndo, cp, option_len) == -1)
goto trunc;
break;
case IPOPT_RA:
if (option_len < 4) {
ND_PRINT((ndo, " [bad length %u]", option_len));
break;
}
ND_TCHECK(cp[3]);
if (EXTRACT_16BITS(&cp[2]) != 0)
ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2])));
break;
case IPOPT_NOP: /* nothing to print - fall through */
case IPOPT_SECURITY:
default:
break;
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
#define IP_RES 0x8000
static const struct tok ip_frag_values[] = {
{ IP_MF, "+" },
{ IP_DF, "DF" },
{ IP_RES, "rsvd" }, /* The RFC3514 evil ;-) bit */
{ 0, NULL }
};
struct ip_print_demux_state {
const struct ip *ip;
const u_char *cp;
u_int len, off;
u_char nh;
int advance;
};
static void
ip_print_demux(netdissect_options *ndo,
struct ip_print_demux_state *ipds)
{
const char *p_name;
again:
switch (ipds->nh) {
case IPPROTO_AH:
if (!ND_TTEST(*ipds->cp)) {
ND_PRINT((ndo, "[|AH]"));
break;
}
ipds->nh = *ipds->cp;
ipds->advance = ah_print(ndo, ipds->cp);
if (ipds->advance <= 0)
break;
ipds->cp += ipds->advance;
ipds->len -= ipds->advance;
goto again;
case IPPROTO_ESP:
{
int enh, padlen;
ipds->advance = esp_print(ndo, ipds->cp, ipds->len,
(const u_char *)ipds->ip,
&enh, &padlen);
if (ipds->advance <= 0)
break;
ipds->cp += ipds->advance;
ipds->len -= ipds->advance + padlen;
ipds->nh = enh & 0xff;
goto again;
}
case IPPROTO_IPCOMP:
{
ipcomp_print(ndo, ipds->cp);
/*
* Either this has decompressed the payload and
* printed it, in which case there's nothing more
* to do, or it hasn't, in which case there's
* nothing more to do.
*/
break;
}
case IPPROTO_SCTP:
sctp_print(ndo, ipds->cp, (const u_char *)ipds->ip, ipds->len);
break;
case IPPROTO_DCCP:
dccp_print(ndo, ipds->cp, (const u_char *)ipds->ip, ipds->len);
break;
case IPPROTO_TCP:
/* pass on the MF bit plus the offset to detect fragments */
tcp_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip,
ipds->off & (IP_MF|IP_OFFMASK));
break;
case IPPROTO_UDP:
/* pass on the MF bit plus the offset to detect fragments */
udp_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip,
ipds->off & (IP_MF|IP_OFFMASK));
break;
case IPPROTO_ICMP:
/* pass on the MF bit plus the offset to detect fragments */
icmp_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip,
ipds->off & (IP_MF|IP_OFFMASK));
break;
case IPPROTO_PIGP:
/*
* XXX - the current IANA protocol number assignments
* page lists 9 as "any private interior gateway
* (used by Cisco for their IGRP)" and 88 as
* "EIGRP" from Cisco.
*
* Recent BSD <netinet/in.h> headers define
* IP_PROTO_PIGP as 9 and IP_PROTO_IGRP as 88.
* We define IP_PROTO_PIGP as 9 and
* IP_PROTO_EIGRP as 88; those names better
* match was the current protocol number
* assignments say.
*/
igrp_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_EIGRP:
eigrp_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_ND:
ND_PRINT((ndo, " nd %d", ipds->len));
break;
case IPPROTO_EGP:
egp_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_OSPF:
ospf_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip);
break;
case IPPROTO_IGMP:
igmp_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_IPV4:
/* DVMRP multicast tunnel (ip-in-ip encapsulation) */
ip_print(ndo, ipds->cp, ipds->len);
if (! ndo->ndo_vflag) {
ND_PRINT((ndo, " (ipip-proto-4)"));
return;
}
break;
case IPPROTO_IPV6:
/* ip6-in-ip encapsulation */
ip6_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_RSVP:
rsvp_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_GRE:
/* do it */
gre_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_MOBILE:
mobile_print(ndo, ipds->cp, ipds->len);
break;
case IPPROTO_PIM:
pim_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip);
break;
case IPPROTO_VRRP:
if (ndo->ndo_packettype == PT_CARP) {
if (ndo->ndo_vflag)
ND_PRINT((ndo, "carp %s > %s: ",
ipaddr_string(ndo, &ipds->ip->ip_src),
ipaddr_string(ndo, &ipds->ip->ip_dst)));
carp_print(ndo, ipds->cp, ipds->len, ipds->ip->ip_ttl);
} else {
if (ndo->ndo_vflag)
ND_PRINT((ndo, "vrrp %s > %s: ",
ipaddr_string(ndo, &ipds->ip->ip_src),
ipaddr_string(ndo, &ipds->ip->ip_dst)));
vrrp_print(ndo, ipds->cp, ipds->len,
(const u_char *)ipds->ip, ipds->ip->ip_ttl);
}
break;
case IPPROTO_PGM:
pgm_print(ndo, ipds->cp, ipds->len, (const u_char *)ipds->ip);
break;
default:
if (ndo->ndo_nflag==0 && (p_name = netdb_protoname(ipds->nh)) != NULL)
ND_PRINT((ndo, " %s", p_name));
else
ND_PRINT((ndo, " ip-proto-%d", ipds->nh));
ND_PRINT((ndo, " %d", ipds->len));
break;
}
}
void
ip_print_inner(netdissect_options *ndo,
const u_char *bp,
u_int length, u_int nh,
const u_char *bp2)
{
struct ip_print_demux_state ipd;
ipd.ip = (const struct ip *)bp2;
ipd.cp = bp;
ipd.len = length;
ipd.off = 0;
ipd.nh = nh;
ipd.advance = 0;
ip_print_demux(ndo, &ipd);
}
/*
* print an IP datagram.
*/
void
ip_print(netdissect_options *ndo,
const u_char *bp,
u_int length)
{
struct ip_print_demux_state ipd;
struct ip_print_demux_state *ipds=&ipd;
const u_char *ipend;
u_int hlen;
struct cksum_vec vec[1];
uint16_t sum, ip_sum;
const char *p_name;
ipds->ip = (const struct ip *)bp;
ND_TCHECK(ipds->ip->ip_vhl);
if (IP_V(ipds->ip) != 4) { /* print version and fail if != 4 */
if (IP_V(ipds->ip) == 6)
ND_PRINT((ndo, "IP6, wrong link-layer encapsulation "));
else
ND_PRINT((ndo, "IP%u ", IP_V(ipds->ip)));
return;
}
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "IP "));
ND_TCHECK(*ipds->ip);
if (length < sizeof (struct ip)) {
ND_PRINT((ndo, "truncated-ip %u", length));
return;
}
hlen = IP_HL(ipds->ip) * 4;
if (hlen < sizeof (struct ip)) {
ND_PRINT((ndo, "bad-hlen %u", hlen));
return;
}
ipds->len = EXTRACT_16BITS(&ipds->ip->ip_len);
if (length < ipds->len)
ND_PRINT((ndo, "truncated-ip - %u bytes missing! ",
ipds->len - length));
if (ipds->len < hlen) {
#ifdef GUESS_TSO
if (ipds->len) {
ND_PRINT((ndo, "bad-len %u", ipds->len));
return;
}
else {
/* we guess that it is a TSO send */
ipds->len = length;
}
#else
ND_PRINT((ndo, "bad-len %u", ipds->len));
return;
#endif /* GUESS_TSO */
}
/*
* Cut off the snapshot length to the end of the IP payload.
*/
ipend = bp + ipds->len;
if (ipend < ndo->ndo_snapend)
ndo->ndo_snapend = ipend;
ipds->len -= hlen;
ipds->off = EXTRACT_16BITS(&ipds->ip->ip_off);
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "(tos 0x%x", (int)ipds->ip->ip_tos));
/* ECN bits */
switch (ipds->ip->ip_tos & 0x03) {
case 0:
break;
case 1:
ND_PRINT((ndo, ",ECT(1)"));
break;
case 2:
ND_PRINT((ndo, ",ECT(0)"));
break;
case 3:
ND_PRINT((ndo, ",CE"));
break;
}
if (ipds->ip->ip_ttl >= 1)
ND_PRINT((ndo, ", ttl %u", ipds->ip->ip_ttl));
/*
* for the firewall guys, print id, offset.
* On all but the last stick a "+" in the flags portion.
* For unfragmented datagrams, note the don't fragment flag.
*/
ND_PRINT((ndo, ", id %u, offset %u, flags [%s], proto %s (%u)",
EXTRACT_16BITS(&ipds->ip->ip_id),
(ipds->off & 0x1fff) * 8,
bittok2str(ip_frag_values, "none", ipds->off&0xe000),
tok2str(ipproto_values,"unknown",ipds->ip->ip_p),
ipds->ip->ip_p));
ND_PRINT((ndo, ", length %u", EXTRACT_16BITS(&ipds->ip->ip_len)));
if ((hlen - sizeof(struct ip)) > 0) {
ND_PRINT((ndo, ", options ("));
ip_optprint(ndo, (const u_char *)(ipds->ip + 1), hlen - sizeof(struct ip));
ND_PRINT((ndo, ")"));
}
if (!ndo->ndo_Kflag && (const u_char *)ipds->ip + hlen <= ndo->ndo_snapend) {
vec[0].ptr = (const uint8_t *)(const void *)ipds->ip;
vec[0].len = hlen;
sum = in_cksum(vec, 1);
if (sum != 0) {
ip_sum = EXTRACT_16BITS(&ipds->ip->ip_sum);
ND_PRINT((ndo, ", bad cksum %x (->%x)!", ip_sum,
in_cksum_shouldbe(ip_sum, sum)));
}
}
ND_PRINT((ndo, ")\n "));
}
/*
* If this is fragment zero, hand it to the next higher
* level protocol.
*/
if ((ipds->off & 0x1fff) == 0) {
ipds->cp = (const u_char *)ipds->ip + hlen;
ipds->nh = ipds->ip->ip_p;
if (ipds->nh != IPPROTO_TCP && ipds->nh != IPPROTO_UDP &&
ipds->nh != IPPROTO_SCTP && ipds->nh != IPPROTO_DCCP) {
ND_PRINT((ndo, "%s > %s: ",
ipaddr_string(ndo, &ipds->ip->ip_src),
ipaddr_string(ndo, &ipds->ip->ip_dst)));
}
ip_print_demux(ndo, ipds);
} else {
/*
* Ultra quiet now means that all this stuff should be
* suppressed.
*/
if (ndo->ndo_qflag > 1)
return;
/*
* This isn't the first frag, so we're missing the
* next level protocol header. print the ip addr
* and the protocol.
*/
ND_PRINT((ndo, "%s > %s:", ipaddr_string(ndo, &ipds->ip->ip_src),
ipaddr_string(ndo, &ipds->ip->ip_dst)));
if (!ndo->ndo_nflag && (p_name = netdb_protoname(ipds->ip->ip_p)) != NULL)
ND_PRINT((ndo, " %s", p_name));
else
ND_PRINT((ndo, " ip-proto-%d", ipds->ip->ip_p));
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
return;
}
void
ipN_print(netdissect_options *ndo, register const u_char *bp, register u_int length)
{
if (length < 1) {
ND_PRINT((ndo, "truncated-ip %d", length));
return;
}
ND_TCHECK(*bp);
switch (*bp & 0xF0) {
case 0x40:
ip_print (ndo, bp, length);
break;
case 0x60:
ip6_print (ndo, bp, length);
break;
default:
ND_PRINT((ndo, "unknown ip %d", (*bp & 0xF0) >> 4));
break;
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
return;
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2713_0 |
crossvul-cpp_data_good_3190_0 | /*
etterfilter -- the actual compiler
Copyright (C) ALoR & NaGA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <ef.h>
#include <ef_functions.h>
/* ef_globals */
/*
* the compiler works this way:
*
* while bison parses the input it calls the function to
* create temporary lists of "blocks". a block is a compound
* of virtual instruction. every block element can contain a
* single instruction or a if block.
* the if block contains a link to the conditions list and two
* link for the two block to be executed if the condition is
* true or the else block (if any).
*
* so, after bison has finished its parsing we have a tree of
* virtual instructions like that:
*
* -----------
* | tree root |
* -----------
* |
* ----------- -------------
* | block elm | --> | instruction |
* ----------- -------------
* |
* ----------- -------------
* | block elm | --> | instruction |
* ----------- -------------
* |
* ----------- ------------- ------------
* | block elm | --> | if block | --> | conditions |
* ----------- ------------- ------------
* . / \
* . ----------- -----------
* . | block elm | | block elm | . . .
* ----------- -----------
* . .
* . .
*
* to create a binary filter we have to unfold the tree by converting
* the conditions into test, eliminating the virtual if block and
* create the right conditional jumps.
* during the first unfolding the jumps are referencing virtual labels.
* all the instructions are unfolded in a double-linked list.
*
* the last phase involves the tanslation of the labels into real offsets
*/
static struct block *tree_root;
struct unfold_elm {
u_int32 label;
struct filter_op fop;
TAILQ_ENTRY (unfold_elm) next;
};
static TAILQ_HEAD(, unfold_elm) unfolded_tree = TAILQ_HEAD_INITIALIZER(unfolded_tree);
/* label = 0 means "no label" */
static u_int32 vlabel = 1;
/* protos */
static void unfold_blk(struct block **blk);
static void unfold_ifblk(struct block **blk);
static void unfold_conds(struct condition *cnd, u_int32 a, u_int32 b);
static void labels_to_offsets(void);
/*******************************************/
/*
* set the entry point of the filter tree
*/
int compiler_set_root(struct block *blk)
{
BUG_IF(blk == NULL);
tree_root = blk;
return E_SUCCESS;
}
/*
* allocate an instruction container for filter_op
*/
struct instruction * compiler_create_instruction(struct filter_op *fop)
{
struct instruction *ins;
SAFE_CALLOC(ins, 1, sizeof(struct instruction));
/* copy the instruction */
memcpy(&ins->fop, fop, sizeof(struct filter_op));
return ins;
}
/*
* allocate a condition container for filter_op
*/
struct condition * compiler_create_condition(struct filter_op *fop)
{
struct condition *cnd;
SAFE_CALLOC(cnd, 1, sizeof(struct condition));
/* copy the instruction */
memcpy(&cnd->fop, fop, sizeof(struct filter_op));
return cnd;
}
/*
* concatenates two conditions with a logical operator
*/
struct condition * compiler_concat_conditions(struct condition *a, u_int16 op, struct condition *b)
{
struct condition *head = a;
/* go to the last conditions in 'a' */
while(a->next != NULL)
a = a->next;
/* set the operation */
a->op = op;
/* contatenate the two block */
a->next = b;
/* return the head of the conditions */
return head;
}
/*
* allocate a ifblock container
*/
struct ifblock * compiler_create_ifblock(struct condition *conds, struct block *blk)
{
struct ifblock *ifblk;
SAFE_CALLOC(ifblk, 1, sizeof(struct ifblock));
/* associate the pointers */
ifblk->conds = conds;
ifblk->blk = blk;
return ifblk;
}
/*
* allocate a if_else_block container
*/
struct ifblock * compiler_create_ifelseblock(struct condition *conds, struct block *blk, struct block *elseblk)
{
struct ifblock *ifblk;
SAFE_CALLOC(ifblk, 1, sizeof(struct ifblock));
/* associate the pointers */
ifblk->conds = conds;
ifblk->blk = blk;
ifblk->elseblk = elseblk;
return ifblk;
}
/*
* add an instruction to a block
*/
struct block * compiler_add_instr(struct instruction *ins, struct block *blk)
{
struct block *bl;
SAFE_CALLOC(bl, 1, sizeof(struct block));
/* copy the current instruction in the block */
bl->type = BLK_INSTR;
bl->un.ins = ins;
/* link it to the old block chain */
bl->next = blk;
return bl;
}
/*
* add an if block to a block
*/
struct block * compiler_add_ifblk(struct ifblock *ifb, struct block *blk)
{
struct block *bl;
SAFE_CALLOC(bl, 1, sizeof(struct block));
/* copy the current instruction in the block */
bl->type = BLK_IFBLK;
bl->un.ifb = ifb;
/* link it to the old block chain */
bl->next = blk;
return bl;
}
/*
* parses the tree and produce a compiled
* array of filter_op
*/
size_t compile_tree(struct filter_op **fop)
{
int i = 1;
struct filter_op *array = NULL;
struct unfold_elm *ue;
// invalid file
if (tree_root == NULL)
return 0;
fprintf(stdout, " Unfolding the meta-tree ");
fflush(stdout);
/* start the recursion on the tree */
unfold_blk(&tree_root);
fprintf(stdout, " done.\n\n");
/* substitute the virtual labels with real offsets */
labels_to_offsets();
/* convert the tailq into an array */
TAILQ_FOREACH(ue, &unfolded_tree, next) {
/* label == 0 means a real instruction */
if (ue->label == 0) {
SAFE_REALLOC(array, i * sizeof(struct filter_op));
memcpy(&array[i - 1], &ue->fop, sizeof(struct filter_op));
i++;
}
}
/* always append the exit function to a script */
SAFE_REALLOC(array, i * sizeof(struct filter_op));
array[i - 1].opcode = FOP_EXIT;
/* return the pointer to the array */
*fop = array;
return (i);
}
/*
* unfold a block putting it in the unfolded_tree list
*/
static void unfold_blk(struct block **blk)
{
struct unfold_elm *ue = NULL;
BUG_IF(*blk == NULL);
/* the progress bar */
ef_debug(1, "+");
do {
switch((*blk)->type) {
case BLK_INSTR:
/* insert the instruction as is */
SAFE_CALLOC(ue, 1, sizeof(struct unfold_elm));
memcpy(&ue->fop, (*blk)->un.ins, sizeof(struct filter_op));
TAILQ_INSERT_TAIL(&unfolded_tree, ue, next);
break;
case BLK_IFBLK:
unfold_ifblk(blk);
break;
default:
BUG("undefined tree element");
break;
}
} while ((*blk = (*blk)->next));
}
/*
* unfold an if block putting it in the unfolded_tree list
*/
static void unfold_ifblk(struct block **blk)
{
struct ifblock *ifblk;
struct unfold_elm *ue;
u_int32 a = vlabel++;
u_int32 b = vlabel++;
u_int32 c = vlabel++;
/*
* the virtual labels represent the three points of an if block:
*
* if (conds) {
* a ->
* ...
* jmp c;
* b ->
* } else {
* ...
* }
* c ->
*
* if the conds are true, jump to 'a'
* if the conds are false, jump to 'b'
* 'c' is used to skip the else if the conds were true
*/
/* the progress bar */
ef_debug(1, "#");
/* cast the if block */
ifblk = (*blk)->un.ifb;
/* compile the conditions */
unfold_conds(ifblk->conds, a, b);
/* if the conditions are match, jump here */
SAFE_CALLOC(ue, 1, sizeof(struct unfold_elm));
ue->label = a;
TAILQ_INSERT_TAIL(&unfolded_tree, ue, next);
/* check if the block is empty. i.e. { } */
if (ifblk->blk != NULL) {
/* recursively compile the main block */
unfold_blk(&ifblk->blk);
}
/*
* if there is the else block, we have to skip it
* if the condition was true
*/
if (ifblk->elseblk != NULL) {
SAFE_CALLOC(ue, 1, sizeof(struct unfold_elm));
ue->fop.opcode = FOP_JMP;
ue->fop.op.jmp = c;
TAILQ_INSERT_TAIL(&unfolded_tree, ue, next);
}
/* if the conditions are NOT match, jump here (after the block) */
SAFE_CALLOC(ue, 1, sizeof(struct unfold_elm));
ue->label = b;
TAILQ_INSERT_TAIL(&unfolded_tree, ue, next);
/* recursively compile the else block */
if (ifblk->elseblk != NULL) {
unfold_blk(&ifblk->elseblk);
/* this is the label to skip the else if the condition was true */
SAFE_CALLOC(ue, 1, sizeof(struct unfold_elm));
ue->label = c;
TAILQ_INSERT_TAIL(&unfolded_tree, ue, next);
}
}
/*
* unfold a conditions block putting it in the unfolded_tree list
*/
static void unfold_conds(struct condition *cnd, u_int32 a, u_int32 b)
{
struct unfold_elm *ue = NULL;
do {
/* the progress bar */
ef_debug(1, "?");
/* insert the condition as is */
SAFE_CALLOC(ue, 1, sizeof(struct unfold_elm));
memcpy(&ue->fop, &cnd->fop, sizeof(struct filter_op));
TAILQ_INSERT_TAIL(&unfolded_tree, ue, next);
/* insert the conditional jump */
SAFE_CALLOC(ue, 1, sizeof(struct unfold_elm));
if (cnd->op == COND_OR) {
ue->fop.opcode = FOP_JTRUE;
ue->fop.op.jmp = a;
} else {
/* AND and single instructions behave equally */
ue->fop.opcode = FOP_JFALSE;
ue->fop.op.jmp = b;
}
TAILQ_INSERT_TAIL(&unfolded_tree, ue, next);
} while ((cnd = cnd->next));
}
/*
* converts the virtual labels to real offsets
*/
static void labels_to_offsets(void)
{
struct unfold_elm *ue;
struct unfold_elm *s;
u_int32 offset = 0;
fprintf(stdout, " Converting labels to real offsets ");
fflush(stdout);
TAILQ_FOREACH(ue, &unfolded_tree, next) {
/* search only for jumps */
if (ue->fop.opcode == FOP_JMP ||
ue->fop.opcode == FOP_JTRUE ||
ue->fop.opcode == FOP_JFALSE) {
switch (ue->fop.opcode) {
case FOP_JMP:
ef_debug(1, "*");
break;
case FOP_JTRUE:
ef_debug(1, "+");
break;
case FOP_JFALSE:
ef_debug(1, "-");
break;
}
/* search the offset associated with the label */
TAILQ_FOREACH(s, &unfolded_tree, next) {
if (s->label == ue->fop.op.jmp) {
ue->fop.op.jmp = offset;
/* reset the offset */
offset = 0;
break;
}
/* if it is an instruction, increment the offset */
if (s->label == 0)
offset++;
}
}
}
fprintf(stdout, " done.\n\n");
}
/* EOF */
// vim:ts=3:expandtab
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3190_0 |
crossvul-cpp_data_bad_140_0 | /* radare - LGPL - Copyright 2009-2018 - nibble, pancake */
#include <assert.h>
#include <stdio.h>
#include <r_types.h>
#include <r_util.h>
#include <r_lib.h>
#include <r_bin.h>
#include <r_io.h>
#include <r_cons.h>
#include "elf/elf.h"
static RBinInfo* info(RBinFile *bf);
//TODO: implement r_bin_symbol_dup() and r_bin_symbol_free ?
static int get_file_type(RBinFile *bf) {
struct Elf_(r_bin_elf_obj_t) *obj = bf->o->bin_obj;
char *type = Elf_(r_bin_elf_get_file_type (obj));
return type? ((!strncmp (type, "CORE", 4)) ? R_BIN_TYPE_CORE : R_BIN_TYPE_DEFAULT) : -1;
}
static RList *maps(RBinFile *bf) {
if (bf && bf->o) {
return Elf_(r_bin_elf_get_maps)(bf->o->bin_obj);
}
return NULL;
}
static char* regstate(RBinFile *bf) {
struct Elf_(r_bin_elf_obj_t) *obj = bf->o->bin_obj;
if (obj->ehdr.e_machine != EM_AARCH64 &&
obj->ehdr.e_machine != EM_ARM &&
obj->ehdr.e_machine != EM_386 &&
obj->ehdr.e_machine != EM_X86_64) {
eprintf ("Cannot retrieve regstate on: %s (not yet supported)\n",
Elf_(r_bin_elf_get_machine_name)(obj));
return NULL;
}
int len = 0;
ut8 *regs = Elf_(r_bin_elf_grab_regstate) (obj, &len);
char *hexregs = (regs && len > 0) ? r_hex_bin2strdup (regs, len) : NULL;
free (regs);
return hexregs;
}
static void setsymord(ELFOBJ* eobj, ut32 ord, RBinSymbol *ptr) {
if (!eobj->symbols_by_ord || ord >= eobj->symbols_by_ord_size) {
return;
}
free (eobj->symbols_by_ord[ord]);
eobj->symbols_by_ord[ord] = r_mem_dup (ptr, sizeof (RBinSymbol));
}
static inline bool setimpord(ELFOBJ* eobj, ut32 ord, RBinImport *ptr) {
if (!eobj->imports_by_ord || ord >= eobj->imports_by_ord_size) {
return false;
}
if (eobj->imports_by_ord[ord]) {
free (eobj->imports_by_ord[ord]->name);
free (eobj->imports_by_ord[ord]);
}
eobj->imports_by_ord[ord] = r_mem_dup (ptr, sizeof (RBinImport));
eobj->imports_by_ord[ord]->name = strdup (ptr->name);
return true;
}
static Sdb* get_sdb(RBinFile *bf) {
RBinObject *o = bf->o;
if (o && o->bin_obj) {
struct Elf_(r_bin_elf_obj_t) *bin = (struct Elf_(r_bin_elf_obj_t) *) o->bin_obj;
return bin->kv;
}
return NULL;
}
static void * load_buffer(RBinFile *bf, RBuffer *buf, ut64 loadaddr, Sdb *sdb) {
struct Elf_(r_bin_elf_obj_t) *res;
if (!buf) {
return NULL;
}
res = Elf_(r_bin_elf_new_buf) (buf, bf->rbin->verbose);
if (res) {
sdb_ns_set (sdb, "info", res->kv);
}
return res;
}
static void * load_bytes(RBinFile *bf, const ut8 *buf, ut64 sz, ut64 loadaddr, Sdb *sdb) {
struct Elf_(r_bin_elf_obj_t) *res;
if (!buf || !sz || sz == UT64_MAX) {
return NULL;
}
RBuffer *tbuf = r_buf_new ();
// NOOOEES must use io!
r_buf_set_bytes (tbuf, buf, sz);
res = Elf_(r_bin_elf_new_buf) (tbuf, bf->rbin->verbose);
if (res) {
sdb_ns_set (sdb, "info", res->kv);
}
r_buf_free (tbuf);
return res;
}
static bool load(RBinFile *bf) {
const ut8 *bytes = bf ? r_buf_buffer (bf->buf) : NULL;
ut64 sz = bf ? r_buf_size (bf->buf): 0;
if (!bf || !bf->o) {
return false;
}
bf->o->bin_obj = load_bytes (bf, bytes, sz, bf->o->loadaddr, bf->sdb);
return bf->o->bin_obj != NULL;
}
static int destroy(RBinFile *bf) {
int i;
ELFOBJ* eobj = bf->o->bin_obj;
if (eobj && eobj->imports_by_ord) {
for (i = 0; i < eobj->imports_by_ord_size; i++) {
RBinImport *imp = eobj->imports_by_ord[i];
if (imp) {
free (imp->name);
free (imp);
eobj->imports_by_ord[i] = NULL;
}
}
R_FREE (eobj->imports_by_ord);
}
Elf_(r_bin_elf_free) ((struct Elf_(r_bin_elf_obj_t)*)bf->o->bin_obj);
return true;
}
static ut64 baddr(RBinFile *bf) {
return Elf_(r_bin_elf_get_baddr) (bf->o->bin_obj);
}
static ut64 boffset(RBinFile *bf) {
return Elf_(r_bin_elf_get_boffset) (bf->o->bin_obj);
}
static RBinAddr* binsym(RBinFile *bf, int sym) {
struct Elf_(r_bin_elf_obj_t)* obj = bf->o->bin_obj;
RBinAddr *ret = NULL;
ut64 addr = 0LL;
switch (sym) {
case R_BIN_SYM_ENTRY:
addr = Elf_(r_bin_elf_get_entry_offset) (bf->o->bin_obj);
break;
case R_BIN_SYM_MAIN:
addr = Elf_(r_bin_elf_get_main_offset) (bf->o->bin_obj);
break;
case R_BIN_SYM_INIT:
addr = Elf_(r_bin_elf_get_init_offset) (bf->o->bin_obj);
break;
case R_BIN_SYM_FINI:
addr = Elf_(r_bin_elf_get_fini_offset) (bf->o->bin_obj);
break;
}
if (addr && addr != UT64_MAX && (ret = R_NEW0 (RBinAddr))) {
struct Elf_(r_bin_elf_obj_t) *bin = bf->o->bin_obj;
bool is_arm = bin->ehdr.e_machine == EM_ARM;
ret->paddr = addr;
ret->vaddr = Elf_(r_bin_elf_p2v) (obj, addr);
if (is_arm && addr & 1) {
ret->bits = 16;
ret->vaddr--;
ret->paddr--;
}
}
return ret;
}
static RList* sections(RBinFile *bf) {
struct Elf_(r_bin_elf_obj_t)* obj = (bf && bf->o)? bf->o->bin_obj : NULL;
struct r_bin_elf_section_t *section = NULL;
int i, num, found_load = 0;
Elf_(Phdr)* phdr = NULL;
RBinSection *ptr = NULL;
RList *ret = NULL;
if (!obj || !(ret = r_list_newf (free))) {
return NULL;
}
//there is not leak in section since they are cached by elf.c
//and freed within Elf_(r_bin_elf_free)
if ((section = Elf_(r_bin_elf_get_sections) (obj))) {
for (i = 0; !section[i].last; i++) {
if (!(ptr = R_NEW0 (RBinSection))) {
break;
}
strncpy (ptr->name, (char*)section[i].name, R_BIN_SIZEOF_STRINGS);
if (strstr (ptr->name, "data") && !strstr (ptr->name, "rel")) {
ptr->is_data = true;
}
ptr->size = section[i].type != SHT_NOBITS ? section[i].size : 0;
ptr->vsize = section[i].size;
ptr->paddr = section[i].offset;
ptr->vaddr = section[i].rva;
ptr->add = !obj->phdr; // Load sections if there is no PHDR
ptr->srwx = 0;
if (R_BIN_ELF_SCN_IS_EXECUTABLE (section[i].flags)) {
ptr->srwx |= R_BIN_SCN_EXECUTABLE;
}
if (R_BIN_ELF_SCN_IS_WRITABLE (section[i].flags)) {
ptr->srwx |= R_BIN_SCN_WRITABLE;
}
if (R_BIN_ELF_SCN_IS_READABLE (section[i].flags)) {
ptr->srwx |= R_BIN_SCN_READABLE;
}
r_list_append (ret, ptr);
}
}
// program headers is another section
num = obj->ehdr.e_phnum;
phdr = obj->phdr;
if (phdr) {
int n = 0;
for (i = 0; i < num; i++) {
if (!(ptr = R_NEW0 (RBinSection))) {
return ret;
}
ptr->add = false;
ptr->size = phdr[i].p_filesz;
ptr->vsize = phdr[i].p_memsz;
ptr->paddr = phdr[i].p_offset;
ptr->vaddr = phdr[i].p_vaddr;
ptr->srwx = phdr[i].p_flags;
switch (phdr[i].p_type) {
case PT_DYNAMIC:
strncpy (ptr->name, "DYNAMIC", R_BIN_SIZEOF_STRINGS);
break;
case PT_LOAD:
snprintf (ptr->name, R_BIN_SIZEOF_STRINGS, "LOAD%d", n++);
found_load = 1;
ptr->add = true;
break;
case PT_INTERP:
strncpy (ptr->name, "INTERP", R_BIN_SIZEOF_STRINGS);
break;
case PT_GNU_STACK:
strncpy (ptr->name, "GNU_STACK", R_BIN_SIZEOF_STRINGS);
break;
case PT_GNU_RELRO:
strncpy (ptr->name, "GNU_RELRO", R_BIN_SIZEOF_STRINGS);
break;
case PT_GNU_EH_FRAME:
strncpy (ptr->name, "GNU_EH_FRAME", R_BIN_SIZEOF_STRINGS);
break;
case PT_PHDR:
strncpy (ptr->name, "PHDR", R_BIN_SIZEOF_STRINGS);
break;
case PT_TLS:
strncpy (ptr->name, "TLS", R_BIN_SIZEOF_STRINGS);
break;
case PT_NOTE:
strncpy (ptr->name, "NOTE", R_BIN_SIZEOF_STRINGS);
break;
default:
strncpy (ptr->name, "UNKNOWN", R_BIN_SIZEOF_STRINGS);
break;
}
ptr->name[R_BIN_SIZEOF_STRINGS - 1] = '\0';
r_list_append (ret, ptr);
}
}
if (r_list_empty (ret)) {
if (!bf->size) {
struct Elf_(r_bin_elf_obj_t) *bin = bf->o->bin_obj;
bf->size = bin? bin->size: 0x9999;
}
if (found_load == 0) {
if (!(ptr = R_NEW0 (RBinSection))) {
return ret;
}
sprintf (ptr->name, "uphdr");
ptr->size = bf->size;
ptr->vsize = bf->size;
ptr->paddr = 0;
ptr->vaddr = 0x10000;
ptr->add = true;
ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_WRITABLE |
R_BIN_SCN_EXECUTABLE;
r_list_append (ret, ptr);
}
}
// add entry for ehdr
ptr = R_NEW0 (RBinSection);
if (ptr) {
ut64 ehdr_size = sizeof (obj->ehdr);
if (bf->size < ehdr_size) {
ehdr_size = bf->size;
}
sprintf (ptr->name, "ehdr");
ptr->paddr = 0;
ptr->vaddr = obj->baddr;
ptr->size = ehdr_size;
ptr->vsize = ehdr_size;
ptr->add = false;
if (obj->ehdr.e_type == ET_REL) {
ptr->add = true;
}
ptr->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_WRITABLE;
r_list_append (ret, ptr);
}
return ret;
}
static RBinAddr* newEntry(ut64 haddr, ut64 paddr, int type, int bits) {
RBinAddr *ptr = R_NEW0 (RBinAddr);
if (ptr) {
ptr->paddr = paddr;
ptr->vaddr = paddr;
ptr->haddr = haddr;
ptr->bits = bits;
ptr->type = type;
//realign due to thumb
if (bits == 16 && ptr->vaddr & 1) {
ptr->paddr--;
ptr->vaddr--;
}
}
return ptr;
}
static void process_constructors (RBinFile *bf, RList *ret, int bits) {
RList *secs = sections (bf);
RListIter *iter;
RBinSection *sec;
int i, type;
r_list_foreach (secs, iter, sec) {
type = -1;
if (!strcmp (sec->name, ".fini_array")) {
type = R_BIN_ENTRY_TYPE_FINI;
} else if (!strcmp (sec->name, ".init_array")) {
type = R_BIN_ENTRY_TYPE_INIT;
} else if (!strcmp (sec->name, ".preinit_array")) {
type = R_BIN_ENTRY_TYPE_PREINIT;
}
if (type != -1) {
ut8 *buf = calloc (sec->size, 1);
if (!buf) {
continue;
}
(void)r_buf_read_at (bf->buf, sec->paddr, buf, sec->size);
if (bits == 32) {
for (i = 0; i < sec->size; i += 4) {
ut32 addr32 = r_read_le32 (buf + i);
if (addr32) {
RBinAddr *ba = newEntry (sec->paddr + i, (ut64)addr32, type, bits);
r_list_append (ret, ba);
}
}
} else {
for (i = 0; i < sec->size; i += 8) {
ut64 addr64 = r_read_le64 (buf + i);
if (addr64) {
RBinAddr *ba = newEntry (sec->paddr + i, addr64, type, bits);
r_list_append (ret, ba);
}
}
}
free (buf);
}
}
r_list_free (secs);
}
static RList* entries(RBinFile *bf) {
struct Elf_(r_bin_elf_obj_t)* obj;
RBinAddr *ptr = NULL;
struct r_bin_elf_symbol_t *symbol;
RList *ret;
int i;
if (!bf || !bf->o || !bf->o->bin_obj) {
return NULL;
}
obj = bf->o->bin_obj;
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
if (!(ptr = R_NEW0 (RBinAddr))) {
return ret;
}
ptr->paddr = Elf_(r_bin_elf_get_entry_offset) (obj);
ptr->vaddr = Elf_(r_bin_elf_p2v) (obj, ptr->paddr);
ptr->haddr = 0x18;
if (obj->ehdr.e_machine == EM_ARM) {
int bin_bits = Elf_(r_bin_elf_get_bits) (obj);
if (bin_bits != 64) {
ptr->bits = 32;
if (ptr->vaddr & 1) {
ptr->vaddr--;
ptr->bits = 16;
}
if (ptr->paddr & 1) {
ptr->paddr--;
ptr->bits = 16;
}
}
}
r_list_append (ret, ptr);
// add entrypoint for jni libraries
// NOTE: this is slow, we shouldnt find for java constructors here
if (!(symbol = Elf_(r_bin_elf_get_symbols) (obj))) {
return ret;
}
for (i = 0; !symbol[i].last; i++) {
if (!strncmp (symbol[i].name, "Java", 4)) {
if (r_str_endswith (symbol[i].name, "_init")) {
if (!(ptr = R_NEW0 (RBinAddr))) {
return ret;
}
ptr->paddr = symbol[i].offset;
ptr->vaddr = Elf_(r_bin_elf_p2v) (obj, ptr->paddr);
ptr->haddr = UT64_MAX;
ptr->type = R_BIN_ENTRY_TYPE_INIT;
r_list_append (ret, ptr);
break;
}
}
}
int bin_bits = Elf_(r_bin_elf_get_bits) (bf->o->bin_obj);
process_constructors (bf, ret, bin_bits < 32 ? 32: bin_bits);
return ret;
}
static void _set_arm_thumb_bits(struct Elf_(r_bin_elf_obj_t) *bin, RBinSymbol **sym) {
int bin_bits = Elf_(r_bin_elf_get_bits) (bin);
RBinSymbol *ptr = *sym;
int len = strlen (ptr->name);
if (ptr->name[0] == '$' && (len >= 2 && !ptr->name[2])) {
switch (ptr->name[1]) {
case 'a' : //arm
ptr->bits = 32;
break;
case 't': //thumb
ptr->bits = 16;
if (ptr->vaddr & 1) {
ptr->vaddr--;
}
if (ptr->paddr & 1) {
ptr->paddr--;
}
break;
case 'd': //data
break;
default:
goto arm_symbol;
}
} else {
arm_symbol:
ptr->bits = bin_bits;
if (bin_bits != 64) {
ptr->bits = 32;
if (ptr->vaddr & 1) {
ptr->vaddr--;
ptr->bits = 16;
}
if (ptr->paddr & 1) {
ptr->paddr--;
ptr->bits = 16;
}
}
}
}
static RList* symbols(RBinFile *bf) {
struct Elf_(r_bin_elf_obj_t) *bin;
struct r_bin_elf_symbol_t *symbol = NULL;
RBinSymbol *ptr = NULL;
RList *ret = NULL;
int i;
if (!bf|| !bf->o || !bf->o->bin_obj) {
return NULL;
}
bin = bf->o->bin_obj;
ret = r_list_newf (free);
if (!ret) {
return NULL;
}
if (!(symbol = Elf_(r_bin_elf_get_symbols) (bin))) {
return ret;
}
for (i = 0; !symbol[i].last; i++) {
ut64 paddr = symbol[i].offset;
ut64 vaddr = Elf_(r_bin_elf_p2v) (bin, paddr);
if (!(ptr = R_NEW0 (RBinSymbol))) {
break;
}
ptr->name = strdup (symbol[i].name);
ptr->forwarder = r_str_const ("NONE");
ptr->bind = r_str_const (symbol[i].bind);
ptr->type = r_str_const (symbol[i].type);
ptr->paddr = paddr;
ptr->vaddr = vaddr;
ptr->size = symbol[i].size;
ptr->ordinal = symbol[i].ordinal;
setsymord (bin, ptr->ordinal, ptr);
if (bin->ehdr.e_machine == EM_ARM && *ptr->name) {
_set_arm_thumb_bits (bin, &ptr);
}
r_list_append (ret, ptr);
}
if (!(symbol = Elf_(r_bin_elf_get_imports) (bin))) {
return ret;
}
for (i = 0; !symbol[i].last; i++) {
ut64 paddr = symbol[i].offset;
ut64 vaddr = Elf_(r_bin_elf_p2v) (bin, paddr);
if (!symbol[i].size) {
continue;
}
if (!(ptr = R_NEW0 (RBinSymbol))) {
break;
}
// TODO(eddyb) make a better distinction between imports and other symbols.
//snprintf (ptr->name, R_BIN_SIZEOF_STRINGS-1, "imp.%s", symbol[i].name);
ptr->name = r_str_newf ("imp.%s", symbol[i].name);
ptr->forwarder = r_str_const ("NONE");
//strncpy (ptr->forwarder, "NONE", R_BIN_SIZEOF_STRINGS);
ptr->bind = r_str_const (symbol[i].bind);
ptr->type = r_str_const (symbol[i].type);
ptr->paddr = paddr;
ptr->vaddr = vaddr;
//special case where there is not entry in the plt for the import
if (ptr->vaddr == UT32_MAX) {
ptr->paddr = 0;
ptr->vaddr = 0;
}
ptr->size = symbol[i].size;
ptr->ordinal = symbol[i].ordinal;
setsymord (bin, ptr->ordinal, ptr);
/* detect thumb */
if (bin->ehdr.e_machine == EM_ARM) {
_set_arm_thumb_bits (bin, &ptr);
}
r_list_append (ret, ptr);
}
return ret;
}
static RList* imports(RBinFile *bf) {
struct Elf_(r_bin_elf_obj_t) *bin = NULL;
RBinElfSymbol *import = NULL;
RBinImport *ptr = NULL;
RList *ret = NULL;
int i;
if (!bf || !bf->o || !bf->o->bin_obj) {
return NULL;
}
bin = bf->o->bin_obj;
if (!(ret = r_list_newf (r_bin_import_free))) {
return NULL;
}
if (!(import = Elf_(r_bin_elf_get_imports) (bin))) {
r_list_free (ret);
return NULL;
}
for (i = 0; !import[i].last; i++) {
if (!(ptr = R_NEW0 (RBinImport))) {
break;
}
ptr->name = strdup (import[i].name);
ptr->bind = r_str_const (import[i].bind);
ptr->type = r_str_const (import[i].type);
ptr->ordinal = import[i].ordinal;
(void)setimpord (bin, ptr->ordinal, ptr);
r_list_append (ret, ptr);
}
return ret;
}
static RList* libs(RBinFile *bf) {
struct r_bin_elf_lib_t *libs = NULL;
RList *ret = NULL;
char *ptr = NULL;
int i;
if (!bf || !bf->o || !bf->o->bin_obj) {
return NULL;
}
if (!(ret = r_list_newf (free))) {
return NULL;
}
if (!(libs = Elf_(r_bin_elf_get_libs) (bf->o->bin_obj))) {
return ret;
}
for (i = 0; !libs[i].last; i++) {
ptr = strdup (libs[i].name);
r_list_append (ret, ptr);
}
free (libs);
return ret;
}
static RBinReloc *reloc_convert(struct Elf_(r_bin_elf_obj_t) *bin, RBinElfReloc *rel, ut64 GOT) {
RBinReloc *r = NULL;
ut64 B, P;
if (!bin || !rel) {
return NULL;
}
B = bin->baddr;
P = rel->rva; // rva has taken baddr into account
if (!(r = R_NEW0 (RBinReloc))) {
return r;
}
r->import = NULL;
r->symbol = NULL;
r->is_ifunc = false;
r->addend = rel->addend;
if (rel->sym) {
if (rel->sym < bin->imports_by_ord_size && bin->imports_by_ord[rel->sym]) {
r->import = bin->imports_by_ord[rel->sym];
} else if (rel->sym < bin->symbols_by_ord_size && bin->symbols_by_ord[rel->sym]) {
r->symbol = bin->symbols_by_ord[rel->sym];
}
}
r->vaddr = rel->rva;
r->paddr = rel->offset;
#define SET(T) r->type = R_BIN_RELOC_ ## T; r->additive = 0; return r
#define ADD(T, A) r->type = R_BIN_RELOC_ ## T; r->addend += A; r->additive = !rel->is_rela; return r
switch (bin->ehdr.e_machine) {
case EM_386: switch (rel->type) {
case R_386_NONE: break; // malloc then free. meh. then again, there's no real world use for _NONE.
case R_386_32: ADD(32, 0);
case R_386_PC32: ADD(32,-P);
case R_386_GLOB_DAT: SET(32);
case R_386_JMP_SLOT: SET(32);
case R_386_RELATIVE: ADD(32, B);
case R_386_GOTOFF: ADD(32,-GOT);
case R_386_GOTPC: ADD(32, GOT-P);
case R_386_16: ADD(16, 0);
case R_386_PC16: ADD(16,-P);
case R_386_8: ADD(8, 0);
case R_386_PC8: ADD(8, -P);
case R_386_COPY: ADD(64, 0); // XXX: copy symbol at runtime
case R_386_IRELATIVE: r->is_ifunc = true; SET(32);
default: break; //eprintf("TODO(eddyb): uninmplemented ELF/x86 reloc type %i\n", rel->type);
}
break;
case EM_X86_64: switch (rel->type) {
case R_X86_64_NONE: break; // malloc then free. meh. then again, there's no real world use for _NONE.
case R_X86_64_64: ADD(64, 0);
case R_X86_64_PLT32: ADD(32,-P /* +L */);
case R_X86_64_GOT32: ADD(32, GOT);
case R_X86_64_PC32: ADD(32,-P);
case R_X86_64_GLOB_DAT: r->vaddr -= rel->sto; SET(64);
case R_X86_64_JUMP_SLOT: r->vaddr -= rel->sto; SET(64);
case R_X86_64_RELATIVE: ADD(64, B);
case R_X86_64_32: ADD(32, 0);
case R_X86_64_32S: ADD(32, 0);
case R_X86_64_16: ADD(16, 0);
case R_X86_64_PC16: ADD(16,-P);
case R_X86_64_8: ADD(8, 0);
case R_X86_64_PC8: ADD(8, -P);
case R_X86_64_GOTPCREL: ADD(64, GOT-P);
case R_X86_64_COPY: ADD(64, 0); // XXX: copy symbol at runtime
case R_X86_64_IRELATIVE: r->is_ifunc = true; SET(64);
default: break; ////eprintf("TODO(eddyb): uninmplemented ELF/x64 reloc type %i\n", rel->type);
}
break;
case EM_ARM: switch (rel->type) {
case R_ARM_NONE: break; // malloc then free. meh. then again, there's no real world use for _NONE.
case R_ARM_ABS32: ADD(32, 0);
case R_ARM_REL32: ADD(32,-P);
case R_ARM_ABS16: ADD(16, 0);
case R_ARM_ABS8: ADD(8, 0);
case R_ARM_SBREL32: ADD(32, -B);
case R_ARM_GLOB_DAT: ADD(32, 0);
case R_ARM_JUMP_SLOT: ADD(32, 0);
case R_ARM_RELATIVE: ADD(32, B);
case R_ARM_GOTOFF: ADD(32,-GOT);
default: ADD(32,GOT); break; // reg relocations
////eprintf("TODO(eddyb): uninmplemented ELF/ARM reloc type %i\n", rel->type);
}
break;
default: break;
}
#undef SET
#undef ADD
free(r);
return 0;
}
static RList* relocs(RBinFile *bf) {
RList *ret = NULL;
RBinReloc *ptr = NULL;
RBinElfReloc *relocs = NULL;
struct Elf_(r_bin_elf_obj_t) *bin = NULL;
ut64 got_addr;
int i;
if (!bf || !bf->o || !bf->o->bin_obj) {
return NULL;
}
bin = bf->o->bin_obj;
if (!(ret = r_list_newf (free))) {
return NULL;
}
/* FIXME: This is a _temporary_ fix/workaround to prevent a use-after-
* free detected by ASan that would corrupt the relocation names */
r_list_free (imports (bf));
if ((got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got")) == -1) {
got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got.plt");
if (got_addr == -1) {
got_addr = 0;
}
}
if (got_addr < 1 && bin->ehdr.e_type == ET_REL) {
got_addr = Elf_(r_bin_elf_get_section_addr) (bin, ".got.r2");
if (got_addr == -1) {
got_addr = 0;
}
}
if (bf->o) {
if (!(relocs = Elf_(r_bin_elf_get_relocs) (bin))) {
return ret;
}
for (i = 0; !relocs[i].last; i++) {
if (!(ptr = reloc_convert (bin, &relocs[i], got_addr))) {
continue;
}
r_list_append (ret, ptr);
}
free (relocs);
}
return ret;
}
static void _patch_reloc (ut16 e_machine, RIOBind *iob, RBinElfReloc *rel, ut64 S, ut64 B, ut64 L) {
ut64 val;
ut64 A = rel->addend, P = rel->rva;
ut8 buf[8];
switch (e_machine) {
case EM_PPC64: {
int low = 0, word = 0;
switch (rel->type) {
case R_PPC64_REL16_HA:
word = 2;
val = (S + A - P + 0x8000) >> 16;
break;
case R_PPC64_REL16_LO:
word = 2;
val = (S + A - P) & 0xffff;
break;
case R_PPC64_REL14:
low = 14;
val = (st64)(S + A - P) >> 2;
break;
case R_PPC64_REL24:
low = 24;
val = (st64)(S + A - P) >> 2;
break;
case R_PPC64_REL32:
word = 4;
val = S + A - P;
break;
default:
break;
}
if (low) {
// TODO big-endian
switch (low) {
case 14:
val &= (1 << 14) - 1;
iob->read_at (iob->io, rel->rva, buf, 2);
r_write_le32 (buf, (r_read_le32 (buf) & ~((1<<16) - (1<<2))) | val << 2);
iob->write_at (iob->io, rel->rva, buf, 2);
break;
case 24:
val &= (1 << 24) - 1;
iob->read_at (iob->io, rel->rva, buf, 4);
r_write_le32 (buf, (r_read_le32 (buf) & ~((1<<26) - (1<<2))) | val << 2);
iob->write_at (iob->io, rel->rva, buf, 4);
break;
}
} else if (word) {
// TODO big-endian
switch (word) {
case 2:
r_write_le16 (buf, val);
iob->write_at (iob->io, rel->rva, buf, 2);
break;
case 4:
r_write_le32 (buf, val);
iob->write_at (iob->io, rel->rva, buf, 4);
break;
}
}
break;
}
case EM_X86_64: {
int word = 0;
switch (rel->type) {
case R_X86_64_8:
word = 1;
val = S + A;
break;
case R_X86_64_16:
word = 2;
val = S + A;
break;
case R_X86_64_32:
case R_X86_64_32S:
word = 4;
val = S + A;
break;
case R_X86_64_64:
word = 8;
val = S + A;
break;
case R_X86_64_GLOB_DAT:
case R_X86_64_JUMP_SLOT:
word = 4;
val = S;
break;
case R_X86_64_PC8:
word = 1;
val = S + A - P;
break;
case R_X86_64_PC16:
word = 2;
val = S + A - P;
break;
case R_X86_64_PC32:
word = 4;
val = S + A - P;
break;
case R_X86_64_PC64:
word = 8;
val = S + A - P;
break;
case R_X86_64_PLT32:
word = 4;
val = L + A - P;
break;
case R_X86_64_RELATIVE:
word = 8;
val = B + A;
break;
default:
//eprintf ("relocation %d not handle at this time\n", rel->type);
break;
}
switch (word) {
case 0:
break;
case 1:
buf[0] = val;
iob->write_at (iob->io, rel->rva, buf, 1);
break;
case 2:
r_write_le16 (buf, val);
iob->write_at (iob->io, rel->rva, buf, 2);
break;
case 4:
r_write_le32 (buf, val);
iob->write_at (iob->io, rel->rva, buf, 4);
break;
case 8:
r_write_le64 (buf, val);
iob->write_at (iob->io, rel->rva, buf, 8);
break;
}
break;
}
}
}
static bool ht_insert_intu64(SdbHash* ht, int key, ut64 value) {
ut64 *mvalue = malloc (sizeof (ut64));
if (!mvalue) {
return false;
}
*mvalue = value;
return ht_insert (ht, sdb_fmt ("%d", key), (void *)mvalue);
}
static ut64 ht_find_intu64(SdbHash* ht, int key, bool* found) {
ut64 *mvalue = (ut64 *)ht_find (ht, sdb_fmt ("%d", key), found);
return *mvalue;
}
static void relocs_by_sym_free(HtKv *kv) {
free (kv->key);
free (kv->value);
}
static RList* patch_relocs(RBin *b) {
RList *ret = NULL;
RBinReloc *ptr = NULL;
RIO *io = NULL;
RBinObject *obj = NULL;
struct Elf_(r_bin_elf_obj_t) *bin = NULL;
RIOSection *g = NULL, *s = NULL;
SdbHash *relocs_by_sym;
SdbListIter *iter;
RBinElfReloc *relcs = NULL;
RBinInfo *info;
int cdsz;
int i;
ut64 n_off, n_vaddr, vaddr, size, offset = 0;
if (!b)
return NULL;
io = b->iob.io;
if (!io || !io->desc)
return NULL;
obj = r_bin_cur_object (b);
if (!obj) {
return NULL;
}
bin = obj->bin_obj;
if (bin->ehdr.e_type != ET_REL) {
return NULL;
}
if (!io->cached) {
eprintf ("Warning: run r2 with -e io.cache=true to fix relocations in disassembly\n");
return relocs (r_bin_cur (b));
}
info = obj ? obj->info: NULL;
cdsz = info? (info->bits == 64? 8: info->bits == 32? 4: info->bits == 16 ? 4: 0): 0;
ls_foreach (io->sections, iter, s) {
if (s->paddr > offset) {
offset = s->paddr;
g = s;
}
}
if (!g) {
return NULL;
}
n_off = g->paddr + g->size;
n_vaddr = g->vaddr + g->vsize;
//reserve at least that space
size = bin->reloc_num * 4;
if (!b->iob.section_add (io, n_off, n_vaddr, size, size, R_BIN_SCN_READABLE, ".got.r2", 0, io->desc->fd)) {
return NULL;
}
if (!(relcs = Elf_(r_bin_elf_get_relocs) (bin))) {
return NULL;
}
if (!(ret = r_list_newf ((RListFree)free))) {
free (relcs);
return NULL;
}
if (!(relocs_by_sym = ht_new (NULL, relocs_by_sym_free, NULL))) {
r_list_free (ret);
free (relcs);
return NULL;
}
vaddr = n_vaddr;
for (i = 0; !relcs[i].last; i++) {
ut64 sym_addr = 0;
if (relcs[i].sym) {
if (relcs[i].sym < bin->imports_by_ord_size && bin->imports_by_ord[relcs[i].sym]) {
bool found;
sym_addr = ht_find_intu64 (relocs_by_sym, relcs[i].sym, &found);
if (!found) {
sym_addr = 0;
}
} else if (relcs[i].sym < bin->symbols_by_ord_size && bin->symbols_by_ord[relcs[i].sym]) {
sym_addr = bin->symbols_by_ord[relcs[i].sym]->vaddr;
}
}
// TODO relocation types B, L
_patch_reloc (bin->ehdr.e_machine, &b->iob, &relcs[i], sym_addr ? sym_addr : vaddr, 0, n_vaddr + size);
if (!(ptr = reloc_convert (bin, &relcs[i], n_vaddr))) {
continue;
}
if (sym_addr) {
ptr->vaddr = sym_addr;
} else {
ptr->vaddr = vaddr;
ht_insert_intu64 (relocs_by_sym, relcs[i].sym, vaddr);
vaddr += cdsz;
}
r_list_append (ret, ptr);
}
ht_free (relocs_by_sym);
free (relcs);
return ret;
}
static bool has_canary(RBinFile *bf) {
bool ret = false;
RList* imports_list = imports (bf);
RListIter *iter;
RBinImport *import;
if (imports_list) {
r_list_foreach (imports_list, iter, import) {
if (!strcmp (import->name, "__stack_chk_fail") || !strcmp (import->name, "__stack_smash_handler")) {
ret = true;
break;
}
}
imports_list->free = r_bin_import_free;
r_list_free (imports_list);
}
return ret;
}
static RBinInfo* info(RBinFile *bf) {
RBinInfo *ret = NULL;
char *str;
if (!(ret = R_NEW0 (RBinInfo))) {
return NULL;
}
ret->lang = "c";
ret->file = bf->file
? strdup (bf->file)
: NULL;
void *obj = bf->o->bin_obj;
if ((str = Elf_(r_bin_elf_get_rpath)(obj))) {
ret->rpath = strdup (str);
free (str);
} else {
ret->rpath = strdup ("NONE");
}
if (!(str = Elf_(r_bin_elf_get_file_type) (obj))) {
free (ret);
return NULL;
}
ret->type = str;
ret->has_pi = (strstr (str, "DYN"))? 1: 0;
ret->has_lit = true;
ret->has_canary = has_canary (bf);
if (!(str = Elf_(r_bin_elf_get_elf_class) (obj))) {
free (ret);
return NULL;
}
ret->bclass = str;
if (!(str = Elf_(r_bin_elf_get_osabi_name) (obj))) {
free (ret);
return NULL;
}
ret->os = str;
if (!(str = Elf_(r_bin_elf_get_osabi_name) (obj))) {
free (ret);
return NULL;
}
ret->subsystem = str;
if (!(str = Elf_(r_bin_elf_get_machine_name) (obj))) {
free (ret);
return NULL;
}
ret->machine = str;
if (!(str = Elf_(r_bin_elf_get_arch) (obj))) {
free (ret);
return NULL;
}
ret->arch = str;
ret->rclass = strdup ("elf");
ret->bits = Elf_(r_bin_elf_get_bits) (obj);
if (!strcmp (ret->arch, "avr")) {
ret->bits = 16;
}
ret->big_endian = Elf_(r_bin_elf_is_big_endian) (obj);
ret->has_va = Elf_(r_bin_elf_has_va) (obj);
ret->has_nx = Elf_(r_bin_elf_has_nx) (obj);
ret->intrp = Elf_(r_bin_elf_intrp) (obj);
ret->dbg_info = 0;
if (!Elf_(r_bin_elf_get_stripped) (obj)) {
ret->dbg_info |= R_BIN_DBG_LINENUMS | R_BIN_DBG_SYMS | R_BIN_DBG_RELOCS;
} else {
ret->dbg_info |= R_BIN_DBG_STRIPPED;
}
if (Elf_(r_bin_elf_get_static) (obj)) {
ret->dbg_info |= R_BIN_DBG_STATIC;
}
RBinElfSymbol *symbol;
if (!(symbol = Elf_(r_bin_elf_get_symbols) (obj))) {
return ret;
}
int i;
for (i = 0; !symbol[i].last; i++) {
if (!strncmp (symbol[i].name, "type.", 5)) {
ret->lang = "go";
break;
}
}
return ret;
}
static RList* fields(RBinFile *bf) {
RList *ret = NULL;
RBinField *ptr = NULL;
struct r_bin_elf_field_t *field = NULL;
int i;
if (!(ret = r_list_new ())) {
return NULL;
}
ret->free = free;
if (!(field = Elf_(r_bin_elf_get_fields) (bf->o->bin_obj))) {
return ret;
}
for (i = 0; !field[i].last; i++) {
if (!(ptr = R_NEW0 (RBinField))) {
break;
}
ptr->name = strdup (field[i].name);
ptr->comment = NULL;
ptr->vaddr = field[i].offset;
ptr->paddr = field[i].offset;
r_list_append (ret, ptr);
}
free (field);
return ret;
}
static ut64 size(RBinFile *bf) {
ut64 off = 0;
ut64 len = 0;
if (!bf->o->sections) {
RListIter *iter;
RBinSection *section;
bf->o->sections = sections (bf);
r_list_foreach (bf->o->sections, iter, section) {
if (section->paddr > off) {
off = section->paddr;
len = section->size;
}
}
}
return off + len;
}
#if !R_BIN_ELF64 && !R_BIN_CGC
static void headers32(RBinFile *bf) {
#define p bf->rbin->cb_printf
const ut8 *buf = r_buf_get_at (bf->buf, 0, NULL);
p ("0x00000000 ELF MAGIC 0x%08x\n", r_read_le32 (buf));
p ("0x00000004 Type 0x%04x\n", r_read_le16 (buf + 4));
p ("0x00000006 Machine 0x%04x\n", r_read_le16 (buf + 6));
p ("0x00000008 Version 0x%08x\n", r_read_le32 (buf + 8));
p ("0x0000000c Entrypoint 0x%08x\n", r_read_le32 (buf + 12));
p ("0x00000010 PhOff 0x%08x\n", r_read_le32 (buf + 16));
p ("0x00000014 ShOff 0x%08x\n", r_read_le32 (buf + 20));
}
static bool check_bytes(const ut8 *buf, ut64 length) {
return buf && length > 4 && memcmp (buf, ELFMAG, SELFMAG) == 0
&& buf[4] != 2;
}
extern struct r_bin_dbginfo_t r_bin_dbginfo_elf;
extern struct r_bin_write_t r_bin_write_elf;
static RBuffer* create(RBin* bin, const ut8 *code, int codelen, const ut8 *data, int datalen) {
ut32 filesize, code_va, code_pa, phoff;
ut32 p_start, p_phoff, p_phdr;
ut32 p_ehdrsz, p_phdrsz;
ut16 ehdrsz, phdrsz;
ut32 p_vaddr, p_paddr, p_fs, p_fs2;
ut32 baddr;
int is_arm = 0;
RBuffer *buf = r_buf_new ();
if (bin && bin->cur && bin->cur->o && bin->cur->o->info) {
is_arm = !strcmp (bin->cur->o->info->arch, "arm");
}
// XXX: hardcoded
if (is_arm) {
baddr = 0x40000;
} else {
baddr = 0x8048000;
}
#define B(x,y) r_buf_append_bytes(buf,(const ut8*)x,y)
#define D(x) r_buf_append_ut32(buf,x)
#define H(x) r_buf_append_ut16(buf,x)
#define Z(x) r_buf_append_nbytes(buf,x)
#define W(x,y,z) r_buf_write_at(buf,x,(const ut8*)y,z)
#define WZ(x,y) p_tmp=buf->length;Z(x);W(p_tmp,y,strlen(y))
B ("\x7F" "ELF" "\x01\x01\x01\x00", 8);
Z (8);
H (2); // ET_EXEC
if (is_arm) {
H (40); // e_machne = EM_ARM
} else {
H (3); // e_machne = EM_I386
}
D (1);
p_start = buf->length;
D (-1); // _start
p_phoff = buf->length;
D (-1); // phoff -- program headers offset
D (0); // shoff -- section headers offset
D (0); // flags
p_ehdrsz = buf->length;
H (-1); // ehdrsz
p_phdrsz = buf->length;
H (-1); // phdrsz
H (1);
H (0);
H (0);
H (0);
// phdr:
p_phdr = buf->length;
D (1);
D (0);
p_vaddr = buf->length;
D (-1); // vaddr = $$
p_paddr = buf->length;
D (-1); // paddr = $$
p_fs = buf->length;
D (-1); // filesize
p_fs2 = buf->length;
D (-1); // filesize
D (5); // flags
D (0x1000); // align
ehdrsz = p_phdr;
phdrsz = buf->length - p_phdr;
code_pa = buf->length;
code_va = code_pa + baddr;
phoff = 0x34;//p_phdr ;
filesize = code_pa + codelen + datalen;
W (p_start, &code_va, 4);
W (p_phoff, &phoff, 4);
W (p_ehdrsz, &ehdrsz, 2);
W (p_phdrsz, &phdrsz, 2);
code_va = baddr; // hack
W (p_vaddr, &code_va, 4);
code_pa = baddr; // hack
W (p_paddr, &code_pa, 4);
W (p_fs, &filesize, 4);
W (p_fs2, &filesize, 4);
B (code, codelen);
if (data && datalen > 0) {
//ut32 data_section = buf->length;
eprintf ("Warning: DATA section not support for ELF yet\n");
B (data, datalen);
}
return buf;
}
RBinPlugin r_bin_plugin_elf = {
.name = "elf",
.desc = "ELF format r2 plugin",
.license = "LGPL3",
.get_sdb = &get_sdb,
.load = &load,
.load_bytes = &load_bytes,
.load_buffer = &load_buffer,
.destroy = &destroy,
.check_bytes = &check_bytes,
.baddr = &baddr,
.boffset = &boffset,
.binsym = &binsym,
.entries = &entries,
.sections = §ions,
.symbols = &symbols,
.minstrlen = 4,
.imports = &imports,
.info = &info,
.fields = &fields,
.header = &headers32,
.size = &size,
.libs = &libs,
.relocs = &relocs,
.patch_relocs = &patch_relocs,
.dbginfo = &r_bin_dbginfo_elf,
.create = &create,
.write = &r_bin_write_elf,
.file_type = &get_file_type,
.regstate = ®state,
.maps = &maps,
};
#ifndef CORELIB
RLibStruct radare_plugin = {
.type = R_LIB_TYPE_BIN,
.data = &r_bin_plugin_elf,
.version = R2_VERSION
};
#endif
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_140_0 |
crossvul-cpp_data_bad_923_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD %
% T H H R R E SS H H O O L D D %
% T HHHHH RRRR EEE SSS HHHHH O O L D D %
% T H H R R E SS H H O O L D D %
% T H H R R EEEEE SSSSS H H OOO LLLLL DDDD %
% %
% %
% MagickCore Image Threshold Methods %
% %
% Software Design %
% Cristy %
% October 1996 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/property.h"
#include "magick/blob.h"
#include "magick/cache-view.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/configure.h"
#include "magick/constitute.h"
#include "magick/decorate.h"
#include "magick/draw.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/effect.h"
#include "magick/fx.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/montage.h"
#include "magick/option.h"
#include "magick/pixel-private.h"
#include "magick/quantize.h"
#include "magick/quantum.h"
#include "magick/random_.h"
#include "magick/random-private.h"
#include "magick/resize.h"
#include "magick/resource_.h"
#include "magick/segment.h"
#include "magick/shear.h"
#include "magick/signature-private.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/thread-private.h"
#include "magick/threshold.h"
#include "magick/transform.h"
#include "magick/xml-tree.h"
/*
Define declarations.
*/
#define ThresholdsFilename "thresholds.xml"
/*
Typedef declarations.
*/
struct _ThresholdMap
{
char
*map_id,
*description;
size_t
width,
height;
ssize_t
divisor,
*levels;
};
/*
Static declarations.
*/
static const char
*MinimalThresholdMap =
"<?xml version=\"1.0\"?>"
"<thresholds>"
" <threshold map=\"threshold\" alias=\"1x1\">"
" <description>Threshold 1x1 (non-dither)</description>"
" <levels width=\"1\" height=\"1\" divisor=\"2\">"
" 1"
" </levels>"
" </threshold>"
" <threshold map=\"checks\" alias=\"2x1\">"
" <description>Checkerboard 2x1 (dither)</description>"
" <levels width=\"2\" height=\"2\" divisor=\"3\">"
" 1 2"
" 2 1"
" </levels>"
" </threshold>"
"</thresholds>";
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A d a p t i v e T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AdaptiveThresholdImage() selects an individual threshold for each pixel
% based on the range of intensity values in its local neighborhood. This
% allows for thresholding of an image whose global intensity histogram
% doesn't contain distinctive peaks.
%
% The format of the AdaptiveThresholdImage method is:
%
% Image *AdaptiveThresholdImage(const Image *image,
% const size_t width,const size_t height,
% const ssize_t offset,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width: the width of the local neighborhood.
%
% o height: the height of the local neighborhood.
%
% o offset: the mean offset.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const ssize_t offset,
ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
MagickRealType
number_pixels;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse)
{
InheritException(exception,&threshold_image->exception);
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Local adaptive threshold.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&zero);
number_pixels=(MagickRealType) (width*height);
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
channel_bias,
channel_sum;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p,
*magick_restrict r;
register IndexPacket
*magick_restrict threshold_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
height/2L,image->columns+width,height,exception);
q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view);
channel_bias=zero;
channel_sum=zero;
r=p;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
{
channel_bias.red+=r[u].red;
channel_bias.green+=r[u].green;
channel_bias.blue+=r[u].blue;
channel_bias.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType)
GetPixelIndex(indexes+(r-p)+u);
}
channel_sum.red+=r[u].red;
channel_sum.green+=r[u].green;
channel_sum.blue+=r[u].blue;
channel_sum.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u);
}
r+=image->columns+width;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickPixelPacket
mean;
mean=zero;
r=p;
channel_sum.red-=channel_bias.red;
channel_sum.green-=channel_bias.green;
channel_sum.blue-=channel_bias.blue;
channel_sum.opacity-=channel_bias.opacity;
channel_sum.index-=channel_bias.index;
channel_bias=zero;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias.red+=r[0].red;
channel_bias.green+=r[0].green;
channel_bias.blue+=r[0].blue;
channel_bias.opacity+=r[0].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0);
channel_sum.red+=r[width-1].red;
channel_sum.green+=r[width-1].green;
channel_sum.blue+=r[width-1].blue;
channel_sum.opacity+=r[width-1].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+
width-1);
r+=image->columns+width;
}
mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset);
mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset);
mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset);
mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset);
if (image->colorspace == CMYKColorspace)
mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset);
SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ?
0 : QuantumRange);
SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ?
0 : QuantumRange);
SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ?
0 : QuantumRange);
SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ?
0 : QuantumRange);
if (image->colorspace == CMYKColorspace)
SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex(
threshold_indexes+x) <= mean.index) ? 0 : QuantumRange));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(threshold_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A u t o T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AutoThresholdImage() automatically performs image thresholding
% dependent on which method you specify.
%
% The format of the AutoThresholdImage method is:
%
% MagickBooleanType AutoThresholdImage(Image *image,
% const AutoThresholdMethod method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: The image to auto-threshold.
%
% o method: choose from Kapur, OTSU, or Triangle.
%
% o exception: return any errors or warnings in this structure.
%
*/
static double KapurThreshold(const Image *image,const double *histogram,
ExceptionInfo *exception)
{
#define MaxIntensity 255
double
*black_entropy,
*cumulative_histogram,
entropy,
epsilon,
maximum_entropy,
*white_entropy;
register ssize_t
i,
j;
size_t
threshold;
/*
Compute optimal threshold from the entopy of the histogram.
*/
cumulative_histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*cumulative_histogram));
black_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*black_entropy));
white_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*white_entropy));
if ((cumulative_histogram == (double *) NULL) ||
(black_entropy == (double *) NULL) || (white_entropy == (double *) NULL))
{
if (white_entropy != (double *) NULL)
white_entropy=(double *) RelinquishMagickMemory(white_entropy);
if (black_entropy != (double *) NULL)
black_entropy=(double *) RelinquishMagickMemory(black_entropy);
if (cumulative_histogram != (double *) NULL)
cumulative_histogram=(double *)
RelinquishMagickMemory(cumulative_histogram);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(-1.0);
}
/*
Entropy for black and white parts of the histogram.
*/
cumulative_histogram[0]=histogram[0];
for (i=1; i <= MaxIntensity; i++)
cumulative_histogram[i]=cumulative_histogram[i-1]+histogram[i];
epsilon=MagickMinimumValue;
for (j=0; j <= MaxIntensity; j++)
{
/*
Black entropy.
*/
black_entropy[j]=0.0;
if (cumulative_histogram[j] > epsilon)
{
entropy=0.0;
for (i=0; i <= j; i++)
if (histogram[i] > epsilon)
entropy-=histogram[i]/cumulative_histogram[j]*
log(histogram[i]/cumulative_histogram[j]);
black_entropy[j]=entropy;
}
/*
White entropy.
*/
white_entropy[j]=0.0;
if ((1.0-cumulative_histogram[j]) > epsilon)
{
entropy=0.0;
for (i=j+1; i <= MaxIntensity; i++)
if (histogram[i] > epsilon)
entropy-=histogram[i]/(1.0-cumulative_histogram[j])*
log(histogram[i]/(1.0-cumulative_histogram[j]));
white_entropy[j]=entropy;
}
}
/*
Find histogram bin with maximum entropy.
*/
maximum_entropy=black_entropy[0]+white_entropy[0];
threshold=0;
for (j=1; j <= MaxIntensity; j++)
if ((black_entropy[j]+white_entropy[j]) > maximum_entropy)
{
maximum_entropy=black_entropy[j]+white_entropy[j];
threshold=(size_t) j;
}
/*
Free resources.
*/
white_entropy=(double *) RelinquishMagickMemory(white_entropy);
black_entropy=(double *) RelinquishMagickMemory(black_entropy);
cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram);
return(100.0*threshold/MaxIntensity);
}
static double OTSUThreshold(const Image *image,const double *histogram,
ExceptionInfo *exception)
{
double
max_sigma,
*myu,
*omega,
*probability,
*sigma,
threshold;
register ssize_t
i;
/*
Compute optimal threshold from maximization of inter-class variance.
*/
myu=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*myu));
omega=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*omega));
probability=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*probability));
sigma=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*sigma));
if ((myu == (double *) NULL) || (omega == (double *) NULL) ||
(probability == (double *) NULL) || (sigma == (double *) NULL))
{
if (sigma != (double *) NULL)
sigma=(double *) RelinquishMagickMemory(sigma);
if (probability != (double *) NULL)
probability=(double *) RelinquishMagickMemory(probability);
if (omega != (double *) NULL)
omega=(double *) RelinquishMagickMemory(omega);
if (myu != (double *) NULL)
myu=(double *) RelinquishMagickMemory(myu);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(-1.0);
}
/*
Calculate probability density.
*/
for (i=0; i <= (ssize_t) MaxIntensity; i++)
probability[i]=histogram[i];
/*
Generate probability of graylevels and mean value for separation.
*/
omega[0]=probability[0];
myu[0]=0.0;
for (i=1; i <= (ssize_t) MaxIntensity; i++)
{
omega[i]=omega[i-1]+probability[i];
myu[i]=myu[i-1]+i*probability[i];
}
/*
Sigma maximization: inter-class variance and compute optimal threshold.
*/
threshold=0;
max_sigma=0.0;
for (i=0; i < (ssize_t) MaxIntensity; i++)
{
sigma[i]=0.0;
if ((omega[i] != 0.0) && (omega[i] != 1.0))
sigma[i]=pow(myu[MaxIntensity]*omega[i]-myu[i],2.0)/(omega[i]*(1.0-
omega[i]));
if (sigma[i] > max_sigma)
{
max_sigma=sigma[i];
threshold=(double) i;
}
}
/*
Free resources.
*/
myu=(double *) RelinquishMagickMemory(myu);
omega=(double *) RelinquishMagickMemory(omega);
probability=(double *) RelinquishMagickMemory(probability);
sigma=(double *) RelinquishMagickMemory(sigma);
return(100.0*threshold/MaxIntensity);
}
static double TriangleThreshold(const Image *image,const double *histogram)
{
double
a,
b,
c,
count,
distance,
inverse_ratio,
max_distance,
segment,
x1,
x2,
y1,
y2;
register ssize_t
i;
ssize_t
end,
max,
start,
threshold;
/*
Compute optimal threshold with triangle algorithm.
*/
start=0; /* find start bin, first bin not zero count */
for (i=0; i <= (ssize_t) MaxIntensity; i++)
if (histogram[i] > 0.0)
{
start=i;
break;
}
end=0; /* find end bin, last bin not zero count */
for (i=(ssize_t) MaxIntensity; i >= 0; i--)
if (histogram[i] > 0.0)
{
end=i;
break;
}
max=0; /* find max bin, bin with largest count */
count=0.0;
for (i=0; i <= (ssize_t) MaxIntensity; i++)
if (histogram[i] > count)
{
max=i;
count=histogram[i];
}
/*
Compute threshold at split point.
*/
x1=(double) max;
y1=histogram[max];
x2=(double) end;
if ((max-start) >= (end-max))
x2=(double) start;
y2=0.0;
a=y1-y2;
b=x2-x1;
c=(-1.0)*(a*x1+b*y1);
inverse_ratio=1.0/sqrt(a*a+b*b+c*c);
threshold=0;
max_distance=0.0;
if (x2 == (double) start)
for (i=start; i < max; i++)
{
segment=inverse_ratio*(a*i+b*histogram[i]+c);
distance=sqrt(segment*segment);
if ((distance > max_distance) && (segment > 0.0))
{
threshold=i;
max_distance=distance;
}
}
else
for (i=end; i > max; i--)
{
segment=inverse_ratio*(a*i+b*histogram[i]+c);
distance=sqrt(segment*segment);
if ((distance > max_distance) && (segment < 0.0))
{
threshold=i;
max_distance=distance;
}
}
return(100.0*threshold/MaxIntensity);
}
MagickExport MagickBooleanType AutoThresholdImage(Image *image,
const AutoThresholdMethod method,ExceptionInfo *exception)
{
CacheView
*image_view;
char
property[MagickPathExtent];
double
gamma,
*histogram,
sum,
threshold;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
y;
/*
Form histogram.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*histogram));
if (histogram == (double *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=MagickTrue;
(void) memset(histogram,0,(MaxIntensity+1UL)*sizeof(*histogram));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
double intensity = GetPixelIntensity(image,p);
histogram[ScaleQuantumToChar(ClampToQuantum(intensity))]++;
p++;
}
}
image_view=DestroyCacheView(image_view);
/*
Normalize histogram.
*/
sum=0.0;
for (i=0; i <= (ssize_t) MaxIntensity; i++)
sum+=histogram[i];
gamma=PerceptibleReciprocal(sum);
for (i=0; i <= (ssize_t) MaxIntensity; i++)
histogram[i]=gamma*histogram[i];
/*
Discover threshold from histogram.
*/
switch (method)
{
case KapurThresholdMethod:
{
threshold=KapurThreshold(image,histogram,exception);
break;
}
case OTSUThresholdMethod:
default:
{
threshold=OTSUThreshold(image,histogram,exception);
break;
}
case TriangleThresholdMethod:
{
threshold=TriangleThreshold(image,histogram);
break;
}
}
histogram=(double *) RelinquishMagickMemory(histogram);
if (threshold < 0.0)
status=MagickFalse;
if (status == MagickFalse)
return(MagickFalse);
/*
Threshold image.
*/
(void) FormatLocaleString(property,MagickPathExtent,"%g%%",threshold);
(void) SetImageProperty(image,"auto-threshold:threshold",property);
return(BilevelImage(image,QuantumRange*threshold/100.0));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B i l e v e l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BilevelImage() changes the value of individual pixels based on the
% intensity of each pixel channel. The result is a high-contrast image.
%
% More precisely each channel value of the image is 'thresholded' so that if
% it is equal to or less than the given value it is set to zero, while any
% value greater than that give is set to it maximum or QuantumRange.
%
% This function is what is used to implement the "-threshold" operator for
% the command line API.
%
% If the default channel setting is given the image is thresholded using just
% the gray 'intensity' of the image, rather than the individual channels.
%
% The format of the BilevelImageChannel method is:
%
% MagickBooleanType BilevelImage(Image *image,const double threshold)
% MagickBooleanType BilevelImageChannel(Image *image,
% const ChannelType channel,const double threshold)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o threshold: define the threshold values.
%
% Aside: You can get the same results as operator using LevelImageChannels()
% with the 'threshold' value for both the black_point and the white_point.
%
*/
MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold)
{
MagickBooleanType
status;
status=BilevelImageChannel(image,DefaultChannels,threshold);
return(status);
}
MagickExport MagickBooleanType BilevelImageChannel(Image *image,
const ChannelType channel,const double threshold)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace);
/*
Bilevel threshold image.
*/
status=MagickTrue;
progress=0;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
if ((channel & SyncChannels) != 0)
{
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,GetPixelIntensity(image,q) <= threshold ? 0 :
QuantumRange);
SetPixelGreen(q,GetPixelRed(q));
SetPixelBlue(q,GetPixelRed(q));
q++;
}
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold ? 0 :
QuantumRange);
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold ? 0 :
QuantumRange);
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold ? 0 :
QuantumRange);
if ((channel & OpacityChannel) != 0)
{
if (image->matte == MagickFalse)
SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <=
threshold ? 0 : QuantumRange);
else
SetPixelAlpha(q,(MagickRealType) GetPixelAlpha(q) <= threshold ?
OpaqueOpacity : TransparentOpacity);
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <=
threshold ? 0 : QuantumRange);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B l a c k T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BlackThresholdImage() is like ThresholdImage() but forces all pixels below
% the threshold into black while leaving all pixels at or above the threshold
% unchanged.
%
% The format of the BlackThresholdImage method is:
%
% MagickBooleanType BlackThresholdImage(Image *image,const char *threshold)
% MagickBooleanType BlackThresholdImageChannel(Image *image,
% const ChannelType channel,const char *threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel or channels to be thresholded.
%
% o threshold: Define the threshold value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType BlackThresholdImage(Image *image,
const char *threshold)
{
MagickBooleanType
status;
status=BlackThresholdImageChannel(image,DefaultChannels,threshold,
&image->exception);
return(status);
}
MagickExport MagickBooleanType BlackThresholdImageChannel(Image *image,
const ChannelType channel,const char *thresholds,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
GeometryInfo
geometry_info;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
threshold;
MagickStatusType
flags;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (thresholds == (const char *) NULL)
return(MagickTrue);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
GetMagickPixelPacket(image,&threshold);
flags=ParseGeometry(thresholds,&geometry_info);
threshold.red=geometry_info.rho;
threshold.green=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
threshold.green=threshold.red;
threshold.blue=geometry_info.xi;
if ((flags & XiValue) == 0)
threshold.blue=threshold.red;
threshold.opacity=geometry_info.psi;
if ((flags & PsiValue) == 0)
threshold.opacity=threshold.red;
threshold.index=geometry_info.chi;
if ((flags & ChiValue) == 0)
threshold.index=threshold.red;
if ((flags & PercentValue) != 0)
{
threshold.red*=(MagickRealType) (QuantumRange/100.0);
threshold.green*=(MagickRealType) (QuantumRange/100.0);
threshold.blue*=(MagickRealType) (QuantumRange/100.0);
threshold.opacity*=(MagickRealType) (QuantumRange/100.0);
threshold.index*=(MagickRealType) (QuantumRange/100.0);
}
if ((IsMagickGray(&threshold) == MagickFalse) &&
(IsGrayColorspace(image->colorspace) != MagickFalse))
(void) SetImageColorspace(image,sRGBColorspace);
/*
Black threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (((channel & RedChannel) != 0) &&
((MagickRealType) GetPixelRed(q) < threshold.red))
SetPixelRed(q,0);
if (((channel & GreenChannel) != 0) &&
((MagickRealType) GetPixelGreen(q) < threshold.green))
SetPixelGreen(q,0);
if (((channel & BlueChannel) != 0) &&
((MagickRealType) GetPixelBlue(q) < threshold.blue))
SetPixelBlue(q,0);
if (((channel & OpacityChannel) != 0) &&
((MagickRealType) GetPixelOpacity(q) < threshold.opacity))
SetPixelOpacity(q,0);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace) &&
((MagickRealType) GetPixelIndex(indexes+x) < threshold.index))
SetPixelIndex(indexes+x,0);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l a m p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClampImage() set each pixel whose value is below zero to zero and any the
% pixel whose value is above the quantum range to the quantum range (e.g.
% 65535) otherwise the pixel value remains unchanged.
%
% The format of the ClampImageChannel method is:
%
% MagickBooleanType ClampImage(Image *image)
% MagickBooleanType ClampImageChannel(Image *image,
% const ChannelType channel)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
*/
MagickExport MagickBooleanType ClampImage(Image *image)
{
MagickBooleanType
status;
status=ClampImageChannel(image,DefaultChannels);
return(status);
}
MagickExport MagickBooleanType ClampImageChannel(Image *image,
const ChannelType channel)
{
#define ClampImageTag "Clamp/Image"
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
register PixelPacket
*magick_restrict q;
q=image->colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
SetPixelRed(q,ClampPixel((MagickRealType) GetPixelRed(q)));
SetPixelGreen(q,ClampPixel((MagickRealType) GetPixelGreen(q)));
SetPixelBlue(q,ClampPixel((MagickRealType) GetPixelBlue(q)));
SetPixelOpacity(q,ClampPixel((MagickRealType) GetPixelOpacity(q)));
q++;
}
return(SyncImage(image));
}
/*
Clamp image.
*/
status=MagickTrue;
progress=0;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampPixel((MagickRealType) GetPixelRed(q)));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampPixel((MagickRealType) GetPixelGreen(q)));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampPixel((MagickRealType) GetPixelBlue(q)));
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,ClampPixel((MagickRealType) GetPixelOpacity(q)));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(indexes+x,ClampPixel((MagickRealType) GetPixelIndex(
indexes+x)));
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ClampImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y T h r e s h o l d M a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyThresholdMap() de-allocate the given ThresholdMap
%
% The format of the ListThresholdMaps method is:
%
% ThresholdMap *DestroyThresholdMap(Threshold *map)
%
% A description of each parameter follows.
%
% o map: Pointer to the Threshold map to destroy
%
*/
MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map)
{
assert(map != (ThresholdMap *) NULL);
if (map->map_id != (char *) NULL)
map->map_id=DestroyString(map->map_id);
if (map->description != (char *) NULL)
map->description=DestroyString(map->description);
if (map->levels != (ssize_t *) NULL)
map->levels=(ssize_t *) RelinquishMagickMemory(map->levels);
map=(ThresholdMap *) RelinquishMagickMemory(map);
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t T h r e s h o l d M a p F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetThresholdMapFile() look for a given threshold map name or alias in the
% given XML file data, and return the allocated the map when found.
%
% The format of the ListThresholdMaps method is:
%
% ThresholdMap *GetThresholdMap(const char *xml,const char *filename,
% const char *map_id,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o xml: The threshold map list in XML format.
%
% o filename: The threshold map XML filename.
%
% o map_id: ID of the map to look for in XML list.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ThresholdMap *GetThresholdMapFile(const char *xml,
const char *filename,const char *map_id,ExceptionInfo *exception)
{
const char
*attribute,
*content;
double
value;
ThresholdMap
*map;
XMLTreeInfo
*description,
*levels,
*threshold,
*thresholds;
map = (ThresholdMap *) NULL;
(void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
"Loading threshold map file \"%s\" ...",filename);
thresholds=NewXMLTree(xml,exception);
if ( thresholds == (XMLTreeInfo *) NULL )
return(map);
for (threshold = GetXMLTreeChild(thresholds,"threshold");
threshold != (XMLTreeInfo *) NULL;
threshold = GetNextXMLTreeTag(threshold) )
{
attribute=GetXMLTreeAttribute(threshold, "map");
if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0))
break;
attribute=GetXMLTreeAttribute(threshold, "alias");
if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0))
break;
}
if (threshold == (XMLTreeInfo *) NULL)
{
thresholds=DestroyXMLTree(thresholds);
return(map);
}
description=GetXMLTreeChild(threshold,"description");
if (description == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<description>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
return(map);
}
levels=GetXMLTreeChild(threshold,"levels");
if (levels == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<levels>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
return(map);
}
/*
The map has been found -- allocate a Threshold Map to return
*/
map=(ThresholdMap *) AcquireMagickMemory(sizeof(ThresholdMap));
if (map == (ThresholdMap *) NULL)
ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap");
map->map_id=(char *) NULL;
map->description=(char *) NULL;
map->levels=(ssize_t *) NULL;
/*
Assign basic attributeibutes.
*/
attribute=GetXMLTreeAttribute(threshold,"map");
if (attribute != (char *) NULL)
map->map_id=ConstantString(attribute);
content=GetXMLTreeContent(description);
if (content != (char *) NULL)
map->description=ConstantString(content);
attribute=GetXMLTreeAttribute(levels,"width");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels width>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->width=StringToUnsignedLong(attribute);
if (map->width == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels width>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
attribute=GetXMLTreeAttribute(levels,"height");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels height>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->height=StringToUnsignedLong(attribute);
if (map->height == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels height>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
attribute=GetXMLTreeAttribute(levels, "divisor");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels divisor>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->divisor=(ssize_t) StringToLong(attribute);
if (map->divisor < 2)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels divisor>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
/*
Allocate theshold levels array.
*/
content=GetXMLTreeContent(levels);
if (content == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingContent", "<levels>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height*
sizeof(*map->levels));
if (map->levels == (ssize_t *) NULL)
ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap");
{
char
*p;
register ssize_t
i;
/*
Parse levels into integer array.
*/
for (i=0; i< (ssize_t) (map->width*map->height); i++)
{
map->levels[i]=(ssize_t) strtol(content,&p,10);
if (p == content)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> too few values, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
if ((map->levels[i] < 0) || (map->levels[i] > map->divisor))
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> %.20g out of range, map \"%s\"",
(double) map->levels[i],map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
content=p;
}
value=(double) strtol(content,&p,10);
(void) value;
if (p != content)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> too many values, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
}
thresholds=DestroyXMLTree(thresholds);
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t T h r e s h o l d M a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetThresholdMap() load and search one or more threshold map files for the
% a map matching the given name or aliase.
%
% The format of the GetThresholdMap method is:
%
% ThresholdMap *GetThresholdMap(const char *map_id,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o map_id: ID of the map to look for.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ThresholdMap *GetThresholdMap(const char *map_id,
ExceptionInfo *exception)
{
const StringInfo
*option;
LinkedListInfo
*options;
ThresholdMap
*map;
map=GetThresholdMapFile(MinimalThresholdMap,"built-in",map_id,exception);
if (map != (ThresholdMap *) NULL)
return(map);
options=GetConfigureOptions(ThresholdsFilename,exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
while (option != (const StringInfo *) NULL)
{
map=GetThresholdMapFile((const char *) GetStringInfoDatum(option),
GetStringInfoPath(option),map_id,exception);
if (map != (ThresholdMap *) NULL)
break;
option=(const StringInfo *) GetNextValueInLinkedList(options);
}
options=DestroyConfigureOptions(options);
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ L i s t T h r e s h o l d M a p F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ListThresholdMapFile() lists the threshold maps and their descriptions
% in the given XML file data.
%
% The format of the ListThresholdMaps method is:
%
% MagickBooleanType ListThresholdMaps(FILE *file,const char*xml,
% const char *filename,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o file: An pointer to the output FILE.
%
% o xml: The threshold map list in XML format.
%
% o filename: The threshold map XML filename.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml,
const char *filename,ExceptionInfo *exception)
{
XMLTreeInfo *thresholds,*threshold,*description;
const char *map,*alias,*content;
assert( xml != (char *) NULL );
assert( file != (FILE *) NULL );
(void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
"Loading threshold map file \"%s\" ...",filename);
thresholds=NewXMLTree(xml,exception);
if ( thresholds == (XMLTreeInfo *) NULL )
return(MagickFalse);
(void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description");
(void) FormatLocaleFile(file,
"----------------------------------------------------\n");
for( threshold = GetXMLTreeChild(thresholds,"threshold");
threshold != (XMLTreeInfo *) NULL;
threshold = GetNextXMLTreeTag(threshold) )
{
map = GetXMLTreeAttribute(threshold, "map");
if (map == (char *) NULL) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<map>");
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
alias = GetXMLTreeAttribute(threshold, "alias");
/* alias is optional, no if test needed */
description=GetXMLTreeChild(threshold,"description");
if ( description == (XMLTreeInfo *) NULL ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<description>, map \"%s\"", map);
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
content=GetXMLTreeContent(description);
if ( content == (char *) NULL ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingContent", "<description>, map \"%s\"", map);
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
(void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "",
content);
}
thresholds=DestroyXMLTree(thresholds);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L i s t T h r e s h o l d M a p s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ListThresholdMaps() lists the threshold maps and their descriptions
% as defined by "threshold.xml" to a file.
%
% The format of the ListThresholdMaps method is:
%
% MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o file: An pointer to the output FILE.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ListThresholdMaps(FILE *file,
ExceptionInfo *exception)
{
const StringInfo
*option;
LinkedListInfo
*options;
MagickStatusType
status;
status=MagickTrue;
if (file == (FILE *) NULL)
file=stdout;
options=GetConfigureOptions(ThresholdsFilename,exception);
(void) FormatLocaleFile(file,
"\n Threshold Maps for Ordered Dither Operations\n");
option=(const StringInfo *) GetNextValueInLinkedList(options);
while (option != (const StringInfo *) NULL)
{
(void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option));
status&=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option),
GetStringInfoPath(option),exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
}
options=DestroyConfigureOptions(options);
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% O r d e r e d D i t h e r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OrderedDitherImage() uses the ordered dithering technique of reducing color
% images to monochrome using positional information to retain as much
% information as possible.
%
% WARNING: This function is deprecated, and is now just a call to
% the more more powerful OrderedPosterizeImage(); function.
%
% The format of the OrderedDitherImage method is:
%
% MagickBooleanType OrderedDitherImage(Image *image)
% MagickBooleanType OrderedDitherImageChannel(Image *image,
% const ChannelType channel,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel or channels to be thresholded.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType OrderedDitherImage(Image *image)
{
MagickBooleanType
status;
status=OrderedDitherImageChannel(image,DefaultChannels,&image->exception);
return(status);
}
MagickExport MagickBooleanType OrderedDitherImageChannel(Image *image,
const ChannelType channel,ExceptionInfo *exception)
{
MagickBooleanType
status;
/*
Call the augumented function OrderedPosterizeImage()
*/
status=OrderedPosterizeImageChannel(image,channel,"o8x8",exception);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% O r d e r e d P o s t e r i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OrderedPosterizeImage() will perform a ordered dither based on a number
% of pre-defined dithering threshold maps, but over multiple intensity
% levels, which can be different for different channels, according to the
% input argument.
%
% The format of the OrderedPosterizeImage method is:
%
% MagickBooleanType OrderedPosterizeImage(Image *image,
% const char *threshold_map,ExceptionInfo *exception)
% MagickBooleanType OrderedPosterizeImageChannel(Image *image,
% const ChannelType channel,const char *threshold_map,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel or channels to be thresholded.
%
% o threshold_map: A string containing the name of the threshold dither
% map to use, followed by zero or more numbers representing the number
% of color levels tho dither between.
%
% Any level number less than 2 will be equivalent to 2, and means only
% binary dithering will be applied to each color channel.
%
% No numbers also means a 2 level (bitmap) dither will be applied to all
% channels, while a single number is the number of levels applied to each
% channel in sequence. More numbers will be applied in turn to each of
% the color channels.
%
% For example: "o3x3,6" will generate a 6 level posterization of the
% image with a ordered 3x3 diffused pixel dither being applied between
% each level. While checker,8,8,4 will produce a 332 colormaped image
% with only a single checkerboard hash pattern (50% grey) between each
% color level, to basically double the number of color levels with
% a bare minimim of dithering.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType OrderedPosterizeImage(Image *image,
const char *threshold_map,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=OrderedPosterizeImageChannel(image,DefaultChannels,threshold_map,
exception);
return(status);
}
MagickExport MagickBooleanType OrderedPosterizeImageChannel(Image *image,
const ChannelType channel,const char *threshold_map,ExceptionInfo *exception)
{
#define DitherImageTag "Dither/Image"
CacheView
*image_view;
LongPixelPacket
levels;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
ThresholdMap
*map;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (threshold_map == (const char *) NULL)
return(MagickTrue);
{
char
token[MaxTextExtent];
register const char
*p;
p=(char *)threshold_map;
while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) &&
(*p != '\0'))
p++;
threshold_map=p;
while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) &&
(*p != '\0')) {
if ((p-threshold_map) >= (MaxTextExtent-1))
break;
token[p-threshold_map] = *p;
p++;
}
token[p-threshold_map] = '\0';
map = GetThresholdMap(token, exception);
if ( map == (ThresholdMap *) NULL ) {
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : '%s'","ordered-dither",threshold_map);
return(MagickFalse);
}
}
/* Set channel levels from extra comma separated arguments
Default to 2, the single value given, or individual channel values
*/
#if 1
{ /* parse directly as a comma separated list of integers */
char *p;
p = strchr((char *) threshold_map,',');
if ( p != (char *) NULL && isdigit((int) ((unsigned char) *(++p))) )
levels.index = (unsigned int) strtoul(p, &p, 10);
else
levels.index = 2;
levels.red = ((channel & RedChannel ) != 0) ? levels.index : 0;
levels.green = ((channel & GreenChannel) != 0) ? levels.index : 0;
levels.blue = ((channel & BlueChannel) != 0) ? levels.index : 0;
levels.opacity = ((channel & OpacityChannel) != 0) ? levels.index : 0;
levels.index = ((channel & IndexChannel) != 0
&& (image->colorspace == CMYKColorspace)) ? levels.index : 0;
/* if more than a single number, each channel has a separate value */
if ( p != (char *) NULL && *p == ',' ) {
p=strchr((char *) threshold_map,',');
p++;
if ((channel & RedChannel) != 0)
levels.red = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++);
if ((channel & GreenChannel) != 0)
levels.green = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++);
if ((channel & BlueChannel) != 0)
levels.blue = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++);
if ((channel & IndexChannel) != 0 && image->colorspace == CMYKColorspace)
levels.index=(unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++);
if ((channel & OpacityChannel) != 0)
levels.opacity = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++);
}
}
#else
/* Parse level values as a geometry */
/* This difficult!
* How to map GeometryInfo structure elements into
* LongPixelPacket structure elements, but according to channel?
* Note the channels list may skip elements!!!!
* EG -channel BA -ordered-dither map,2,3
* will need to map g.rho -> l.blue, and g.sigma -> l.opacity
* A simpler way is needed, probably converting geometry to a temporary
* array, then using channel to advance the index into ssize_t pixel packet.
*/
#endif
#if 0
printf("DEBUG levels r=%u g=%u b=%u a=%u i=%u\n",
levels.red, levels.green, levels.blue, levels.opacity, levels.index);
#endif
{ /* Do the posterized ordered dithering of the image */
ssize_t
d;
/* d = number of psuedo-level divisions added between color levels */
d = map->divisor-1;
/* reduce levels to levels - 1 */
levels.red = levels.red ? levels.red-1 : 0;
levels.green = levels.green ? levels.green-1 : 0;
levels.blue = levels.blue ? levels.blue-1 : 0;
levels.opacity = levels.opacity ? levels.opacity-1 : 0;
levels.index = levels.index ? levels.index-1 : 0;
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
InheritException(exception,&image->exception);
return(MagickFalse);
}
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
threshold,
t,
l;
/*
Figure out the dither threshold for this pixel
This must be a integer from 1 to map->divisor-1
*/
threshold = map->levels[(x%map->width) +map->width*(y%map->height)];
/* Dither each channel in the image as appropriate
Notes on the integer Math...
total number of divisions = (levels-1)*(divisor-1)+1)
t1 = this colors psuedo_level =
q->red * total_divisions / (QuantumRange+1)
l = posterization level 0..levels
t = dither threshold level 0..divisor-1 NB: 0 only on last
Each color_level is of size QuantumRange / (levels-1)
NB: All input levels and divisor are already had 1 subtracted
Opacity is inverted so 'off' represents transparent.
*/
if (levels.red) {
t = (ssize_t) (QuantumScale*GetPixelRed(q)*(levels.red*d+1));
l = t/d; t = t-l*d;
SetPixelRed(q,ClampToQuantum((MagickRealType)
((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.red)));
}
if (levels.green) {
t = (ssize_t) (QuantumScale*GetPixelGreen(q)*
(levels.green*d+1));
l = t/d; t = t-l*d;
SetPixelGreen(q,ClampToQuantum((MagickRealType)
((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.green)));
}
if (levels.blue) {
t = (ssize_t) (QuantumScale*GetPixelBlue(q)*
(levels.blue*d+1));
l = t/d; t = t-l*d;
SetPixelBlue(q,ClampToQuantum((MagickRealType)
((l+(t >= threshold))*(MagickRealType) QuantumRange/levels.blue)));
}
if (levels.opacity) {
t = (ssize_t) ((1.0-QuantumScale*GetPixelOpacity(q))*
(levels.opacity*d+1));
l = t/d; t = t-l*d;
SetPixelOpacity(q,ClampToQuantum((MagickRealType)
((1.0-l-(t >= threshold))*(MagickRealType) QuantumRange/
levels.opacity)));
}
if (levels.index) {
t = (ssize_t) (QuantumScale*GetPixelIndex(indexes+x)*
(levels.index*d+1));
l = t/d; t = t-l*d;
SetPixelIndex(indexes+x,ClampToQuantum((MagickRealType) ((l+
(t>=threshold))*(MagickRealType) QuantumRange/levels.index)));
}
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,DitherImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
}
map=DestroyThresholdMap(map);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P e r c e p t i b l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PerceptibleImage() set each pixel whose value is less than |epsilon| to
% epsilon or -epsilon (whichever is closer) otherwise the pixel value remains
% unchanged.
%
% The format of the PerceptibleImageChannel method is:
%
% MagickBooleanType PerceptibleImage(Image *image,const double epsilon)
% MagickBooleanType PerceptibleImageChannel(Image *image,
% const ChannelType channel,const double epsilon)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel type.
%
% o epsilon: the epsilon threshold (e.g. 1.0e-9).
%
*/
static inline Quantum PerceptibleThreshold(const Quantum quantum,
const double epsilon)
{
double
sign;
sign=(double) quantum < 0.0 ? -1.0 : 1.0;
if ((sign*quantum) >= epsilon)
return(quantum);
return((Quantum) (sign*epsilon));
}
MagickExport MagickBooleanType PerceptibleImage(Image *image,
const double epsilon)
{
MagickBooleanType
status;
status=PerceptibleImageChannel(image,DefaultChannels,epsilon);
return(status);
}
MagickExport MagickBooleanType PerceptibleImageChannel(Image *image,
const ChannelType channel,const double epsilon)
{
#define PerceptibleImageTag "Perceptible/Image"
CacheView
*image_view;
ExceptionInfo
*exception;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
register PixelPacket
*magick_restrict q;
q=image->colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
SetPixelRed(q,PerceptibleThreshold(GetPixelRed(q),epsilon));
SetPixelGreen(q,PerceptibleThreshold(GetPixelGreen(q),epsilon));
SetPixelBlue(q,PerceptibleThreshold(GetPixelBlue(q),epsilon));
SetPixelOpacity(q,PerceptibleThreshold(GetPixelOpacity(q),epsilon));
q++;
}
return(SyncImage(image));
}
/*
Perceptible image.
*/
status=MagickTrue;
progress=0;
exception=(&image->exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
SetPixelRed(q,PerceptibleThreshold(GetPixelRed(q),epsilon));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,PerceptibleThreshold(GetPixelGreen(q),epsilon));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,PerceptibleThreshold(GetPixelBlue(q),epsilon));
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,PerceptibleThreshold(GetPixelOpacity(q),epsilon));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(indexes+x,PerceptibleThreshold(GetPixelIndex(indexes+x),
epsilon));
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,PerceptibleImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R a n d o m T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RandomThresholdImage() changes the value of individual pixels based on the
% intensity of each pixel compared to a random threshold. The result is a
% low-contrast, two color image.
%
% The format of the RandomThresholdImage method is:
%
% MagickBooleanType RandomThresholdImageChannel(Image *image,
% const char *thresholds,ExceptionInfo *exception)
% MagickBooleanType RandomThresholdImageChannel(Image *image,
% const ChannelType channel,const char *thresholds,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel or channels to be thresholded.
%
% o thresholds: a geometry string containing low,high thresholds. If the
% string contains 2x2, 3x3, or 4x4, an ordered dither of order 2, 3, or 4
% is performed instead.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType RandomThresholdImage(Image *image,
const char *thresholds,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=RandomThresholdImageChannel(image,DefaultChannels,thresholds,
exception);
return(status);
}
MagickExport MagickBooleanType RandomThresholdImageChannel(Image *image,
const ChannelType channel,const char *thresholds,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
GeometryInfo
geometry_info;
MagickStatusType
flags;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
threshold;
MagickRealType
min_threshold,
max_threshold;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (thresholds == (const char *) NULL)
return(MagickTrue);
GetMagickPixelPacket(image,&threshold);
min_threshold=0.0;
max_threshold=(MagickRealType) QuantumRange;
flags=ParseGeometry(thresholds,&geometry_info);
min_threshold=geometry_info.rho;
max_threshold=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
max_threshold=min_threshold;
if (strchr(thresholds,'%') != (char *) NULL)
{
max_threshold*=(MagickRealType) (0.01*QuantumRange);
min_threshold*=(MagickRealType) (0.01*QuantumRange);
}
else
if (((max_threshold == min_threshold) || (max_threshold == 1)) &&
(min_threshold <= 8))
{
/*
Backward Compatibility -- ordered-dither -- IM v 6.2.9-6.
*/
status=OrderedPosterizeImageChannel(image,channel,thresholds,exception);
return(status);
}
/*
Random threshold image.
*/
status=MagickTrue;
progress=0;
if (channel == CompositeChannels)
{
if (AcquireImageColormap(image,2) == MagickFalse)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
random_info=AcquireRandomInfoThreadSet();
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
MagickBooleanType
sync;
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
IndexPacket
index;
MagickRealType
intensity;
intensity=GetPixelIntensity(image,q);
if (intensity < min_threshold)
threshold.index=min_threshold;
else if (intensity > max_threshold)
threshold.index=max_threshold;
else
threshold.index=(MagickRealType)(QuantumRange*
GetPseudoRandomValue(random_info[id]));
index=(IndexPacket) (intensity <= threshold.index ? 0 : 1);
SetPixelIndex(indexes+x,index);
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
return(status);
}
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
InheritException(exception,&image->exception);
return(MagickFalse);
}
random_info=AcquireRandomInfoThreadSet();
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register IndexPacket
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
{
if ((MagickRealType) GetPixelRed(q) < min_threshold)
threshold.red=min_threshold;
else
if ((MagickRealType) GetPixelRed(q) > max_threshold)
threshold.red=max_threshold;
else
threshold.red=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if ((channel & GreenChannel) != 0)
{
if ((MagickRealType) GetPixelGreen(q) < min_threshold)
threshold.green=min_threshold;
else
if ((MagickRealType) GetPixelGreen(q) > max_threshold)
threshold.green=max_threshold;
else
threshold.green=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if ((channel & BlueChannel) != 0)
{
if ((MagickRealType) GetPixelBlue(q) < min_threshold)
threshold.blue=min_threshold;
else
if ((MagickRealType) GetPixelBlue(q) > max_threshold)
threshold.blue=max_threshold;
else
threshold.blue=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if ((channel & OpacityChannel) != 0)
{
if ((MagickRealType) GetPixelOpacity(q) < min_threshold)
threshold.opacity=min_threshold;
else
if ((MagickRealType) GetPixelOpacity(q) > max_threshold)
threshold.opacity=max_threshold;
else
threshold.opacity=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
if ((MagickRealType) GetPixelIndex(indexes+x) < min_threshold)
threshold.index=min_threshold;
else
if ((MagickRealType) GetPixelIndex(indexes+x) > max_threshold)
threshold.index=max_threshold;
else
threshold.index=(MagickRealType) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
}
if ((channel & RedChannel) != 0)
SetPixelRed(q,(MagickRealType) GetPixelRed(q) <= threshold.red ?
0 : QuantumRange);
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,(MagickRealType) GetPixelGreen(q) <= threshold.green ?
0 : QuantumRange);
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,(MagickRealType) GetPixelBlue(q) <= threshold.blue ?
0 : QuantumRange);
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,(MagickRealType) GetPixelOpacity(q) <=
threshold.opacity ? 0 : QuantumRange);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(indexes+x,(MagickRealType) GetPixelIndex(indexes+x) <=
threshold.index ? 0 : QuantumRange);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W h i t e T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WhiteThresholdImage() is like ThresholdImage() but forces all pixels above
% the threshold into white while leaving all pixels at or below the threshold
% unchanged.
%
% The format of the WhiteThresholdImage method is:
%
% MagickBooleanType WhiteThresholdImage(Image *image,const char *threshold)
% MagickBooleanType WhiteThresholdImageChannel(Image *image,
% const ChannelType channel,const char *threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel or channels to be thresholded.
%
% o threshold: Define the threshold value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType WhiteThresholdImage(Image *image,
const char *threshold)
{
MagickBooleanType
status;
status=WhiteThresholdImageChannel(image,DefaultChannels,threshold,
&image->exception);
return(status);
}
MagickExport MagickBooleanType WhiteThresholdImageChannel(Image *image,
const ChannelType channel,const char *thresholds,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
GeometryInfo
geometry_info;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
threshold;
MagickStatusType
flags;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (thresholds == (const char *) NULL)
return(MagickTrue);
if (SetImageStorageClass(image,DirectClass) == MagickFalse)
return(MagickFalse);
flags=ParseGeometry(thresholds,&geometry_info);
GetMagickPixelPacket(image,&threshold);
threshold.red=geometry_info.rho;
threshold.green=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
threshold.green=threshold.red;
threshold.blue=geometry_info.xi;
if ((flags & XiValue) == 0)
threshold.blue=threshold.red;
threshold.opacity=geometry_info.psi;
if ((flags & PsiValue) == 0)
threshold.opacity=threshold.red;
threshold.index=geometry_info.chi;
if ((flags & ChiValue) == 0)
threshold.index=threshold.red;
if ((flags & PercentValue) != 0)
{
threshold.red*=(MagickRealType) (QuantumRange/100.0);
threshold.green*=(MagickRealType) (QuantumRange/100.0);
threshold.blue*=(MagickRealType) (QuantumRange/100.0);
threshold.opacity*=(MagickRealType) (QuantumRange/100.0);
threshold.index*=(MagickRealType) (QuantumRange/100.0);
}
if ((IsMagickGray(&threshold) == MagickFalse) &&
(IsGrayColorspace(image->colorspace) != MagickFalse))
(void) SetImageColorspace(image,sRGBColorspace);
/*
White threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register IndexPacket
*magick_restrict indexes;
register ssize_t
x;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewAuthenticIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (((channel & RedChannel) != 0) &&
((MagickRealType) GetPixelRed(q) > threshold.red))
SetPixelRed(q,QuantumRange);
if (((channel & GreenChannel) != 0) &&
((MagickRealType) GetPixelGreen(q) > threshold.green))
SetPixelGreen(q,QuantumRange);
if (((channel & BlueChannel) != 0) &&
((MagickRealType) GetPixelBlue(q) > threshold.blue))
SetPixelBlue(q,QuantumRange);
if (((channel & OpacityChannel) != 0) &&
((MagickRealType) GetPixelOpacity(q) > threshold.opacity))
SetPixelOpacity(q,QuantumRange);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace) &&
((MagickRealType) GetPixelIndex(indexes+x)) > threshold.index)
SetPixelIndex(indexes+x,QuantumRange);
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_923_0 |
crossvul-cpp_data_bad_4857_2 | /* $Id$ */
/*
* Copyright (c) 1991-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
/*
* TIFF Library.
*
* Strip-organized Image Support Routines.
*/
#include "tiffiop.h"
/*
* Compute which strip a (row,sample) value is in.
*/
uint32
TIFFComputeStrip(TIFF* tif, uint32 row, uint16 sample)
{
static const char module[] = "TIFFComputeStrip";
TIFFDirectory *td = &tif->tif_dir;
uint32 strip;
strip = row / td->td_rowsperstrip;
if (td->td_planarconfig == PLANARCONFIG_SEPARATE) {
if (sample >= td->td_samplesperpixel) {
TIFFErrorExt(tif->tif_clientdata, module,
"%lu: Sample out of range, max %lu",
(unsigned long) sample, (unsigned long) td->td_samplesperpixel);
return (0);
}
strip += (uint32)sample*td->td_stripsperimage;
}
return (strip);
}
/*
* Compute how many strips are in an image.
*/
uint32
TIFFNumberOfStrips(TIFF* tif)
{
TIFFDirectory *td = &tif->tif_dir;
uint32 nstrips;
/* If the value was already computed and store in td_nstrips, then return it,
since ChopUpSingleUncompressedStrip might have altered and resized the
since the td_stripbytecount and td_stripoffset arrays to the new value
after the initial affectation of td_nstrips = TIFFNumberOfStrips() in
tif_dirread.c ~line 3612.
See http://bugzilla.maptools.org/show_bug.cgi?id=2587 */
if( td->td_nstrips )
return td->td_nstrips;
nstrips = (td->td_rowsperstrip == (uint32) -1 ? 1 :
TIFFhowmany_32(td->td_imagelength, td->td_rowsperstrip));
if (td->td_planarconfig == PLANARCONFIG_SEPARATE)
nstrips = _TIFFMultiply32(tif, nstrips, (uint32)td->td_samplesperpixel,
"TIFFNumberOfStrips");
return (nstrips);
}
/*
* Compute the # bytes in a variable height, row-aligned strip.
*/
uint64
TIFFVStripSize64(TIFF* tif, uint32 nrows)
{
static const char module[] = "TIFFVStripSize64";
TIFFDirectory *td = &tif->tif_dir;
if (nrows==(uint32)(-1))
nrows=td->td_imagelength;
if ((td->td_planarconfig==PLANARCONFIG_CONTIG)&&
(td->td_photometric == PHOTOMETRIC_YCBCR)&&
(!isUpSampled(tif)))
{
/*
* Packed YCbCr data contain one Cb+Cr for every
* HorizontalSampling*VerticalSampling Y values.
* Must also roundup width and height when calculating
* since images that are not a multiple of the
* horizontal/vertical subsampling area include
* YCbCr data for the extended image.
*/
uint16 ycbcrsubsampling[2];
uint16 samplingblock_samples;
uint32 samplingblocks_hor;
uint32 samplingblocks_ver;
uint64 samplingrow_samples;
uint64 samplingrow_size;
if(td->td_samplesperpixel!=3)
{
TIFFErrorExt(tif->tif_clientdata,module,
"Invalid td_samplesperpixel value");
return 0;
}
TIFFGetFieldDefaulted(tif,TIFFTAG_YCBCRSUBSAMPLING,ycbcrsubsampling+0,
ycbcrsubsampling+1);
if ((ycbcrsubsampling[0] != 1 && ycbcrsubsampling[0] != 2 && ycbcrsubsampling[0] != 4)
||(ycbcrsubsampling[1] != 1 && ycbcrsubsampling[1] != 2 && ycbcrsubsampling[1] != 4))
{
TIFFErrorExt(tif->tif_clientdata,module,
"Invalid YCbCr subsampling (%dx%d)",
ycbcrsubsampling[0],
ycbcrsubsampling[1] );
return 0;
}
samplingblock_samples=ycbcrsubsampling[0]*ycbcrsubsampling[1]+2;
samplingblocks_hor=TIFFhowmany_32(td->td_imagewidth,ycbcrsubsampling[0]);
samplingblocks_ver=TIFFhowmany_32(nrows,ycbcrsubsampling[1]);
samplingrow_samples=_TIFFMultiply64(tif,samplingblocks_hor,samplingblock_samples,module);
samplingrow_size=TIFFhowmany8_64(_TIFFMultiply64(tif,samplingrow_samples,td->td_bitspersample,module));
return(_TIFFMultiply64(tif,samplingrow_size,samplingblocks_ver,module));
}
else
return(_TIFFMultiply64(tif,nrows,TIFFScanlineSize64(tif),module));
}
tmsize_t
TIFFVStripSize(TIFF* tif, uint32 nrows)
{
static const char module[] = "TIFFVStripSize";
uint64 m;
tmsize_t n;
m=TIFFVStripSize64(tif,nrows);
n=(tmsize_t)m;
if ((uint64)n!=m)
{
TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow");
n=0;
}
return(n);
}
/*
* Compute the # bytes in a raw strip.
*/
uint64
TIFFRawStripSize64(TIFF* tif, uint32 strip)
{
static const char module[] = "TIFFRawStripSize64";
TIFFDirectory* td = &tif->tif_dir;
uint64 bytecount = td->td_stripbytecount[strip];
if (bytecount == 0)
{
#if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
TIFFErrorExt(tif->tif_clientdata, module,
"%I64u: Invalid strip byte count, strip %lu",
(unsigned __int64) bytecount,
(unsigned long) strip);
#else
TIFFErrorExt(tif->tif_clientdata, module,
"%llu: Invalid strip byte count, strip %lu",
(unsigned long long) bytecount,
(unsigned long) strip);
#endif
bytecount = (uint64) -1;
}
return bytecount;
}
tmsize_t
TIFFRawStripSize(TIFF* tif, uint32 strip)
{
static const char module[] = "TIFFRawStripSize";
uint64 m;
tmsize_t n;
m=TIFFRawStripSize64(tif,strip);
if (m==(uint64)(-1))
n=(tmsize_t)(-1);
else
{
n=(tmsize_t)m;
if ((uint64)n!=m)
{
TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow");
n=0;
}
}
return(n);
}
/*
* Compute the # bytes in a (row-aligned) strip.
*
* Note that if RowsPerStrip is larger than the
* recorded ImageLength, then the strip size is
* truncated to reflect the actual space required
* to hold the strip.
*/
uint64
TIFFStripSize64(TIFF* tif)
{
TIFFDirectory* td = &tif->tif_dir;
uint32 rps = td->td_rowsperstrip;
if (rps > td->td_imagelength)
rps = td->td_imagelength;
return (TIFFVStripSize64(tif, rps));
}
tmsize_t
TIFFStripSize(TIFF* tif)
{
static const char module[] = "TIFFStripSize";
uint64 m;
tmsize_t n;
m=TIFFStripSize64(tif);
n=(tmsize_t)m;
if ((uint64)n!=m)
{
TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow");
n=0;
}
return(n);
}
/*
* Compute a default strip size based on the image
* characteristics and a requested value. If the
* request is <1 then we choose a strip size according
* to certain heuristics.
*/
uint32
TIFFDefaultStripSize(TIFF* tif, uint32 request)
{
return (*tif->tif_defstripsize)(tif, request);
}
uint32
_TIFFDefaultStripSize(TIFF* tif, uint32 s)
{
if ((int32) s < 1) {
/*
* If RowsPerStrip is unspecified, try to break the
* image up into strips that are approximately
* STRIP_SIZE_DEFAULT bytes long.
*/
uint64 scanlinesize;
uint64 rows;
scanlinesize=TIFFScanlineSize64(tif);
if (scanlinesize==0)
scanlinesize=1;
rows=(uint64)STRIP_SIZE_DEFAULT/scanlinesize;
if (rows==0)
rows=1;
else if (rows>0xFFFFFFFF)
rows=0xFFFFFFFF;
s=(uint32)rows;
}
return (s);
}
/*
* Return the number of bytes to read/write in a call to
* one of the scanline-oriented i/o routines. Note that
* this number may be 1/samples-per-pixel if data is
* stored as separate planes.
* The ScanlineSize in case of YCbCrSubsampling is defined as the
* strip size divided by the strip height, i.e. the size of a pack of vertical
* subsampling lines divided by vertical subsampling. It should thus make
* sense when multiplied by a multiple of vertical subsampling.
*/
uint64
TIFFScanlineSize64(TIFF* tif)
{
static const char module[] = "TIFFScanlineSize64";
TIFFDirectory *td = &tif->tif_dir;
uint64 scanline_size;
if (td->td_planarconfig==PLANARCONFIG_CONTIG)
{
if ((td->td_photometric==PHOTOMETRIC_YCBCR)&&
(td->td_samplesperpixel==3)&&
(!isUpSampled(tif)))
{
uint16 ycbcrsubsampling[2];
uint16 samplingblock_samples;
uint32 samplingblocks_hor;
uint64 samplingrow_samples;
uint64 samplingrow_size;
if(td->td_samplesperpixel!=3)
{
TIFFErrorExt(tif->tif_clientdata,module,
"Invalid td_samplesperpixel value");
return 0;
}
TIFFGetFieldDefaulted(tif,TIFFTAG_YCBCRSUBSAMPLING,
ycbcrsubsampling+0,
ycbcrsubsampling+1);
if (((ycbcrsubsampling[0]!=1)&&(ycbcrsubsampling[0]!=2)&&(ycbcrsubsampling[0]!=4)) ||
((ycbcrsubsampling[1]!=1)&&(ycbcrsubsampling[1]!=2)&&(ycbcrsubsampling[1]!=4)))
{
TIFFErrorExt(tif->tif_clientdata,module,
"Invalid YCbCr subsampling");
return 0;
}
samplingblock_samples = ycbcrsubsampling[0]*ycbcrsubsampling[1]+2;
samplingblocks_hor = TIFFhowmany_32(td->td_imagewidth,ycbcrsubsampling[0]);
samplingrow_samples = _TIFFMultiply64(tif,samplingblocks_hor,samplingblock_samples,module);
samplingrow_size = TIFFhowmany_64(_TIFFMultiply64(tif,samplingrow_samples,td->td_bitspersample,module),8);
scanline_size = (samplingrow_size/ycbcrsubsampling[1]);
}
else
{
uint64 scanline_samples;
scanline_samples=_TIFFMultiply64(tif,td->td_imagewidth,td->td_samplesperpixel,module);
scanline_size=TIFFhowmany_64(_TIFFMultiply64(tif,scanline_samples,td->td_bitspersample,module),8);
}
}
else
{
scanline_size=TIFFhowmany_64(_TIFFMultiply64(tif,td->td_imagewidth,td->td_bitspersample,module),8);
}
if (scanline_size == 0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Computed scanline size is zero");
return 0;
}
return(scanline_size);
}
tmsize_t
TIFFScanlineSize(TIFF* tif)
{
static const char module[] = "TIFFScanlineSize";
uint64 m;
tmsize_t n;
m=TIFFScanlineSize64(tif);
n=(tmsize_t)m;
if ((uint64)n!=m) {
TIFFErrorExt(tif->tif_clientdata,module,"Integer arithmetic overflow");
n=0;
}
return(n);
}
/*
* Return the number of bytes required to store a complete
* decoded and packed raster scanline (as opposed to the
* I/O size returned by TIFFScanlineSize which may be less
* if data is store as separate planes).
*/
uint64
TIFFRasterScanlineSize64(TIFF* tif)
{
static const char module[] = "TIFFRasterScanlineSize64";
TIFFDirectory *td = &tif->tif_dir;
uint64 scanline;
scanline = _TIFFMultiply64(tif, td->td_bitspersample, td->td_imagewidth, module);
if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
scanline = _TIFFMultiply64(tif, scanline, td->td_samplesperpixel, module);
return (TIFFhowmany8_64(scanline));
} else
return (_TIFFMultiply64(tif, TIFFhowmany8_64(scanline),
td->td_samplesperpixel, module));
}
tmsize_t
TIFFRasterScanlineSize(TIFF* tif)
{
static const char module[] = "TIFFRasterScanlineSize";
uint64 m;
tmsize_t n;
m=TIFFRasterScanlineSize64(tif);
n=(tmsize_t)m;
if ((uint64)n!=m)
{
TIFFErrorExt(tif->tif_clientdata,module,"Integer arithmetic overflow");
n=0;
}
return(n);
}
/* vim: set ts=8 sts=8 sw=8 noet: */
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4857_2 |
crossvul-cpp_data_good_2644_7 | /* NetBSD: print-juniper.c,v 1.2 2007/07/24 11:53:45 drochner Exp */
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Original code by Hannes Gredler (hannes@gredler.at)
*/
/* \summary: DLT_JUNIPER_* printers */
#ifndef lint
#else
__RCSID("NetBSD: print-juniper.c,v 1.3 2007/07/25 06:31:32 dogcow Exp ");
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ppp.h"
#include "llc.h"
#include "nlpid.h"
#include "ethertype.h"
#include "atm.h"
#define JUNIPER_BPF_OUT 0 /* Outgoing packet */
#define JUNIPER_BPF_IN 1 /* Incoming packet */
#define JUNIPER_BPF_PKT_IN 0x1 /* Incoming packet */
#define JUNIPER_BPF_NO_L2 0x2 /* L2 header stripped */
#define JUNIPER_BPF_IIF 0x4 /* IIF is valid */
#define JUNIPER_BPF_FILTER 0x40 /* BPF filtering is supported */
#define JUNIPER_BPF_EXT 0x80 /* extensions present */
#define JUNIPER_MGC_NUMBER 0x4d4743 /* = "MGC" */
#define JUNIPER_LSQ_COOKIE_RE (1 << 3)
#define JUNIPER_LSQ_COOKIE_DIR (1 << 2)
#define JUNIPER_LSQ_L3_PROTO_SHIFT 4
#define JUNIPER_LSQ_L3_PROTO_MASK (0x17 << JUNIPER_LSQ_L3_PROTO_SHIFT)
#define JUNIPER_LSQ_L3_PROTO_IPV4 (0 << JUNIPER_LSQ_L3_PROTO_SHIFT)
#define JUNIPER_LSQ_L3_PROTO_IPV6 (1 << JUNIPER_LSQ_L3_PROTO_SHIFT)
#define JUNIPER_LSQ_L3_PROTO_MPLS (2 << JUNIPER_LSQ_L3_PROTO_SHIFT)
#define JUNIPER_LSQ_L3_PROTO_ISO (3 << JUNIPER_LSQ_L3_PROTO_SHIFT)
#define AS_PIC_COOKIE_LEN 8
#define JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE 1
#define JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE 2
#define JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE 3
#define JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE 4
#define JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE 5
static const struct tok juniper_ipsec_type_values[] = {
{ JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE, "ESP ENCR-AUTH" },
{ JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE, "ESP ENCR-AH AUTH" },
{ JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE, "ESP AUTH" },
{ JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE, "AH AUTH" },
{ JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE, "ESP ENCR" },
{ 0, NULL}
};
static const struct tok juniper_direction_values[] = {
{ JUNIPER_BPF_IN, "In"},
{ JUNIPER_BPF_OUT, "Out"},
{ 0, NULL}
};
/* codepoints for encoding extensions to a .pcap file */
enum {
JUNIPER_EXT_TLV_IFD_IDX = 1,
JUNIPER_EXT_TLV_IFD_NAME = 2,
JUNIPER_EXT_TLV_IFD_MEDIATYPE = 3,
JUNIPER_EXT_TLV_IFL_IDX = 4,
JUNIPER_EXT_TLV_IFL_UNIT = 5,
JUNIPER_EXT_TLV_IFL_ENCAPS = 6,
JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE = 7,
JUNIPER_EXT_TLV_TTP_IFL_ENCAPS = 8
};
/* 1 byte type and 1-byte length */
#define JUNIPER_EXT_TLV_OVERHEAD 2U
static const struct tok jnx_ext_tlv_values[] = {
{ JUNIPER_EXT_TLV_IFD_IDX, "Device Interface Index" },
{ JUNIPER_EXT_TLV_IFD_NAME,"Device Interface Name" },
{ JUNIPER_EXT_TLV_IFD_MEDIATYPE, "Device Media Type" },
{ JUNIPER_EXT_TLV_IFL_IDX, "Logical Interface Index" },
{ JUNIPER_EXT_TLV_IFL_UNIT,"Logical Unit Number" },
{ JUNIPER_EXT_TLV_IFL_ENCAPS, "Logical Interface Encapsulation" },
{ JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE, "TTP derived Device Media Type" },
{ JUNIPER_EXT_TLV_TTP_IFL_ENCAPS, "TTP derived Logical Interface Encapsulation" },
{ 0, NULL }
};
static const struct tok jnx_flag_values[] = {
{ JUNIPER_BPF_EXT, "Ext" },
{ JUNIPER_BPF_FILTER, "Filter" },
{ JUNIPER_BPF_IIF, "IIF" },
{ JUNIPER_BPF_NO_L2, "no-L2" },
{ JUNIPER_BPF_PKT_IN, "In" },
{ 0, NULL }
};
#define JUNIPER_IFML_ETHER 1
#define JUNIPER_IFML_FDDI 2
#define JUNIPER_IFML_TOKENRING 3
#define JUNIPER_IFML_PPP 4
#define JUNIPER_IFML_FRAMERELAY 5
#define JUNIPER_IFML_CISCOHDLC 6
#define JUNIPER_IFML_SMDSDXI 7
#define JUNIPER_IFML_ATMPVC 8
#define JUNIPER_IFML_PPP_CCC 9
#define JUNIPER_IFML_FRAMERELAY_CCC 10
#define JUNIPER_IFML_IPIP 11
#define JUNIPER_IFML_GRE 12
#define JUNIPER_IFML_PIM 13
#define JUNIPER_IFML_PIMD 14
#define JUNIPER_IFML_CISCOHDLC_CCC 15
#define JUNIPER_IFML_VLAN_CCC 16
#define JUNIPER_IFML_MLPPP 17
#define JUNIPER_IFML_MLFR 18
#define JUNIPER_IFML_ML 19
#define JUNIPER_IFML_LSI 20
#define JUNIPER_IFML_DFE 21
#define JUNIPER_IFML_ATM_CELLRELAY_CCC 22
#define JUNIPER_IFML_CRYPTO 23
#define JUNIPER_IFML_GGSN 24
#define JUNIPER_IFML_LSI_PPP 25
#define JUNIPER_IFML_LSI_CISCOHDLC 26
#define JUNIPER_IFML_PPP_TCC 27
#define JUNIPER_IFML_FRAMERELAY_TCC 28
#define JUNIPER_IFML_CISCOHDLC_TCC 29
#define JUNIPER_IFML_ETHERNET_CCC 30
#define JUNIPER_IFML_VT 31
#define JUNIPER_IFML_EXTENDED_VLAN_CCC 32
#define JUNIPER_IFML_ETHER_OVER_ATM 33
#define JUNIPER_IFML_MONITOR 34
#define JUNIPER_IFML_ETHERNET_TCC 35
#define JUNIPER_IFML_VLAN_TCC 36
#define JUNIPER_IFML_EXTENDED_VLAN_TCC 37
#define JUNIPER_IFML_CONTROLLER 38
#define JUNIPER_IFML_MFR 39
#define JUNIPER_IFML_LS 40
#define JUNIPER_IFML_ETHERNET_VPLS 41
#define JUNIPER_IFML_ETHERNET_VLAN_VPLS 42
#define JUNIPER_IFML_ETHERNET_EXTENDED_VLAN_VPLS 43
#define JUNIPER_IFML_LT 44
#define JUNIPER_IFML_SERVICES 45
#define JUNIPER_IFML_ETHER_VPLS_OVER_ATM 46
#define JUNIPER_IFML_FR_PORT_CCC 47
#define JUNIPER_IFML_FRAMERELAY_EXT_CCC 48
#define JUNIPER_IFML_FRAMERELAY_EXT_TCC 49
#define JUNIPER_IFML_FRAMERELAY_FLEX 50
#define JUNIPER_IFML_GGSNI 51
#define JUNIPER_IFML_ETHERNET_FLEX 52
#define JUNIPER_IFML_COLLECTOR 53
#define JUNIPER_IFML_AGGREGATOR 54
#define JUNIPER_IFML_LAPD 55
#define JUNIPER_IFML_PPPOE 56
#define JUNIPER_IFML_PPP_SUBORDINATE 57
#define JUNIPER_IFML_CISCOHDLC_SUBORDINATE 58
#define JUNIPER_IFML_DFC 59
#define JUNIPER_IFML_PICPEER 60
static const struct tok juniper_ifmt_values[] = {
{ JUNIPER_IFML_ETHER, "Ethernet" },
{ JUNIPER_IFML_FDDI, "FDDI" },
{ JUNIPER_IFML_TOKENRING, "Token-Ring" },
{ JUNIPER_IFML_PPP, "PPP" },
{ JUNIPER_IFML_PPP_SUBORDINATE, "PPP-Subordinate" },
{ JUNIPER_IFML_FRAMERELAY, "Frame-Relay" },
{ JUNIPER_IFML_CISCOHDLC, "Cisco-HDLC" },
{ JUNIPER_IFML_SMDSDXI, "SMDS-DXI" },
{ JUNIPER_IFML_ATMPVC, "ATM-PVC" },
{ JUNIPER_IFML_PPP_CCC, "PPP-CCC" },
{ JUNIPER_IFML_FRAMERELAY_CCC, "Frame-Relay-CCC" },
{ JUNIPER_IFML_FRAMERELAY_EXT_CCC, "Extended FR-CCC" },
{ JUNIPER_IFML_IPIP, "IP-over-IP" },
{ JUNIPER_IFML_GRE, "GRE" },
{ JUNIPER_IFML_PIM, "PIM-Encapsulator" },
{ JUNIPER_IFML_PIMD, "PIM-Decapsulator" },
{ JUNIPER_IFML_CISCOHDLC_CCC, "Cisco-HDLC-CCC" },
{ JUNIPER_IFML_VLAN_CCC, "VLAN-CCC" },
{ JUNIPER_IFML_EXTENDED_VLAN_CCC, "Extended-VLAN-CCC" },
{ JUNIPER_IFML_MLPPP, "Multilink-PPP" },
{ JUNIPER_IFML_MLFR, "Multilink-FR" },
{ JUNIPER_IFML_MFR, "Multilink-FR-UNI-NNI" },
{ JUNIPER_IFML_ML, "Multilink" },
{ JUNIPER_IFML_LS, "LinkService" },
{ JUNIPER_IFML_LSI, "LSI" },
{ JUNIPER_IFML_ATM_CELLRELAY_CCC, "ATM-CCC-Cell-Relay" },
{ JUNIPER_IFML_CRYPTO, "IPSEC-over-IP" },
{ JUNIPER_IFML_GGSN, "GGSN" },
{ JUNIPER_IFML_PPP_TCC, "PPP-TCC" },
{ JUNIPER_IFML_FRAMERELAY_TCC, "Frame-Relay-TCC" },
{ JUNIPER_IFML_FRAMERELAY_EXT_TCC, "Extended FR-TCC" },
{ JUNIPER_IFML_CISCOHDLC_TCC, "Cisco-HDLC-TCC" },
{ JUNIPER_IFML_ETHERNET_CCC, "Ethernet-CCC" },
{ JUNIPER_IFML_VT, "VPN-Loopback-tunnel" },
{ JUNIPER_IFML_ETHER_OVER_ATM, "Ethernet-over-ATM" },
{ JUNIPER_IFML_ETHER_VPLS_OVER_ATM, "Ethernet-VPLS-over-ATM" },
{ JUNIPER_IFML_MONITOR, "Monitor" },
{ JUNIPER_IFML_ETHERNET_TCC, "Ethernet-TCC" },
{ JUNIPER_IFML_VLAN_TCC, "VLAN-TCC" },
{ JUNIPER_IFML_EXTENDED_VLAN_TCC, "Extended-VLAN-TCC" },
{ JUNIPER_IFML_CONTROLLER, "Controller" },
{ JUNIPER_IFML_ETHERNET_VPLS, "VPLS" },
{ JUNIPER_IFML_ETHERNET_VLAN_VPLS, "VLAN-VPLS" },
{ JUNIPER_IFML_ETHERNET_EXTENDED_VLAN_VPLS, "Extended-VLAN-VPLS" },
{ JUNIPER_IFML_LT, "Logical-tunnel" },
{ JUNIPER_IFML_SERVICES, "General-Services" },
{ JUNIPER_IFML_PPPOE, "PPPoE" },
{ JUNIPER_IFML_ETHERNET_FLEX, "Flexible-Ethernet-Services" },
{ JUNIPER_IFML_FRAMERELAY_FLEX, "Flexible-FrameRelay" },
{ JUNIPER_IFML_COLLECTOR, "Flow-collection" },
{ JUNIPER_IFML_PICPEER, "PIC Peer" },
{ JUNIPER_IFML_DFC, "Dynamic-Flow-Capture" },
{0, NULL}
};
#define JUNIPER_IFLE_ATM_SNAP 2
#define JUNIPER_IFLE_ATM_NLPID 3
#define JUNIPER_IFLE_ATM_VCMUX 4
#define JUNIPER_IFLE_ATM_LLC 5
#define JUNIPER_IFLE_ATM_PPP_VCMUX 6
#define JUNIPER_IFLE_ATM_PPP_LLC 7
#define JUNIPER_IFLE_ATM_PPP_FUNI 8
#define JUNIPER_IFLE_ATM_CCC 9
#define JUNIPER_IFLE_FR_NLPID 10
#define JUNIPER_IFLE_FR_SNAP 11
#define JUNIPER_IFLE_FR_PPP 12
#define JUNIPER_IFLE_FR_CCC 13
#define JUNIPER_IFLE_ENET2 14
#define JUNIPER_IFLE_IEEE8023_SNAP 15
#define JUNIPER_IFLE_IEEE8023_LLC 16
#define JUNIPER_IFLE_PPP 17
#define JUNIPER_IFLE_CISCOHDLC 18
#define JUNIPER_IFLE_PPP_CCC 19
#define JUNIPER_IFLE_IPIP_NULL 20
#define JUNIPER_IFLE_PIM_NULL 21
#define JUNIPER_IFLE_GRE_NULL 22
#define JUNIPER_IFLE_GRE_PPP 23
#define JUNIPER_IFLE_PIMD_DECAPS 24
#define JUNIPER_IFLE_CISCOHDLC_CCC 25
#define JUNIPER_IFLE_ATM_CISCO_NLPID 26
#define JUNIPER_IFLE_VLAN_CCC 27
#define JUNIPER_IFLE_MLPPP 28
#define JUNIPER_IFLE_MLFR 29
#define JUNIPER_IFLE_LSI_NULL 30
#define JUNIPER_IFLE_AGGREGATE_UNUSED 31
#define JUNIPER_IFLE_ATM_CELLRELAY_CCC 32
#define JUNIPER_IFLE_CRYPTO 33
#define JUNIPER_IFLE_GGSN 34
#define JUNIPER_IFLE_ATM_TCC 35
#define JUNIPER_IFLE_FR_TCC 36
#define JUNIPER_IFLE_PPP_TCC 37
#define JUNIPER_IFLE_CISCOHDLC_TCC 38
#define JUNIPER_IFLE_ETHERNET_CCC 39
#define JUNIPER_IFLE_VT 40
#define JUNIPER_IFLE_ATM_EOA_LLC 41
#define JUNIPER_IFLE_EXTENDED_VLAN_CCC 42
#define JUNIPER_IFLE_ATM_SNAP_TCC 43
#define JUNIPER_IFLE_MONITOR 44
#define JUNIPER_IFLE_ETHERNET_TCC 45
#define JUNIPER_IFLE_VLAN_TCC 46
#define JUNIPER_IFLE_EXTENDED_VLAN_TCC 47
#define JUNIPER_IFLE_MFR 48
#define JUNIPER_IFLE_ETHERNET_VPLS 49
#define JUNIPER_IFLE_ETHERNET_VLAN_VPLS 50
#define JUNIPER_IFLE_ETHERNET_EXTENDED_VLAN_VPLS 51
#define JUNIPER_IFLE_SERVICES 52
#define JUNIPER_IFLE_ATM_ETHER_VPLS_ATM_LLC 53
#define JUNIPER_IFLE_FR_PORT_CCC 54
#define JUNIPER_IFLE_ATM_MLPPP_LLC 55
#define JUNIPER_IFLE_ATM_EOA_CCC 56
#define JUNIPER_IFLE_LT_VLAN 57
#define JUNIPER_IFLE_COLLECTOR 58
#define JUNIPER_IFLE_AGGREGATOR 59
#define JUNIPER_IFLE_LAPD 60
#define JUNIPER_IFLE_ATM_PPPOE_LLC 61
#define JUNIPER_IFLE_ETHERNET_PPPOE 62
#define JUNIPER_IFLE_PPPOE 63
#define JUNIPER_IFLE_PPP_SUBORDINATE 64
#define JUNIPER_IFLE_CISCOHDLC_SUBORDINATE 65
#define JUNIPER_IFLE_DFC 66
#define JUNIPER_IFLE_PICPEER 67
static const struct tok juniper_ifle_values[] = {
{ JUNIPER_IFLE_AGGREGATOR, "Aggregator" },
{ JUNIPER_IFLE_ATM_CCC, "CCC over ATM" },
{ JUNIPER_IFLE_ATM_CELLRELAY_CCC, "ATM CCC Cell Relay" },
{ JUNIPER_IFLE_ATM_CISCO_NLPID, "CISCO compatible NLPID" },
{ JUNIPER_IFLE_ATM_EOA_CCC, "Ethernet over ATM CCC" },
{ JUNIPER_IFLE_ATM_EOA_LLC, "Ethernet over ATM LLC" },
{ JUNIPER_IFLE_ATM_ETHER_VPLS_ATM_LLC, "Ethernet VPLS over ATM LLC" },
{ JUNIPER_IFLE_ATM_LLC, "ATM LLC" },
{ JUNIPER_IFLE_ATM_MLPPP_LLC, "MLPPP over ATM LLC" },
{ JUNIPER_IFLE_ATM_NLPID, "ATM NLPID" },
{ JUNIPER_IFLE_ATM_PPPOE_LLC, "PPPoE over ATM LLC" },
{ JUNIPER_IFLE_ATM_PPP_FUNI, "PPP over FUNI" },
{ JUNIPER_IFLE_ATM_PPP_LLC, "PPP over ATM LLC" },
{ JUNIPER_IFLE_ATM_PPP_VCMUX, "PPP over ATM VCMUX" },
{ JUNIPER_IFLE_ATM_SNAP, "ATM SNAP" },
{ JUNIPER_IFLE_ATM_SNAP_TCC, "ATM SNAP TCC" },
{ JUNIPER_IFLE_ATM_TCC, "ATM VCMUX TCC" },
{ JUNIPER_IFLE_ATM_VCMUX, "ATM VCMUX" },
{ JUNIPER_IFLE_CISCOHDLC, "C-HDLC" },
{ JUNIPER_IFLE_CISCOHDLC_CCC, "C-HDLC CCC" },
{ JUNIPER_IFLE_CISCOHDLC_SUBORDINATE, "C-HDLC via dialer" },
{ JUNIPER_IFLE_CISCOHDLC_TCC, "C-HDLC TCC" },
{ JUNIPER_IFLE_COLLECTOR, "Collector" },
{ JUNIPER_IFLE_CRYPTO, "Crypto" },
{ JUNIPER_IFLE_ENET2, "Ethernet" },
{ JUNIPER_IFLE_ETHERNET_CCC, "Ethernet CCC" },
{ JUNIPER_IFLE_ETHERNET_EXTENDED_VLAN_VPLS, "Extended VLAN VPLS" },
{ JUNIPER_IFLE_ETHERNET_PPPOE, "PPPoE over Ethernet" },
{ JUNIPER_IFLE_ETHERNET_TCC, "Ethernet TCC" },
{ JUNIPER_IFLE_ETHERNET_VLAN_VPLS, "VLAN VPLS" },
{ JUNIPER_IFLE_ETHERNET_VPLS, "VPLS" },
{ JUNIPER_IFLE_EXTENDED_VLAN_CCC, "Extended VLAN CCC" },
{ JUNIPER_IFLE_EXTENDED_VLAN_TCC, "Extended VLAN TCC" },
{ JUNIPER_IFLE_FR_CCC, "FR CCC" },
{ JUNIPER_IFLE_FR_NLPID, "FR NLPID" },
{ JUNIPER_IFLE_FR_PORT_CCC, "FR CCC" },
{ JUNIPER_IFLE_FR_PPP, "FR PPP" },
{ JUNIPER_IFLE_FR_SNAP, "FR SNAP" },
{ JUNIPER_IFLE_FR_TCC, "FR TCC" },
{ JUNIPER_IFLE_GGSN, "GGSN" },
{ JUNIPER_IFLE_GRE_NULL, "GRE NULL" },
{ JUNIPER_IFLE_GRE_PPP, "PPP over GRE" },
{ JUNIPER_IFLE_IPIP_NULL, "IPIP" },
{ JUNIPER_IFLE_LAPD, "LAPD" },
{ JUNIPER_IFLE_LSI_NULL, "LSI Null" },
{ JUNIPER_IFLE_LT_VLAN, "LT VLAN" },
{ JUNIPER_IFLE_MFR, "MFR" },
{ JUNIPER_IFLE_MLFR, "MLFR" },
{ JUNIPER_IFLE_MLPPP, "MLPPP" },
{ JUNIPER_IFLE_MONITOR, "Monitor" },
{ JUNIPER_IFLE_PIMD_DECAPS, "PIMd" },
{ JUNIPER_IFLE_PIM_NULL, "PIM Null" },
{ JUNIPER_IFLE_PPP, "PPP" },
{ JUNIPER_IFLE_PPPOE, "PPPoE" },
{ JUNIPER_IFLE_PPP_CCC, "PPP CCC" },
{ JUNIPER_IFLE_PPP_SUBORDINATE, "" },
{ JUNIPER_IFLE_PPP_TCC, "PPP TCC" },
{ JUNIPER_IFLE_SERVICES, "General Services" },
{ JUNIPER_IFLE_VLAN_CCC, "VLAN CCC" },
{ JUNIPER_IFLE_VLAN_TCC, "VLAN TCC" },
{ JUNIPER_IFLE_VT, "VT" },
{0, NULL}
};
struct juniper_cookie_table_t {
uint32_t pictype; /* pic type */
uint8_t cookie_len; /* cookie len */
const char *s; /* pic name */
};
static const struct juniper_cookie_table_t juniper_cookie_table[] = {
#ifdef DLT_JUNIPER_ATM1
{ DLT_JUNIPER_ATM1, 4, "ATM1"},
#endif
#ifdef DLT_JUNIPER_ATM2
{ DLT_JUNIPER_ATM2, 8, "ATM2"},
#endif
#ifdef DLT_JUNIPER_MLPPP
{ DLT_JUNIPER_MLPPP, 2, "MLPPP"},
#endif
#ifdef DLT_JUNIPER_MLFR
{ DLT_JUNIPER_MLFR, 2, "MLFR"},
#endif
#ifdef DLT_JUNIPER_MFR
{ DLT_JUNIPER_MFR, 4, "MFR"},
#endif
#ifdef DLT_JUNIPER_PPPOE
{ DLT_JUNIPER_PPPOE, 0, "PPPoE"},
#endif
#ifdef DLT_JUNIPER_PPPOE_ATM
{ DLT_JUNIPER_PPPOE_ATM, 0, "PPPoE ATM"},
#endif
#ifdef DLT_JUNIPER_GGSN
{ DLT_JUNIPER_GGSN, 8, "GGSN"},
#endif
#ifdef DLT_JUNIPER_MONITOR
{ DLT_JUNIPER_MONITOR, 8, "MONITOR"},
#endif
#ifdef DLT_JUNIPER_SERVICES
{ DLT_JUNIPER_SERVICES, 8, "AS"},
#endif
#ifdef DLT_JUNIPER_ES
{ DLT_JUNIPER_ES, 0, "ES"},
#endif
{ 0, 0, NULL }
};
struct juniper_l2info_t {
uint32_t length;
uint32_t caplen;
uint32_t pictype;
uint8_t direction;
uint8_t header_len;
uint8_t cookie_len;
uint8_t cookie_type;
uint8_t cookie[8];
uint8_t bundle;
uint16_t proto;
uint8_t flags;
};
#define LS_COOKIE_ID 0x54
#define AS_COOKIE_ID 0x47
#define LS_MLFR_COOKIE_LEN 4
#define ML_MLFR_COOKIE_LEN 2
#define LS_MFR_COOKIE_LEN 6
#define ATM1_COOKIE_LEN 4
#define ATM2_COOKIE_LEN 8
#define ATM2_PKT_TYPE_MASK 0x70
#define ATM2_GAP_COUNT_MASK 0x3F
#define JUNIPER_PROTO_NULL 1
#define JUNIPER_PROTO_IPV4 2
#define JUNIPER_PROTO_IPV6 6
#define MFR_BE_MASK 0xc0
static const struct tok juniper_protocol_values[] = {
{ JUNIPER_PROTO_NULL, "Null" },
{ JUNIPER_PROTO_IPV4, "IPv4" },
{ JUNIPER_PROTO_IPV6, "IPv6" },
{ 0, NULL}
};
static int ip_heuristic_guess(netdissect_options *, register const u_char *, u_int);
static int juniper_ppp_heuristic_guess(netdissect_options *, register const u_char *, u_int);
static int juniper_parse_header(netdissect_options *, const u_char *, const struct pcap_pkthdr *, struct juniper_l2info_t *);
#ifdef DLT_JUNIPER_GGSN
u_int
juniper_ggsn_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
struct juniper_ggsn_header {
uint8_t svc_id;
uint8_t flags_len;
uint8_t proto;
uint8_t flags;
uint8_t vlan_id[2];
uint8_t res[2];
};
const struct juniper_ggsn_header *gh;
l2info.pictype = DLT_JUNIPER_GGSN;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
gh = (struct juniper_ggsn_header *)&l2info.cookie;
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "proto %s (%u), vlan %u: ",
tok2str(juniper_protocol_values,"Unknown",gh->proto),
gh->proto,
EXTRACT_16BITS(&gh->vlan_id[0])));
}
switch (gh->proto) {
case JUNIPER_PROTO_IPV4:
ip_print(ndo, p, l2info.length);
break;
case JUNIPER_PROTO_IPV6:
ip6_print(ndo, p, l2info.length);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "unknown GGSN proto (%u)", gh->proto));
}
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_ES
u_int
juniper_es_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
struct juniper_ipsec_header {
uint8_t sa_index[2];
uint8_t ttl;
uint8_t type;
uint8_t spi[4];
uint8_t src_ip[4];
uint8_t dst_ip[4];
};
u_int rewrite_len,es_type_bundle;
const struct juniper_ipsec_header *ih;
l2info.pictype = DLT_JUNIPER_ES;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
ih = (const struct juniper_ipsec_header *)p;
switch (ih->type) {
case JUNIPER_IPSEC_O_ESP_ENCRYPT_ESP_AUTHEN_TYPE:
case JUNIPER_IPSEC_O_ESP_ENCRYPT_AH_AUTHEN_TYPE:
rewrite_len = 0;
es_type_bundle = 1;
break;
case JUNIPER_IPSEC_O_ESP_AUTHENTICATION_TYPE:
case JUNIPER_IPSEC_O_AH_AUTHENTICATION_TYPE:
case JUNIPER_IPSEC_O_ESP_ENCRYPTION_TYPE:
rewrite_len = 16;
es_type_bundle = 0;
break;
default:
ND_PRINT((ndo, "ES Invalid type %u, length %u",
ih->type,
l2info.length));
return l2info.header_len;
}
l2info.length-=rewrite_len;
p+=rewrite_len;
if (ndo->ndo_eflag) {
if (!es_type_bundle) {
ND_PRINT((ndo, "ES SA, index %u, ttl %u type %s (%u), spi %u, Tunnel %s > %s, length %u\n",
EXTRACT_16BITS(&ih->sa_index),
ih->ttl,
tok2str(juniper_ipsec_type_values,"Unknown",ih->type),
ih->type,
EXTRACT_32BITS(&ih->spi),
ipaddr_string(ndo, &ih->src_ip),
ipaddr_string(ndo, &ih->dst_ip),
l2info.length));
} else {
ND_PRINT((ndo, "ES SA, index %u, ttl %u type %s (%u), length %u\n",
EXTRACT_16BITS(&ih->sa_index),
ih->ttl,
tok2str(juniper_ipsec_type_values,"Unknown",ih->type),
ih->type,
l2info.length));
}
}
ip_print(ndo, p, l2info.length);
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_MONITOR
u_int
juniper_monitor_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
struct juniper_monitor_header {
uint8_t pkt_type;
uint8_t padding;
uint8_t iif[2];
uint8_t service_id[4];
};
const struct juniper_monitor_header *mh;
l2info.pictype = DLT_JUNIPER_MONITOR;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
mh = (const struct juniper_monitor_header *)p;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "service-id %u, iif %u, pkt-type %u: ",
EXTRACT_32BITS(&mh->service_id),
EXTRACT_16BITS(&mh->iif),
mh->pkt_type));
/* no proto field - lets guess by first byte of IP header*/
ip_heuristic_guess (ndo, p, l2info.length);
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_SERVICES
u_int
juniper_services_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
struct juniper_services_header {
uint8_t svc_id;
uint8_t flags_len;
uint8_t svc_set_id[2];
uint8_t dir_iif[4];
};
const struct juniper_services_header *sh;
l2info.pictype = DLT_JUNIPER_SERVICES;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
sh = (const struct juniper_services_header *)p;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "service-id %u flags 0x%02x service-set-id 0x%04x iif %u: ",
sh->svc_id,
sh->flags_len,
EXTRACT_16BITS(&sh->svc_set_id),
EXTRACT_24BITS(&sh->dir_iif[1])));
/* no proto field - lets guess by first byte of IP header*/
ip_heuristic_guess (ndo, p, l2info.length);
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_PPPOE
u_int
juniper_pppoe_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_PPPOE;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* this DLT contains nothing but raw ethernet frames */
ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_ETHER
u_int
juniper_ether_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ETHER;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* this DLT contains nothing but raw Ethernet frames */
ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_PPP
u_int
juniper_ppp_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_PPP;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* this DLT contains nothing but raw ppp frames */
ppp_print(ndo, p, l2info.length);
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_FRELAY
u_int
juniper_frelay_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_FRELAY;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* this DLT contains nothing but raw frame-relay frames */
fr_print(ndo, p, l2info.length);
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_CHDLC
u_int
juniper_chdlc_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_CHDLC;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* this DLT contains nothing but raw c-hdlc frames */
chdlc_print(ndo, p, l2info.length);
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_PPPOE_ATM
u_int
juniper_pppoe_atm_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
uint16_t extracted_ethertype;
l2info.pictype = DLT_JUNIPER_PPPOE_ATM;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
extracted_ethertype = EXTRACT_16BITS(p);
/* this DLT contains nothing but raw PPPoE frames,
* prepended with a type field*/
if (ethertype_print(ndo, extracted_ethertype,
p+ETHERTYPE_LEN,
l2info.length-ETHERTYPE_LEN,
l2info.caplen-ETHERTYPE_LEN,
NULL, NULL) == 0)
/* ether_type not known, probably it wasn't one */
ND_PRINT((ndo, "unknown ethertype 0x%04x", extracted_ethertype));
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_MLPPP
u_int
juniper_mlppp_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_MLPPP;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
/* suppress Bundle-ID if frame was captured on a child-link
* best indicator if the cookie looks like a proto */
if (ndo->ndo_eflag &&
EXTRACT_16BITS(&l2info.cookie) != PPP_OSI &&
EXTRACT_16BITS(&l2info.cookie) != (PPP_ADDRESS << 8 | PPP_CONTROL))
ND_PRINT((ndo, "Bundle-ID %u: ", l2info.bundle));
p+=l2info.header_len;
/* first try the LSQ protos */
switch(l2info.proto) {
case JUNIPER_LSQ_L3_PROTO_IPV4:
/* IP traffic going to the RE would not have a cookie
* -> this must be incoming IS-IS over PPP
*/
if (l2info.cookie[4] == (JUNIPER_LSQ_COOKIE_RE|JUNIPER_LSQ_COOKIE_DIR))
ppp_print(ndo, p, l2info.length);
else
ip_print(ndo, p, l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_IPV6:
ip6_print(ndo, p,l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_MPLS:
mpls_print(ndo, p, l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_ISO:
isoclns_print(ndo, p, l2info.length);
return l2info.header_len;
default:
break;
}
/* zero length cookie ? */
switch (EXTRACT_16BITS(&l2info.cookie)) {
case PPP_OSI:
ppp_print(ndo, p - 2, l2info.length + 2);
break;
case (PPP_ADDRESS << 8 | PPP_CONTROL): /* fall through */
default:
ppp_print(ndo, p, l2info.length);
break;
}
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_MFR
u_int
juniper_mfr_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
memset(&l2info, 0, sizeof(l2info));
l2info.pictype = DLT_JUNIPER_MFR;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* child-link ? */
if (l2info.cookie_len == 0) {
mfr_print(ndo, p, l2info.length);
return l2info.header_len;
}
/* first try the LSQ protos */
if (l2info.cookie_len == AS_PIC_COOKIE_LEN) {
switch(l2info.proto) {
case JUNIPER_LSQ_L3_PROTO_IPV4:
ip_print(ndo, p, l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_IPV6:
ip6_print(ndo, p,l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_MPLS:
mpls_print(ndo, p, l2info.length);
return l2info.header_len;
case JUNIPER_LSQ_L3_PROTO_ISO:
isoclns_print(ndo, p, l2info.length);
return l2info.header_len;
default:
break;
}
return l2info.header_len;
}
/* suppress Bundle-ID if frame was captured on a child-link */
if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1)
ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle));
switch (l2info.proto) {
case (LLCSAP_ISONS<<8 | LLCSAP_ISONS):
isoclns_print(ndo, p + 1, l2info.length - 1);
break;
case (LLC_UI<<8 | NLPID_Q933):
case (LLC_UI<<8 | NLPID_IP):
case (LLC_UI<<8 | NLPID_IP6):
/* pass IP{4,6} to the OSI layer for proper link-layer printing */
isoclns_print(ndo, p - 1, l2info.length + 1);
break;
default:
ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length));
}
return l2info.header_len;
}
#endif
#ifdef DLT_JUNIPER_MLFR
u_int
juniper_mlfr_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_MLFR;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
/* suppress Bundle-ID if frame was captured on a child-link */
if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1)
ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle));
switch (l2info.proto) {
case (LLC_UI):
case (LLC_UI<<8):
isoclns_print(ndo, p, l2info.length);
break;
case (LLC_UI<<8 | NLPID_Q933):
case (LLC_UI<<8 | NLPID_IP):
case (LLC_UI<<8 | NLPID_IP6):
/* pass IP{4,6} to the OSI layer for proper link-layer printing */
isoclns_print(ndo, p - 1, l2info.length + 1);
break;
default:
ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length));
}
return l2info.header_len;
}
#endif
/*
* ATM1 PIC cookie format
*
* +-----+-------------------------+-------------------------------+
* |fmtid| vc index | channel ID |
* +-----+-------------------------+-------------------------------+
*/
#ifdef DLT_JUNIPER_ATM1
u_int
juniper_atm1_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM1;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[0] == 0x80) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
}
#endif
/*
* ATM2 PIC cookie format
*
* +-------------------------------+---------+---+-----+-----------+
* | channel ID | reserv |AAL| CCRQ| gap cnt |
* +-------------------------------+---------+---+-----+-----------+
*/
#ifdef DLT_JUNIPER_ATM2
u_int
juniper_atm2_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM2;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[7] & ATM2_PKT_TYPE_MASK) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (l2info.direction != JUNIPER_BPF_PKT_IN && /* ether-over-1483 encaps ? */
(EXTRACT_32BITS(l2info.cookie) & ATM2_GAP_COUNT_MASK)) {
ether_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if(juniper_ppp_heuristic_guess(ndo, p, l2info.length) != 0) /* PPPoA vcmux encaps ? */
return l2info.header_len;
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
}
#endif
/* try to guess, based on all PPP protos that are supported in
* a juniper router if the payload data is encapsulated using PPP */
static int
juniper_ppp_heuristic_guess(netdissect_options *ndo,
register const u_char *p, u_int length)
{
switch(EXTRACT_16BITS(p)) {
case PPP_IP :
case PPP_OSI :
case PPP_MPLS_UCAST :
case PPP_MPLS_MCAST :
case PPP_IPCP :
case PPP_OSICP :
case PPP_MPLSCP :
case PPP_LCP :
case PPP_PAP :
case PPP_CHAP :
case PPP_ML :
case PPP_IPV6 :
case PPP_IPV6CP :
ppp_print(ndo, p, length);
break;
default:
return 0; /* did not find a ppp header */
break;
}
return 1; /* we printed a ppp packet */
}
static int
ip_heuristic_guess(netdissect_options *ndo,
register const u_char *p, u_int length)
{
switch(p[0]) {
case 0x45:
case 0x46:
case 0x47:
case 0x48:
case 0x49:
case 0x4a:
case 0x4b:
case 0x4c:
case 0x4d:
case 0x4e:
case 0x4f:
ip_print(ndo, p, length);
break;
case 0x60:
case 0x61:
case 0x62:
case 0x63:
case 0x64:
case 0x65:
case 0x66:
case 0x67:
case 0x68:
case 0x69:
case 0x6a:
case 0x6b:
case 0x6c:
case 0x6d:
case 0x6e:
case 0x6f:
ip6_print(ndo, p, length);
break;
default:
return 0; /* did not find a ip header */
break;
}
return 1; /* we printed an v4/v6 packet */
}
static int
juniper_read_tlv_value(const u_char *p, u_int tlv_type, u_int tlv_len)
{
int tlv_value;
/* TLVs < 128 are little endian encoded */
if (tlv_type < 128) {
switch (tlv_len) {
case 1:
tlv_value = *p;
break;
case 2:
tlv_value = EXTRACT_LE_16BITS(p);
break;
case 3:
tlv_value = EXTRACT_LE_24BITS(p);
break;
case 4:
tlv_value = EXTRACT_LE_32BITS(p);
break;
default:
tlv_value = -1;
break;
}
} else {
/* TLVs >= 128 are big endian encoded */
switch (tlv_len) {
case 1:
tlv_value = *p;
break;
case 2:
tlv_value = EXTRACT_16BITS(p);
break;
case 3:
tlv_value = EXTRACT_24BITS(p);
break;
case 4:
tlv_value = EXTRACT_32BITS(p);
break;
default:
tlv_value = -1;
break;
}
}
return tlv_value;
}
static int
juniper_parse_header(netdissect_options *ndo,
const u_char *p, const struct pcap_pkthdr *h, struct juniper_l2info_t *l2info)
{
const struct juniper_cookie_table_t *lp = juniper_cookie_table;
u_int idx, jnx_ext_len, jnx_header_len = 0;
uint8_t tlv_type,tlv_len;
uint32_t control_word;
int tlv_value;
const u_char *tptr;
l2info->header_len = 0;
l2info->cookie_len = 0;
l2info->proto = 0;
l2info->length = h->len;
l2info->caplen = h->caplen;
ND_TCHECK2(p[0], 4);
l2info->flags = p[3];
l2info->direction = p[3]&JUNIPER_BPF_PKT_IN;
if (EXTRACT_24BITS(p) != JUNIPER_MGC_NUMBER) { /* magic number found ? */
ND_PRINT((ndo, "no magic-number found!"));
return 0;
}
if (ndo->ndo_eflag) /* print direction */
ND_PRINT((ndo, "%3s ", tok2str(juniper_direction_values, "---", l2info->direction)));
/* magic number + flags */
jnx_header_len = 4;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\tJuniper PCAP Flags [%s]",
bittok2str(jnx_flag_values, "none", l2info->flags)));
/* extensions present ? - calculate how much bytes to skip */
if ((l2info->flags & JUNIPER_BPF_EXT ) == JUNIPER_BPF_EXT ) {
tptr = p+jnx_header_len;
/* ok to read extension length ? */
ND_TCHECK2(tptr[0], 2);
jnx_ext_len = EXTRACT_16BITS(tptr);
jnx_header_len += 2;
tptr +=2;
/* nail up the total length -
* just in case something goes wrong
* with TLV parsing */
jnx_header_len += jnx_ext_len;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, ", PCAP Extension(s) total length %u", jnx_ext_len));
ND_TCHECK2(tptr[0], jnx_ext_len);
while (jnx_ext_len > JUNIPER_EXT_TLV_OVERHEAD) {
tlv_type = *(tptr++);
tlv_len = *(tptr++);
tlv_value = 0;
/* sanity checks */
if (tlv_type == 0 || tlv_len == 0)
break;
if (tlv_len+JUNIPER_EXT_TLV_OVERHEAD > jnx_ext_len)
goto trunc;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t %s Extension TLV #%u, length %u, value ",
tok2str(jnx_ext_tlv_values,"Unknown",tlv_type),
tlv_type,
tlv_len));
tlv_value = juniper_read_tlv_value(tptr, tlv_type, tlv_len);
switch (tlv_type) {
case JUNIPER_EXT_TLV_IFD_NAME:
/* FIXME */
break;
case JUNIPER_EXT_TLV_IFD_MEDIATYPE:
case JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%s (%u)",
tok2str(juniper_ifmt_values, "Unknown", tlv_value),
tlv_value));
}
break;
case JUNIPER_EXT_TLV_IFL_ENCAPS:
case JUNIPER_EXT_TLV_TTP_IFL_ENCAPS:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%s (%u)",
tok2str(juniper_ifle_values, "Unknown", tlv_value),
tlv_value));
}
break;
case JUNIPER_EXT_TLV_IFL_IDX: /* fall through */
case JUNIPER_EXT_TLV_IFL_UNIT:
case JUNIPER_EXT_TLV_IFD_IDX:
default:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%u", tlv_value));
}
break;
}
tptr+=tlv_len;
jnx_ext_len -= tlv_len+JUNIPER_EXT_TLV_OVERHEAD;
}
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t-----original packet-----\n\t"));
}
if ((l2info->flags & JUNIPER_BPF_NO_L2 ) == JUNIPER_BPF_NO_L2 ) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "no-L2-hdr, "));
/* there is no link-layer present -
* perform the v4/v6 heuristics
* to figure out what it is
*/
ND_TCHECK2(p[jnx_header_len + 4], 1);
if (ip_heuristic_guess(ndo, p + jnx_header_len + 4,
l2info->length - (jnx_header_len + 4)) == 0)
ND_PRINT((ndo, "no IP-hdr found!"));
l2info->header_len=jnx_header_len+4;
return 0; /* stop parsing the output further */
}
l2info->header_len = jnx_header_len;
p+=l2info->header_len;
l2info->length -= l2info->header_len;
l2info->caplen -= l2info->header_len;
/* search through the cookie table and copy values matching for our PIC type */
while (lp->s != NULL) {
if (lp->pictype == l2info->pictype) {
l2info->cookie_len += lp->cookie_len;
switch (p[0]) {
case LS_COOKIE_ID:
l2info->cookie_type = LS_COOKIE_ID;
l2info->cookie_len += 2;
break;
case AS_COOKIE_ID:
l2info->cookie_type = AS_COOKIE_ID;
l2info->cookie_len = 8;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
#ifdef DLT_JUNIPER_MFR
/* MFR child links don't carry cookies */
if (l2info->pictype == DLT_JUNIPER_MFR &&
(p[0] & MFR_BE_MASK) == MFR_BE_MASK) {
l2info->cookie_len = 0;
}
#endif
l2info->header_len += l2info->cookie_len;
l2info->length -= l2info->cookie_len;
l2info->caplen -= l2info->cookie_len;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%s-PIC, cookie-len %u",
lp->s,
l2info->cookie_len));
if (l2info->cookie_len > 0) {
ND_TCHECK2(p[0], l2info->cookie_len);
if (ndo->ndo_eflag)
ND_PRINT((ndo, ", cookie 0x"));
for (idx = 0; idx < l2info->cookie_len; idx++) {
l2info->cookie[idx] = p[idx]; /* copy cookie data */
if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x", p[idx]));
}
}
if (ndo->ndo_eflag) ND_PRINT((ndo, ": ")); /* print demarc b/w L2/L3*/
l2info->proto = EXTRACT_16BITS(p+l2info->cookie_len);
break;
}
++lp;
}
p+=l2info->cookie_len;
/* DLT_ specific parsing */
switch(l2info->pictype) {
#ifdef DLT_JUNIPER_MLPPP
case DLT_JUNIPER_MLPPP:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
l2info->bundle = l2info->cookie[1];
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
break;
#endif
#ifdef DLT_JUNIPER_MLFR
case DLT_JUNIPER_MLFR:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
l2info->bundle = l2info->cookie[1];
l2info->proto = EXTRACT_16BITS(p);
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
}
break;
#endif
#ifdef DLT_JUNIPER_MFR
case DLT_JUNIPER_MFR:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
l2info->bundle = l2info->cookie[1];
l2info->proto = EXTRACT_16BITS(p);
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
break;
#endif
#ifdef DLT_JUNIPER_ATM2
case DLT_JUNIPER_ATM2:
ND_TCHECK2(p[0], 4);
/* ATM cell relay control word present ? */
if (l2info->cookie[7] & ATM2_PKT_TYPE_MASK) {
control_word = EXTRACT_32BITS(p);
/* some control word heuristics */
switch(control_word) {
case 0: /* zero control word */
case 0x08000000: /* < JUNOS 7.4 control-word */
case 0x08380000: /* cntl word plus cell length (56) >= JUNOS 7.4*/
l2info->header_len += 4;
break;
default:
break;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "control-word 0x%08x ", control_word));
}
break;
#endif
#ifdef DLT_JUNIPER_GGSN
case DLT_JUNIPER_GGSN:
break;
#endif
#ifdef DLT_JUNIPER_ATM1
case DLT_JUNIPER_ATM1:
break;
#endif
#ifdef DLT_JUNIPER_PPP
case DLT_JUNIPER_PPP:
break;
#endif
#ifdef DLT_JUNIPER_CHDLC
case DLT_JUNIPER_CHDLC:
break;
#endif
#ifdef DLT_JUNIPER_ETHER
case DLT_JUNIPER_ETHER:
break;
#endif
#ifdef DLT_JUNIPER_FRELAY
case DLT_JUNIPER_FRELAY:
break;
#endif
default:
ND_PRINT((ndo, "Unknown Juniper DLT_ type %u: ", l2info->pictype));
break;
}
if (ndo->ndo_eflag > 1)
ND_PRINT((ndo, "hlen %u, proto 0x%04x, ", l2info->header_len, l2info->proto));
return 1; /* everything went ok so far. continue parsing */
trunc:
ND_PRINT((ndo, "[|juniper_hdr], length %u", h->len));
return 0;
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 4
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2644_7 |
crossvul-cpp_data_bad_351_2 | /*
* card-authentic.c: Support for the Oberthur smart cards
* with PKI applet AuthentIC v3.2
*
* Copyright (C) 2010 Viktor Tarasov <vtarasov@opentrust.com>
* OpenTrust <www.opentrust.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef ENABLE_OPENSSL /* empty file without openssl */
#include <string.h>
#include <stdlib.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
#include "opensc.h"
#include "pkcs15.h"
#include "iso7816.h"
/* #include "hash-strings.h" */
#include "authentic.h"
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/pkcs12.h>
#include <openssl/x509v3.h>
#include <openssl/sha.h>
#define AUTHENTIC_CARD_DEFAULT_FLAGS ( 0 \
| SC_ALGORITHM_ONBOARD_KEY_GEN \
| SC_ALGORITHM_RSA_PAD_ISO9796 \
| SC_ALGORITHM_RSA_PAD_PKCS1 \
| SC_ALGORITHM_RSA_HASH_NONE \
| SC_ALGORITHM_RSA_HASH_SHA1 \
| SC_ALGORITHM_RSA_HASH_SHA256)
#define AUTHENTIC_READ_BINARY_LENGTH_MAX 0xE7
/* generic iso 7816 operations table */
static const struct sc_card_operations *iso_ops = NULL;
/* our operations table with overrides */
static struct sc_card_operations authentic_ops;
static struct sc_card_driver authentic_drv = {
"Oberthur AuthentIC v3.1", "authentic", &authentic_ops,
NULL, 0, NULL
};
/*
* FIXME: use dynamic allocation for the PIN data to reduce memory usage
* actually size of 'authentic_private_data' 140kb
*/
struct authentic_private_data {
struct sc_pin_cmd_data pins[8];
unsigned char pins_sha1[8][SHA_DIGEST_LENGTH];
struct sc_cplc cplc;
};
static struct sc_atr_table authentic_known_atrs[] = {
{ "3B:DD:18:00:81:31:FE:45:80:F9:A0:00:00:00:77:01:00:70:0A:90:00:8B", NULL,
"Oberthur AuthentIC 3.2.2", SC_CARD_TYPE_OBERTHUR_AUTHENTIC_3_2, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
unsigned char aid_AuthentIC_3_2[] = {
0xA0,0x00,0x00,0x00,0x77,0x01,0x00,0x70,0x0A,0x10,0x00,0xF1,0x00,0x00,0x01,0x00
};
static int authentic_select_file(struct sc_card *card, const struct sc_path *path, struct sc_file **file_out);
static int authentic_process_fci(struct sc_card *card, struct sc_file *file, const unsigned char *buf, size_t buflen);
static int authentic_get_serialnr(struct sc_card *card, struct sc_serial_number *serial);
static int authentic_pin_get_policy (struct sc_card *card, struct sc_pin_cmd_data *data);
static int authentic_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left);
static int authentic_select_mf(struct sc_card *card, struct sc_file **file_out);
static int authentic_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr);
static void authentic_debug_select_file(struct sc_card *card, const struct sc_path *path);
#ifdef ENABLE_SM
static int authentic_sm_open(struct sc_card *card);
static int authentic_sm_get_wrapped_apdu(struct sc_card *card, struct sc_apdu *apdu, struct sc_apdu **sm_apdu);
static int authentic_sm_free_wrapped_apdu(struct sc_card *card, struct sc_apdu *apdu, struct sc_apdu **sm_apdu);
#endif
static int
authentic_update_blob(struct sc_context *ctx, unsigned tag, unsigned char *data, size_t data_len,
unsigned char **blob, size_t *blob_size)
{
unsigned char *pp = NULL;
int offs = 0, sz;
if (data_len == 0)
return SC_SUCCESS;
sz = data_len + 2;
if (tag > 0xFF)
sz++;
if (data_len > 0x7F && data_len < 0x100)
sz++;
else if (data_len >= 0x100)
sz += 2;
pp = realloc(*blob, *blob_size + sz);
if (!pp)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
if (tag > 0xFF)
*(pp + *blob_size + offs++) = (tag >> 8) & 0xFF;
*(pp + *blob_size + offs++) = tag & 0xFF;
if (data_len >= 0x100) {
*(pp + *blob_size + offs++) = 0x82;
*(pp + *blob_size + offs++) = (data_len >> 8) & 0xFF;
}
else if (data_len > 0x7F) {
*(pp + *blob_size + offs++) = 0x81;
}
*(pp + *blob_size + offs++) = data_len & 0xFF;
memcpy(pp + *blob_size + offs, data, data_len);
*blob_size += sz;
*blob = pp;
return SC_SUCCESS;
}
static int
authentic_parse_size(unsigned char *in, size_t *out)
{
if (!in || !out)
return SC_ERROR_INVALID_ARGUMENTS;
if (*in < 0x80) {
*out = *in;
return 1;
}
else if (*in == 0x81) {
*out = *(in + 1);
return 2;
}
else if (*in == 0x82) {
*out = *(in + 1) * 0x100 + *(in + 2);
return 3;
}
return SC_ERROR_INVALID_DATA;
}
static int
authentic_get_tagged_data(struct sc_context *ctx, unsigned char *in, size_t in_len,
unsigned in_tag, unsigned char **out, size_t *out_len)
{
size_t size_len, tag_len, offs, size;
unsigned tag;
if (!out || !out_len)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
for (offs = 0; offs < in_len; ) {
if ((*(in + offs) == 0x7F) || (*(in + offs) == 0x5F)) {
tag = *(in + offs) * 0x100 + *(in + offs + 1);
tag_len = 2;
}
else {
tag = *(in + offs);
tag_len = 1;
}
size_len = authentic_parse_size(in + offs + tag_len, &size);
LOG_TEST_RET(ctx, size_len, "parse error: invalid size data");
if (tag == in_tag) {
*out = in + offs + tag_len + size_len;
*out_len = size;
return SC_SUCCESS;
}
offs += tag_len + size_len + size;
}
return SC_ERROR_ASN1_OBJECT_NOT_FOUND;
}
static int
authentic_decode_pubkey_rsa(struct sc_context *ctx, unsigned char *blob, size_t blob_len,
struct sc_pkcs15_prkey **out_key)
{
struct sc_pkcs15_prkey_rsa *key;
unsigned char *data;
size_t data_len;
int rv;
LOG_FUNC_CALLED(ctx);
if (!out_key)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
if (!(*out_key)) {
*out_key = calloc(1, sizeof(struct sc_pkcs15_prkey));
if (!(*out_key))
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot callocate pkcs15 private key");
(*out_key)->algorithm = SC_ALGORITHM_RSA;
}
else if (*out_key && (*out_key)->algorithm != SC_ALGORITHM_RSA) {
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_DATA);
}
key = &(*out_key)->u.rsa;
rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_RSA_PUBLIC, &data, &data_len);
LOG_TEST_RET(ctx, rv, "cannot get public key SDO data");
blob = data;
blob_len = data_len;
/* Get RSA public modulus */
rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_RSA_PUBLIC_MODULUS, &data, &data_len);
LOG_TEST_RET(ctx, rv, "cannot get public key SDO data");
if (key->modulus.data)
free(key->modulus.data);
key->modulus.data = calloc(1, data_len);
if (!key->modulus.data)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot callocate modulus BN");
memcpy(key->modulus.data, data, data_len);
key->modulus.len = data_len;
/* Get RSA public exponent */
rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_RSA_PUBLIC_EXPONENT, &data, &data_len);
LOG_TEST_RET(ctx, rv, "cannot get public key SDO data");
if (key->exponent.data)
free(key->exponent.data);
key->exponent.data = calloc(1, data_len);
if (!key->exponent.data)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot callocate modulus BN");
memcpy(key->exponent.data, data, data_len);
key->exponent.len = data_len;
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_parse_credential_data(struct sc_context *ctx, struct sc_pin_cmd_data *pin_cmd,
unsigned char *blob, size_t blob_len)
{
unsigned char *data;
size_t data_len;
int rv, ii;
unsigned tag = AUTHENTIC_TAG_CREDENTIAL | pin_cmd->pin_reference;
rv = authentic_get_tagged_data(ctx, blob, blob_len, tag, &blob, &blob_len);
LOG_TEST_RET(ctx, rv, "cannot get credential data");
rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_CREDENTIAL_TRYLIMIT, &data, &data_len);
LOG_TEST_RET(ctx, rv, "cannot get try limit");
pin_cmd->pin1.max_tries = *data;
rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_DOCP_MECH, &data, &data_len);
LOG_TEST_RET(ctx, rv, "cannot get PIN type");
if (*data == 0)
pin_cmd->pin_type = SC_AC_CHV;
else if (*data >= 2 && *data <= 7)
pin_cmd->pin_type = SC_AC_AUT;
else
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "unsupported Credential type");
rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_DOCP_ACLS, &data, &data_len);
LOG_TEST_RET(ctx, rv, "failed to get ACLs");
sc_log(ctx, "data_len:%"SC_FORMAT_LEN_SIZE_T"u", data_len);
if (data_len == 10) {
for (ii=0; ii<5; ii++) {
unsigned char acl = *(data + ii*2);
unsigned char cred_id = *(data + ii*2 + 1);
unsigned sc = acl * 0x100 + cred_id;
sc_log(ctx, "%i: SC:%X", ii, sc);
if (!sc)
continue;
if (acl & AUTHENTIC_AC_SM_MASK) {
pin_cmd->pin1.acls[ii].method = SC_AC_SCB;
pin_cmd->pin1.acls[ii].key_ref = sc;
}
else if (acl!=0xFF && cred_id) {
sc_log(ctx, "%i: ACL(method:SC_AC_CHV,id:%i)", ii, cred_id);
pin_cmd->pin1.acls[ii].method = SC_AC_CHV;
pin_cmd->pin1.acls[ii].key_ref = cred_id;
}
else {
pin_cmd->pin1.acls[ii].method = SC_AC_NEVER;
pin_cmd->pin1.acls[ii].key_ref = 0;
}
}
}
rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_CREDENTIAL_PINPOLICY, &data, &data_len);
if (!rv) {
blob = data;
blob_len = data_len;
rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_CREDENTIAL_PINPOLICY_MAXLENGTH, &data, &data_len);
LOG_TEST_RET(ctx, rv, "failed to get PIN max.length value");
pin_cmd->pin1.max_length = *data;
rv = authentic_get_tagged_data(ctx, blob, blob_len, AUTHENTIC_TAG_CREDENTIAL_PINPOLICY_MINLENGTH, &data, &data_len);
LOG_TEST_RET(ctx, rv, "failed to get PIN min.length value");
pin_cmd->pin1.min_length = *data;
}
return SC_SUCCESS;
}
static int
authentic_get_cplc(struct sc_card *card)
{
struct authentic_private_data *prv_data = (struct authentic_private_data *) card->drv_data;
struct sc_apdu apdu;
int rv, ii;
unsigned char p1, p2;
p1 = (SC_CPLC_TAG >> 8) & 0xFF;
p2 = SC_CPLC_TAG & 0xFF;
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xCA, p1, p2);
for (ii=0;ii<2;ii++) {
apdu.le = SC_CPLC_DER_SIZE;
apdu.resplen = sizeof(prv_data->cplc.value);
apdu.resp = prv_data->cplc.value;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (rv != SC_ERROR_CLASS_NOT_SUPPORTED)
break;
apdu.cla = 0x80;
}
LOG_TEST_RET(card->ctx, rv, "'GET CPLC' error");
prv_data->cplc.len = SC_CPLC_DER_SIZE;
return SC_SUCCESS;
}
static int
authentic_select_aid(struct sc_card *card, unsigned char *aid, size_t aid_len,
unsigned char *out, size_t *out_len)
{
struct sc_apdu apdu;
unsigned char apdu_resp[SC_MAX_APDU_BUFFER_SIZE];
int rv;
/* Select Card Manager (to deselect previously selected application) */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 0x04, 0x00);
apdu.lc = aid_len;
apdu.data = aid;
apdu.datalen = aid_len;
apdu.resplen = sizeof(apdu_resp);
apdu.resp = apdu_resp;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, rv, "Cannot select AID");
if (out && out_len) {
if (*out_len < apdu.resplen)
LOG_TEST_RET(card->ctx, SC_ERROR_BUFFER_TOO_SMALL, "Cannot select AID");
memcpy(out, apdu.resp, apdu.resplen);
}
return SC_SUCCESS;
}
static int
authentic_match_card(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
int i;
sc_log_hex(ctx, "try to match card with ATR", card->atr.value, card->atr.len);
i = _sc_match_atr(card, authentic_known_atrs, &card->type);
if (i < 0) {
sc_log(ctx, "card not matched");
return 0;
}
sc_log(ctx, "'%s' card matched", authentic_known_atrs[i].name);
return 1;
}
static int
authentic_init_oberthur_authentic_3_2(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
unsigned int flags;
int rv = 0;
LOG_FUNC_CALLED(ctx);
flags = AUTHENTIC_CARD_DEFAULT_FLAGS;
_sc_card_add_rsa_alg(card, 1024, flags, 0x10001);
_sc_card_add_rsa_alg(card, 2048, flags, 0x10001);
card->caps = SC_CARD_CAP_RNG;
card->caps |= SC_CARD_CAP_APDU_EXT;
card->caps |= SC_CARD_CAP_USE_FCI_AC;
#ifdef ENABLE_SM
card->sm_ctx.ops.open = authentic_sm_open;
card->sm_ctx.ops.get_sm_apdu = authentic_sm_get_wrapped_apdu;
card->sm_ctx.ops.free_sm_apdu = authentic_sm_free_wrapped_apdu;
#endif
rv = authentic_select_aid(card, aid_AuthentIC_3_2, sizeof(aid_AuthentIC_3_2), NULL, NULL);
LOG_TEST_RET(ctx, rv, "AuthentIC application select error");
rv = authentic_select_mf(card, NULL);
LOG_TEST_RET(ctx, rv, "MF selection error");
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_init(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
int ii, rv = SC_ERROR_INVALID_CARD;
LOG_FUNC_CALLED(ctx);
for(ii=0;authentic_known_atrs[ii].atr;ii++) {
if (card->type == authentic_known_atrs[ii].type) {
card->name = authentic_known_atrs[ii].name;
card->flags = authentic_known_atrs[ii].flags;
break;
}
}
if (!authentic_known_atrs[ii].atr)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_CARD);
card->cla = 0x00;
card->drv_data = (struct authentic_private_data *) calloc(sizeof(struct authentic_private_data), 1);
if (!card->drv_data)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
if (card->type == SC_CARD_TYPE_OBERTHUR_AUTHENTIC_3_2)
rv = authentic_init_oberthur_authentic_3_2(card);
if (rv != SC_SUCCESS)
rv = authentic_get_serialnr(card, NULL);
if (rv != SC_SUCCESS)
rv = SC_ERROR_INVALID_CARD;
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_erase_binary(struct sc_card *card, unsigned int offs, size_t count, unsigned long flags)
{
struct sc_context *ctx = card->ctx;
int rv;
unsigned char *buf_zero = NULL;
LOG_FUNC_CALLED(ctx);
if (!count)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "'ERASE BINARY' with ZERO count not supported");
if (card->cache.valid && card->cache.current_ef)
sc_log(ctx, "current_ef(type=%i) %s", card->cache.current_ef->path.type,
sc_print_path(&card->cache.current_ef->path));
buf_zero = calloc(1, count);
if (!buf_zero)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "cannot allocate buff 'zero'");
rv = sc_update_binary(card, offs, buf_zero, count, flags);
free(buf_zero);
LOG_TEST_RET(ctx, rv, "'ERASE BINARY' failed");
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
authentic_set_current_files(struct sc_card *card, struct sc_path *path,
unsigned char *resp, size_t resplen, struct sc_file **file_out)
{
struct sc_context *ctx = card->ctx;
struct sc_file *file = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
if (resplen) {
switch (resp[0]) {
case 0x62:
case 0x6F:
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
if (path)
file->path = *path;
rv = authentic_process_fci(card, file, resp, resplen);
LOG_TEST_RET(ctx, rv, "cannot set 'current file': FCI process error");
break;
default:
LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
if (file->type == SC_FILE_TYPE_DF) {
struct sc_path cur_df_path;
memset(&cur_df_path, 0, sizeof(cur_df_path));
if (card->cache.valid && card->cache.current_df) {
cur_df_path = card->cache.current_df->path;
sc_file_free(card->cache.current_df);
}
card->cache.current_df = NULL;
sc_file_dup(&card->cache.current_df, file);
if (cur_df_path.len) {
memcpy(card->cache.current_df->path.value + cur_df_path.len,
card->cache.current_df->path.value,
card->cache.current_df->path.len);
memcpy(card->cache.current_df->path.value, cur_df_path.value, cur_df_path.len);
card->cache.current_df->path.len += cur_df_path.len;
}
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
card->cache.valid = 1;
}
else {
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
sc_file_dup(&card->cache.current_ef, file);
}
if (file_out)
*file_out = file;
else
sc_file_free(file);
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
authentic_select_mf(struct sc_card *card, struct sc_file **file_out)
{
struct sc_context *ctx = card->ctx;
struct sc_path mfpath;
int rv;
struct sc_apdu apdu;
unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE];
LOG_FUNC_CALLED(ctx);
sc_format_path("3F00", &mfpath);
mfpath.type = SC_PATH_TYPE_PATH;
if (card->cache.valid == 1
&& card->cache.current_df
&& card->cache.current_df->path.len == 2
&& !memcmp(card->cache.current_df->path.value, "\x3F\x00", 2)) {
if (file_out)
sc_file_dup(file_out, card->cache.current_df);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xA4, 0x00, 0x00);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "authentic_select_file() check SW failed");
if (card->cache.valid == 1) {
sc_file_free(card->cache.current_df);
card->cache.current_df = NULL;
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
}
rv = authentic_set_current_files(card, &mfpath, apdu.resp, apdu.resplen, file_out);
LOG_TEST_RET(ctx, rv, "authentic_select_file() cannot set 'current_file'");
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_reduce_path(struct sc_card *card, struct sc_path *path)
{
struct sc_context *ctx = card->ctx;
struct sc_path in_path, cur_path;
size_t offs;
LOG_FUNC_CALLED(ctx);
if (!path || path->len <= 2 || path->type == SC_PATH_TYPE_DF_NAME)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
if (!card->cache.valid || !card->cache.current_df)
LOG_FUNC_RETURN(ctx, 0);
in_path = *path;
cur_path = card->cache.current_df->path;
if (!memcmp(cur_path.value, "\x3F\x00", 2) && memcmp(in_path.value, "\x3F\x00", 2)) {
memmove(in_path.value + 2, in_path.value, in_path.len);
memcpy(in_path.value, "\x3F\x00", 2);
in_path.len += 2;
}
for (offs=0; offs < in_path.len && offs < cur_path.len; offs += 2) {
if (cur_path.value[offs] != in_path.value[offs])
break;
if (cur_path.value[offs + 1] != in_path.value[offs + 1])
break;
}
memmove(in_path.value, in_path.value + offs, sizeof(in_path.value) - offs);
in_path.len -= offs;
*path = in_path;
LOG_FUNC_RETURN(ctx, offs);
}
static void
authentic_debug_select_file(struct sc_card *card, const struct sc_path *path)
{
struct sc_context *ctx = card->ctx;
struct sc_card_cache *cache = &card->cache;
if (path)
sc_log(ctx, "try to select path(type:%i) %s",
path->type, sc_print_path(path));
if (!cache->valid)
return;
if (cache->current_df)
sc_log(ctx, "current_df(type=%i) %s",
cache->current_df->path.type, sc_print_path(&cache->current_df->path));
else
sc_log(ctx, "current_df empty");
if (cache->current_ef)
sc_log(ctx, "current_ef(type=%i) %s",
cache->current_ef->path.type, sc_print_path(&cache->current_ef->path));
else
sc_log(ctx, "current_ef empty");
}
static int
authentic_is_selected(struct sc_card *card, const struct sc_path *path, struct sc_file **file_out)
{
if (!path->len) {
if (file_out && card->cache.valid && card->cache.current_df)
sc_file_dup(file_out, card->cache.current_df);
return SC_SUCCESS;
}
else if (path->len == 2 && card->cache.valid && card->cache.current_ef) {
if (!memcmp(card->cache.current_ef->path.value, path->value, 2)) {
if (file_out)
sc_file_dup(file_out, card->cache.current_ef);
return SC_SUCCESS;
}
}
return SC_ERROR_FILE_NOT_FOUND;
}
static int
authentic_select_file(struct sc_card *card, const struct sc_path *path,
struct sc_file **file_out)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
struct sc_path lpath;
unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE];
int pathlen, rv;
LOG_FUNC_CALLED(ctx);
authentic_debug_select_file(card, path);
memcpy(&lpath, path, sizeof(struct sc_path));
rv = authentic_reduce_path(card, &lpath);
LOG_TEST_RET(ctx, rv, "reduce path error");
if (lpath.len >= 2 && lpath.value[0] == 0x3F && lpath.value[1] == 0x00) {
rv = authentic_select_mf(card, file_out);
LOG_TEST_RET(ctx, rv, "cannot select MF");
memmove(&lpath.value[0], &lpath.value[2], lpath.len - 2);
lpath.len -= 2;
if (!lpath.len)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
if (lpath.type == SC_PATH_TYPE_PATH && (lpath.len == 2))
lpath.type = SC_PATH_TYPE_FILE_ID;
rv = authentic_is_selected(card, &lpath, file_out);
if (!rv)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
pathlen = lpath.len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00);
if (card->type != SC_CARD_TYPE_OBERTHUR_AUTHENTIC_3_2)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Unsupported card");
if (lpath.type == SC_PATH_TYPE_FILE_ID) {
apdu.p1 = 0x00;
}
else if (lpath.type == SC_PATH_TYPE_PATH) {
apdu.p1 = 0x08;
}
else if (lpath.type == SC_PATH_TYPE_FROM_CURRENT) {
apdu.p1 = 0x09;
}
else if (lpath.type == SC_PATH_TYPE_DF_NAME) {
apdu.p1 = 4;
}
else if (lpath.type == SC_PATH_TYPE_PARENT) {
apdu.p1 = 0x03;
pathlen = 0;
apdu.cse = SC_APDU_CASE_2_SHORT;
}
else {
sc_log(ctx, "Invalid PATH type: 0x%X", lpath.type);
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "authentic_select_file() invalid PATH type");
}
apdu.lc = pathlen;
apdu.data = lpath.value;
apdu.datalen = pathlen;
if (apdu.cse == SC_APDU_CASE_4_SHORT || apdu.cse == SC_APDU_CASE_2_SHORT) {
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
}
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "authentic_select_file() check SW failed");
rv = authentic_set_current_files(card, &lpath, apdu.resp, apdu.resplen, file_out);
LOG_TEST_RET(ctx, rv, "authentic_select_file() cannot set 'current_file'");
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
authentic_read_binary(struct sc_card *card, unsigned int idx,
unsigned char *buf, size_t count, unsigned long flags)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
size_t sz, rest, ret_count = 0;
int rv = SC_SUCCESS;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"offs:%i,count:%"SC_FORMAT_LEN_SIZE_T"u,max_recv_size:%"SC_FORMAT_LEN_SIZE_T"u",
idx, count, card->max_recv_size);
rest = count;
while(rest) {
sz = rest > 256 ? 256 : rest;
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, (idx >> 8) & 0x7F, idx & 0xFF);
apdu.le = sz;
apdu.resplen = sz;
apdu.resp = (buf + ret_count);
rv = sc_transmit_apdu(card, &apdu);
if(!rv)
ret_count += apdu.resplen;
else
break;
idx += sz;
rest -= sz;
}
if (rv) {
LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "authentic_read_binary() failed");
LOG_FUNC_RETURN(ctx, count);
}
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (!rv)
count = ret_count;
LOG_TEST_RET(ctx, rv, "authentic_read_binary() failed");
LOG_FUNC_RETURN(ctx, count);
}
static int
authentic_write_binary(struct sc_card *card, unsigned int idx,
const unsigned char *buf, size_t count, unsigned long flags)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
size_t sz, rest;
int rv = SC_SUCCESS;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"offs:%i,count:%"SC_FORMAT_LEN_SIZE_T"u,max_send_size:%"SC_FORMAT_LEN_SIZE_T"u",
idx, count, card->max_send_size);
rest = count;
while(rest) {
sz = rest > 255 ? 255 : rest;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xD0, (idx >> 8) & 0x7F, idx & 0xFF);
apdu.lc = sz;
apdu.datalen = sz;
apdu.data = buf + count - rest;
rv = sc_transmit_apdu(card, &apdu);
if(rv)
break;
idx += sz;
rest -= sz;
}
if (rv)
{
LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "authentic_write_binary() failed");
LOG_FUNC_RETURN(ctx, count);
}
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "authentic_write_binary() failed");
LOG_FUNC_RETURN(ctx, count);
}
static int
authentic_update_binary(struct sc_card *card, unsigned int idx,
const unsigned char *buf, size_t count, unsigned long flags)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
size_t sz, rest;
int rv = SC_SUCCESS;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"offs:%i,count:%"SC_FORMAT_LEN_SIZE_T"u,max_send_size:%"SC_FORMAT_LEN_SIZE_T"u",
idx, count, card->max_send_size);
rest = count;
while(rest) {
sz = rest > 255 ? 255 : rest;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xD6, (idx >> 8) & 0x7F, idx & 0xFF);
apdu.lc = sz;
apdu.datalen = sz;
apdu.data = buf + count - rest;
rv = sc_transmit_apdu(card, &apdu);
if(rv)
break;
idx += sz;
rest -= sz;
}
if (rv)
{
LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "authentic_update_binary() failed");
LOG_FUNC_RETURN(ctx, count);
}
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "authentic_update_binary() failed");
LOG_FUNC_RETURN(ctx, count);
}
static int
authentic_process_fci(struct sc_card *card, struct sc_file *file,
const unsigned char *buf, size_t buflen)
{
struct sc_context *ctx = card->ctx;
size_t taglen;
int rv;
unsigned ii;
const unsigned char *tag = NULL;
unsigned char ops_DF[8] = {
SC_AC_OP_CREATE, SC_AC_OP_DELETE, SC_AC_OP_CRYPTO, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
unsigned char ops_EF[8] = {
SC_AC_OP_READ, SC_AC_OP_DELETE, SC_AC_OP_UPDATE, SC_AC_OP_RESIZE, 0xFF, 0xFF, 0xFF, 0xFF
};
LOG_FUNC_CALLED(ctx);
tag = sc_asn1_find_tag(card->ctx, buf, buflen, 0x6F, &taglen);
if (tag != NULL) {
sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen);
buf = tag;
buflen = taglen;
}
tag = sc_asn1_find_tag(card->ctx, buf, buflen, 0x62, &taglen);
if (tag != NULL) {
sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen);
buf = tag;
buflen = taglen;
}
rv = iso_ops->process_fci(card, file, buf, buflen);
LOG_TEST_RET(ctx, rv, "ISO parse FCI failed");
if (!file->sec_attr_len) {
sc_log_hex(ctx, "ACLs not found in data", buf, buflen);
sc_log(ctx, "Path:%s; Type:%X; PathType:%X", sc_print_path(&file->path), file->type, file->path.type);
if (file->path.type == SC_PATH_TYPE_DF_NAME || file->type == SC_FILE_TYPE_DF) {
file->type = SC_FILE_TYPE_DF;
}
else {
LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "ACLs tag missing");
}
}
sc_log_hex(ctx, "ACL data", file->sec_attr, file->sec_attr_len);
for (ii = 0; ii < file->sec_attr_len / 2; ii++) {
unsigned char op = file->type == SC_FILE_TYPE_DF ? ops_DF[ii] : ops_EF[ii];
unsigned char acl = *(file->sec_attr + ii*2);
unsigned char cred_id = *(file->sec_attr + ii*2 + 1);
unsigned sc = acl * 0x100 + cred_id;
sc_log(ctx, "ACL(%i) op 0x%X, acl %X:%X", ii, op, acl, cred_id);
if (op == 0xFF)
;
else if (!acl && !cred_id)
sc_file_add_acl_entry(file, op, SC_AC_NONE, 0);
else if (acl == 0xFF)
sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0);
else if (acl & AUTHENTIC_AC_SM_MASK)
sc_file_add_acl_entry(file, op, SC_AC_SCB, sc);
else if (cred_id)
sc_file_add_acl_entry(file, op, SC_AC_CHV, cred_id);
else
sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0);
}
LOG_FUNC_RETURN(ctx, 0);
}
static int
authentic_fcp_encode(struct sc_card *card, struct sc_file *file, unsigned char *out, size_t out_len)
{
struct sc_context *ctx = card->ctx;
unsigned char buf[0x80];
size_t ii, offs;
unsigned char ops_ef[4] = { SC_AC_OP_READ, SC_AC_OP_DELETE, SC_AC_OP_UPDATE, SC_AC_OP_RESIZE };
unsigned char ops_df[3] = { SC_AC_OP_CREATE, SC_AC_OP_DELETE, SC_AC_OP_CRYPTO };
unsigned char *ops = file->type == SC_FILE_TYPE_DF ? ops_df : ops_ef;
size_t ops_len = file->type == SC_FILE_TYPE_DF ? 3 : 4;
LOG_FUNC_CALLED(ctx);
offs = 0;
buf[offs++] = ISO7816_TAG_FCP_SIZE;
buf[offs++] = 2;
buf[offs++] = (file->size >> 8) & 0xFF;
buf[offs++] = file->size & 0xFF;
buf[offs++] = ISO7816_TAG_FCP_TYPE;
buf[offs++] = 1;
buf[offs++] = file->type == SC_FILE_TYPE_DF ? ISO7816_FILE_TYPE_DF : ISO7816_FILE_TYPE_TRANSPARENT_EF;
buf[offs++] = ISO7816_TAG_FCP_FID;
buf[offs++] = 2;
buf[offs++] = (file->id >> 8) & 0xFF;
buf[offs++] = file->id & 0xFF;
buf[offs++] = ISO7816_TAG_FCP_ACLS;
buf[offs++] = ops_len * 2;
for (ii=0; ii < ops_len; ii++) {
const struct sc_acl_entry *entry;
entry = sc_file_get_acl_entry(file, ops[ii]);
sc_log(ctx, "acl entry(method:%X,ref:%X)", entry->method, entry->key_ref);
if (entry->method == SC_AC_NEVER) {
/* TODO: After development change for 0xFF */
buf[offs++] = 0x00;
buf[offs++] = 0x00;
}
else if (entry->method == SC_AC_NONE) {
buf[offs++] = 0x00;
buf[offs++] = 0x00;
}
else if (entry->method == SC_AC_CHV) {
if (!(entry->key_ref & AUTHENTIC_V3_CREDENTIAL_ID_MASK)
|| (entry->key_ref & ~AUTHENTIC_V3_CREDENTIAL_ID_MASK))
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Non supported Credential Reference");
buf[offs++] = 0x00;
buf[offs++] = 0x01 << (entry->key_ref - 1);
}
else
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Non supported AC method");
}
if (out) {
if (out_len < offs)
LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Buffer too small to encode FCP");
memcpy(out, buf, offs);
}
LOG_FUNC_RETURN(ctx, offs);
}
static int
authentic_create_file(struct sc_card *card, struct sc_file *file)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char sbuf[0x100];
size_t sbuf_len;
struct sc_path path;
int rv;
LOG_FUNC_CALLED(ctx);
if (file->type != SC_FILE_TYPE_WORKING_EF)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Creation of the file with of this type is not supported");
authentic_debug_select_file(card, &file->path);
sbuf_len = authentic_fcp_encode(card, file, sbuf + 2, sizeof(sbuf)-2);
LOG_TEST_RET(ctx, sbuf_len, "FCP encode error");
sbuf[0] = ISO7816_TAG_FCP;
sbuf[1] = sbuf_len;
if (card->cache.valid && card->cache.current_df) {
const struct sc_acl_entry *entry = sc_file_get_acl_entry(card->cache.current_df, SC_AC_OP_CREATE);
sc_log(ctx, "CREATE method/reference %X/%X", entry->method, entry->key_ref);
if (entry->method == SC_AC_SCB)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Not yet supported");
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0, 0);
apdu.data = sbuf;
apdu.datalen = sbuf_len + 2;
apdu.lc = sbuf_len + 2;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "authentic_create_file() create file error");
path = file->path;
memcpy(path.value, path.value + path.len - 2, 2);
path.len = 2;
rv = authentic_set_current_files(card, &path, sbuf, sbuf_len + 2, NULL);
LOG_TEST_RET(ctx, rv, "authentic_select_file() cannot set 'current_file'");
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_delete_file(struct sc_card *card, const struct sc_path *path)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char p1;
int rv, ii;
LOG_FUNC_CALLED(ctx);
if (!path)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
for (ii=0, p1 = 0x02; ii<2; ii++, p1 = 0x01) {
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE4, p1, 0x00);
apdu.data = path->value + path->len - 2;
apdu.datalen = 2;
apdu.lc = 2;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (rv != SC_ERROR_FILE_NOT_FOUND || p1 != 0x02)
break;
}
LOG_TEST_RET(ctx, rv, "Delete file failed");
if (card->cache.valid) {
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_chv_verify_pinpad(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left)
{
struct sc_context *ctx = card->ctx;
unsigned char buffer[0x100];
struct sc_pin_cmd_pin *pin1 = &pin_cmd->pin1;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "Verify PIN(ref:%i) with pin-pad", pin_cmd->pin_reference);
rv = authentic_pin_is_verified(card, pin_cmd, tries_left);
if (!rv)
LOG_FUNC_RETURN(ctx, rv);
if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) {
sc_log(ctx, "Reader not ready for PIN PAD");
LOG_FUNC_RETURN(ctx, SC_ERROR_READER);
}
pin1->len = pin1->min_length;
pin1->max_length = 8;
memset(buffer, pin1->pad_char, sizeof(buffer));
pin1->data = buffer;
pin_cmd->cmd = SC_PIN_CMD_VERIFY;
pin_cmd->flags |= SC_PIN_CMD_USE_PINPAD;
rv = iso_ops->pin_cmd(card, pin_cmd, tries_left);
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_chv_verify(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd,
int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
struct sc_pin_cmd_pin *pin1 = &pin_cmd->pin1;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "CHV PIN reference %i, pin1(%p,len:%i)", pin_cmd->pin_reference, pin1->data, pin1->len);
if (pin1->data && !pin1->len) {
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x20, 0, pin_cmd->pin_reference);
}
else if (pin1->data && pin1->len) {
unsigned char pin_buff[SC_MAX_APDU_BUFFER_SIZE];
size_t pin_len;
memcpy(pin_buff, pin1->data, pin1->len);
pin_len = pin1->len;
if (pin1->pad_length && pin_cmd->flags & SC_PIN_CMD_NEED_PADDING) {
memset(pin_buff + pin1->len, pin1->pad_char, pin1->pad_length - pin1->len);
pin_len = pin1->pad_length;
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x20, 0, pin_cmd->pin_reference);
apdu.data = pin_buff;
apdu.datalen = pin_len;
apdu.lc = pin_len;
}
else if ((card->reader->capabilities & SC_READER_CAP_PIN_PAD) && !pin1->data && !pin1->len) {
rv = authentic_chv_verify_pinpad(card, pin_cmd, tries_left);
sc_log(ctx, "authentic_chv_verify() authentic_chv_verify_pinpad returned %i", rv);
LOG_FUNC_RETURN(ctx, rv);
}
else {
LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
}
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
if (apdu.sw1 == 0x63 && (apdu.sw2 & 0xF0) == 0xC0) {
pin1->tries_left = apdu.sw2 & 0x0F;
if (tries_left)
*tries_left = apdu.sw2 & 0x0F;
}
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd_data,
int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct sc_pin_cmd_data pin_cmd;
int rv;
LOG_FUNC_CALLED(ctx);
if (pin_cmd_data->pin_type != SC_AC_CHV)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "PIN type is not supported for the verification");
pin_cmd = *pin_cmd_data;
pin_cmd.pin1.data = (unsigned char *)"";
pin_cmd.pin1.len = 0;
rv = authentic_chv_verify(card, &pin_cmd, tries_left);
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_pin_verify(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd)
{
struct sc_context *ctx = card->ctx;
struct authentic_private_data *prv_data = (struct authentic_private_data *) card->drv_data;
unsigned char pin_sha1[SHA_DIGEST_LENGTH];
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "PIN(type:%X,reference:%X,data:%p,length:%i)",
pin_cmd->pin_type, pin_cmd->pin_reference, pin_cmd->pin1.data, pin_cmd->pin1.len);
if (pin_cmd->pin1.data && !pin_cmd->pin1.len) {
pin_cmd->pin1.tries_left = -1;
rv = authentic_pin_is_verified(card, pin_cmd, &pin_cmd->pin1.tries_left);
LOG_FUNC_RETURN(ctx, rv);
}
if (pin_cmd->pin1.data)
SHA1(pin_cmd->pin1.data, pin_cmd->pin1.len, pin_sha1);
else
SHA1((unsigned char *)"", 0, pin_sha1);
if (!memcmp(pin_sha1, prv_data->pins_sha1[pin_cmd->pin_reference], SHA_DIGEST_LENGTH)) {
sc_log(ctx, "Already verified");
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
memset(prv_data->pins_sha1[pin_cmd->pin_reference], 0, sizeof(prv_data->pins_sha1[0]));
rv = authentic_pin_get_policy(card, pin_cmd);
LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error");
if (pin_cmd->pin1.len > (int)pin_cmd->pin1.max_length)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_PIN_LENGTH, "PIN policy check failed");
pin_cmd->pin1.tries_left = -1;
rv = authentic_chv_verify(card, pin_cmd, &pin_cmd->pin1.tries_left);
LOG_TEST_RET(ctx, rv, "PIN CHV verification error");
memcpy(prv_data->pins_sha1[pin_cmd->pin_reference], pin_sha1, SHA_DIGEST_LENGTH);
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_pin_change_pinpad(struct sc_card *card, unsigned reference, int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct sc_pin_cmd_data pin_cmd;
unsigned char pin1_data[SC_MAX_APDU_BUFFER_SIZE], pin2_data[SC_MAX_APDU_BUFFER_SIZE];
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "CHV PINPAD PIN reference %i", reference);
if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) {
sc_log(ctx, "Reader not ready for PIN PAD");
LOG_FUNC_RETURN(ctx, SC_ERROR_READER);
}
memset(&pin_cmd, 0, sizeof(pin_cmd));
pin_cmd.pin_type = SC_AC_CHV;
pin_cmd.pin_reference = reference;
pin_cmd.cmd = SC_PIN_CMD_CHANGE;
pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD | SC_PIN_CMD_NEED_PADDING;
rv = authentic_pin_get_policy(card, &pin_cmd);
LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error");
memset(pin1_data, pin_cmd.pin1.pad_char, sizeof(pin1_data));
pin_cmd.pin1.data = pin1_data;
pin_cmd.pin1.len = pin_cmd.pin1.min_length;
pin_cmd.pin1.max_length = 8;
memcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin1));
memset(pin2_data, pin_cmd.pin2.pad_char, sizeof(pin2_data));
pin_cmd.pin2.data = pin2_data;
sc_log(ctx,
"PIN1 lengths max/min/pad: %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u",
pin_cmd.pin1.max_length, pin_cmd.pin1.min_length,
pin_cmd.pin1.pad_length);
sc_log(ctx,
"PIN2 lengths max/min/pad: %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u",
pin_cmd.pin2.max_length, pin_cmd.pin2.min_length,
pin_cmd.pin2.pad_length);
rv = iso_ops->pin_cmd(card, &pin_cmd, tries_left);
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_pin_change(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct authentic_private_data *prv_data = (struct authentic_private_data *) card->drv_data;
struct sc_apdu apdu;
unsigned char pin_data[SC_MAX_APDU_BUFFER_SIZE];
size_t offs;
int rv;
rv = authentic_pin_get_policy(card, data);
LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error");
memset(prv_data->pins_sha1[data->pin_reference], 0, sizeof(prv_data->pins_sha1[0]));
if (!data->pin1.data && !data->pin1.len && !data->pin2.data && !data->pin2.len) {
if (!(card->reader->capabilities & SC_READER_CAP_PIN_PAD))
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "PIN pad not supported");
rv = authentic_pin_change_pinpad(card, data->pin_reference, tries_left);
sc_log(ctx, "authentic_pin_cmd(SC_PIN_CMD_CHANGE) chv_change_pinpad returned %i", rv);
LOG_FUNC_RETURN(ctx, rv);
}
if (card->max_send_size && (data->pin1.len + data->pin2.len > (int)card->max_send_size))
LOG_TEST_RET(ctx, SC_ERROR_INVALID_PIN_LENGTH, "APDU transmit failed");
memset(pin_data, data->pin1.pad_char, sizeof(pin_data));
offs = 0;
if (data->pin1.data && data->pin1.len) {
memcpy(pin_data, data->pin1.data, data->pin1.len);
offs += data->pin1.pad_length;
}
if (data->pin2.data && data->pin2.len)
memcpy(pin_data + offs, data->pin2.data, data->pin2.len);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x24, offs ? 0x00 : 0x01, data->pin_reference);
apdu.data = pin_data;
apdu.datalen = offs + data->pin1.pad_length;
apdu.lc = offs + data->pin1.pad_length;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_chv_set_pinpad(struct sc_card *card, unsigned char reference)
{
struct sc_context *ctx = card->ctx;
struct sc_pin_cmd_data pin_cmd;
unsigned char pin_data[0x100];
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "Set CHV PINPAD PIN reference %i", reference);
if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) {
sc_log(ctx, "Reader not ready for PIN PAD");
LOG_FUNC_RETURN(ctx, SC_ERROR_READER);
}
memset(&pin_cmd, 0, sizeof(pin_cmd));
pin_cmd.pin_type = SC_AC_CHV;
pin_cmd.pin_reference = reference;
pin_cmd.cmd = SC_PIN_CMD_UNBLOCK;
pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD | SC_PIN_CMD_NEED_PADDING;
rv = authentic_pin_get_policy(card, &pin_cmd);
LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error");
memset(pin_data, pin_cmd.pin1.pad_char, sizeof(pin_data));
pin_cmd.pin1.data = pin_data;
pin_cmd.pin1.len = pin_cmd.pin1.min_length;
pin_cmd.pin1.max_length = 8;
memcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin1));
memset(&pin_cmd.pin1, 0, sizeof(pin_cmd.pin1));
sc_log(ctx,
"PIN2 max/min/pad %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u",
pin_cmd.pin2.max_length, pin_cmd.pin2.min_length,
pin_cmd.pin2.pad_length);
rv = iso_ops->pin_cmd(card, &pin_cmd, NULL);
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_pin_get_policy (struct sc_card *card, struct sc_pin_cmd_data *data)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char rbuf[0x100];
int ii, rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "get PIN(type:%X,ref:%X,tries-left:%i)", data->pin_type, data->pin_reference, data->pin1.tries_left);
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xCA, 0x5F, data->pin_reference);
for (ii=0;ii<2;ii++) {
apdu.le = sizeof(rbuf);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (rv != SC_ERROR_CLASS_NOT_SUPPORTED)
break;
apdu.cla = 0x80;
}
LOG_TEST_RET(ctx, rv, "'GET DATA' error");
data->pin1.tries_left = -1;
rv = authentic_parse_credential_data(ctx, data, apdu.resp, apdu.resplen);
LOG_TEST_RET(ctx, rv, "Cannot parse credential data");
data->pin1.encoding = SC_PIN_ENCODING_ASCII;
data->pin1.offset = 5;
data->pin1.pad_char = 0xFF;
data->pin1.pad_length = data->pin1.max_length;
data->pin1.logged_in = SC_PIN_STATE_UNKNOWN;
data->flags |= SC_PIN_CMD_NEED_PADDING;
sc_log(ctx,
"PIN policy: size max/min/pad %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u, tries max/left %i/%i",
data->pin1.max_length, data->pin1.min_length,
data->pin1.pad_length, data->pin1.max_tries,
data->pin1.tries_left);
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_pin_reset(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct authentic_private_data *prv_data = (struct authentic_private_data *) card->drv_data;
struct sc_pin_cmd_data pin_cmd, puk_cmd;
struct sc_apdu apdu;
unsigned reference;
int rv, ii;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "reset PIN (ref:%i,lengths %i/%i)", data->pin_reference, data->pin1.len, data->pin2.len);
memset(prv_data->pins_sha1[data->pin_reference], 0, sizeof(prv_data->pins_sha1[0]));
memset(&pin_cmd, 0, sizeof(pin_cmd));
pin_cmd.pin_reference = data->pin_reference;
pin_cmd.pin_type = data->pin_type;
pin_cmd.pin1.tries_left = -1;
rv = authentic_pin_get_policy(card, &pin_cmd);
LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error");
if (pin_cmd.pin1.acls[AUTHENTIC_ACL_NUM_PIN_RESET].method == SC_AC_CHV) {
for (ii=0;ii<8;ii++) {
unsigned char mask = 0x01 << ii;
if (pin_cmd.pin1.acls[AUTHENTIC_ACL_NUM_PIN_RESET].key_ref & mask) {
memset(&puk_cmd, 0, sizeof(puk_cmd));
puk_cmd.pin_reference = ii + 1;
rv = authentic_pin_get_policy(card, &puk_cmd);
LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error");
if (puk_cmd.pin_type == SC_AC_CHV)
break;
}
}
if (ii < 8) {
puk_cmd.pin1.data = data->pin1.data;
puk_cmd.pin1.len = data->pin1.len;
rv = authentic_pin_verify(card, &puk_cmd);
if (tries_left && rv == SC_ERROR_PIN_CODE_INCORRECT)
*tries_left = puk_cmd.pin1.tries_left;
LOG_TEST_RET(ctx, rv, "Cannot verify PUK");
}
}
reference = data->pin_reference;
if (data->pin2.len) {
unsigned char pin_data[SC_MAX_APDU_BUFFER_SIZE];
memset(pin_data, pin_cmd.pin1.pad_char, sizeof(pin_data));
memcpy(pin_data, data->pin2.data, data->pin2.len);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2C, 0x02, reference);
apdu.data = pin_data;
apdu.datalen = pin_cmd.pin1.pad_length;
apdu.lc = pin_cmd.pin1.pad_length;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "PIN cmd failed");
}
else if (data->pin2.data) {
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x2C, 3, reference);
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "PIN cmd failed");
}
else {
rv = authentic_chv_set_pinpad(card, reference);
LOG_TEST_RET(ctx, rv, "Failed to set PIN with pin-pad");
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
struct sc_context *ctx = card->ctx;
int rv = SC_ERROR_INTERNAL;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "PIN-CMD:%X,PIN(type:%X,ret:%i)", data->cmd, data->pin_type, data->pin_reference);
sc_log(ctx, "PIN1(%p,len:%i,tries-left:%i)", data->pin1.data, data->pin1.len, data->pin1.tries_left);
sc_log(ctx, "PIN2(%p,len:%i)", data->pin2.data, data->pin2.len);
switch (data->cmd) {
case SC_PIN_CMD_VERIFY:
rv = authentic_pin_verify(card, data);
break;
case SC_PIN_CMD_CHANGE:
rv = authentic_pin_change(card, data, tries_left);
break;
case SC_PIN_CMD_UNBLOCK:
rv = authentic_pin_reset(card, data, tries_left);
break;
case SC_PIN_CMD_GET_INFO:
rv = authentic_pin_get_policy(card, data);
break;
default:
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Unsupported PIN command");
}
if (rv == SC_ERROR_PIN_CODE_INCORRECT && tries_left)
*tries_left = data->pin1.tries_left;
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_get_serialnr(struct sc_card *card, struct sc_serial_number *serial)
{
struct sc_context *ctx = card->ctx;
struct authentic_private_data *prv_data = (struct authentic_private_data *) card->drv_data;
int rv;
LOG_FUNC_CALLED(ctx);
if (!card->serialnr.len) {
rv = authentic_get_cplc(card);
LOG_TEST_RET(ctx, rv, "get CPLC data error");
card->serialnr.len = 4;
memcpy(card->serialnr.value, prv_data->cplc.value + 15, 4);
sc_log(ctx, "serial %02X%02X%02X%02X",
card->serialnr.value[0], card->serialnr.value[1],
card->serialnr.value[2], card->serialnr.value[3]);
}
if (serial)
memcpy(serial, &card->serialnr, sizeof(*serial));
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
authentic_get_challenge(struct sc_card *card, unsigned char *rnd, size_t len)
{
/* 'GET CHALLENGE' returns always 24 bytes */
unsigned char rbuf[0x18];
size_t out_len;
int r;
LOG_FUNC_CALLED(card->ctx);
r = iso_ops->get_challenge(card, rbuf, sizeof rbuf);
LOG_TEST_RET(card->ctx, r, "GET CHALLENGE cmd failed");
if (len < (size_t) r) {
out_len = len;
} else {
out_len = (size_t) r;
}
memcpy(rnd, rbuf, out_len);
LOG_FUNC_RETURN(card->ctx, out_len);
}
static int
authentic_manage_sdo_encode_prvkey(struct sc_card *card, struct sc_pkcs15_prkey *prvkey,
unsigned char **out, size_t *out_len)
{
struct sc_context *ctx = card->ctx;
struct sc_pkcs15_prkey_rsa rsa;
unsigned char *blob = NULL, *blob01 = NULL;
size_t blob_len = 0, blob01_len = 0;
int rv;
if (!prvkey || !out || !out_len)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid arguments");
if (prvkey->algorithm != SC_ALGORITHM_RSA)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO operation");
rsa = prvkey->u.rsa;
/* Encode private RSA key part */
rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE_P, rsa.p.data, rsa.p.len, &blob, &blob_len);
LOG_TEST_RET(ctx, rv, "SDO RSA P encode error");
rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE_Q, rsa.q.data, rsa.q.len, &blob, &blob_len);
LOG_TEST_RET(ctx, rv, "SDO RSA Q encode error");
rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE_PQ, rsa.iqmp.data, rsa.iqmp.len, &blob, &blob_len);
LOG_TEST_RET(ctx, rv, "SDO RSA PQ encode error");
rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE_DP1, rsa.dmp1.data, rsa.dmp1.len, &blob, &blob_len);
LOG_TEST_RET(ctx, rv, "SDO RSA DP1 encode error");
rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE_DQ1, rsa.dmq1.data, rsa.dmq1.len, &blob, &blob_len);
LOG_TEST_RET(ctx, rv, "SDO RSA DQ1 encode error");
rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PRIVATE, blob, blob_len, &blob01, &blob01_len);
LOG_TEST_RET(ctx, rv, "SDO RSA Private encode error");
free (blob);
blob = NULL;
blob_len = 0;
/* Encode public RSA key part */
sc_log(ctx,
"modulus.len:%"SC_FORMAT_LEN_SIZE_T"u blob_len:%"SC_FORMAT_LEN_SIZE_T"u",
rsa.modulus.len, blob_len);
rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PUBLIC_MODULUS, rsa.modulus.data, rsa.modulus.len, &blob, &blob_len);
LOG_TEST_RET(ctx, rv, "SDO RSA Modulus encode error");
sc_log(ctx,
"exponent.len:%"SC_FORMAT_LEN_SIZE_T"u blob_len:%"SC_FORMAT_LEN_SIZE_T"u",
rsa.exponent.len, blob_len);
rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PUBLIC_EXPONENT, rsa.exponent.data, rsa.exponent.len, &blob, &blob_len);
LOG_TEST_RET(ctx, rv, "SDO RSA Exponent encode error");
rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PUBLIC, blob, blob_len, &blob01, &blob01_len);
LOG_TEST_RET(ctx, rv, "SDO RSA Private encode error");
free (blob);
rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA, blob01, blob01_len, out, out_len);
LOG_TEST_RET(ctx, rv, "SDO RSA encode error");
free(blob01);
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_manage_sdo_encode(struct sc_card *card, struct sc_authentic_sdo *sdo, unsigned long cmd,
unsigned char **out, size_t *out_len)
{
struct sc_context *ctx = card->ctx;
unsigned char *data = NULL;
size_t data_len = 0;
unsigned char data_tag = AUTHENTIC_TAG_DOCP;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "encode SDO operation (cmd:%lX,mech:%X,id:%X)", cmd, sdo->docp.mech, sdo->docp.id);
if (!out || !out_len)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid arguments");
rv = authentic_update_blob(ctx, AUTHENTIC_TAG_DOCP_MECH, &sdo->docp.mech, sizeof(sdo->docp.mech),
&data, &data_len);
LOG_TEST_RET(ctx, rv, "DOCP MECH encode error");
rv = authentic_update_blob(ctx, AUTHENTIC_TAG_DOCP_ID, &sdo->docp.id, sizeof(sdo->docp.id),
&data, &data_len);
LOG_TEST_RET(ctx, rv, "DOCP ID encode error");
if (cmd == SC_CARDCTL_AUTHENTIC_SDO_CREATE) {
rv = authentic_update_blob(ctx, AUTHENTIC_TAG_DOCP_ACLS, sdo->docp.acl_data, sdo->docp.acl_data_len,
&data, &data_len);
LOG_TEST_RET(ctx, rv, "DOCP ACLs encode error");
if (sdo->docp.security_parameter) {
rv = authentic_update_blob(ctx, AUTHENTIC_TAG_DOCP_SCP,
&sdo->docp.security_parameter, sizeof(sdo->docp.security_parameter),
&data, &data_len);
LOG_TEST_RET(ctx, rv, "DOCP ACLs encode error");
}
if (sdo->docp.usage_counter[0] || sdo->docp.usage_counter[1]) {
rv = authentic_update_blob(ctx, AUTHENTIC_TAG_DOCP_USAGE_COUNTER,
sdo->docp.usage_counter, sizeof(sdo->docp.usage_counter),
&data, &data_len);
LOG_TEST_RET(ctx, rv, "DOCP ACLs encode error");
}
}
else if (cmd == SC_CARDCTL_AUTHENTIC_SDO_STORE) {
if (sdo->docp.mech == AUTHENTIC_MECH_CRYPTO_RSA1024
|| sdo->docp.mech == AUTHENTIC_MECH_CRYPTO_RSA1280
|| sdo->docp.mech == AUTHENTIC_MECH_CRYPTO_RSA1536
|| sdo->docp.mech == AUTHENTIC_MECH_CRYPTO_RSA1792
|| sdo->docp.mech == AUTHENTIC_MECH_CRYPTO_RSA2048) {
rv = authentic_manage_sdo_encode_prvkey(card, sdo->data.prvkey, &data, &data_len);
LOG_TEST_RET(ctx, rv, "SDO RSA encode error");
}
else {
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Cryptographic object unsupported for encoding");
}
}
else if (cmd == SC_CARDCTL_AUTHENTIC_SDO_GENERATE) {
if (sdo->data.prvkey) {
rv = authentic_update_blob(ctx, AUTHENTIC_TAG_RSA_PUBLIC_EXPONENT,
sdo->data.prvkey->u.rsa.exponent.data, sdo->data.prvkey->u.rsa.exponent.len,
&data, &data_len);
LOG_TEST_RET(ctx, rv, "SDO RSA Exponent encode error");
}
data_tag = AUTHENTIC_TAG_RSA_GENERATE_DATA;
}
else if (cmd != SC_CARDCTL_AUTHENTIC_SDO_DELETE) {
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO operation");
}
rv = authentic_update_blob(ctx, data_tag, data, data_len, out, out_len);
LOG_TEST_RET(ctx, rv, "SDO DOCP encode error");
free(data);
sc_log_hex(ctx, "encoded SDO operation data", *out, *out_len);
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_manage_sdo_generate(struct sc_card *card, struct sc_authentic_sdo *sdo)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char rbuf[0x400];
unsigned char *data = NULL;
size_t data_len = 0;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "Generate SDO(mech:%X,id:%X)", sdo->docp.mech, sdo->docp.id);
rv = authentic_manage_sdo_encode(card, sdo, SC_CARDCTL_AUTHENTIC_SDO_GENERATE, &data, &data_len);
LOG_TEST_RET(ctx, rv, "Cannot encode SDO data");
sc_log(ctx, "encoded SDO length %"SC_FORMAT_LEN_SIZE_T"u", data_len);
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x47, 0x00, 0x00);
apdu.data = data;
apdu.datalen = data_len;
apdu.lc = data_len;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0x100;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "authentic_sdo_create() SDO put data error");
rv = authentic_decode_pubkey_rsa(ctx, apdu.resp, apdu.resplen, &sdo->data.prvkey);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, rv, "cannot decode public key");
free(data);
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_manage_sdo(struct sc_card *card, struct sc_authentic_sdo *sdo, unsigned long cmd)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char *data = NULL;
size_t data_len = 0, save_max_send = card->max_send_size;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "SDO(cmd:%lX,mech:%X,id:%X)", cmd, sdo->docp.mech, sdo->docp.id);
rv = authentic_manage_sdo_encode(card, sdo, cmd, &data, &data_len);
LOG_TEST_RET(ctx, rv, "Cannot encode SDO data");
sc_log(ctx, "encoded SDO length %"SC_FORMAT_LEN_SIZE_T"u", data_len);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF);
apdu.data = data;
apdu.datalen = data_len;
apdu.lc = data_len;
apdu.flags |= SC_APDU_FLAGS_CHAINING;
if (card->max_send_size > 255)
card->max_send_size = 255;
rv = sc_transmit_apdu(card, &apdu);
card->max_send_size = save_max_send;
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "authentic_sdo_create() SDO put data error");
free(data);
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr)
{
struct sc_context *ctx = card->ctx;
struct sc_authentic_sdo *sdo = (struct sc_authentic_sdo *) ptr;
switch (cmd) {
case SC_CARDCTL_GET_SERIALNR:
return authentic_get_serialnr(card, (struct sc_serial_number *)ptr);
case SC_CARDCTL_AUTHENTIC_SDO_CREATE:
sc_log(ctx, "CARDCTL SDO_CREATE: sdo(mech:%X,id:%X)", sdo->docp.mech, sdo->docp.id);
return authentic_manage_sdo(card, (struct sc_authentic_sdo *) ptr, cmd);
case SC_CARDCTL_AUTHENTIC_SDO_DELETE:
sc_log(ctx, "CARDCTL SDO_DELETE: sdo(mech:%X,id:%X)", sdo->docp.mech, sdo->docp.id);
return authentic_manage_sdo(card, (struct sc_authentic_sdo *) ptr, cmd);
case SC_CARDCTL_AUTHENTIC_SDO_STORE:
sc_log(ctx, "CARDCTL SDO_STORE: sdo(mech:%X,id:%X)", sdo->docp.mech, sdo->docp.id);
return authentic_manage_sdo(card, (struct sc_authentic_sdo *) ptr, cmd);
case SC_CARDCTL_AUTHENTIC_SDO_GENERATE:
sc_log(ctx, "CARDCTL SDO_GENERATE: sdo(mech:%X,id:%X)", sdo->docp.mech, sdo->docp.id);
return authentic_manage_sdo_generate(card, (struct sc_authentic_sdo *) ptr);
}
return SC_ERROR_NOT_SUPPORTED;
}
static int
authentic_set_security_env(struct sc_card *card,
const struct sc_security_env *env, int se_num)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char cse_crt_dst[] = {
0x80, 0x01, AUTHENTIC_ALGORITHM_RSA_PKCS1,
0x83, 0x01, env->key_ref[0] & ~AUTHENTIC_OBJECT_REF_FLAG_LOCAL,
};
unsigned char cse_crt_ct[] = {
0x80, 0x01, AUTHENTIC_ALGORITHM_RSA_PKCS1,
0x83, 0x01, env->key_ref[0] & ~AUTHENTIC_OBJECT_REF_FLAG_LOCAL,
};
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "set SE#%i(op:0x%X,algo:0x%X,algo_ref:0x%X,flags:0x%X), key_ref:0x%X",
se_num, env->operation, env->algorithm, env->algorithm_ref, env->algorithm_flags, env->key_ref[0]);
switch (env->operation) {
case SC_SEC_OPERATION_SIGN:
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, AUTHENTIC_TAG_CRT_DST);
apdu.data = cse_crt_dst;
apdu.datalen = sizeof(cse_crt_dst);
apdu.lc = sizeof(cse_crt_dst);
break;
case SC_SEC_OPERATION_DECIPHER:
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, AUTHENTIC_TAG_CRT_CT);
apdu.data = cse_crt_ct;
apdu.datalen = sizeof(cse_crt_ct);
apdu.lc = sizeof(cse_crt_ct);
break;
default:
LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
}
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "MSE restore error");
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_decipher(struct sc_card *card, const unsigned char *in, size_t in_len,
unsigned char *out, size_t out_len)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char resp[SC_MAX_APDU_BUFFER_SIZE];
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"crgram_len %"SC_FORMAT_LEN_SIZE_T"u; outlen %"SC_FORMAT_LEN_SIZE_T"u",
in_len, out_len);
if (!out || !out_len || in_len > SC_MAX_APDU_BUFFER_SIZE)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);
apdu.flags |= SC_APDU_FLAGS_CHAINING;
apdu.data = in;
apdu.datalen = in_len;
apdu.lc = in_len;
apdu.resp = resp;
apdu.resplen = sizeof(resp);
apdu.le = 256;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "Card returned error");
if (out_len > apdu.resplen)
out_len = apdu.resplen;
memcpy(out, apdu.resp, out_len);
rv = out_len;
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_finish(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
LOG_FUNC_CALLED(ctx);
#ifdef ENABLE_SM
if (card->sm_ctx.ops.close)
card->sm_ctx.ops.close(card);
#endif
if (card->drv_data)
free(card->drv_data);
card->drv_data = NULL;
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int authentic_card_reader_lock_obtained(sc_card_t *card, int was_reset)
{
int r = SC_SUCCESS;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (was_reset > 0
&& card->type == SC_CARD_TYPE_OBERTHUR_AUTHENTIC_3_2) {
r = authentic_select_aid(card, aid_AuthentIC_3_2, sizeof(aid_AuthentIC_3_2), NULL, NULL);
}
LOG_FUNC_RETURN(card->ctx, r);
}
/* SM related */
#ifdef ENABLE_SM
static int
authentic_sm_acl_init (struct sc_card *card, struct sm_info *sm_info, int cmd,
unsigned char *resp, size_t *resp_len)
{
struct sc_context *ctx;
struct sm_type_params_gp *params_gp;
struct sc_remote_data rdata;
int rv;
if (!card || !sm_info || !resp || !resp_len)
return SC_ERROR_INVALID_ARGUMENTS;
ctx = card->ctx;
params_gp = &sm_info->session.gp.params;
if (!card->sm_ctx.module.ops.initialize || !card->sm_ctx.module.ops.get_apdus)
LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
if (*resp_len < 28)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
sm_info->cmd = cmd;
sm_info->sm_type = SM_TYPE_GP_SCP01;
sm_info->card_type = card->type;
params_gp->index = 0; /* logical channel */
params_gp->version = 1;
params_gp->level = 3; /* Only supported SM level 'ENC & MAC' */
sm_info->serialnr = card->serialnr;
sc_remote_data_init(&rdata);
rv = card->sm_ctx.module.ops.initialize(ctx, sm_info, &rdata);
LOG_TEST_RET(ctx, rv, "SM: INITIALIZE failed");
if (!rdata.length)
LOG_FUNC_RETURN(ctx, SC_ERROR_INTERNAL);
rv = sc_transmit_apdu(card, &rdata.data->apdu);
LOG_TEST_RET(ctx, rv, "transmit APDU failed");
rv = sc_check_sw(card, rdata.data->apdu.sw1, rdata.data->apdu.sw2);
LOG_TEST_RET(ctx, rv, "Card returned error");
if (rdata.data->apdu.resplen != 28 || *resp_len < 28)
LOG_FUNC_RETURN(ctx, SC_ERROR_INTERNAL);
memcpy(resp, rdata.data->apdu.resp, 28);
*resp_len = 28;
rdata.free(&rdata);
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_sm_execute (struct sc_card *card, struct sm_info *sm_info,
unsigned char *data, int data_len, unsigned char *out, size_t len)
{
struct sc_context *ctx = card->ctx;
struct sc_remote_data rdata;
int rv, ii;
if (!card->sm_ctx.module.ops.get_apdus)
LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
sc_remote_data_init(&rdata);
rv = card->sm_ctx.module.ops.get_apdus(ctx, sm_info, data, data_len, &rdata);
LOG_TEST_RET(ctx, rv, "SM: GET_APDUS failed");
if (!rdata.length)
LOG_FUNC_RETURN(ctx, SC_ERROR_INTERNAL);
sc_log(ctx, "GET_APDUS: rv %i; rdata length %i", rv, rdata.length);
for (ii=0; ii < rdata.length; ii++) {
struct sc_apdu *apdu = &((rdata.data + ii)->apdu);
if (!apdu->ins)
break;
rv = sc_transmit_apdu(card, apdu);
if (rv < 0)
break;
rv = sc_check_sw(card, apdu->sw1, apdu->sw2);
if (rv < 0)
break;
}
rdata.free(&rdata);
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_sm_open(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
unsigned char init_data[SC_MAX_APDU_BUFFER_SIZE];
size_t init_data_len = sizeof(init_data);
int rv;
LOG_FUNC_CALLED(ctx);
memset(&card->sm_ctx.info, 0, sizeof(card->sm_ctx.info));
memcpy(card->sm_ctx.info.config_section, card->sm_ctx.config_section, sizeof(card->sm_ctx.info.config_section));
sc_log(ctx, "SM context config '%s'; SM mode 0x%X", card->sm_ctx.info.config_section, card->sm_ctx.sm_mode);
if (card->sm_ctx.sm_mode == SM_MODE_TRANSMIT && card->max_send_size == 0)
card->max_send_size = 239;
rv = authentic_sm_acl_init (card, &card->sm_ctx.info, SM_CMD_INITIALIZE, init_data, &init_data_len);
LOG_TEST_RET(ctx, rv, "authentIC: cannot open SM");
rv = authentic_sm_execute (card, &card->sm_ctx.info, init_data, init_data_len, NULL, 0);
LOG_TEST_RET(ctx, rv, "SM: execute failed");
card->sm_ctx.info.cmd = SM_CMD_APDU_TRANSMIT;
LOG_FUNC_RETURN(ctx, rv);
}
static int
authentic_sm_free_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu)
{
struct sc_context *ctx = card->ctx;
LOG_FUNC_CALLED(ctx);
if (!sm_apdu)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
if (!(*sm_apdu))
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
if (plain) {
if (plain->resplen < (*sm_apdu)->resplen)
LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Insufficient plain APDU response size");
memcpy(plain->resp, (*sm_apdu)->resp, (*sm_apdu)->resplen);
plain->resplen = (*sm_apdu)->resplen;
plain->sw1 = (*sm_apdu)->sw1;
plain->sw2 = (*sm_apdu)->sw2;
}
if ((*sm_apdu)->data)
free((unsigned char *) (*sm_apdu)->data);
if ((*sm_apdu)->resp)
free((unsigned char *) (*sm_apdu)->resp);
free(*sm_apdu);
*sm_apdu = NULL;
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
authentic_sm_get_wrapped_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_apdu **sm_apdu)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu *apdu = NULL;
int rv = 0;
LOG_FUNC_CALLED(ctx);
if (!plain || !sm_apdu)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
sc_log(ctx,
"called; CLA:%X, INS:%X, P1:%X, P2:%X, data(%"SC_FORMAT_LEN_SIZE_T"u) %p",
plain->cla, plain->ins, plain->p1, plain->p2, plain->datalen,
plain->data);
*sm_apdu = NULL;
if ((plain->cla & 0x04)
|| (plain->cla==0x00 && plain->ins==0x22)
|| (plain->cla==0x00 && plain->ins==0x2A)
|| (plain->cla==0x00 && plain->ins==0x84)
|| (plain->cla==0x00 && plain->ins==0x88)
|| (plain->cla==0x00 && plain->ins==0xA4)
|| (plain->cla==0x00 && plain->ins==0xC0)
|| (plain->cla==0x00 && plain->ins==0xCA)
|| (plain->cla==0x80 && plain->ins==0x50)
) {
sc_log(ctx, "SM wrap is not applied for this APDU");
LOG_FUNC_RETURN(ctx, SC_ERROR_SM_NOT_APPLIED);
}
if (card->sm_ctx.sm_mode != SM_MODE_TRANSMIT)
LOG_FUNC_RETURN(ctx, SC_ERROR_SM_NOT_INITIALIZED);
if (!card->sm_ctx.module.ops.get_apdus)
LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
apdu = calloc(1, sizeof(struct sc_apdu));
if (!apdu)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy((void *)apdu, (void *)plain, sizeof(struct sc_apdu));
apdu->data = calloc (1, plain->datalen + 24);
if (!apdu->data) {
free(apdu);
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
}
if (plain->data && plain->datalen)
memcpy((unsigned char *) apdu->data, plain->data, plain->datalen);
apdu->resp = calloc (1, plain->resplen + 32);
if (!apdu->resp) {
free(apdu);
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
}
card->sm_ctx.info.cmd = SM_CMD_APDU_TRANSMIT;
card->sm_ctx.info.cmd_data = (void *)apdu;
rv = card->sm_ctx.module.ops.get_apdus(ctx, &card->sm_ctx.info, NULL, 0, NULL);
if (rv < 0) {
free(apdu->resp);
free(apdu);
}
LOG_TEST_RET(ctx, rv, "SM: GET_APDUS failed");
*sm_apdu = apdu;
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
#endif
static struct sc_card_driver *
sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (!iso_ops)
iso_ops = iso_drv->ops;
authentic_ops = *iso_ops;
authentic_ops.match_card = authentic_match_card;
authentic_ops.init = authentic_init;
authentic_ops.finish = authentic_finish;
authentic_ops.read_binary = authentic_read_binary;
authentic_ops.write_binary = authentic_write_binary;
authentic_ops.update_binary = authentic_update_binary;
authentic_ops.erase_binary = authentic_erase_binary;
/* authentic_ops.resize_file = authentic_resize_file; */
authentic_ops.select_file = authentic_select_file;
/* get_response: Untested */
authentic_ops.get_challenge = authentic_get_challenge;
authentic_ops.set_security_env = authentic_set_security_env;
/* decipher: Untested */
authentic_ops.decipher = authentic_decipher;
/* authentic_ops.compute_signature = authentic_compute_signature; */
authentic_ops.create_file = authentic_create_file;
authentic_ops.delete_file = authentic_delete_file;
authentic_ops.card_ctl = authentic_card_ctl;
authentic_ops.process_fci = authentic_process_fci;
authentic_ops.pin_cmd = authentic_pin_cmd;
authentic_ops.card_reader_lock_obtained = authentic_card_reader_lock_obtained;
return &authentic_drv;
}
struct sc_card_driver *
sc_get_authentic_driver(void)
{
return sc_get_driver();
}
#endif /* ENABLE_OPENSSL */
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_351_2 |
crossvul-cpp_data_bad_701_0 | /*
* SSLv3/TLSv1 client-side functions
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_SSL_CLI_C)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
#include "mbedtls/debug.h"
#include "mbedtls/ssl.h"
#include "mbedtls/ssl_internal.h"
#include <string.h>
#include <stdint.h>
#if defined(MBEDTLS_HAVE_TIME)
#include "mbedtls/platform_time.h"
#endif
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
/* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = v; while( n-- ) *p++ = 0;
}
#endif
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
static void ssl_write_hostname_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t hostname_len;
*olen = 0;
if( ssl->hostname == NULL )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding server name extension: %s",
ssl->hostname ) );
hostname_len = strlen( ssl->hostname );
if( end < p || (size_t)( end - p ) < hostname_len + 9 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
/*
* Sect. 3, RFC 6066 (TLS Extensions Definitions)
*
* In order to provide any of the server names, clients MAY include an
* extension of type "server_name" in the (extended) client hello. The
* "extension_data" field of this extension SHALL contain
* "ServerNameList" where:
*
* struct {
* NameType name_type;
* select (name_type) {
* case host_name: HostName;
* } name;
* } ServerName;
*
* enum {
* host_name(0), (255)
* } NameType;
*
* opaque HostName<1..2^16-1>;
*
* struct {
* ServerName server_name_list<1..2^16-1>
* } ServerNameList;
*
*/
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 5) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 5) ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 3) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 3) ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME ) & 0xFF );
*p++ = (unsigned char)( ( hostname_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( hostname_len ) & 0xFF );
memcpy( p, ssl->hostname, hostname_len );
*olen = hostname_len + 9;
}
#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
#if defined(MBEDTLS_SSL_RENEGOTIATION)
static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
/* We're always including an TLS_EMPTY_RENEGOTIATION_INFO_SCSV in the
* initial ClientHello, in which case also adding the renegotiation
* info extension is NOT RECOMMENDED as per RFC 5746 Section 3.4. */
if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding renegotiation extension" ) );
if( end < p || (size_t)( end - p ) < 5 + ssl->verify_data_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
/*
* Secure renegotiation
*/
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO ) & 0xFF );
*p++ = 0x00;
*p++ = ( ssl->verify_data_len + 1 ) & 0xFF;
*p++ = ssl->verify_data_len & 0xFF;
memcpy( p, ssl->own_verify_data, ssl->verify_data_len );
*olen = 5 + ssl->verify_data_len;
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
/*
* Only if we handle at least one key exchange that needs signatures.
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
static void ssl_write_signature_algorithms_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t sig_alg_len = 0;
const int *md;
#if defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C)
unsigned char *sig_alg_list = buf + 6;
#endif
*olen = 0;
if( ssl->conf->max_minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding signature_algorithms extension" ) );
for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
{
#if defined(MBEDTLS_ECDSA_C)
sig_alg_len += 2;
#endif
#if defined(MBEDTLS_RSA_C)
sig_alg_len += 2;
#endif
}
if( end < p || (size_t)( end - p ) < sig_alg_len + 6 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
/*
* Prepare signature_algorithms extension (TLS 1.2)
*/
sig_alg_len = 0;
for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
{
#if defined(MBEDTLS_ECDSA_C)
sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );
sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_ECDSA;
#endif
#if defined(MBEDTLS_RSA_C)
sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );
sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_RSA;
#endif
}
/*
* enum {
* none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5),
* sha512(6), (255)
* } HashAlgorithm;
*
* enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }
* SignatureAlgorithm;
*
* struct {
* HashAlgorithm hash;
* SignatureAlgorithm signature;
* } SignatureAndHashAlgorithm;
*
* SignatureAndHashAlgorithm
* supported_signature_algorithms<2..2^16-2>;
*/
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG ) & 0xFF );
*p++ = (unsigned char)( ( ( sig_alg_len + 2 ) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ( sig_alg_len + 2 ) ) & 0xFF );
*p++ = (unsigned char)( ( sig_alg_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( sig_alg_len ) & 0xFF );
*olen = 6 + sig_alg_len;
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static void ssl_write_supported_elliptic_curves_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
unsigned char *elliptic_curve_list = p + 6;
size_t elliptic_curve_len = 0;
const mbedtls_ecp_curve_info *info;
#if defined(MBEDTLS_ECP_C)
const mbedtls_ecp_group_id *grp_id;
#else
((void) ssl);
#endif
*olen = 0;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_elliptic_curves extension" ) );
#if defined(MBEDTLS_ECP_C)
for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ )
#else
for( info = mbedtls_ecp_curve_list(); info->grp_id != MBEDTLS_ECP_DP_NONE; info++ )
#endif
{
#if defined(MBEDTLS_ECP_C)
info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );
#endif
if( info == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid curve in ssl configuration" ) );
return;
}
elliptic_curve_len += 2;
}
if( end < p || (size_t)( end - p ) < 6 + elliptic_curve_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
elliptic_curve_len = 0;
#if defined(MBEDTLS_ECP_C)
for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ )
#else
for( info = mbedtls_ecp_curve_list(); info->grp_id != MBEDTLS_ECP_DP_NONE; info++ )
#endif
{
#if defined(MBEDTLS_ECP_C)
info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );
#endif
elliptic_curve_list[elliptic_curve_len++] = info->tls_id >> 8;
elliptic_curve_list[elliptic_curve_len++] = info->tls_id & 0xFF;
}
if( elliptic_curve_len == 0 )
return;
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len ) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len ) ) & 0xFF );
*olen = 6 + elliptic_curve_len;
}
static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_point_formats extension" ) );
if( end < p || (size_t)( end - p ) < 6 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS ) & 0xFF );
*p++ = 0x00;
*p++ = 2;
*p++ = 1;
*p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
*olen = 6;
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
int ret;
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t kkpp_len;
*olen = 0;
/* Skip costly extension if we can't use EC J-PAKE anyway */
if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding ecjpake_kkpp extension" ) );
if( end - p < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP ) & 0xFF );
/*
* We may need to send ClientHello multiple times for Hello verification.
* We don't want to compute fresh values every time (both for performance
* and consistency reasons), so cache the extension content.
*/
if( ssl->handshake->ecjpake_cache == NULL ||
ssl->handshake->ecjpake_cache_len == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "generating new ecjpake parameters" ) );
ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx,
p + 2, end - p - 2, &kkpp_len,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret );
return;
}
ssl->handshake->ecjpake_cache = mbedtls_calloc( 1, kkpp_len );
if( ssl->handshake->ecjpake_cache == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "allocation failed" ) );
return;
}
memcpy( ssl->handshake->ecjpake_cache, p + 2, kkpp_len );
ssl->handshake->ecjpake_cache_len = kkpp_len;
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "re-using cached ecjpake parameters" ) );
kkpp_len = ssl->handshake->ecjpake_cache_len;
if( (size_t)( end - p - 2 ) < kkpp_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
memcpy( p + 2, ssl->handshake->ecjpake_cache, kkpp_len );
}
*p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( kkpp_len ) & 0xFF );
*olen = kkpp_len + 4;
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ) {
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding max_fragment_length extension" ) );
if( end < p || (size_t)( end - p ) < 5 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH ) & 0xFF );
*p++ = 0x00;
*p++ = 1;
*p++ = ssl->conf->mfl_code;
*olen = 5;
}
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
static void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding truncated_hmac extension" ) );
if( end < p || (size_t)( end - p ) < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
static void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding encrypt_then_mac "
"extension" ) );
if( end < p || (size_t)( end - p ) < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
static void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding extended_master_secret "
"extension" ) );
if( end < p || (size_t)( end - p ) < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t tlen = ssl->session_negotiate->ticket_len;
*olen = 0;
if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding session ticket extension" ) );
if( end < p || (size_t)( end - p ) < 4 + tlen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET ) & 0xFF );
*p++ = (unsigned char)( ( tlen >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( tlen ) & 0xFF );
*olen = 4;
if( ssl->session_negotiate->ticket == NULL || tlen == 0 )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "sending session ticket of length %d", tlen ) );
memcpy( p, ssl->session_negotiate->ticket, tlen );
*olen += tlen;
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_SSL_ALPN)
static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t alpnlen = 0;
const char **cur;
*olen = 0;
if( ssl->conf->alpn_list == NULL )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding alpn extension" ) );
for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
alpnlen += (unsigned char)( strlen( *cur ) & 0xFF ) + 1;
if( end < p || (size_t)( end - p ) < 6 + alpnlen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN ) & 0xFF );
/*
* opaque ProtocolName<1..2^8-1>;
*
* struct {
* ProtocolName protocol_name_list<2..2^16-1>
* } ProtocolNameList;
*/
/* Skip writing extension and list length for now */
p += 4;
for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
{
*p = (unsigned char)( strlen( *cur ) & 0xFF );
memcpy( p + 1, *cur, *p );
p += 1 + *p;
}
*olen = p - buf;
/* List length = olen - 2 (ext_type) - 2 (ext_len) - 2 (list_len) */
buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF );
buf[5] = (unsigned char)( ( ( *olen - 6 ) ) & 0xFF );
/* Extension length = olen - 2 (ext_type) - 2 (ext_len) */
buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF );
buf[3] = (unsigned char)( ( ( *olen - 4 ) ) & 0xFF );
}
#endif /* MBEDTLS_SSL_ALPN */
/*
* Generate random bytes for ClientHello
*/
static int ssl_generate_random( mbedtls_ssl_context *ssl )
{
int ret;
unsigned char *p = ssl->handshake->randbytes;
#if defined(MBEDTLS_HAVE_TIME)
mbedtls_time_t t;
#endif
/*
* When responding to a verify request, MUST reuse random (RFC 6347 4.2.1)
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
ssl->handshake->verify_cookie != NULL )
{
return( 0 );
}
#endif
#if defined(MBEDTLS_HAVE_TIME)
t = mbedtls_time( NULL );
*p++ = (unsigned char)( t >> 24 );
*p++ = (unsigned char)( t >> 16 );
*p++ = (unsigned char)( t >> 8 );
*p++ = (unsigned char)( t );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, current time: %lu", t ) );
#else
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 )
return( ret );
p += 4;
#endif /* MBEDTLS_HAVE_TIME */
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 )
return( ret );
return( 0 );
}
static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
{
int ret;
size_t i, n, olen, ext_len = 0;
unsigned char *buf;
unsigned char *p, *q;
unsigned char offer_compress;
const int *ciphersuites;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client hello" ) );
if( ssl->conf->f_rng == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") );
return( MBEDTLS_ERR_SSL_NO_RNG );
}
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
ssl->major_ver = ssl->conf->min_major_ver;
ssl->minor_ver = ssl->conf->min_minor_ver;
}
if( ssl->conf->max_major_ver == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "configured max major version is invalid, "
"consider using mbedtls_ssl_config_defaults()" ) );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
/*
* 0 . 0 handshake type
* 1 . 3 handshake length
* 4 . 5 highest version supported
* 6 . 9 current UNIX time
* 10 . 37 random bytes
*/
buf = ssl->out_msg;
p = buf + 4;
mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,
ssl->conf->transport, p );
p += 2;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, max version: [%d:%d]",
buf[4], buf[5] ) );
if( ( ret = ssl_generate_random( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_generate_random", ret );
return( ret );
}
memcpy( p, ssl->handshake->randbytes, 32 );
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", p, 32 );
p += 32;
/*
* 38 . 38 session id length
* 39 . 39+n session id
* 39+n . 39+n DTLS only: cookie length (1 byte)
* 40+n . .. DTSL only: cookie
* .. . .. ciphersuitelist length (2 bytes)
* .. . .. ciphersuitelist
* .. . .. compression methods length (1 byte)
* .. . .. compression methods
* .. . .. extensions length (2 bytes)
* .. . .. extensions
*/
n = ssl->session_negotiate->id_len;
if( n < 16 || n > 32 ||
#if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
#endif
ssl->handshake->resume == 0 )
{
n = 0;
}
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
/*
* RFC 5077 section 3.4: "When presenting a ticket, the client MAY
* generate and include a Session ID in the TLS ClientHello."
*/
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
if( ssl->session_negotiate->ticket != NULL &&
ssl->session_negotiate->ticket_len != 0 )
{
ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id, 32 );
if( ret != 0 )
return( ret );
ssl->session_negotiate->id_len = n = 32;
}
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
*p++ = (unsigned char) n;
for( i = 0; i < n; i++ )
*p++ = ssl->session_negotiate->id[i];
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, session id len.: %d", n ) );
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 39, n );
/*
* DTLS cookie
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
{
if( ssl->handshake->verify_cookie == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "no verify cookie to send" ) );
*p++ = 0;
}
else
{
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie",
ssl->handshake->verify_cookie,
ssl->handshake->verify_cookie_len );
*p++ = ssl->handshake->verify_cookie_len;
memcpy( p, ssl->handshake->verify_cookie,
ssl->handshake->verify_cookie_len );
p += ssl->handshake->verify_cookie_len;
}
}
#endif
/*
* Ciphersuite list
*/
ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
/* Skip writing ciphersuite length for now */
n = 0;
q = p;
p += 2;
for( i = 0; ciphersuites[i] != 0; i++ )
{
ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuites[i] );
if( ciphersuite_info == NULL )
continue;
if( ciphersuite_info->min_minor_ver > ssl->conf->max_minor_ver ||
ciphersuite_info->max_minor_ver < ssl->conf->min_minor_ver )
continue;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
( ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )
continue;
#endif
#if defined(MBEDTLS_ARC4_C)
if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&
ciphersuite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
continue;
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
continue;
#endif
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, add ciphersuite: %04x",
ciphersuites[i] ) );
n++;
*p++ = (unsigned char)( ciphersuites[i] >> 8 );
*p++ = (unsigned char)( ciphersuites[i] );
}
/*
* Add TLS_EMPTY_RENEGOTIATION_INFO_SCSV
*/
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
*p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO >> 8 );
*p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO );
n++;
}
/* Some versions of OpenSSL don't handle it correctly if not at end */
#if defined(MBEDTLS_SSL_FALLBACK_SCSV)
if( ssl->conf->fallback == MBEDTLS_SSL_IS_FALLBACK )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding FALLBACK_SCSV" ) );
*p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 );
*p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE );
n++;
}
#endif
*q++ = (unsigned char)( n >> 7 );
*q++ = (unsigned char)( n << 1 );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, got %d ciphersuites", n ) );
#if defined(MBEDTLS_ZLIB_SUPPORT)
offer_compress = 1;
#else
offer_compress = 0;
#endif
/*
* We don't support compression with DTLS right now: is many records come
* in the same datagram, uncompressing one could overwrite the next one.
* We don't want to add complexity for handling that case unless there is
* an actual need for it.
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
offer_compress = 0;
#endif
if( offer_compress )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 2 ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d %d",
MBEDTLS_SSL_COMPRESS_DEFLATE, MBEDTLS_SSL_COMPRESS_NULL ) );
*p++ = 2;
*p++ = MBEDTLS_SSL_COMPRESS_DEFLATE;
*p++ = MBEDTLS_SSL_COMPRESS_NULL;
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 1 ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d",
MBEDTLS_SSL_COMPRESS_NULL ) );
*p++ = 1;
*p++ = MBEDTLS_SSL_COMPRESS_NULL;
}
// First write extensions, then the total length
//
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
ssl_write_hostname_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
/* Note that TLS_EMPTY_RENEGOTIATION_INFO_SCSV is always added
* even if MBEDTLS_SSL_RENEGOTIATION is not defined. */
#if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
ssl_write_signature_algorithms_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_supported_elliptic_curves_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_ALPN)
ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
/* olen unused if all extensions are disabled */
((void) olen);
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, total extension length: %d",
ext_len ) );
if( ext_len > 0 )
{
*p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ext_len ) & 0xFF );
p += ext_len;
}
ssl->out_msglen = p - buf;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_CLIENT_HELLO;
ssl->state++;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
mbedtls_ssl_send_flight_completed( ssl );
#endif
if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client hello" ) );
return( 0 );
}
static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
{
/* Check verify-data in constant-time. The length OTOH is no secret */
if( len != 1 + ssl->verify_data_len * 2 ||
buf[0] != ssl->verify_data_len * 2 ||
mbedtls_ssl_safer_memcmp( buf + 1,
ssl->own_verify_data, ssl->verify_data_len ) != 0 ||
mbedtls_ssl_safer_memcmp( buf + 1 + ssl->verify_data_len,
ssl->peer_verify_data, ssl->verify_data_len ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
}
else
#endif /* MBEDTLS_SSL_RENEGOTIATION */
{
if( len != 1 || buf[0] != 0x00 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
}
return( 0 );
}
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
/*
* server should use the extension only if we did,
* and if so the server's value should match ours (and len is always 1)
*/
if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ||
len != 1 ||
buf[0] != ssl->conf->mfl_code )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching max fragment length extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
return( 0 );
}
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching truncated HMAC extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED;
return( 0 );
}
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching encrypt-then-MAC extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
return( 0 );
}
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching extended master secret extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
return( 0 );
}
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching session ticket extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->handshake->new_session_ticket = 1;
return( 0 );
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
size_t list_size;
const unsigned char *p;
list_size = buf[0];
if( list_size + 1 != len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
p = buf + 1;
while( list_size > 0 )
{
if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
p[0] == MBEDTLS_ECP_PF_COMPRESSED )
{
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
ssl->handshake->ecdh_ctx.point_format = p[0];
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl->handshake->ecjpake_ctx.point_format = p[0];
#endif
MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) );
return( 0 );
}
list_size--;
p++;
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "no point format in common" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
int ret;
if( ssl->transform_negotiate->ciphersuite_info->key_exchange !=
MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) );
return( 0 );
}
/* If we got here, we no longer need our cached extension */
mbedtls_free( ssl->handshake->ecjpake_cache );
ssl->handshake->ecjpake_cache = NULL;
ssl->handshake->ecjpake_cache_len = 0;
if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx,
buf, len ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( ret );
}
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_ALPN)
static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf, size_t len )
{
size_t list_len, name_len;
const char **p;
/* If we didn't send it, the server shouldn't send it */
if( ssl->conf->alpn_list == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching ALPN extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/*
* opaque ProtocolName<1..2^8-1>;
*
* struct {
* ProtocolName protocol_name_list<2..2^16-1>
* } ProtocolNameList;
*
* the "ProtocolNameList" MUST contain exactly one "ProtocolName"
*/
/* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
if( len < 4 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
list_len = ( buf[0] << 8 ) | buf[1];
if( list_len != len - 2 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
name_len = buf[2];
if( name_len != list_len - 1 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/* Check that the server chosen protocol was in our list and save it */
for( p = ssl->conf->alpn_list; *p != NULL; p++ )
{
if( name_len == strlen( *p ) &&
memcmp( buf + 3, *p, name_len ) == 0 )
{
ssl->alpn_chosen = *p;
return( 0 );
}
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ALPN extension: no matching protocol" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
#endif /* MBEDTLS_SSL_ALPN */
/*
* Parse HelloVerifyRequest. Only called after verifying the HS type.
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
static int ssl_parse_hello_verify_request( mbedtls_ssl_context *ssl )
{
const unsigned char *p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
int major_ver, minor_ver;
unsigned char cookie_len;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse hello verify request" ) );
/*
* struct {
* ProtocolVersion server_version;
* opaque cookie<0..2^8-1>;
* } HelloVerifyRequest;
*/
MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 );
mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, p );
p += 2;
/*
* Since the RFC is not clear on this point, accept DTLS 1.0 (TLS 1.1)
* even is lower than our min version.
*/
if( major_ver < MBEDTLS_SSL_MAJOR_VERSION_3 ||
minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ||
major_ver > ssl->conf->max_major_ver ||
minor_ver > ssl->conf->max_minor_ver )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server version" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
}
cookie_len = *p++;
MBEDTLS_SSL_DEBUG_BUF( 3, "cookie", p, cookie_len );
if( ( ssl->in_msg + ssl->in_msglen ) - p < cookie_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1,
( "cookie length does not match incoming message size" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
mbedtls_free( ssl->handshake->verify_cookie );
ssl->handshake->verify_cookie = mbedtls_calloc( 1, cookie_len );
if( ssl->handshake->verify_cookie == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", cookie_len ) );
return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
}
memcpy( ssl->handshake->verify_cookie, p, cookie_len );
ssl->handshake->verify_cookie_len = cookie_len;
/* Start over at ClientHello */
ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
mbedtls_ssl_reset_checksum( ssl );
mbedtls_ssl_recv_flight_completed( ssl );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse hello verify request" ) );
return( 0 );
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
static int ssl_parse_server_hello( mbedtls_ssl_context *ssl )
{
int ret, i;
size_t n;
size_t ext_len;
unsigned char *buf, *ext;
unsigned char comp;
#if defined(MBEDTLS_ZLIB_SUPPORT)
int accept_comp;
#endif
#if defined(MBEDTLS_SSL_RENEGOTIATION)
int renegotiation_info_seen = 0;
#endif
int handshake_failure = 0;
const mbedtls_ssl_ciphersuite_t *suite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello" ) );
buf = ssl->in_msg;
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
/* No alert on a read error. */
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
{
ssl->renego_records_seen++;
if( ssl->conf->renego_max_records >= 0 &&
ssl->renego_records_seen > ssl->conf->renego_max_records )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
"but not honored by server" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-handshake message during renego" ) );
ssl->keep_current_message = 1;
return( MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO );
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
{
if( buf[0] == MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "received hello verify request" ) );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
return( ssl_parse_hello_verify_request( ssl ) );
}
else
{
/* We made it through the verification process */
mbedtls_free( ssl->handshake->verify_cookie );
ssl->handshake->verify_cookie = NULL;
ssl->handshake->verify_cookie_len = 0;
}
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
if( ssl->in_hslen < 38 + mbedtls_ssl_hs_hdr_len( ssl ) ||
buf[0] != MBEDTLS_SSL_HS_SERVER_HELLO )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/*
* 0 . 1 server_version
* 2 . 33 random (maybe including 4 bytes of Unix time)
* 34 . 34 session_id length = n
* 35 . 34+n session_id
* 35+n . 36+n cipher_suite
* 37+n . 37+n compression_method
*
* 38+n . 39+n extensions length (optional)
* 40+n . .. extensions
*/
buf += mbedtls_ssl_hs_hdr_len( ssl );
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, version", buf + 0, 2 );
mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver,
ssl->conf->transport, buf + 0 );
if( ssl->major_ver < ssl->conf->min_major_ver ||
ssl->minor_ver < ssl->conf->min_minor_ver ||
ssl->major_ver > ssl->conf->max_major_ver ||
ssl->minor_ver > ssl->conf->max_minor_ver )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server version out of bounds - "
" min: [%d:%d], server: [%d:%d], max: [%d:%d]",
ssl->conf->min_major_ver, ssl->conf->min_minor_ver,
ssl->major_ver, ssl->minor_ver,
ssl->conf->max_major_ver, ssl->conf->max_minor_ver ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu",
( (uint32_t) buf[2] << 24 ) |
( (uint32_t) buf[3] << 16 ) |
( (uint32_t) buf[4] << 8 ) |
( (uint32_t) buf[5] ) ) );
memcpy( ssl->handshake->randbytes + 32, buf + 2, 32 );
n = buf[34];
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", buf + 2, 32 );
if( n > 32 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
if( ssl->in_hslen > mbedtls_ssl_hs_hdr_len( ssl ) + 39 + n )
{
ext_len = ( ( buf[38 + n] << 8 )
| ( buf[39 + n] ) );
if( ( ext_len > 0 && ext_len < 4 ) ||
ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 40 + n + ext_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
}
else if( ssl->in_hslen == mbedtls_ssl_hs_hdr_len( ssl ) + 38 + n )
{
ext_len = 0;
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/* ciphersuite (used later) */
i = ( buf[35 + n] << 8 ) | buf[36 + n];
/*
* Read and check compression
*/
comp = buf[37 + n];
#if defined(MBEDTLS_ZLIB_SUPPORT)
/* See comments in ssl_write_client_hello() */
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
accept_comp = 0;
else
#endif
accept_comp = 1;
if( comp != MBEDTLS_SSL_COMPRESS_NULL &&
( comp != MBEDTLS_SSL_COMPRESS_DEFLATE || accept_comp == 0 ) )
#else /* MBEDTLS_ZLIB_SUPPORT */
if( comp != MBEDTLS_SSL_COMPRESS_NULL )
#endif/* MBEDTLS_ZLIB_SUPPORT */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server hello, bad compression: %d", comp ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
}
/*
* Initialize update checksum functions
*/
ssl->transform_negotiate->ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( i );
if( ssl->transform_negotiate->ciphersuite_info == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ciphersuite info for %04x not found", i ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
mbedtls_ssl_optimize_checksum( ssl, ssl->transform_negotiate->ciphersuite_info );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %d", n ) );
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, session id", buf + 35, n );
/*
* Check if the session can be resumed
*/
if( ssl->handshake->resume == 0 || n == 0 ||
#if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
#endif
ssl->session_negotiate->ciphersuite != i ||
ssl->session_negotiate->compression != comp ||
ssl->session_negotiate->id_len != n ||
memcmp( ssl->session_negotiate->id, buf + 35, n ) != 0 )
{
ssl->state++;
ssl->handshake->resume = 0;
#if defined(MBEDTLS_HAVE_TIME)
ssl->session_negotiate->start = mbedtls_time( NULL );
#endif
ssl->session_negotiate->ciphersuite = i;
ssl->session_negotiate->compression = comp;
ssl->session_negotiate->id_len = n;
memcpy( ssl->session_negotiate->id, buf + 35, n );
}
else
{
ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
return( ret );
}
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed",
ssl->handshake->resume ? "a" : "no" ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %04x", i ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: %d", buf[37 + n] ) );
suite_info = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite );
if( suite_info == NULL
#if defined(MBEDTLS_ARC4_C)
|| ( ssl->conf->arc4_disabled &&
suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
#endif
)
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", suite_info->name ) );
i = 0;
while( 1 )
{
if( ssl->conf->ciphersuite_list[ssl->minor_ver][i] == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
if( ssl->conf->ciphersuite_list[ssl->minor_ver][i++] ==
ssl->session_negotiate->ciphersuite )
{
break;
}
}
if( comp != MBEDTLS_SSL_COMPRESS_NULL
#if defined(MBEDTLS_ZLIB_SUPPORT)
&& comp != MBEDTLS_SSL_COMPRESS_DEFLATE
#endif
)
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
ssl->session_negotiate->compression = comp;
ext = buf + 40 + n;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "server hello, total extension length: %d", ext_len ) );
while( ext_len )
{
unsigned int ext_id = ( ( ext[0] << 8 )
| ( ext[1] ) );
unsigned int ext_size = ( ( ext[2] << 8 )
| ( ext[3] ) );
if( ext_size + 4 > ext_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
switch( ext_id )
{
case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) );
#if defined(MBEDTLS_SSL_RENEGOTIATION)
renegotiation_info_seen = 1;
#endif
if( ( ret = ssl_parse_renegotiation_info( ssl, ext + 4,
ext_size ) ) != 0 )
return( ret );
break;
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max_fragment_length extension" ) );
if( ( ret = ssl_parse_max_fragment_length_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found truncated_hmac extension" ) );
if( ( ret = ssl_parse_truncated_hmac_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt_then_mac extension" ) );
if( ( ret = ssl_parse_encrypt_then_mac_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended_master_secret extension" ) );
if( ( ret = ssl_parse_extended_ms_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
case MBEDTLS_TLS_EXT_SESSION_TICKET:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session_ticket extension" ) );
if( ( ret = ssl_parse_session_ticket_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported_point_formats extension" ) );
if( ( ret = ssl_parse_supported_point_formats_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake_kkpp extension" ) );
if( ( ret = ssl_parse_ecjpake_kkpp( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_ALPN)
case MBEDTLS_TLS_EXT_ALPN:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) );
if( ( ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ) ) != 0 )
return( ret );
break;
#endif /* MBEDTLS_SSL_ALPN */
default:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %d (ignoring)",
ext_id ) );
}
ext_len -= 4 + ext_size;
ext += 4 + ext_size;
if( ext_len > 0 && ext_len < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
}
/*
* Renegotiation security checks
*/
if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) );
handshake_failure = 1;
}
#if defined(MBEDTLS_SSL_RENEGOTIATION)
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
renegotiation_info_seen == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) );
handshake_failure = 1;
}
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) );
handshake_failure = 1;
}
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
renegotiation_info_seen == 1 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) );
handshake_failure = 1;
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
if( handshake_failure == 1 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
return( 0 );
}
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
static int ssl_parse_server_dh_params( mbedtls_ssl_context *ssl, unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
/*
* Ephemeral DH parameters:
*
* struct {
* opaque dh_p<1..2^16-1>;
* opaque dh_g<1..2^16-1>;
* opaque dh_Ys<1..2^16-1>;
* } ServerDHParams;
*/
if( ( ret = mbedtls_dhm_read_params( &ssl->handshake->dhm_ctx, p, end ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 2, ( "mbedtls_dhm_read_params" ), ret );
return( ret );
}
if( ssl->handshake->dhm_ctx.len * 8 < ssl->conf->dhm_min_bitlen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "DHM prime too short: %d < %d",
ssl->handshake->dhm_ctx.len * 8,
ssl->conf->dhm_min_bitlen ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY );
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
static int ssl_check_server_ecdh_params( const mbedtls_ssl_context *ssl )
{
const mbedtls_ecp_curve_info *curve_info;
curve_info = mbedtls_ecp_curve_info_from_grp_id( ssl->handshake->ecdh_ctx.grp.id );
if( curve_info == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDH curve: %s", curve_info->name ) );
#if defined(MBEDTLS_ECP_C)
if( mbedtls_ssl_check_curve( ssl, ssl->handshake->ecdh_ctx.grp.id ) != 0 )
#else
if( ssl->handshake->ecdh_ctx.grp.nbits < 163 ||
ssl->handshake->ecdh_ctx.grp.nbits > 521 )
#endif
return( -1 );
MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Qp", &ssl->handshake->ecdh_ctx.Qp );
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
static int ssl_parse_server_ecdh_params( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
/*
* Ephemeral ECDH parameters:
*
* struct {
* ECParameters curve_params;
* ECPoint public;
* } ServerECDHParams;
*/
if( ( ret = mbedtls_ecdh_read_params( &ssl->handshake->ecdh_ctx,
(const unsigned char **) p, end ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_read_params" ), ret );
return( ret );
}
if( ssl_check_server_ecdh_params( ssl ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message (ECDHE curve)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
if( (*p) > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) + len > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
/*
* Generate a pre-master secret and encrypt it with the server's RSA key
*/
static int ssl_write_encrypted_pms( mbedtls_ssl_context *ssl,
size_t offset, size_t *olen,
size_t pms_offset )
{
int ret;
size_t len_bytes = ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ? 0 : 2;
unsigned char *p = ssl->handshake->premaster + pms_offset;
if( offset + len_bytes > MBEDTLS_SSL_MAX_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small for encrypted pms" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
/*
* Generate (part of) the pre-master as
* struct {
* ProtocolVersion client_version;
* opaque random[46];
* } PreMasterSecret;
*/
mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,
ssl->conf->transport, p );
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p + 2, 46 ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "f_rng", ret );
return( ret );
}
ssl->handshake->pmslen = 48;
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* Now write it out, encrypted
*/
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
MBEDTLS_PK_RSA ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate key type mismatch" ) );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
if( ( ret = mbedtls_pk_encrypt( &ssl->session_negotiate->peer_cert->pk,
p, ssl->handshake->pmslen,
ssl->out_msg + offset + len_bytes, olen,
MBEDTLS_SSL_MAX_CONTENT_LEN - offset - len_bytes,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_rsa_pkcs1_encrypt", ret );
return( ret );
}
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( len_bytes == 2 )
{
ssl->out_msg[offset+0] = (unsigned char)( *olen >> 8 );
ssl->out_msg[offset+1] = (unsigned char)( *olen );
*olen += 2;
}
#endif
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
static int ssl_parse_signature_algorithm( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end,
mbedtls_md_type_t *md_alg,
mbedtls_pk_type_t *pk_alg )
{
((void) ssl);
*md_alg = MBEDTLS_MD_NONE;
*pk_alg = MBEDTLS_PK_NONE;
/* Only in TLS 1.2 */
if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
{
return( 0 );
}
if( (*p) + 2 > end )
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
/*
* Get hash algorithm
*/
if( ( *md_alg = mbedtls_ssl_md_alg_from_hash( (*p)[0] ) ) == MBEDTLS_MD_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "Server used unsupported "
"HashAlgorithm %d", *(p)[0] ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Get signature algorithm
*/
if( ( *pk_alg = mbedtls_ssl_pk_alg_from_sig( (*p)[1] ) ) == MBEDTLS_PK_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used unsupported "
"SignatureAlgorithm %d", (*p)[1] ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Check if the hash is acceptable
*/
if( mbedtls_ssl_check_sig_hash( ssl, *md_alg ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used HashAlgorithm %d that was not offered",
*(p)[0] ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used SignatureAlgorithm %d", (*p)[1] ) );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used HashAlgorithm %d", (*p)[0] ) );
*p += 2;
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
{
int ret;
const mbedtls_ecp_keypair *peer_key;
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
MBEDTLS_PK_ECKEY ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
peer_key = mbedtls_pk_ec( ssl->session_negotiate->peer_cert->pk );
if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx, peer_key,
MBEDTLS_ECDH_THEIRS ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret );
return( ret );
}
if( ssl_check_server_ecdh_params( ssl ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server certificate (ECDH curve)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
}
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
{
int ret;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
unsigned char *p = NULL, *end = NULL;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
{
if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* ServerKeyExchange may be skipped with PSK and RSA-PSK when the server
* doesn't use a psk_identity_hint
*/
if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )
{
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
{
/* Current message is probably either
* CertificateRequest or ServerHelloDone */
ssl->keep_current_message = 1;
goto exit;
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key exchange message must "
"not be skipped" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
end = ssl->in_msg + ssl->in_hslen;
MBEDTLS_SSL_DEBUG_BUF( 3, "server key exchange", p, end - p );
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
} /* FALLTROUGH */
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
; /* nothing more to do */
else
#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
{
if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
{
if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
p, end - p );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
{
size_t sig_len, hashlen;
unsigned char hash[64];
mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
size_t params_len = p - params;
/*
* Handle the digitally-signed structure
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
if( ssl_parse_signature_algorithm( ssl, &p, end,
&md_alg, &pk_alg ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
{
pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
/* Default hash for ECDSA is SHA-1 */
if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE )
md_alg = MBEDTLS_MD_SHA1;
}
else
#endif
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
/*
* Read signature
*/
sig_len = ( p[0] << 8 ) | p[1];
p += 2;
if( end != p + sig_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len );
/*
* Compute the hash that has been signed
*/
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( md_alg == MBEDTLS_MD_NONE )
{
hashlen = 36;
ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params,
params_len );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( md_alg != MBEDTLS_MD_NONE )
{
/* Info from md_alg will be used instead */
hashlen = 0;
ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, params,
params_len, md_alg );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen != 0 ? hashlen :
(unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) );
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* Verify signature
*/
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,
md_alg, hash, hashlen, p, sig_len ) ) != 0 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
return( ret );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
exit:
ssl->state++;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) );
return( 0 );
}
#if ! defined(MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED)
static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
{
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
ssl->state++;
return( 0 );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#else /* MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED */
static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
{
int ret;
unsigned char *buf;
size_t n = 0;
size_t cert_type_len = 0, dn_len = 0;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
ssl->state++;
return( 0 );
}
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
ssl->state++;
ssl->client_auth = ( ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE_REQUEST );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "got %s certificate request",
ssl->client_auth ? "a" : "no" ) );
if( ssl->client_auth == 0 )
{
/* Current message is probably the ServerHelloDone */
ssl->keep_current_message = 1;
goto exit;
}
/*
* struct {
* ClientCertificateType certificate_types<1..2^8-1>;
* SignatureAndHashAlgorithm
* supported_signature_algorithms<2^16-1>; -- TLS 1.2 only
* DistinguishedName certificate_authorities<0..2^16-1>;
* } CertificateRequest;
*
* Since we only support a single certificate on clients, let's just
* ignore all the information that's supposed to help us pick a
* certificate.
*
* We could check that our certificate matches the request, and bail out
* if it doesn't, but it's simpler to just send the certificate anyway,
* and give the server the opportunity to decide if it should terminate
* the connection when it doesn't like our certificate.
*
* Same goes for the hash in TLS 1.2's signature_algorithms: at this
* point we only have one hash available (see comments in
* write_certificate_verify), so let's just use what we have.
*
* However, we still minimally parse the message to check it is at least
* superficially sane.
*/
buf = ssl->in_msg;
/* certificate_types */
cert_type_len = buf[mbedtls_ssl_hs_hdr_len( ssl )];
n = cert_type_len;
if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
/* supported_signature_algorithms */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
size_t sig_alg_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 )
| ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) );
#if defined(MBEDTLS_DEBUG_C)
unsigned char* sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n;
size_t i;
for( i = 0; i < sig_alg_len; i += 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "Supported Signature Algorithm found: %d"
",%d", sig_alg[i], sig_alg[i + 1] ) );
}
#endif
n += 2 + sig_alg_len;
if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
/* certificate_authorities */
dn_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 )
| ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) );
n += dn_len;
if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
exit:
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate request" ) );
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED */
static int ssl_parse_server_hello_done( mbedtls_ssl_context *ssl )
{
int ret;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello done" ) );
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) ||
ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_HELLO_DONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE );
}
ssl->state++;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
mbedtls_ssl_recv_flight_completed( ssl );
#endif
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello done" ) );
return( 0 );
}
static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl )
{
int ret;
size_t i, n;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client key exchange" ) );
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA )
{
/*
* DHM key exchange -- send G^X mod P
*/
n = ssl->handshake->dhm_ctx.len;
ssl->out_msg[4] = (unsigned char)( n >> 8 );
ssl->out_msg[5] = (unsigned char)( n );
i = 6;
ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
(int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
&ssl->out_msg[i], n,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX );
if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
ssl->handshake->premaster,
MBEDTLS_PREMASTER_SIZE,
&ssl->handshake->pmslen,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
{
/*
* ECDH key exchange -- send client public value
*/
i = 4;
ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx,
&n,
&ssl->out_msg[i], 1000,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q );
if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx,
&ssl->handshake->pmslen,
ssl->handshake->premaster,
MBEDTLS_MPI_MAX_SIZE,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
if( mbedtls_ssl_ciphersuite_uses_psk( ciphersuite_info ) )
{
/*
* opaque psk_identity<0..2^16-1>;
*/
if( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for PSK" ) );
return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
}
i = 4;
n = ssl->conf->psk_identity_len;
if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity too long or "
"SSL buffer too short" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
ssl->out_msg[i++] = (unsigned char)( n >> 8 );
ssl->out_msg[i++] = (unsigned char)( n );
memcpy( ssl->out_msg + i, ssl->conf->psk_identity, ssl->conf->psk_identity_len );
i += ssl->conf->psk_identity_len;
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK )
{
n = 0;
}
else
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
{
if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 2 ) ) != 0 )
return( ret );
}
else
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
{
/*
* ClientDiffieHellmanPublic public (DHM send G^X mod P)
*/
n = ssl->handshake->dhm_ctx.len;
if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity or DHM size too long"
" or SSL buffer too short" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
ssl->out_msg[i++] = (unsigned char)( n >> 8 );
ssl->out_msg[i++] = (unsigned char)( n );
ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
(int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
&ssl->out_msg[i], n,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
/*
* ClientECDiffieHellmanPublic public;
*/
ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx, &n,
&ssl->out_msg[i], MBEDTLS_SSL_MAX_CONTENT_LEN - i,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
ciphersuite_info->key_exchange ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
{
i = 4;
if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 0 ) ) != 0 )
return( ret );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
i = 4;
ret = mbedtls_ecjpake_write_round_two( &ssl->handshake->ecjpake_ctx,
ssl->out_msg + i, MBEDTLS_SSL_MAX_CONTENT_LEN - i, &n,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret );
return( ret );
}
ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx,
ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
{
((void) ciphersuite_info);
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
ssl->out_msglen = i + n;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE;
ssl->state++;
if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client key exchange" ) );
return( 0 );
}
#if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)&& \
!defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
{
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
int ret;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
return( ret );
}
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
ssl->state++;
return( 0 );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#else
static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
size_t n = 0, offset = 0;
unsigned char hash[48];
unsigned char *hash_start = hash;
mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
unsigned int hashlen;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
return( ret );
}
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
ssl->state++;
return( 0 );
}
if( ssl->client_auth == 0 || mbedtls_ssl_own_cert( ssl ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
ssl->state++;
return( 0 );
}
if( mbedtls_ssl_own_key( ssl ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for certificate" ) );
return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
}
/*
* Make an RSA signature of the handshake digests
*/
ssl->handshake->calc_verify( ssl, hash );
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
{
/*
* digitally-signed struct {
* opaque md5_hash[16];
* opaque sha_hash[20];
* };
*
* md5_hash
* MD5(handshake_messages);
*
* sha_hash
* SHA(handshake_messages);
*/
hashlen = 36;
md_alg = MBEDTLS_MD_NONE;
/*
* For ECDSA, default hash is SHA-1 only
*/
if( mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECDSA ) )
{
hash_start += 16;
hashlen -= 16;
md_alg = MBEDTLS_MD_SHA1;
}
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
/*
* digitally-signed struct {
* opaque handshake_messages[handshake_messages_length];
* };
*
* Taking shortcut here. We assume that the server always allows the
* PRF Hash function and has sent it in the allowed signature
* algorithms list received in the Certificate Request message.
*
* Until we encounter a server that does not, we will take this
* shortcut.
*
* Reason: Otherwise we should have running hashes for SHA512 and SHA224
* in order to satisfy 'weird' needs from the server side.
*/
if( ssl->transform_negotiate->ciphersuite_info->mac ==
MBEDTLS_MD_SHA384 )
{
md_alg = MBEDTLS_MD_SHA384;
ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA384;
}
else
{
md_alg = MBEDTLS_MD_SHA256;
ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA256;
}
ssl->out_msg[5] = mbedtls_ssl_sig_from_pk( mbedtls_ssl_own_key( ssl ) );
/* Info from md_alg will be used instead */
hashlen = 0;
offset = 2;
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ), md_alg, hash_start, hashlen,
ssl->out_msg + 6 + offset, &n,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret );
return( ret );
}
ssl->out_msg[4 + offset] = (unsigned char)( n >> 8 );
ssl->out_msg[5 + offset] = (unsigned char)( n );
ssl->out_msglen = 6 + n + offset;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE_VERIFY;
ssl->state++;
if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate verify" ) );
return( ret );
}
#endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl )
{
int ret;
uint32_t lifetime;
size_t ticket_len;
unsigned char *ticket;
const unsigned char *msg;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse new session ticket" ) );
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* struct {
* uint32 ticket_lifetime_hint;
* opaque ticket<0..2^16-1>;
* } NewSessionTicket;
*
* 0 . 3 ticket_lifetime_hint
* 4 . 5 ticket_len (n)
* 6 . 5+n ticket content
*/
if( ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET ||
ssl->in_hslen < 6 + mbedtls_ssl_hs_hdr_len( ssl ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
}
msg = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
lifetime = ( msg[0] << 24 ) | ( msg[1] << 16 ) |
( msg[2] << 8 ) | ( msg[3] );
ticket_len = ( msg[4] << 8 ) | ( msg[5] );
if( ticket_len + 6 + mbedtls_ssl_hs_hdr_len( ssl ) != ssl->in_hslen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %d", ticket_len ) );
/* We're not waiting for a NewSessionTicket message any more */
ssl->handshake->new_session_ticket = 0;
ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
/*
* Zero-length ticket means the server changed his mind and doesn't want
* to send a ticket after all, so just forget it
*/
if( ticket_len == 0 )
return( 0 );
mbedtls_zeroize( ssl->session_negotiate->ticket,
ssl->session_negotiate->ticket_len );
mbedtls_free( ssl->session_negotiate->ticket );
ssl->session_negotiate->ticket = NULL;
ssl->session_negotiate->ticket_len = 0;
if( ( ticket = mbedtls_calloc( 1, ticket_len ) ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ticket alloc failed" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
}
memcpy( ticket, msg + 6, ticket_len );
ssl->session_negotiate->ticket = ticket;
ssl->session_negotiate->ticket_len = ticket_len;
ssl->session_negotiate->ticket_lifetime = lifetime;
/*
* RFC 5077 section 3.4:
* "If the client receives a session ticket from the server, then it
* discards any Session ID that was sent in the ServerHello."
*/
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket in use, discarding session id" ) );
ssl->session_negotiate->id_len = 0;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse new session ticket" ) );
return( 0 );
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
/*
* SSL handshake -- client side -- single step
*/
int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl )
{
int ret = 0;
if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL )
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "client state: %d", ssl->state ) );
if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
return( ret );
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
{
if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
return( ret );
}
#endif
/* Change state now, so that it is right in mbedtls_ssl_read_record(), used
* by DTLS for dropping out-of-sequence ChangeCipherSpec records */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
if( ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC &&
ssl->handshake->new_session_ticket != 0 )
{
ssl->state = MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET;
}
#endif
switch( ssl->state )
{
case MBEDTLS_SSL_HELLO_REQUEST:
ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
break;
/*
* ==> ClientHello
*/
case MBEDTLS_SSL_CLIENT_HELLO:
ret = ssl_write_client_hello( ssl );
break;
/*
* <== ServerHello
* Certificate
* ( ServerKeyExchange )
* ( CertificateRequest )
* ServerHelloDone
*/
case MBEDTLS_SSL_SERVER_HELLO:
ret = ssl_parse_server_hello( ssl );
break;
case MBEDTLS_SSL_SERVER_CERTIFICATE:
ret = mbedtls_ssl_parse_certificate( ssl );
break;
case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
ret = ssl_parse_server_key_exchange( ssl );
break;
case MBEDTLS_SSL_CERTIFICATE_REQUEST:
ret = ssl_parse_certificate_request( ssl );
break;
case MBEDTLS_SSL_SERVER_HELLO_DONE:
ret = ssl_parse_server_hello_done( ssl );
break;
/*
* ==> ( Certificate/Alert )
* ClientKeyExchange
* ( CertificateVerify )
* ChangeCipherSpec
* Finished
*/
case MBEDTLS_SSL_CLIENT_CERTIFICATE:
ret = mbedtls_ssl_write_certificate( ssl );
break;
case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
ret = ssl_write_client_key_exchange( ssl );
break;
case MBEDTLS_SSL_CERTIFICATE_VERIFY:
ret = ssl_write_certificate_verify( ssl );
break;
case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
ret = mbedtls_ssl_write_change_cipher_spec( ssl );
break;
case MBEDTLS_SSL_CLIENT_FINISHED:
ret = mbedtls_ssl_write_finished( ssl );
break;
/*
* <== ( NewSessionTicket )
* ChangeCipherSpec
* Finished
*/
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
case MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET:
ret = ssl_parse_new_session_ticket( ssl );
break;
#endif
case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
ret = mbedtls_ssl_parse_change_cipher_spec( ssl );
break;
case MBEDTLS_SSL_SERVER_FINISHED:
ret = mbedtls_ssl_parse_finished( ssl );
break;
case MBEDTLS_SSL_FLUSH_BUFFERS:
MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) );
ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
break;
case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
mbedtls_ssl_handshake_wrapup( ssl );
break;
default:
MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
return( ret );
}
#endif /* MBEDTLS_SSL_CLI_C */
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_701_0 |
crossvul-cpp_data_good_2676_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997
* 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: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: Network File System (NFS) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "nfs.h"
#include "nfsfh.h"
#include "ip.h"
#include "ip6.h"
#include "rpc_auth.h"
#include "rpc_msg.h"
static const char tstr[] = " [|nfs]";
static void nfs_printfh(netdissect_options *, const uint32_t *, const u_int);
static int xid_map_enter(netdissect_options *, const struct sunrpc_msg *, const u_char *);
static int xid_map_find(const struct sunrpc_msg *, const u_char *,
uint32_t *, uint32_t *);
static void interp_reply(netdissect_options *, const struct sunrpc_msg *, uint32_t, uint32_t, int);
static const uint32_t *parse_post_op_attr(netdissect_options *, const uint32_t *, int);
/*
* Mapping of old NFS Version 2 RPC numbers to generic numbers.
*/
static uint32_t nfsv3_procid[NFS_NPROCS] = {
NFSPROC_NULL,
NFSPROC_GETATTR,
NFSPROC_SETATTR,
NFSPROC_NOOP,
NFSPROC_LOOKUP,
NFSPROC_READLINK,
NFSPROC_READ,
NFSPROC_NOOP,
NFSPROC_WRITE,
NFSPROC_CREATE,
NFSPROC_REMOVE,
NFSPROC_RENAME,
NFSPROC_LINK,
NFSPROC_SYMLINK,
NFSPROC_MKDIR,
NFSPROC_RMDIR,
NFSPROC_READDIR,
NFSPROC_FSSTAT,
NFSPROC_NOOP,
NFSPROC_NOOP,
NFSPROC_NOOP,
NFSPROC_NOOP,
NFSPROC_NOOP,
NFSPROC_NOOP,
NFSPROC_NOOP,
NFSPROC_NOOP
};
static const struct tok nfsproc_str[] = {
{ NFSPROC_NOOP, "nop" },
{ NFSPROC_NULL, "null" },
{ NFSPROC_GETATTR, "getattr" },
{ NFSPROC_SETATTR, "setattr" },
{ NFSPROC_LOOKUP, "lookup" },
{ NFSPROC_ACCESS, "access" },
{ NFSPROC_READLINK, "readlink" },
{ NFSPROC_READ, "read" },
{ NFSPROC_WRITE, "write" },
{ NFSPROC_CREATE, "create" },
{ NFSPROC_MKDIR, "mkdir" },
{ NFSPROC_SYMLINK, "symlink" },
{ NFSPROC_MKNOD, "mknod" },
{ NFSPROC_REMOVE, "remove" },
{ NFSPROC_RMDIR, "rmdir" },
{ NFSPROC_RENAME, "rename" },
{ NFSPROC_LINK, "link" },
{ NFSPROC_READDIR, "readdir" },
{ NFSPROC_READDIRPLUS, "readdirplus" },
{ NFSPROC_FSSTAT, "fsstat" },
{ NFSPROC_FSINFO, "fsinfo" },
{ NFSPROC_PATHCONF, "pathconf" },
{ NFSPROC_COMMIT, "commit" },
{ 0, NULL }
};
/*
* NFS V2 and V3 status values.
*
* Some of these come from the RFCs for NFS V2 and V3, with the message
* strings taken from the FreeBSD C library "errlst.c".
*
* Others are errors that are not in the RFC but that I suspect some
* NFS servers could return; the values are FreeBSD errno values, as
* the first NFS server was the SunOS 2.0 one, and until 5.0 SunOS
* was primarily BSD-derived.
*/
static const struct tok status2str[] = {
{ 1, "Operation not permitted" }, /* EPERM */
{ 2, "No such file or directory" }, /* ENOENT */
{ 5, "Input/output error" }, /* EIO */
{ 6, "Device not configured" }, /* ENXIO */
{ 11, "Resource deadlock avoided" }, /* EDEADLK */
{ 12, "Cannot allocate memory" }, /* ENOMEM */
{ 13, "Permission denied" }, /* EACCES */
{ 17, "File exists" }, /* EEXIST */
{ 18, "Cross-device link" }, /* EXDEV */
{ 19, "Operation not supported by device" }, /* ENODEV */
{ 20, "Not a directory" }, /* ENOTDIR */
{ 21, "Is a directory" }, /* EISDIR */
{ 22, "Invalid argument" }, /* EINVAL */
{ 26, "Text file busy" }, /* ETXTBSY */
{ 27, "File too large" }, /* EFBIG */
{ 28, "No space left on device" }, /* ENOSPC */
{ 30, "Read-only file system" }, /* EROFS */
{ 31, "Too many links" }, /* EMLINK */
{ 45, "Operation not supported" }, /* EOPNOTSUPP */
{ 62, "Too many levels of symbolic links" }, /* ELOOP */
{ 63, "File name too long" }, /* ENAMETOOLONG */
{ 66, "Directory not empty" }, /* ENOTEMPTY */
{ 69, "Disc quota exceeded" }, /* EDQUOT */
{ 70, "Stale NFS file handle" }, /* ESTALE */
{ 71, "Too many levels of remote in path" }, /* EREMOTE */
{ 99, "Write cache flushed to disk" }, /* NFSERR_WFLUSH (not used) */
{ 10001, "Illegal NFS file handle" }, /* NFS3ERR_BADHANDLE */
{ 10002, "Update synchronization mismatch" }, /* NFS3ERR_NOT_SYNC */
{ 10003, "READDIR/READDIRPLUS cookie is stale" }, /* NFS3ERR_BAD_COOKIE */
{ 10004, "Operation not supported" }, /* NFS3ERR_NOTSUPP */
{ 10005, "Buffer or request is too small" }, /* NFS3ERR_TOOSMALL */
{ 10006, "Unspecified error on server" }, /* NFS3ERR_SERVERFAULT */
{ 10007, "Object of that type not supported" }, /* NFS3ERR_BADTYPE */
{ 10008, "Request couldn't be completed in time" }, /* NFS3ERR_JUKEBOX */
{ 0, NULL }
};
static const struct tok nfsv3_writemodes[] = {
{ 0, "unstable" },
{ 1, "datasync" },
{ 2, "filesync" },
{ 0, NULL }
};
static const struct tok type2str[] = {
{ NFNON, "NON" },
{ NFREG, "REG" },
{ NFDIR, "DIR" },
{ NFBLK, "BLK" },
{ NFCHR, "CHR" },
{ NFLNK, "LNK" },
{ NFFIFO, "FIFO" },
{ 0, NULL }
};
static const struct tok sunrpc_auth_str[] = {
{ SUNRPC_AUTH_OK, "OK" },
{ SUNRPC_AUTH_BADCRED, "Bogus Credentials (seal broken)" },
{ SUNRPC_AUTH_REJECTEDCRED, "Rejected Credentials (client should begin new session)" },
{ SUNRPC_AUTH_BADVERF, "Bogus Verifier (seal broken)" },
{ SUNRPC_AUTH_REJECTEDVERF, "Verifier expired or was replayed" },
{ SUNRPC_AUTH_TOOWEAK, "Credentials are too weak" },
{ SUNRPC_AUTH_INVALIDRESP, "Bogus response verifier" },
{ SUNRPC_AUTH_FAILED, "Unknown failure" },
{ 0, NULL }
};
static const struct tok sunrpc_str[] = {
{ SUNRPC_PROG_UNAVAIL, "PROG_UNAVAIL" },
{ SUNRPC_PROG_MISMATCH, "PROG_MISMATCH" },
{ SUNRPC_PROC_UNAVAIL, "PROC_UNAVAIL" },
{ SUNRPC_GARBAGE_ARGS, "GARBAGE_ARGS" },
{ SUNRPC_SYSTEM_ERR, "SYSTEM_ERR" },
{ 0, NULL }
};
static void
print_nfsaddr(netdissect_options *ndo,
const u_char *bp, const char *s, const char *d)
{
const struct ip *ip;
const struct ip6_hdr *ip6;
char srcaddr[INET6_ADDRSTRLEN], dstaddr[INET6_ADDRSTRLEN];
srcaddr[0] = dstaddr[0] = '\0';
switch (IP_V((const struct ip *)bp)) {
case 4:
ip = (const struct ip *)bp;
strlcpy(srcaddr, ipaddr_string(ndo, &ip->ip_src), sizeof(srcaddr));
strlcpy(dstaddr, ipaddr_string(ndo, &ip->ip_dst), sizeof(dstaddr));
break;
case 6:
ip6 = (const struct ip6_hdr *)bp;
strlcpy(srcaddr, ip6addr_string(ndo, &ip6->ip6_src),
sizeof(srcaddr));
strlcpy(dstaddr, ip6addr_string(ndo, &ip6->ip6_dst),
sizeof(dstaddr));
break;
default:
strlcpy(srcaddr, "?", sizeof(srcaddr));
strlcpy(dstaddr, "?", sizeof(dstaddr));
break;
}
ND_PRINT((ndo, "%s.%s > %s.%s: ", srcaddr, s, dstaddr, d));
}
static const uint32_t *
parse_sattr3(netdissect_options *ndo,
const uint32_t *dp, struct nfsv3_sattr *sa3)
{
ND_TCHECK(dp[0]);
sa3->sa_modeset = EXTRACT_32BITS(dp);
dp++;
if (sa3->sa_modeset) {
ND_TCHECK(dp[0]);
sa3->sa_mode = EXTRACT_32BITS(dp);
dp++;
}
ND_TCHECK(dp[0]);
sa3->sa_uidset = EXTRACT_32BITS(dp);
dp++;
if (sa3->sa_uidset) {
ND_TCHECK(dp[0]);
sa3->sa_uid = EXTRACT_32BITS(dp);
dp++;
}
ND_TCHECK(dp[0]);
sa3->sa_gidset = EXTRACT_32BITS(dp);
dp++;
if (sa3->sa_gidset) {
ND_TCHECK(dp[0]);
sa3->sa_gid = EXTRACT_32BITS(dp);
dp++;
}
ND_TCHECK(dp[0]);
sa3->sa_sizeset = EXTRACT_32BITS(dp);
dp++;
if (sa3->sa_sizeset) {
ND_TCHECK(dp[0]);
sa3->sa_size = EXTRACT_32BITS(dp);
dp++;
}
ND_TCHECK(dp[0]);
sa3->sa_atimetype = EXTRACT_32BITS(dp);
dp++;
if (sa3->sa_atimetype == NFSV3SATTRTIME_TOCLIENT) {
ND_TCHECK(dp[1]);
sa3->sa_atime.nfsv3_sec = EXTRACT_32BITS(dp);
dp++;
sa3->sa_atime.nfsv3_nsec = EXTRACT_32BITS(dp);
dp++;
}
ND_TCHECK(dp[0]);
sa3->sa_mtimetype = EXTRACT_32BITS(dp);
dp++;
if (sa3->sa_mtimetype == NFSV3SATTRTIME_TOCLIENT) {
ND_TCHECK(dp[1]);
sa3->sa_mtime.nfsv3_sec = EXTRACT_32BITS(dp);
dp++;
sa3->sa_mtime.nfsv3_nsec = EXTRACT_32BITS(dp);
dp++;
}
return dp;
trunc:
return NULL;
}
static int nfserr; /* true if we error rather than trunc */
static void
print_sattr3(netdissect_options *ndo,
const struct nfsv3_sattr *sa3, int verbose)
{
if (sa3->sa_modeset)
ND_PRINT((ndo, " mode %o", sa3->sa_mode));
if (sa3->sa_uidset)
ND_PRINT((ndo, " uid %u", sa3->sa_uid));
if (sa3->sa_gidset)
ND_PRINT((ndo, " gid %u", sa3->sa_gid));
if (verbose > 1) {
if (sa3->sa_atimetype == NFSV3SATTRTIME_TOCLIENT)
ND_PRINT((ndo, " atime %u.%06u", sa3->sa_atime.nfsv3_sec,
sa3->sa_atime.nfsv3_nsec));
if (sa3->sa_mtimetype == NFSV3SATTRTIME_TOCLIENT)
ND_PRINT((ndo, " mtime %u.%06u", sa3->sa_mtime.nfsv3_sec,
sa3->sa_mtime.nfsv3_nsec));
}
}
void
nfsreply_print(netdissect_options *ndo,
register const u_char *bp, u_int length,
register const u_char *bp2)
{
register const struct sunrpc_msg *rp;
char srcid[20], dstid[20]; /*fits 32bit*/
nfserr = 0; /* assume no error */
rp = (const struct sunrpc_msg *)bp;
ND_TCHECK(rp->rm_xid);
if (!ndo->ndo_nflag) {
strlcpy(srcid, "nfs", sizeof(srcid));
snprintf(dstid, sizeof(dstid), "%u",
EXTRACT_32BITS(&rp->rm_xid));
} else {
snprintf(srcid, sizeof(srcid), "%u", NFS_PORT);
snprintf(dstid, sizeof(dstid), "%u",
EXTRACT_32BITS(&rp->rm_xid));
}
print_nfsaddr(ndo, bp2, srcid, dstid);
nfsreply_print_noaddr(ndo, bp, length, bp2);
return;
trunc:
if (!nfserr)
ND_PRINT((ndo, "%s", tstr));
}
void
nfsreply_print_noaddr(netdissect_options *ndo,
register const u_char *bp, u_int length,
register const u_char *bp2)
{
register const struct sunrpc_msg *rp;
uint32_t proc, vers, reply_stat;
enum sunrpc_reject_stat rstat;
uint32_t rlow;
uint32_t rhigh;
enum sunrpc_auth_stat rwhy;
nfserr = 0; /* assume no error */
rp = (const struct sunrpc_msg *)bp;
ND_TCHECK(rp->rm_reply.rp_stat);
reply_stat = EXTRACT_32BITS(&rp->rm_reply.rp_stat);
switch (reply_stat) {
case SUNRPC_MSG_ACCEPTED:
ND_PRINT((ndo, "reply ok %u", length));
if (xid_map_find(rp, bp2, &proc, &vers) >= 0)
interp_reply(ndo, rp, proc, vers, length);
break;
case SUNRPC_MSG_DENIED:
ND_PRINT((ndo, "reply ERR %u: ", length));
ND_TCHECK(rp->rm_reply.rp_reject.rj_stat);
rstat = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_stat);
switch (rstat) {
case SUNRPC_RPC_MISMATCH:
ND_TCHECK(rp->rm_reply.rp_reject.rj_vers.high);
rlow = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_vers.low);
rhigh = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_vers.high);
ND_PRINT((ndo, "RPC Version mismatch (%u-%u)", rlow, rhigh));
break;
case SUNRPC_AUTH_ERROR:
ND_TCHECK(rp->rm_reply.rp_reject.rj_why);
rwhy = EXTRACT_32BITS(&rp->rm_reply.rp_reject.rj_why);
ND_PRINT((ndo, "Auth %s", tok2str(sunrpc_auth_str, "Invalid failure code %u", rwhy)));
break;
default:
ND_PRINT((ndo, "Unknown reason for rejecting rpc message %u", (unsigned int)rstat));
break;
}
break;
default:
ND_PRINT((ndo, "reply Unknown rpc response code=%u %u", reply_stat, length));
break;
}
return;
trunc:
if (!nfserr)
ND_PRINT((ndo, "%s", tstr));
}
/*
* Return a pointer to the first file handle in the packet.
* If the packet was truncated, return 0.
*/
static const uint32_t *
parsereq(netdissect_options *ndo,
register const struct sunrpc_msg *rp, register u_int length)
{
register const uint32_t *dp;
register u_int len;
/*
* find the start of the req data (if we captured it)
*/
dp = (const uint32_t *)&rp->rm_call.cb_cred;
ND_TCHECK(dp[1]);
len = EXTRACT_32BITS(&dp[1]);
if (len < length) {
dp += (len + (2 * sizeof(*dp) + 3)) / sizeof(*dp);
ND_TCHECK(dp[1]);
len = EXTRACT_32BITS(&dp[1]);
if (len < length) {
dp += (len + (2 * sizeof(*dp) + 3)) / sizeof(*dp);
ND_TCHECK2(dp[0], 0);
return (dp);
}
}
trunc:
return (NULL);
}
/*
* Print out an NFS file handle and return a pointer to following word.
* If packet was truncated, return 0.
*/
static const uint32_t *
parsefh(netdissect_options *ndo,
register const uint32_t *dp, int v3)
{
u_int len;
if (v3) {
ND_TCHECK(dp[0]);
len = EXTRACT_32BITS(dp) / 4;
dp++;
} else
len = NFSX_V2FH / 4;
if (ND_TTEST2(*dp, len * sizeof(*dp))) {
nfs_printfh(ndo, dp, len);
return (dp + len);
}
trunc:
return (NULL);
}
/*
* Print out a file name and return pointer to 32-bit word past it.
* If packet was truncated, return 0.
*/
static const uint32_t *
parsefn(netdissect_options *ndo,
register const uint32_t *dp)
{
register uint32_t len;
register const u_char *cp;
/* Bail if we don't have the string length */
ND_TCHECK(*dp);
/* Fetch string length; convert to host order */
len = *dp++;
NTOHL(len);
ND_TCHECK2(*dp, ((len + 3) & ~3));
cp = (const u_char *)dp;
/* Update 32-bit pointer (NFS filenames padded to 32-bit boundaries) */
dp += ((len + 3) & ~3) / sizeof(*dp);
ND_PRINT((ndo, "\""));
if (fn_printn(ndo, cp, len, ndo->ndo_snapend)) {
ND_PRINT((ndo, "\""));
goto trunc;
}
ND_PRINT((ndo, "\""));
return (dp);
trunc:
return NULL;
}
/*
* Print out file handle and file name.
* Return pointer to 32-bit word past file name.
* If packet was truncated (or there was some other error), return 0.
*/
static const uint32_t *
parsefhn(netdissect_options *ndo,
register const uint32_t *dp, int v3)
{
dp = parsefh(ndo, dp, v3);
if (dp == NULL)
return (NULL);
ND_PRINT((ndo, " "));
return (parsefn(ndo, dp));
}
void
nfsreq_print_noaddr(netdissect_options *ndo,
register const u_char *bp, u_int length,
register const u_char *bp2)
{
register const struct sunrpc_msg *rp;
register const uint32_t *dp;
nfs_type type;
int v3;
uint32_t proc;
uint32_t access_flags;
struct nfsv3_sattr sa3;
ND_PRINT((ndo, "%d", length));
nfserr = 0; /* assume no error */
rp = (const struct sunrpc_msg *)bp;
if (!xid_map_enter(ndo, rp, bp2)) /* record proc number for later on */
goto trunc;
v3 = (EXTRACT_32BITS(&rp->rm_call.cb_vers) == NFS_VER3);
proc = EXTRACT_32BITS(&rp->rm_call.cb_proc);
if (!v3 && proc < NFS_NPROCS)
proc = nfsv3_procid[proc];
ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc)));
switch (proc) {
case NFSPROC_GETATTR:
case NFSPROC_SETATTR:
case NFSPROC_READLINK:
case NFSPROC_FSSTAT:
case NFSPROC_FSINFO:
case NFSPROC_PATHCONF:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
parsefh(ndo, dp, v3) != NULL)
return;
break;
case NFSPROC_LOOKUP:
case NFSPROC_CREATE:
case NFSPROC_MKDIR:
case NFSPROC_REMOVE:
case NFSPROC_RMDIR:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
parsefhn(ndo, dp, v3) != NULL)
return;
break;
case NFSPROC_ACCESS:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
ND_TCHECK(dp[0]);
access_flags = EXTRACT_32BITS(&dp[0]);
if (access_flags & ~NFSV3ACCESS_FULL) {
/* NFSV3ACCESS definitions aren't up to date */
ND_PRINT((ndo, " %04x", access_flags));
} else if ((access_flags & NFSV3ACCESS_FULL) == NFSV3ACCESS_FULL) {
ND_PRINT((ndo, " NFS_ACCESS_FULL"));
} else {
char separator = ' ';
if (access_flags & NFSV3ACCESS_READ) {
ND_PRINT((ndo, " NFS_ACCESS_READ"));
separator = '|';
}
if (access_flags & NFSV3ACCESS_LOOKUP) {
ND_PRINT((ndo, "%cNFS_ACCESS_LOOKUP", separator));
separator = '|';
}
if (access_flags & NFSV3ACCESS_MODIFY) {
ND_PRINT((ndo, "%cNFS_ACCESS_MODIFY", separator));
separator = '|';
}
if (access_flags & NFSV3ACCESS_EXTEND) {
ND_PRINT((ndo, "%cNFS_ACCESS_EXTEND", separator));
separator = '|';
}
if (access_flags & NFSV3ACCESS_DELETE) {
ND_PRINT((ndo, "%cNFS_ACCESS_DELETE", separator));
separator = '|';
}
if (access_flags & NFSV3ACCESS_EXECUTE)
ND_PRINT((ndo, "%cNFS_ACCESS_EXECUTE", separator));
}
return;
}
break;
case NFSPROC_READ:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
if (v3) {
ND_TCHECK(dp[2]);
ND_PRINT((ndo, " %u bytes @ %" PRIu64,
EXTRACT_32BITS(&dp[2]),
EXTRACT_64BITS(&dp[0])));
} else {
ND_TCHECK(dp[1]);
ND_PRINT((ndo, " %u bytes @ %u",
EXTRACT_32BITS(&dp[1]),
EXTRACT_32BITS(&dp[0])));
}
return;
}
break;
case NFSPROC_WRITE:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
if (v3) {
ND_TCHECK(dp[4]);
ND_PRINT((ndo, " %u (%u) bytes @ %" PRIu64,
EXTRACT_32BITS(&dp[4]),
EXTRACT_32BITS(&dp[2]),
EXTRACT_64BITS(&dp[0])));
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " <%s>",
tok2str(nfsv3_writemodes,
NULL, EXTRACT_32BITS(&dp[3]))));
}
} else {
ND_TCHECK(dp[3]);
ND_PRINT((ndo, " %u (%u) bytes @ %u (%u)",
EXTRACT_32BITS(&dp[3]),
EXTRACT_32BITS(&dp[2]),
EXTRACT_32BITS(&dp[1]),
EXTRACT_32BITS(&dp[0])));
}
return;
}
break;
case NFSPROC_SYMLINK:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefhn(ndo, dp, v3)) != NULL) {
ND_PRINT((ndo, " ->"));
if (v3 && (dp = parse_sattr3(ndo, dp, &sa3)) == NULL)
break;
if (parsefn(ndo, dp) == NULL)
break;
if (v3 && ndo->ndo_vflag)
print_sattr3(ndo, &sa3, ndo->ndo_vflag);
return;
}
break;
case NFSPROC_MKNOD:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefhn(ndo, dp, v3)) != NULL) {
ND_TCHECK(*dp);
type = (nfs_type)EXTRACT_32BITS(dp);
dp++;
if ((dp = parse_sattr3(ndo, dp, &sa3)) == NULL)
break;
ND_PRINT((ndo, " %s", tok2str(type2str, "unk-ft %d", type)));
if (ndo->ndo_vflag && (type == NFCHR || type == NFBLK)) {
ND_TCHECK(dp[1]);
ND_PRINT((ndo, " %u/%u",
EXTRACT_32BITS(&dp[0]),
EXTRACT_32BITS(&dp[1])));
dp += 2;
}
if (ndo->ndo_vflag)
print_sattr3(ndo, &sa3, ndo->ndo_vflag);
return;
}
break;
case NFSPROC_RENAME:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefhn(ndo, dp, v3)) != NULL) {
ND_PRINT((ndo, " ->"));
if (parsefhn(ndo, dp, v3) != NULL)
return;
}
break;
case NFSPROC_LINK:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
ND_PRINT((ndo, " ->"));
if (parsefhn(ndo, dp, v3) != NULL)
return;
}
break;
case NFSPROC_READDIR:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
if (v3) {
ND_TCHECK(dp[4]);
/*
* We shouldn't really try to interpret the
* offset cookie here.
*/
ND_PRINT((ndo, " %u bytes @ %" PRId64,
EXTRACT_32BITS(&dp[4]),
EXTRACT_64BITS(&dp[0])));
if (ndo->ndo_vflag)
ND_PRINT((ndo, " verf %08x%08x", dp[2], dp[3]));
} else {
ND_TCHECK(dp[1]);
/*
* Print the offset as signed, since -1 is
* common, but offsets > 2^31 aren't.
*/
ND_PRINT((ndo, " %u bytes @ %d",
EXTRACT_32BITS(&dp[1]),
EXTRACT_32BITS(&dp[0])));
}
return;
}
break;
case NFSPROC_READDIRPLUS:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
ND_TCHECK(dp[4]);
/*
* We don't try to interpret the offset
* cookie here.
*/
ND_PRINT((ndo, " %u bytes @ %" PRId64,
EXTRACT_32BITS(&dp[4]),
EXTRACT_64BITS(&dp[0])));
if (ndo->ndo_vflag) {
ND_TCHECK(dp[5]);
ND_PRINT((ndo, " max %u verf %08x%08x",
EXTRACT_32BITS(&dp[5]), dp[2], dp[3]));
}
return;
}
break;
case NFSPROC_COMMIT:
if ((dp = parsereq(ndo, rp, length)) != NULL &&
(dp = parsefh(ndo, dp, v3)) != NULL) {
ND_TCHECK(dp[2]);
ND_PRINT((ndo, " %u bytes @ %" PRIu64,
EXTRACT_32BITS(&dp[2]),
EXTRACT_64BITS(&dp[0])));
return;
}
break;
default:
return;
}
trunc:
if (!nfserr)
ND_PRINT((ndo, "%s", tstr));
}
/*
* Print out an NFS file handle.
* We assume packet was not truncated before the end of the
* file handle pointed to by dp.
*
* Note: new version (using portable file-handle parser) doesn't produce
* generation number. It probably could be made to do that, with some
* additional hacking on the parser code.
*/
static void
nfs_printfh(netdissect_options *ndo,
register const uint32_t *dp, const u_int len)
{
my_fsid fsid;
uint32_t ino;
const char *sfsname = NULL;
char *spacep;
if (ndo->ndo_uflag) {
u_int i;
char const *sep = "";
ND_PRINT((ndo, " fh["));
for (i=0; i<len; i++) {
ND_PRINT((ndo, "%s%x", sep, dp[i]));
sep = ":";
}
ND_PRINT((ndo, "]"));
return;
}
Parse_fh((const u_char *)dp, len, &fsid, &ino, NULL, &sfsname, 0);
if (sfsname) {
/* file system ID is ASCII, not numeric, for this server OS */
char temp[NFSX_V3FHMAX+1];
u_int stringlen;
/* Make sure string is null-terminated */
stringlen = len;
if (stringlen > NFSX_V3FHMAX)
stringlen = NFSX_V3FHMAX;
strncpy(temp, sfsname, stringlen);
temp[stringlen] = '\0';
/* Remove trailing spaces */
spacep = strchr(temp, ' ');
if (spacep)
*spacep = '\0';
ND_PRINT((ndo, " fh %s/", temp));
} else {
ND_PRINT((ndo, " fh %d,%d/",
fsid.Fsid_dev.Major, fsid.Fsid_dev.Minor));
}
if(fsid.Fsid_dev.Minor == 257)
/* Print the undecoded handle */
ND_PRINT((ndo, "%s", fsid.Opaque_Handle));
else
ND_PRINT((ndo, "%ld", (long) ino));
}
/*
* Maintain a small cache of recent client.XID.server/proc pairs, to allow
* us to match up replies with requests and thus to know how to parse
* the reply.
*/
struct xid_map_entry {
uint32_t xid; /* transaction ID (net order) */
int ipver; /* IP version (4 or 6) */
struct in6_addr client; /* client IP address (net order) */
struct in6_addr server; /* server IP address (net order) */
uint32_t proc; /* call proc number (host order) */
uint32_t vers; /* program version (host order) */
};
/*
* Map entries are kept in an array that we manage as a ring;
* new entries are always added at the tail of the ring. Initially,
* all the entries are zero and hence don't match anything.
*/
#define XIDMAPSIZE 64
static struct xid_map_entry xid_map[XIDMAPSIZE];
static int xid_map_next = 0;
static int xid_map_hint = 0;
static int
xid_map_enter(netdissect_options *ndo,
const struct sunrpc_msg *rp, const u_char *bp)
{
const struct ip *ip = NULL;
const struct ip6_hdr *ip6 = NULL;
struct xid_map_entry *xmep;
if (!ND_TTEST(rp->rm_call.cb_vers))
return (0);
switch (IP_V((const struct ip *)bp)) {
case 4:
ip = (const struct ip *)bp;
break;
case 6:
ip6 = (const struct ip6_hdr *)bp;
break;
default:
return (1);
}
xmep = &xid_map[xid_map_next];
if (++xid_map_next >= XIDMAPSIZE)
xid_map_next = 0;
UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid));
if (ip) {
xmep->ipver = 4;
UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src));
UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst));
}
else if (ip6) {
xmep->ipver = 6;
UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src));
UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst));
}
xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc);
xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers);
return (1);
}
/*
* Returns 0 and puts NFSPROC_xxx in proc return and
* version in vers return, or returns -1 on failure
*/
static int
xid_map_find(const struct sunrpc_msg *rp, const u_char *bp, uint32_t *proc,
uint32_t *vers)
{
int i;
struct xid_map_entry *xmep;
uint32_t xid;
const struct ip *ip = (const struct ip *)bp;
const struct ip6_hdr *ip6 = (const struct ip6_hdr *)bp;
int cmp;
UNALIGNED_MEMCPY(&xid, &rp->rm_xid, sizeof(xmep->xid));
/* Start searching from where we last left off */
i = xid_map_hint;
do {
xmep = &xid_map[i];
cmp = 1;
if (xmep->ipver != IP_V(ip) || xmep->xid != xid)
goto nextitem;
switch (xmep->ipver) {
case 4:
if (UNALIGNED_MEMCMP(&ip->ip_src, &xmep->server,
sizeof(ip->ip_src)) != 0 ||
UNALIGNED_MEMCMP(&ip->ip_dst, &xmep->client,
sizeof(ip->ip_dst)) != 0) {
cmp = 0;
}
break;
case 6:
if (UNALIGNED_MEMCMP(&ip6->ip6_src, &xmep->server,
sizeof(ip6->ip6_src)) != 0 ||
UNALIGNED_MEMCMP(&ip6->ip6_dst, &xmep->client,
sizeof(ip6->ip6_dst)) != 0) {
cmp = 0;
}
break;
default:
cmp = 0;
break;
}
if (cmp) {
/* match */
xid_map_hint = i;
*proc = xmep->proc;
*vers = xmep->vers;
return 0;
}
nextitem:
if (++i >= XIDMAPSIZE)
i = 0;
} while (i != xid_map_hint);
/* search failed */
return (-1);
}
/*
* Routines for parsing reply packets
*/
/*
* Return a pointer to the beginning of the actual results.
* If the packet was truncated, return 0.
*/
static const uint32_t *
parserep(netdissect_options *ndo,
register const struct sunrpc_msg *rp, register u_int length)
{
register const uint32_t *dp;
u_int len;
enum sunrpc_accept_stat astat;
/*
* Portability note:
* Here we find the address of the ar_verf credentials.
* Originally, this calculation was
* dp = (uint32_t *)&rp->rm_reply.rp_acpt.ar_verf
* On the wire, the rp_acpt field starts immediately after
* the (32 bit) rp_stat field. However, rp_acpt (which is a
* "struct accepted_reply") contains a "struct opaque_auth",
* whose internal representation contains a pointer, so on a
* 64-bit machine the compiler inserts 32 bits of padding
* before rp->rm_reply.rp_acpt.ar_verf. So, we cannot use
* the internal representation to parse the on-the-wire
* representation. Instead, we skip past the rp_stat field,
* which is an "enum" and so occupies one 32-bit word.
*/
dp = ((const uint32_t *)&rp->rm_reply) + 1;
ND_TCHECK(dp[1]);
len = EXTRACT_32BITS(&dp[1]);
if (len >= length)
return (NULL);
/*
* skip past the ar_verf credentials.
*/
dp += (len + (2*sizeof(uint32_t) + 3)) / sizeof(uint32_t);
/*
* now we can check the ar_stat field
*/
ND_TCHECK(dp[0]);
astat = (enum sunrpc_accept_stat) EXTRACT_32BITS(dp);
if (astat != SUNRPC_SUCCESS) {
ND_PRINT((ndo, " %s", tok2str(sunrpc_str, "ar_stat %d", astat)));
nfserr = 1; /* suppress trunc string */
return (NULL);
}
/* successful return */
ND_TCHECK2(*dp, sizeof(astat));
return ((const uint32_t *) (sizeof(astat) + ((const char *)dp)));
trunc:
return (0);
}
static const uint32_t *
parsestatus(netdissect_options *ndo,
const uint32_t *dp, int *er)
{
int errnum;
ND_TCHECK(dp[0]);
errnum = EXTRACT_32BITS(&dp[0]);
if (er)
*er = errnum;
if (errnum != 0) {
if (!ndo->ndo_qflag)
ND_PRINT((ndo, " ERROR: %s",
tok2str(status2str, "unk %d", errnum)));
nfserr = 1;
}
return (dp + 1);
trunc:
return NULL;
}
static const uint32_t *
parsefattr(netdissect_options *ndo,
const uint32_t *dp, int verbose, int v3)
{
const struct nfs_fattr *fap;
fap = (const struct nfs_fattr *)dp;
ND_TCHECK(fap->fa_gid);
if (verbose) {
ND_PRINT((ndo, " %s %o ids %d/%d",
tok2str(type2str, "unk-ft %d ",
EXTRACT_32BITS(&fap->fa_type)),
EXTRACT_32BITS(&fap->fa_mode),
EXTRACT_32BITS(&fap->fa_uid),
EXTRACT_32BITS(&fap->fa_gid)));
if (v3) {
ND_TCHECK(fap->fa3_size);
ND_PRINT((ndo, " sz %" PRIu64,
EXTRACT_64BITS((const uint32_t *)&fap->fa3_size)));
} else {
ND_TCHECK(fap->fa2_size);
ND_PRINT((ndo, " sz %d", EXTRACT_32BITS(&fap->fa2_size)));
}
}
/* print lots more stuff */
if (verbose > 1) {
if (v3) {
ND_TCHECK(fap->fa3_ctime);
ND_PRINT((ndo, " nlink %d rdev %d/%d",
EXTRACT_32BITS(&fap->fa_nlink),
EXTRACT_32BITS(&fap->fa3_rdev.specdata1),
EXTRACT_32BITS(&fap->fa3_rdev.specdata2)));
ND_PRINT((ndo, " fsid %" PRIx64,
EXTRACT_64BITS((const uint32_t *)&fap->fa3_fsid)));
ND_PRINT((ndo, " fileid %" PRIx64,
EXTRACT_64BITS((const uint32_t *)&fap->fa3_fileid)));
ND_PRINT((ndo, " a/m/ctime %u.%06u",
EXTRACT_32BITS(&fap->fa3_atime.nfsv3_sec),
EXTRACT_32BITS(&fap->fa3_atime.nfsv3_nsec)));
ND_PRINT((ndo, " %u.%06u",
EXTRACT_32BITS(&fap->fa3_mtime.nfsv3_sec),
EXTRACT_32BITS(&fap->fa3_mtime.nfsv3_nsec)));
ND_PRINT((ndo, " %u.%06u",
EXTRACT_32BITS(&fap->fa3_ctime.nfsv3_sec),
EXTRACT_32BITS(&fap->fa3_ctime.nfsv3_nsec)));
} else {
ND_TCHECK(fap->fa2_ctime);
ND_PRINT((ndo, " nlink %d rdev 0x%x fsid 0x%x nodeid 0x%x a/m/ctime",
EXTRACT_32BITS(&fap->fa_nlink),
EXTRACT_32BITS(&fap->fa2_rdev),
EXTRACT_32BITS(&fap->fa2_fsid),
EXTRACT_32BITS(&fap->fa2_fileid)));
ND_PRINT((ndo, " %u.%06u",
EXTRACT_32BITS(&fap->fa2_atime.nfsv2_sec),
EXTRACT_32BITS(&fap->fa2_atime.nfsv2_usec)));
ND_PRINT((ndo, " %u.%06u",
EXTRACT_32BITS(&fap->fa2_mtime.nfsv2_sec),
EXTRACT_32BITS(&fap->fa2_mtime.nfsv2_usec)));
ND_PRINT((ndo, " %u.%06u",
EXTRACT_32BITS(&fap->fa2_ctime.nfsv2_sec),
EXTRACT_32BITS(&fap->fa2_ctime.nfsv2_usec)));
}
}
return ((const uint32_t *)((const unsigned char *)dp +
(v3 ? NFSX_V3FATTR : NFSX_V2FATTR)));
trunc:
return (NULL);
}
static int
parseattrstat(netdissect_options *ndo,
const uint32_t *dp, int verbose, int v3)
{
int er;
dp = parsestatus(ndo, dp, &er);
if (dp == NULL)
return (0);
if (er)
return (1);
return (parsefattr(ndo, dp, verbose, v3) != NULL);
}
static int
parsediropres(netdissect_options *ndo,
const uint32_t *dp)
{
int er;
if (!(dp = parsestatus(ndo, dp, &er)))
return (0);
if (er)
return (1);
dp = parsefh(ndo, dp, 0);
if (dp == NULL)
return (0);
return (parsefattr(ndo, dp, ndo->ndo_vflag, 0) != NULL);
}
static int
parselinkres(netdissect_options *ndo,
const uint32_t *dp, int v3)
{
int er;
dp = parsestatus(ndo, dp, &er);
if (dp == NULL)
return(0);
if (er)
return(1);
if (v3 && !(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
return (0);
ND_PRINT((ndo, " "));
return (parsefn(ndo, dp) != NULL);
}
static int
parsestatfs(netdissect_options *ndo,
const uint32_t *dp, int v3)
{
const struct nfs_statfs *sfsp;
int er;
dp = parsestatus(ndo, dp, &er);
if (dp == NULL)
return (0);
if (!v3 && er)
return (1);
if (ndo->ndo_qflag)
return(1);
if (v3) {
if (ndo->ndo_vflag)
ND_PRINT((ndo, " POST:"));
if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
return (0);
}
ND_TCHECK2(*dp, (v3 ? NFSX_V3STATFS : NFSX_V2STATFS));
sfsp = (const struct nfs_statfs *)dp;
if (v3) {
ND_PRINT((ndo, " tbytes %" PRIu64 " fbytes %" PRIu64 " abytes %" PRIu64,
EXTRACT_64BITS((const uint32_t *)&sfsp->sf_tbytes),
EXTRACT_64BITS((const uint32_t *)&sfsp->sf_fbytes),
EXTRACT_64BITS((const uint32_t *)&sfsp->sf_abytes)));
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " tfiles %" PRIu64 " ffiles %" PRIu64 " afiles %" PRIu64 " invar %u",
EXTRACT_64BITS((const uint32_t *)&sfsp->sf_tfiles),
EXTRACT_64BITS((const uint32_t *)&sfsp->sf_ffiles),
EXTRACT_64BITS((const uint32_t *)&sfsp->sf_afiles),
EXTRACT_32BITS(&sfsp->sf_invarsec)));
}
} else {
ND_PRINT((ndo, " tsize %d bsize %d blocks %d bfree %d bavail %d",
EXTRACT_32BITS(&sfsp->sf_tsize),
EXTRACT_32BITS(&sfsp->sf_bsize),
EXTRACT_32BITS(&sfsp->sf_blocks),
EXTRACT_32BITS(&sfsp->sf_bfree),
EXTRACT_32BITS(&sfsp->sf_bavail)));
}
return (1);
trunc:
return (0);
}
static int
parserddires(netdissect_options *ndo,
const uint32_t *dp)
{
int er;
dp = parsestatus(ndo, dp, &er);
if (dp == NULL)
return (0);
if (er)
return (1);
if (ndo->ndo_qflag)
return (1);
ND_TCHECK(dp[2]);
ND_PRINT((ndo, " offset 0x%x size %d ",
EXTRACT_32BITS(&dp[0]), EXTRACT_32BITS(&dp[1])));
if (dp[2] != 0)
ND_PRINT((ndo, " eof"));
return (1);
trunc:
return (0);
}
static const uint32_t *
parse_wcc_attr(netdissect_options *ndo,
const uint32_t *dp)
{
/* Our caller has already checked this */
ND_PRINT((ndo, " sz %" PRIu64, EXTRACT_64BITS(&dp[0])));
ND_PRINT((ndo, " mtime %u.%06u ctime %u.%06u",
EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[3]),
EXTRACT_32BITS(&dp[4]), EXTRACT_32BITS(&dp[5])));
return (dp + 6);
}
/*
* Pre operation attributes. Print only if vflag > 1.
*/
static const uint32_t *
parse_pre_op_attr(netdissect_options *ndo,
const uint32_t *dp, int verbose)
{
ND_TCHECK(dp[0]);
if (!EXTRACT_32BITS(&dp[0]))
return (dp + 1);
dp++;
ND_TCHECK2(*dp, 24);
if (verbose > 1) {
return parse_wcc_attr(ndo, dp);
} else {
/* If not verbose enough, just skip over wcc_attr */
return (dp + 6);
}
trunc:
return (NULL);
}
/*
* Post operation attributes are printed if vflag >= 1
*/
static const uint32_t *
parse_post_op_attr(netdissect_options *ndo,
const uint32_t *dp, int verbose)
{
ND_TCHECK(dp[0]);
if (!EXTRACT_32BITS(&dp[0]))
return (dp + 1);
dp++;
if (verbose) {
return parsefattr(ndo, dp, verbose, 1);
} else
return (dp + (NFSX_V3FATTR / sizeof (uint32_t)));
trunc:
return (NULL);
}
static const uint32_t *
parse_wcc_data(netdissect_options *ndo,
const uint32_t *dp, int verbose)
{
if (verbose > 1)
ND_PRINT((ndo, " PRE:"));
if (!(dp = parse_pre_op_attr(ndo, dp, verbose)))
return (0);
if (verbose)
ND_PRINT((ndo, " POST:"));
return parse_post_op_attr(ndo, dp, verbose);
}
static const uint32_t *
parsecreateopres(netdissect_options *ndo,
const uint32_t *dp, int verbose)
{
int er;
if (!(dp = parsestatus(ndo, dp, &er)))
return (0);
if (er)
dp = parse_wcc_data(ndo, dp, verbose);
else {
ND_TCHECK(dp[0]);
if (!EXTRACT_32BITS(&dp[0]))
return (dp + 1);
dp++;
if (!(dp = parsefh(ndo, dp, 1)))
return (0);
if (verbose) {
if (!(dp = parse_post_op_attr(ndo, dp, verbose)))
return (0);
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " dir attr:"));
dp = parse_wcc_data(ndo, dp, verbose);
}
}
}
return (dp);
trunc:
return (NULL);
}
static int
parsewccres(netdissect_options *ndo,
const uint32_t *dp, int verbose)
{
int er;
if (!(dp = parsestatus(ndo, dp, &er)))
return (0);
return parse_wcc_data(ndo, dp, verbose) != NULL;
}
static const uint32_t *
parsev3rddirres(netdissect_options *ndo,
const uint32_t *dp, int verbose)
{
int er;
if (!(dp = parsestatus(ndo, dp, &er)))
return (0);
if (ndo->ndo_vflag)
ND_PRINT((ndo, " POST:"));
if (!(dp = parse_post_op_attr(ndo, dp, verbose)))
return (0);
if (er)
return dp;
if (ndo->ndo_vflag) {
ND_TCHECK(dp[1]);
ND_PRINT((ndo, " verf %08x%08x", dp[0], dp[1]));
dp += 2;
}
return dp;
trunc:
return (NULL);
}
static int
parsefsinfo(netdissect_options *ndo,
const uint32_t *dp)
{
const struct nfsv3_fsinfo *sfp;
int er;
if (!(dp = parsestatus(ndo, dp, &er)))
return (0);
if (ndo->ndo_vflag)
ND_PRINT((ndo, " POST:"));
if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
return (0);
if (er)
return (1);
sfp = (const struct nfsv3_fsinfo *)dp;
ND_TCHECK(*sfp);
ND_PRINT((ndo, " rtmax %u rtpref %u wtmax %u wtpref %u dtpref %u",
EXTRACT_32BITS(&sfp->fs_rtmax),
EXTRACT_32BITS(&sfp->fs_rtpref),
EXTRACT_32BITS(&sfp->fs_wtmax),
EXTRACT_32BITS(&sfp->fs_wtpref),
EXTRACT_32BITS(&sfp->fs_dtpref)));
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " rtmult %u wtmult %u maxfsz %" PRIu64,
EXTRACT_32BITS(&sfp->fs_rtmult),
EXTRACT_32BITS(&sfp->fs_wtmult),
EXTRACT_64BITS((const uint32_t *)&sfp->fs_maxfilesize)));
ND_PRINT((ndo, " delta %u.%06u ",
EXTRACT_32BITS(&sfp->fs_timedelta.nfsv3_sec),
EXTRACT_32BITS(&sfp->fs_timedelta.nfsv3_nsec)));
}
return (1);
trunc:
return (0);
}
static int
parsepathconf(netdissect_options *ndo,
const uint32_t *dp)
{
int er;
const struct nfsv3_pathconf *spp;
if (!(dp = parsestatus(ndo, dp, &er)))
return (0);
if (ndo->ndo_vflag)
ND_PRINT((ndo, " POST:"));
if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
return (0);
if (er)
return (1);
spp = (const struct nfsv3_pathconf *)dp;
ND_TCHECK(*spp);
ND_PRINT((ndo, " linkmax %u namemax %u %s %s %s %s",
EXTRACT_32BITS(&spp->pc_linkmax),
EXTRACT_32BITS(&spp->pc_namemax),
EXTRACT_32BITS(&spp->pc_notrunc) ? "notrunc" : "",
EXTRACT_32BITS(&spp->pc_chownrestricted) ? "chownres" : "",
EXTRACT_32BITS(&spp->pc_caseinsensitive) ? "igncase" : "",
EXTRACT_32BITS(&spp->pc_casepreserving) ? "keepcase" : ""));
return (1);
trunc:
return (0);
}
static void
interp_reply(netdissect_options *ndo,
const struct sunrpc_msg *rp, uint32_t proc, uint32_t vers, int length)
{
register const uint32_t *dp;
register int v3;
int er;
v3 = (vers == NFS_VER3);
if (!v3 && proc < NFS_NPROCS)
proc = nfsv3_procid[proc];
ND_PRINT((ndo, " %s", tok2str(nfsproc_str, "proc-%u", proc)));
switch (proc) {
case NFSPROC_GETATTR:
dp = parserep(ndo, rp, length);
if (dp != NULL && parseattrstat(ndo, dp, !ndo->ndo_qflag, v3) != 0)
return;
break;
case NFSPROC_SETATTR:
if (!(dp = parserep(ndo, rp, length)))
return;
if (v3) {
if (parsewccres(ndo, dp, ndo->ndo_vflag))
return;
} else {
if (parseattrstat(ndo, dp, !ndo->ndo_qflag, 0) != 0)
return;
}
break;
case NFSPROC_LOOKUP:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (er) {
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " post dattr:"));
dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag);
}
} else {
if (!(dp = parsefh(ndo, dp, v3)))
break;
if ((dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)) &&
ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " post dattr:"));
dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag);
}
}
if (dp)
return;
} else {
if (parsediropres(ndo, dp) != 0)
return;
}
break;
case NFSPROC_ACCESS:
if (!(dp = parserep(ndo, rp, length)))
break;
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (ndo->ndo_vflag)
ND_PRINT((ndo, " attr:"));
if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
break;
if (!er) {
ND_TCHECK(dp[0]);
ND_PRINT((ndo, " c %04x", EXTRACT_32BITS(&dp[0])));
}
return;
case NFSPROC_READLINK:
dp = parserep(ndo, rp, length);
if (dp != NULL && parselinkres(ndo, dp, v3) != 0)
return;
break;
case NFSPROC_READ:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
break;
if (er)
return;
if (ndo->ndo_vflag) {
ND_TCHECK(dp[1]);
ND_PRINT((ndo, " %u bytes", EXTRACT_32BITS(&dp[0])));
if (EXTRACT_32BITS(&dp[1]))
ND_PRINT((ndo, " EOF"));
}
return;
} else {
if (parseattrstat(ndo, dp, ndo->ndo_vflag, 0) != 0)
return;
}
break;
case NFSPROC_WRITE:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag)))
break;
if (er)
return;
if (ndo->ndo_vflag) {
ND_TCHECK(dp[0]);
ND_PRINT((ndo, " %u bytes", EXTRACT_32BITS(&dp[0])));
if (ndo->ndo_vflag > 1) {
ND_TCHECK(dp[1]);
ND_PRINT((ndo, " <%s>",
tok2str(nfsv3_writemodes,
NULL, EXTRACT_32BITS(&dp[1]))));
}
return;
}
} else {
if (parseattrstat(ndo, dp, ndo->ndo_vflag, v3) != 0)
return;
}
break;
case NFSPROC_CREATE:
case NFSPROC_MKDIR:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL)
return;
} else {
if (parsediropres(ndo, dp) != 0)
return;
}
break;
case NFSPROC_SYMLINK:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL)
return;
} else {
if (parsestatus(ndo, dp, &er) != NULL)
return;
}
break;
case NFSPROC_MKNOD:
if (!(dp = parserep(ndo, rp, length)))
break;
if (parsecreateopres(ndo, dp, ndo->ndo_vflag) != NULL)
return;
break;
case NFSPROC_REMOVE:
case NFSPROC_RMDIR:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (parsewccres(ndo, dp, ndo->ndo_vflag))
return;
} else {
if (parsestatus(ndo, dp, &er) != NULL)
return;
}
break;
case NFSPROC_RENAME:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " from:"));
if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag)))
break;
ND_PRINT((ndo, " to:"));
if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag)))
break;
}
return;
} else {
if (parsestatus(ndo, dp, &er) != NULL)
return;
}
break;
case NFSPROC_LINK:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (!(dp = parsestatus(ndo, dp, &er)))
break;
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " file POST:"));
if (!(dp = parse_post_op_attr(ndo, dp, ndo->ndo_vflag)))
break;
ND_PRINT((ndo, " dir:"));
if (!(dp = parse_wcc_data(ndo, dp, ndo->ndo_vflag)))
break;
return;
}
} else {
if (parsestatus(ndo, dp, &er) != NULL)
return;
}
break;
case NFSPROC_READDIR:
if (!(dp = parserep(ndo, rp, length)))
break;
if (v3) {
if (parsev3rddirres(ndo, dp, ndo->ndo_vflag))
return;
} else {
if (parserddires(ndo, dp) != 0)
return;
}
break;
case NFSPROC_READDIRPLUS:
if (!(dp = parserep(ndo, rp, length)))
break;
if (parsev3rddirres(ndo, dp, ndo->ndo_vflag))
return;
break;
case NFSPROC_FSSTAT:
dp = parserep(ndo, rp, length);
if (dp != NULL && parsestatfs(ndo, dp, v3) != 0)
return;
break;
case NFSPROC_FSINFO:
dp = parserep(ndo, rp, length);
if (dp != NULL && parsefsinfo(ndo, dp) != 0)
return;
break;
case NFSPROC_PATHCONF:
dp = parserep(ndo, rp, length);
if (dp != NULL && parsepathconf(ndo, dp) != 0)
return;
break;
case NFSPROC_COMMIT:
dp = parserep(ndo, rp, length);
if (dp != NULL && parsewccres(ndo, dp, ndo->ndo_vflag) != 0)
return;
break;
default:
return;
}
trunc:
if (!nfserr)
ND_PRINT((ndo, "%s", tstr));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2676_0 |
crossvul-cpp_data_bad_267_0 | /*
* Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
* 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 project 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 PROJECT 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 PROJECT 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.
*
*/
/* \summary: Internet Security Association and Key Management Protocol (ISAKMP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* The functions from print-esp.c used in this file are only defined when both
* OpenSSL and evp.h are detected. Employ the same preprocessor device here.
*/
#ifndef HAVE_OPENSSL_EVP_H
#undef HAVE_LIBCRYPTO
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ip.h"
#include "ip6.h"
#include "ipproto.h"
/* refer to RFC 2408 */
typedef u_char cookie_t[8];
typedef u_char msgid_t[4];
#define PORT_ISAKMP 500
/* 3.1 ISAKMP Header Format (IKEv1 and IKEv2)
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Initiator !
! Cookie !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Responder !
! Cookie !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Next Payload ! MjVer ! MnVer ! Exchange Type ! Flags !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Message ID !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Length !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct isakmp {
cookie_t i_ck; /* Initiator Cookie */
cookie_t r_ck; /* Responder Cookie */
uint8_t np; /* Next Payload Type */
uint8_t vers;
#define ISAKMP_VERS_MAJOR 0xf0
#define ISAKMP_VERS_MAJOR_SHIFT 4
#define ISAKMP_VERS_MINOR 0x0f
#define ISAKMP_VERS_MINOR_SHIFT 0
uint8_t etype; /* Exchange Type */
uint8_t flags; /* Flags */
msgid_t msgid;
uint32_t len; /* Length */
};
/* Next Payload Type */
#define ISAKMP_NPTYPE_NONE 0 /* NONE*/
#define ISAKMP_NPTYPE_SA 1 /* Security Association */
#define ISAKMP_NPTYPE_P 2 /* Proposal */
#define ISAKMP_NPTYPE_T 3 /* Transform */
#define ISAKMP_NPTYPE_KE 4 /* Key Exchange */
#define ISAKMP_NPTYPE_ID 5 /* Identification */
#define ISAKMP_NPTYPE_CERT 6 /* Certificate */
#define ISAKMP_NPTYPE_CR 7 /* Certificate Request */
#define ISAKMP_NPTYPE_HASH 8 /* Hash */
#define ISAKMP_NPTYPE_SIG 9 /* Signature */
#define ISAKMP_NPTYPE_NONCE 10 /* Nonce */
#define ISAKMP_NPTYPE_N 11 /* Notification */
#define ISAKMP_NPTYPE_D 12 /* Delete */
#define ISAKMP_NPTYPE_VID 13 /* Vendor ID */
#define ISAKMP_NPTYPE_v2E 46 /* v2 Encrypted payload */
#define IKEv1_MAJOR_VERSION 1
#define IKEv1_MINOR_VERSION 0
#define IKEv2_MAJOR_VERSION 2
#define IKEv2_MINOR_VERSION 0
/* Flags */
#define ISAKMP_FLAG_E 0x01 /* Encryption Bit */
#define ISAKMP_FLAG_C 0x02 /* Commit Bit */
#define ISAKMP_FLAG_extra 0x04
/* IKEv2 */
#define ISAKMP_FLAG_I (1 << 3) /* (I)nitiator */
#define ISAKMP_FLAG_V (1 << 4) /* (V)ersion */
#define ISAKMP_FLAG_R (1 << 5) /* (R)esponse */
/* 3.2 Payload Generic Header
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
! Next Payload ! RESERVED ! Payload Length !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct isakmp_gen {
uint8_t np; /* Next Payload */
uint8_t critical; /* bit 7 - critical, rest is RESERVED */
uint16_t len; /* Payload Length */
};
/* 3.3 Data Attributes
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
!A! Attribute Type ! AF=0 Attribute Length !
!F! ! AF=1 Attribute Value !
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
. AF=0 Attribute Value .
. AF=1 Not Transmitted .
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct isakmp_data {
uint16_t type; /* defined by DOI-spec, and Attribute Format */
uint16_t lorv; /* if f equal 1, Attribute Length */
/* if f equal 0, Attribute Value */
/* if f equal 1, Attribute Value */
};
/* 3.4 Security Association Payload */
/* MAY NOT be used, because of being defined in ipsec-doi. */
/*
If the current payload is the last in the message,
then the value of the next payload field will be 0.
This field MUST NOT contain the
values for the Proposal or Transform payloads as they are considered
part of the security association negotiation. For example, this
field would contain the value "10" (Nonce payload) in the first
message of a Base Exchange (see Section 4.4) and the value "0" in the
first message of an Identity Protect Exchange (see Section 4.5).
*/
struct ikev1_pl_sa {
struct isakmp_gen h;
uint32_t doi; /* Domain of Interpretation */
uint32_t sit; /* Situation */
};
/* 3.5 Proposal Payload */
/*
The value of the next payload field MUST only contain the value "2"
or "0". If there are additional Proposal payloads in the message,
then this field will be 2. If the current Proposal payload is the
last within the security association proposal, then this field will
be 0.
*/
struct ikev1_pl_p {
struct isakmp_gen h;
uint8_t p_no; /* Proposal # */
uint8_t prot_id; /* Protocol */
uint8_t spi_size; /* SPI Size */
uint8_t num_t; /* Number of Transforms */
/* SPI */
};
/* 3.6 Transform Payload */
/*
The value of the next payload field MUST only contain the value "3"
or "0". If there are additional Transform payloads in the proposal,
then this field will be 3. If the current Transform payload is the
last within the proposal, then this field will be 0.
*/
struct ikev1_pl_t {
struct isakmp_gen h;
uint8_t t_no; /* Transform # */
uint8_t t_id; /* Transform-Id */
uint16_t reserved; /* RESERVED2 */
/* SA Attributes */
};
/* 3.7 Key Exchange Payload */
struct ikev1_pl_ke {
struct isakmp_gen h;
/* Key Exchange Data */
};
/* 3.8 Identification Payload */
/* MUST NOT to be used, because of being defined in ipsec-doi. */
struct ikev1_pl_id {
struct isakmp_gen h;
union {
uint8_t id_type; /* ID Type */
uint32_t doi_data; /* DOI Specific ID Data */
} d;
/* Identification Data */
};
/* 3.9 Certificate Payload */
struct ikev1_pl_cert {
struct isakmp_gen h;
uint8_t encode; /* Cert Encoding */
char cert; /* Certificate Data */
/*
This field indicates the type of
certificate or certificate-related information contained in the
Certificate Data field.
*/
};
/* 3.10 Certificate Request Payload */
struct ikev1_pl_cr {
struct isakmp_gen h;
uint8_t num_cert; /* # Cert. Types */
/*
Certificate Types (variable length)
-- Contains a list of the types of certificates requested,
sorted in order of preference. Each individual certificate
type is 1 octet. This field is NOT requiredo
*/
/* # Certificate Authorities (1 octet) */
/* Certificate Authorities (variable length) */
};
/* 3.11 Hash Payload */
/* may not be used, because of having only data. */
struct ikev1_pl_hash {
struct isakmp_gen h;
/* Hash Data */
};
/* 3.12 Signature Payload */
/* may not be used, because of having only data. */
struct ikev1_pl_sig {
struct isakmp_gen h;
/* Signature Data */
};
/* 3.13 Nonce Payload */
/* may not be used, because of having only data. */
struct ikev1_pl_nonce {
struct isakmp_gen h;
/* Nonce Data */
};
/* 3.14 Notification Payload */
struct ikev1_pl_n {
struct isakmp_gen h;
uint32_t doi; /* Domain of Interpretation */
uint8_t prot_id; /* Protocol-ID */
uint8_t spi_size; /* SPI Size */
uint16_t type; /* Notify Message Type */
/* SPI */
/* Notification Data */
};
/* 3.14.1 Notify Message Types */
/* NOTIFY MESSAGES - ERROR TYPES */
#define ISAKMP_NTYPE_INVALID_PAYLOAD_TYPE 1
#define ISAKMP_NTYPE_DOI_NOT_SUPPORTED 2
#define ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED 3
#define ISAKMP_NTYPE_INVALID_COOKIE 4
#define ISAKMP_NTYPE_INVALID_MAJOR_VERSION 5
#define ISAKMP_NTYPE_INVALID_MINOR_VERSION 6
#define ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE 7
#define ISAKMP_NTYPE_INVALID_FLAGS 8
#define ISAKMP_NTYPE_INVALID_MESSAGE_ID 9
#define ISAKMP_NTYPE_INVALID_PROTOCOL_ID 10
#define ISAKMP_NTYPE_INVALID_SPI 11
#define ISAKMP_NTYPE_INVALID_TRANSFORM_ID 12
#define ISAKMP_NTYPE_ATTRIBUTES_NOT_SUPPORTED 13
#define ISAKMP_NTYPE_NO_PROPOSAL_CHOSEN 14
#define ISAKMP_NTYPE_BAD_PROPOSAL_SYNTAX 15
#define ISAKMP_NTYPE_PAYLOAD_MALFORMED 16
#define ISAKMP_NTYPE_INVALID_KEY_INFORMATION 17
#define ISAKMP_NTYPE_INVALID_ID_INFORMATION 18
#define ISAKMP_NTYPE_INVALID_CERT_ENCODING 19
#define ISAKMP_NTYPE_INVALID_CERTIFICATE 20
#define ISAKMP_NTYPE_BAD_CERT_REQUEST_SYNTAX 21
#define ISAKMP_NTYPE_INVALID_CERT_AUTHORITY 22
#define ISAKMP_NTYPE_INVALID_HASH_INFORMATION 23
#define ISAKMP_NTYPE_AUTHENTICATION_FAILED 24
#define ISAKMP_NTYPE_INVALID_SIGNATURE 25
#define ISAKMP_NTYPE_ADDRESS_NOTIFICATION 26
/* 3.15 Delete Payload */
struct ikev1_pl_d {
struct isakmp_gen h;
uint32_t doi; /* Domain of Interpretation */
uint8_t prot_id; /* Protocol-Id */
uint8_t spi_size; /* SPI Size */
uint16_t num_spi; /* # of SPIs */
/* SPI(es) */
};
struct ikev1_ph1tab {
struct ikev1_ph1 *head;
struct ikev1_ph1 *tail;
int len;
};
struct isakmp_ph2tab {
struct ikev1_ph2 *head;
struct ikev1_ph2 *tail;
int len;
};
/* IKEv2 (RFC4306) */
/* 3.3 Security Association Payload -- generic header */
/* 3.3.1. Proposal Substructure */
struct ikev2_p {
struct isakmp_gen h;
uint8_t p_no; /* Proposal # */
uint8_t prot_id; /* Protocol */
uint8_t spi_size; /* SPI Size */
uint8_t num_t; /* Number of Transforms */
};
/* 3.3.2. Transform Substructure */
struct ikev2_t {
struct isakmp_gen h;
uint8_t t_type; /* Transform Type (ENCR,PRF,INTEG,etc.*/
uint8_t res2; /* reserved byte */
uint16_t t_id; /* Transform ID */
};
enum ikev2_t_type {
IV2_T_ENCR = 1,
IV2_T_PRF = 2,
IV2_T_INTEG= 3,
IV2_T_DH = 4,
IV2_T_ESN = 5
};
/* 3.4. Key Exchange Payload */
struct ikev2_ke {
struct isakmp_gen h;
uint16_t ke_group;
uint16_t ke_res1;
/* KE data */
};
/* 3.5. Identification Payloads */
enum ikev2_id_type {
ID_IPV4_ADDR=1,
ID_FQDN=2,
ID_RFC822_ADDR=3,
ID_IPV6_ADDR=5,
ID_DER_ASN1_DN=9,
ID_DER_ASN1_GN=10,
ID_KEY_ID=11
};
struct ikev2_id {
struct isakmp_gen h;
uint8_t type; /* ID type */
uint8_t res1;
uint16_t res2;
/* SPI */
/* Notification Data */
};
/* 3.10 Notification Payload */
struct ikev2_n {
struct isakmp_gen h;
uint8_t prot_id; /* Protocol-ID */
uint8_t spi_size; /* SPI Size */
uint16_t type; /* Notify Message Type */
};
enum ikev2_n_type {
IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD = 1,
IV2_NOTIFY_INVALID_IKE_SPI = 4,
IV2_NOTIFY_INVALID_MAJOR_VERSION = 5,
IV2_NOTIFY_INVALID_SYNTAX = 7,
IV2_NOTIFY_INVALID_MESSAGE_ID = 9,
IV2_NOTIFY_INVALID_SPI =11,
IV2_NOTIFY_NO_PROPOSAL_CHOSEN =14,
IV2_NOTIFY_INVALID_KE_PAYLOAD =17,
IV2_NOTIFY_AUTHENTICATION_FAILED =24,
IV2_NOTIFY_SINGLE_PAIR_REQUIRED =34,
IV2_NOTIFY_NO_ADDITIONAL_SAS =35,
IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE =36,
IV2_NOTIFY_FAILED_CP_REQUIRED =37,
IV2_NOTIFY_INVALID_SELECTORS =39,
IV2_NOTIFY_INITIAL_CONTACT =16384,
IV2_NOTIFY_SET_WINDOW_SIZE =16385,
IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE =16386,
IV2_NOTIFY_IPCOMP_SUPPORTED =16387,
IV2_NOTIFY_NAT_DETECTION_SOURCE_IP =16388,
IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP =16389,
IV2_NOTIFY_COOKIE =16390,
IV2_NOTIFY_USE_TRANSPORT_MODE =16391,
IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED =16392,
IV2_NOTIFY_REKEY_SA =16393,
IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED =16394,
IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO =16395
};
struct notify_messages {
uint16_t type;
char *msg;
};
/* 3.8 Authentication Payload */
struct ikev2_auth {
struct isakmp_gen h;
uint8_t auth_method; /* Protocol-ID */
uint8_t reserved[3];
/* authentication data */
};
enum ikev2_auth_type {
IV2_RSA_SIG = 1,
IV2_SHARED = 2,
IV2_DSS_SIG = 3
};
/* refer to RFC 2409 */
#if 0
/* isakmp sa structure */
struct oakley_sa {
uint8_t proto_id; /* OAKLEY */
vchar_t *spi; /* spi */
uint8_t dhgrp; /* DH; group */
uint8_t auth_t; /* method of authentication */
uint8_t prf_t; /* type of prf */
uint8_t hash_t; /* type of hash */
uint8_t enc_t; /* type of cipher */
uint8_t life_t; /* type of duration of lifetime */
uint32_t ldur; /* life duration */
};
#endif
/* refer to RFC 2407 */
#define IPSEC_DOI 1
/* 4.2 IPSEC Situation Definition */
#define IPSECDOI_SIT_IDENTITY_ONLY 0x00000001
#define IPSECDOI_SIT_SECRECY 0x00000002
#define IPSECDOI_SIT_INTEGRITY 0x00000004
/* 4.4.1 IPSEC Security Protocol Identifiers */
/* 4.4.2 IPSEC ISAKMP Transform Values */
#define IPSECDOI_PROTO_ISAKMP 1
#define IPSECDOI_KEY_IKE 1
/* 4.4.1 IPSEC Security Protocol Identifiers */
#define IPSECDOI_PROTO_IPSEC_AH 2
/* 4.4.3 IPSEC AH Transform Values */
#define IPSECDOI_AH_MD5 2
#define IPSECDOI_AH_SHA 3
#define IPSECDOI_AH_DES 4
#define IPSECDOI_AH_SHA2_256 5
#define IPSECDOI_AH_SHA2_384 6
#define IPSECDOI_AH_SHA2_512 7
/* 4.4.1 IPSEC Security Protocol Identifiers */
#define IPSECDOI_PROTO_IPSEC_ESP 3
/* 4.4.4 IPSEC ESP Transform Identifiers */
#define IPSECDOI_ESP_DES_IV64 1
#define IPSECDOI_ESP_DES 2
#define IPSECDOI_ESP_3DES 3
#define IPSECDOI_ESP_RC5 4
#define IPSECDOI_ESP_IDEA 5
#define IPSECDOI_ESP_CAST 6
#define IPSECDOI_ESP_BLOWFISH 7
#define IPSECDOI_ESP_3IDEA 8
#define IPSECDOI_ESP_DES_IV32 9
#define IPSECDOI_ESP_RC4 10
#define IPSECDOI_ESP_NULL 11
#define IPSECDOI_ESP_RIJNDAEL 12
#define IPSECDOI_ESP_AES 12
/* 4.4.1 IPSEC Security Protocol Identifiers */
#define IPSECDOI_PROTO_IPCOMP 4
/* 4.4.5 IPSEC IPCOMP Transform Identifiers */
#define IPSECDOI_IPCOMP_OUI 1
#define IPSECDOI_IPCOMP_DEFLATE 2
#define IPSECDOI_IPCOMP_LZS 3
/* 4.5 IPSEC Security Association Attributes */
#define IPSECDOI_ATTR_SA_LTYPE 1 /* B */
#define IPSECDOI_ATTR_SA_LTYPE_DEFAULT 1
#define IPSECDOI_ATTR_SA_LTYPE_SEC 1
#define IPSECDOI_ATTR_SA_LTYPE_KB 2
#define IPSECDOI_ATTR_SA_LDUR 2 /* V */
#define IPSECDOI_ATTR_SA_LDUR_DEFAULT 28800 /* 8 hours */
#define IPSECDOI_ATTR_GRP_DESC 3 /* B */
#define IPSECDOI_ATTR_ENC_MODE 4 /* B */
/* default value: host dependent */
#define IPSECDOI_ATTR_ENC_MODE_TUNNEL 1
#define IPSECDOI_ATTR_ENC_MODE_TRNS 2
#define IPSECDOI_ATTR_AUTH 5 /* B */
/* 0 means not to use authentication. */
#define IPSECDOI_ATTR_AUTH_HMAC_MD5 1
#define IPSECDOI_ATTR_AUTH_HMAC_SHA1 2
#define IPSECDOI_ATTR_AUTH_DES_MAC 3
#define IPSECDOI_ATTR_AUTH_KPDK 4 /*RFC-1826(Key/Pad/Data/Key)*/
/*
* When negotiating ESP without authentication, the Auth
* Algorithm attribute MUST NOT be included in the proposal.
* When negotiating ESP without confidentiality, the Auth
* Algorithm attribute MUST be included in the proposal and
* the ESP transform ID must be ESP_NULL.
*/
#define IPSECDOI_ATTR_KEY_LENGTH 6 /* B */
#define IPSECDOI_ATTR_KEY_ROUNDS 7 /* B */
#define IPSECDOI_ATTR_COMP_DICT_SIZE 8 /* B */
#define IPSECDOI_ATTR_COMP_PRIVALG 9 /* V */
/* 4.6.1 Security Association Payload */
struct ipsecdoi_sa {
struct isakmp_gen h;
uint32_t doi; /* Domain of Interpretation */
uint32_t sit; /* Situation */
};
struct ipsecdoi_secrecy_h {
uint16_t len;
uint16_t reserved;
};
/* 4.6.2.1 Identification Type Values */
struct ipsecdoi_id {
struct isakmp_gen h;
uint8_t type; /* ID Type */
uint8_t proto_id; /* Protocol ID */
uint16_t port; /* Port */
/* Identification Data */
};
#define IPSECDOI_ID_IPV4_ADDR 1
#define IPSECDOI_ID_FQDN 2
#define IPSECDOI_ID_USER_FQDN 3
#define IPSECDOI_ID_IPV4_ADDR_SUBNET 4
#define IPSECDOI_ID_IPV6_ADDR 5
#define IPSECDOI_ID_IPV6_ADDR_SUBNET 6
#define IPSECDOI_ID_IPV4_ADDR_RANGE 7
#define IPSECDOI_ID_IPV6_ADDR_RANGE 8
#define IPSECDOI_ID_DER_ASN1_DN 9
#define IPSECDOI_ID_DER_ASN1_GN 10
#define IPSECDOI_ID_KEY_ID 11
/* 4.6.3 IPSEC DOI Notify Message Types */
/* Notify Messages - Status Types */
#define IPSECDOI_NTYPE_RESPONDER_LIFETIME 24576
#define IPSECDOI_NTYPE_REPLAY_STATUS 24577
#define IPSECDOI_NTYPE_INITIAL_CONTACT 24578
#define DECLARE_PRINTER(func) static const u_char *ike##func##_print( \
netdissect_options *ndo, u_char tpay, \
const struct isakmp_gen *ext, \
u_int item_len, \
const u_char *end_pointer, \
uint32_t phase,\
uint32_t doi0, \
uint32_t proto0, int depth)
DECLARE_PRINTER(v1_sa);
DECLARE_PRINTER(v1_p);
DECLARE_PRINTER(v1_t);
DECLARE_PRINTER(v1_ke);
DECLARE_PRINTER(v1_id);
DECLARE_PRINTER(v1_cert);
DECLARE_PRINTER(v1_cr);
DECLARE_PRINTER(v1_sig);
DECLARE_PRINTER(v1_hash);
DECLARE_PRINTER(v1_nonce);
DECLARE_PRINTER(v1_n);
DECLARE_PRINTER(v1_d);
DECLARE_PRINTER(v1_vid);
DECLARE_PRINTER(v2_sa);
DECLARE_PRINTER(v2_ke);
DECLARE_PRINTER(v2_ID);
DECLARE_PRINTER(v2_cert);
DECLARE_PRINTER(v2_cr);
DECLARE_PRINTER(v2_auth);
DECLARE_PRINTER(v2_nonce);
DECLARE_PRINTER(v2_n);
DECLARE_PRINTER(v2_d);
DECLARE_PRINTER(v2_vid);
DECLARE_PRINTER(v2_TS);
DECLARE_PRINTER(v2_cp);
DECLARE_PRINTER(v2_eap);
static const u_char *ikev2_e_print(netdissect_options *ndo,
struct isakmp *base,
u_char tpay,
const struct isakmp_gen *ext,
u_int item_len,
const u_char *end_pointer,
uint32_t phase,
uint32_t doi0,
uint32_t proto0, int depth);
static const u_char *ike_sub0_print(netdissect_options *ndo,u_char, const struct isakmp_gen *,
const u_char *, uint32_t, uint32_t, uint32_t, int);
static const u_char *ikev1_sub_print(netdissect_options *ndo,u_char, const struct isakmp_gen *,
const u_char *, uint32_t, uint32_t, uint32_t, int);
static const u_char *ikev2_sub_print(netdissect_options *ndo,
struct isakmp *base,
u_char np, const struct isakmp_gen *ext,
const u_char *ep, uint32_t phase,
uint32_t doi, uint32_t proto,
int depth);
static char *numstr(int);
static void
ikev1_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2, struct isakmp *base);
#define MAXINITIATORS 20
static int ninitiator = 0;
union inaddr_u {
struct in_addr in4;
struct in6_addr in6;
};
static struct {
cookie_t initiator;
u_int version;
union inaddr_u iaddr;
union inaddr_u raddr;
} cookiecache[MAXINITIATORS];
/* protocol id */
static const char *protoidstr[] = {
NULL, "isakmp", "ipsec-ah", "ipsec-esp", "ipcomp",
};
/* isakmp->np */
static const char *npstr[] = {
"none", "sa", "p", "t", "ke", "id", "cert", "cr", "hash", /* 0 - 8 */
"sig", "nonce", "n", "d", "vid", /* 9 - 13 */
"pay14", "pay15", "pay16", "pay17", "pay18", /* 14- 18 */
"pay19", "pay20", "pay21", "pay22", "pay23", /* 19- 23 */
"pay24", "pay25", "pay26", "pay27", "pay28", /* 24- 28 */
"pay29", "pay30", "pay31", "pay32", /* 29- 32 */
"v2sa", "v2ke", "v2IDi", "v2IDr", "v2cert",/* 33- 37 */
"v2cr", "v2auth","v2nonce", "v2n", "v2d", /* 38- 42 */
"v2vid", "v2TSi", "v2TSr", "v2e", "v2cp", /* 43- 47 */
"v2eap", /* 48 */
};
/* isakmp->np */
static const u_char *(*npfunc[])(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len,
const u_char *end_pointer,
uint32_t phase,
uint32_t doi0,
uint32_t proto0, int depth) = {
NULL,
ikev1_sa_print,
ikev1_p_print,
ikev1_t_print,
ikev1_ke_print,
ikev1_id_print,
ikev1_cert_print,
ikev1_cr_print,
ikev1_hash_print,
ikev1_sig_print,
ikev1_nonce_print,
ikev1_n_print,
ikev1_d_print,
ikev1_vid_print, /* 13 */
NULL, NULL, NULL, NULL, NULL, /* 14- 18 */
NULL, NULL, NULL, NULL, NULL, /* 19- 23 */
NULL, NULL, NULL, NULL, NULL, /* 24- 28 */
NULL, NULL, NULL, NULL, /* 29- 32 */
ikev2_sa_print, /* 33 */
ikev2_ke_print, /* 34 */
ikev2_ID_print, /* 35 */
ikev2_ID_print, /* 36 */
ikev2_cert_print, /* 37 */
ikev2_cr_print, /* 38 */
ikev2_auth_print, /* 39 */
ikev2_nonce_print, /* 40 */
ikev2_n_print, /* 41 */
ikev2_d_print, /* 42 */
ikev2_vid_print, /* 43 */
ikev2_TS_print, /* 44 */
ikev2_TS_print, /* 45 */
NULL, /* ikev2_e_print,*/ /* 46 - special */
ikev2_cp_print, /* 47 */
ikev2_eap_print, /* 48 */
};
/* isakmp->etype */
static const char *etypestr[] = {
/* IKEv1 exchange types */
"none", "base", "ident", "auth", "agg", "inf", NULL, NULL, /* 0-7 */
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 8-15 */
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 16-23 */
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, /* 24-31 */
"oakley-quick", "oakley-newgroup", /* 32-33 */
/* IKEv2 exchange types */
"ikev2_init", "ikev2_auth", "child_sa", "inf2" /* 34-37 */
};
#define STR_OR_ID(x, tab) \
(((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x))
#define PROTOIDSTR(x) STR_OR_ID(x, protoidstr)
#define NPSTR(x) STR_OR_ID(x, npstr)
#define ETYPESTR(x) STR_OR_ID(x, etypestr)
#define CHECKLEN(p, np) \
if (ep < (const u_char *)(p)) { \
ND_PRINT((ndo," [|%s]", NPSTR(np))); \
goto done; \
}
#define NPFUNC(x) \
(((x) < sizeof(npfunc)/sizeof(npfunc[0]) && npfunc[(x)]) \
? npfunc[(x)] : NULL)
static int
iszero(const u_char *p, size_t l)
{
while (l--) {
if (*p++)
return 0;
}
return 1;
}
/* find cookie from initiator cache */
static int
cookie_find(cookie_t *in)
{
int i;
for (i = 0; i < MAXINITIATORS; i++) {
if (memcmp(in, &cookiecache[i].initiator, sizeof(*in)) == 0)
return i;
}
return -1;
}
/* record initiator */
static void
cookie_record(cookie_t *in, const u_char *bp2)
{
int i;
const struct ip *ip;
const struct ip6_hdr *ip6;
i = cookie_find(in);
if (0 <= i) {
ninitiator = (i + 1) % MAXINITIATORS;
return;
}
ip = (const struct ip *)bp2;
switch (IP_V(ip)) {
case 4:
cookiecache[ninitiator].version = 4;
UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in4, &ip->ip_src, sizeof(struct in_addr));
UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in4, &ip->ip_dst, sizeof(struct in_addr));
break;
case 6:
ip6 = (const struct ip6_hdr *)bp2;
cookiecache[ninitiator].version = 6;
UNALIGNED_MEMCPY(&cookiecache[ninitiator].iaddr.in6, &ip6->ip6_src, sizeof(struct in6_addr));
UNALIGNED_MEMCPY(&cookiecache[ninitiator].raddr.in6, &ip6->ip6_dst, sizeof(struct in6_addr));
break;
default:
return;
}
UNALIGNED_MEMCPY(&cookiecache[ninitiator].initiator, in, sizeof(*in));
ninitiator = (ninitiator + 1) % MAXINITIATORS;
}
#define cookie_isinitiator(x, y) cookie_sidecheck((x), (y), 1)
#define cookie_isresponder(x, y) cookie_sidecheck((x), (y), 0)
static int
cookie_sidecheck(int i, const u_char *bp2, int initiator)
{
const struct ip *ip;
const struct ip6_hdr *ip6;
ip = (const struct ip *)bp2;
switch (IP_V(ip)) {
case 4:
if (cookiecache[i].version != 4)
return 0;
if (initiator) {
if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].iaddr.in4, sizeof(struct in_addr)) == 0)
return 1;
} else {
if (UNALIGNED_MEMCMP(&ip->ip_src, &cookiecache[i].raddr.in4, sizeof(struct in_addr)) == 0)
return 1;
}
break;
case 6:
if (cookiecache[i].version != 6)
return 0;
ip6 = (const struct ip6_hdr *)bp2;
if (initiator) {
if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].iaddr.in6, sizeof(struct in6_addr)) == 0)
return 1;
} else {
if (UNALIGNED_MEMCMP(&ip6->ip6_src, &cookiecache[i].raddr.in6, sizeof(struct in6_addr)) == 0)
return 1;
}
break;
default:
break;
}
return 0;
}
static void
hexprint(netdissect_options *ndo, const uint8_t *loc, size_t len)
{
const uint8_t *p;
size_t i;
p = loc;
for (i = 0; i < len; i++)
ND_PRINT((ndo,"%02x", p[i] & 0xff));
}
static int
rawprint(netdissect_options *ndo, const uint8_t *loc, size_t len)
{
ND_TCHECK2(*loc, len);
hexprint(ndo, loc, len);
return 1;
trunc:
return 0;
}
/*
* returns false if we run out of data buffer
*/
static int ike_show_somedata(netdissect_options *ndo,
const u_char *cp, const u_char *ep)
{
/* there is too much data, just show some of it */
const u_char *end = ep - 20;
int elen = 20;
int len = ep - cp;
if(len > 10) {
len = 10;
}
/* really shouldn't happen because of above */
if(end < cp + len) {
end = cp+len;
elen = ep - end;
}
ND_PRINT((ndo," data=("));
if(!rawprint(ndo, (const uint8_t *)(cp), len)) goto trunc;
ND_PRINT((ndo, "..."));
if(elen) {
if(!rawprint(ndo, (const uint8_t *)(end), elen)) goto trunc;
}
ND_PRINT((ndo,")"));
return 1;
trunc:
return 0;
}
struct attrmap {
const char *type;
u_int nvalue;
const char *value[30]; /*XXX*/
};
static const u_char *
ikev1_attrmap_print(netdissect_options *ndo,
const u_char *p, const u_char *ep2,
const struct attrmap *map, size_t nmap)
{
int totlen;
uint32_t t, v;
ND_TCHECK(p[0]);
if (p[0] & 0x80)
totlen = 4;
else {
ND_TCHECK_16BITS(&p[2]);
totlen = 4 + EXTRACT_16BITS(&p[2]);
}
if (ep2 < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep2 + 1;
}
ND_TCHECK_16BITS(&p[0]);
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
if (map && t < nmap && map[t].type)
ND_PRINT((ndo,"type=%s ", map[t].type));
else
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
ND_TCHECK_16BITS(&p[2]);
v = EXTRACT_16BITS(&p[2]);
if (map && t < nmap && v < map[t].nvalue && map[t].value[v])
ND_PRINT((ndo,"%s", map[t].value[v]));
else {
if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
} else {
ND_PRINT((ndo,"len=%d value=", totlen - 4));
if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
ND_PRINT((ndo,")"));
return p + totlen;
trunc:
return NULL;
}
static const u_char *
ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2)
{
int totlen;
uint32_t t;
ND_TCHECK(p[0]);
if (p[0] & 0x80)
totlen = 4;
else {
ND_TCHECK_16BITS(&p[2]);
totlen = 4 + EXTRACT_16BITS(&p[2]);
}
if (ep2 < p + totlen) {
ND_PRINT((ndo,"[|attr]"));
return ep2 + 1;
}
ND_TCHECK_16BITS(&p[0]);
ND_PRINT((ndo,"("));
t = EXTRACT_16BITS(&p[0]) & 0x7fff;
ND_PRINT((ndo,"type=#%d ", t));
if (p[0] & 0x80) {
ND_PRINT((ndo,"value="));
t = p[2];
if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) {
ND_PRINT((ndo,")"));
goto trunc;
}
} else {
ND_PRINT((ndo,"len=%d value=", totlen - 4));
if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
ND_PRINT((ndo,")"));
return p + totlen;
trunc:
return NULL;
}
static const u_char *
ikev1_sa_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_,
const u_char *ep, uint32_t phase, uint32_t doi0 _U_,
uint32_t proto0, int depth)
{
const struct ikev1_pl_sa *p;
struct ikev1_pl_sa sa;
uint32_t doi, sit, ident;
const u_char *cp, *np;
int t;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SA)));
p = (const struct ikev1_pl_sa *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&sa, ext, sizeof(sa));
doi = ntohl(sa.doi);
sit = ntohl(sa.sit);
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," situation=%u", (uint32_t)ntohl(sa.sit)));
return (const u_char *)(p + 1);
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," situation="));
t = 0;
if (sit & 0x01) {
ND_PRINT((ndo,"identity"));
t++;
}
if (sit & 0x02) {
ND_PRINT((ndo,"%ssecrecy", t ? "+" : ""));
t++;
}
if (sit & 0x04)
ND_PRINT((ndo,"%sintegrity", t ? "+" : ""));
np = (const u_char *)ext + sizeof(sa);
if (sit != 0x01) {
ND_TCHECK2(*(ext + 1), sizeof(ident));
UNALIGNED_MEMCPY(&ident, ext + 1, sizeof(ident));
ND_PRINT((ndo," ident=%u", (uint32_t)ntohl(ident)));
np += sizeof(ident);
}
ext = (const struct isakmp_gen *)np;
ND_TCHECK(*ext);
cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_P, ext, ep, phase, doi, proto0,
depth);
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SA)));
return NULL;
}
static const u_char *
ikev1_p_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep, uint32_t phase, uint32_t doi0,
uint32_t proto0 _U_, int depth)
{
const struct ikev1_pl_p *p;
struct ikev1_pl_p prop;
const u_char *cp;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_P)));
p = (const struct ikev1_pl_p *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&prop, ext, sizeof(prop));
ND_PRINT((ndo," #%d protoid=%s transform=%d",
prop.p_no, PROTOIDSTR(prop.prot_id), prop.num_t));
if (prop.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), prop.spi_size))
goto trunc;
}
ext = (const struct isakmp_gen *)((const u_char *)(p + 1) + prop.spi_size);
ND_TCHECK(*ext);
cp = ikev1_sub_print(ndo, ISAKMP_NPTYPE_T, ext, ep, phase, doi0,
prop.prot_id, depth);
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return NULL;
}
static const char *ikev1_p_map[] = {
NULL, "ike",
};
static const char *ikev2_t_type_map[]={
NULL, "encr", "prf", "integ", "dh", "esn"
};
static const char *ah_p_map[] = {
NULL, "(reserved)", "md5", "sha", "1des",
"sha2-256", "sha2-384", "sha2-512",
};
static const char *prf_p_map[] = {
NULL, "hmac-md5", "hmac-sha", "hmac-tiger",
"aes128_xcbc"
};
static const char *integ_p_map[] = {
NULL, "hmac-md5", "hmac-sha", "dec-mac",
"kpdk-md5", "aes-xcbc"
};
static const char *esn_p_map[] = {
"no-esn", "esn"
};
static const char *dh_p_map[] = {
NULL, "modp768",
"modp1024", /* group 2 */
"EC2N 2^155", /* group 3 */
"EC2N 2^185", /* group 4 */
"modp1536", /* group 5 */
"iana-grp06", "iana-grp07", /* reserved */
"iana-grp08", "iana-grp09",
"iana-grp10", "iana-grp11",
"iana-grp12", "iana-grp13",
"modp2048", /* group 14 */
"modp3072", /* group 15 */
"modp4096", /* group 16 */
"modp6144", /* group 17 */
"modp8192", /* group 18 */
};
static const char *esp_p_map[] = {
NULL, "1des-iv64", "1des", "3des", "rc5", "idea", "cast",
"blowfish", "3idea", "1des-iv32", "rc4", "null", "aes"
};
static const char *ipcomp_p_map[] = {
NULL, "oui", "deflate", "lzs",
};
static const struct attrmap ipsec_t_map[] = {
{ NULL, 0, { NULL } },
{ "lifetype", 3, { NULL, "sec", "kb", }, },
{ "life", 0, { NULL } },
{ "group desc", 18, { NULL, "modp768",
"modp1024", /* group 2 */
"EC2N 2^155", /* group 3 */
"EC2N 2^185", /* group 4 */
"modp1536", /* group 5 */
"iana-grp06", "iana-grp07", /* reserved */
"iana-grp08", "iana-grp09",
"iana-grp10", "iana-grp11",
"iana-grp12", "iana-grp13",
"modp2048", /* group 14 */
"modp3072", /* group 15 */
"modp4096", /* group 16 */
"modp6144", /* group 17 */
"modp8192", /* group 18 */
}, },
{ "enc mode", 3, { NULL, "tunnel", "transport", }, },
{ "auth", 5, { NULL, "hmac-md5", "hmac-sha1", "1des-mac", "keyed", }, },
{ "keylen", 0, { NULL } },
{ "rounds", 0, { NULL } },
{ "dictsize", 0, { NULL } },
{ "privalg", 0, { NULL } },
};
static const struct attrmap encr_t_map[] = {
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 0, 1 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 2, 3 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 4, 5 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 6, 7 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 8, 9 */
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 10,11*/
{ NULL, 0, { NULL } }, { NULL, 0, { NULL } }, /* 12,13*/
{ "keylen", 14, { NULL }},
};
static const struct attrmap oakley_t_map[] = {
{ NULL, 0, { NULL } },
{ "enc", 8, { NULL, "1des", "idea", "blowfish", "rc5",
"3des", "cast", "aes", }, },
{ "hash", 7, { NULL, "md5", "sha1", "tiger",
"sha2-256", "sha2-384", "sha2-512", }, },
{ "auth", 6, { NULL, "preshared", "dss", "rsa sig", "rsa enc",
"rsa enc revised", }, },
{ "group desc", 18, { NULL, "modp768",
"modp1024", /* group 2 */
"EC2N 2^155", /* group 3 */
"EC2N 2^185", /* group 4 */
"modp1536", /* group 5 */
"iana-grp06", "iana-grp07", /* reserved */
"iana-grp08", "iana-grp09",
"iana-grp10", "iana-grp11",
"iana-grp12", "iana-grp13",
"modp2048", /* group 14 */
"modp3072", /* group 15 */
"modp4096", /* group 16 */
"modp6144", /* group 17 */
"modp8192", /* group 18 */
}, },
{ "group type", 4, { NULL, "MODP", "ECP", "EC2N", }, },
{ "group prime", 0, { NULL } },
{ "group gen1", 0, { NULL } },
{ "group gen2", 0, { NULL } },
{ "group curve A", 0, { NULL } },
{ "group curve B", 0, { NULL } },
{ "lifetype", 3, { NULL, "sec", "kb", }, },
{ "lifeduration", 0, { NULL } },
{ "prf", 0, { NULL } },
{ "keylen", 0, { NULL } },
{ "field", 0, { NULL } },
{ "order", 0, { NULL } },
};
static const u_char *
ikev1_t_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto, int depth _U_)
{
const struct ikev1_pl_t *p;
struct ikev1_pl_t t;
const u_char *cp;
const char *idstr;
const struct attrmap *map;
size_t nmap;
const u_char *ep2;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_T)));
p = (const struct ikev1_pl_t *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&t, ext, sizeof(t));
switch (proto) {
case 1:
idstr = STR_OR_ID(t.t_id, ikev1_p_map);
map = oakley_t_map;
nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
break;
case 2:
idstr = STR_OR_ID(t.t_id, ah_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
case 3:
idstr = STR_OR_ID(t.t_id, esp_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
case 4:
idstr = STR_OR_ID(t.t_id, ipcomp_p_map);
map = ipsec_t_map;
nmap = sizeof(ipsec_t_map)/sizeof(ipsec_t_map[0]);
break;
default:
idstr = NULL;
map = NULL;
nmap = 0;
break;
}
if (idstr)
ND_PRINT((ndo," #%d id=%s ", t.t_no, idstr));
else
ND_PRINT((ndo," #%d id=%d ", t.t_no, t.t_id));
cp = (const u_char *)(p + 1);
ep2 = (const u_char *)p + item_len;
while (cp < ep && cp < ep2) {
if (map && nmap)
cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);
else
cp = ikev1_attr_print(ndo, cp, ep2);
if (cp == NULL)
goto trunc;
}
if (ep < ep2)
ND_PRINT((ndo,"..."));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T)));
return NULL;
}
static const u_char *
ikev1_ke_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_KE)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," key len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_KE)));
return NULL;
}
static const u_char *
ikev1_id_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
#define USE_IPSECDOI_IN_PHASE1 1
const struct ikev1_pl_id *p;
struct ikev1_pl_id id;
static const char *idtypestr[] = {
"IPv4", "IPv4net", "IPv6", "IPv6net",
};
static const char *ipsecidtypestr[] = {
NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6",
"IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN",
"keyid",
};
int len;
const u_char *data;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID)));
p = (const struct ikev1_pl_id *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&id, ext, sizeof(id));
if (sizeof(*p) < item_len) {
data = (const u_char *)(p + 1);
len = item_len - sizeof(*p);
} else {
data = NULL;
len = 0;
}
#if 0 /*debug*/
ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto));
#endif
switch (phase) {
#ifndef USE_IPSECDOI_IN_PHASE1
case 1:
#endif
default:
ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr)));
ND_PRINT((ndo," doi_data=%u",
(uint32_t)(ntohl(id.d.doi_data) & 0xffffff)));
break;
#ifdef USE_IPSECDOI_IN_PHASE1
case 1:
#endif
case 2:
{
const struct ipsecdoi_id *doi_p;
struct ipsecdoi_id doi_id;
const char *p_name;
doi_p = (const struct ipsecdoi_id *)ext;
ND_TCHECK(*doi_p);
UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id));
ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr)));
/* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */
if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL)
ND_PRINT((ndo," protoid=%s", p_name));
else
ND_PRINT((ndo," protoid=%u", doi_id.proto_id));
ND_PRINT((ndo," port=%d", ntohs(doi_id.port)));
if (!len)
break;
if (data == NULL)
goto trunc;
ND_TCHECK2(*data, len);
switch (doi_id.type) {
case IPSECDOI_ID_IPV4_ADDR:
if (len < 4)
ND_PRINT((ndo," len=%d [bad: < 4]", len));
else
ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data)));
len = 0;
break;
case IPSECDOI_ID_FQDN:
case IPSECDOI_ID_USER_FQDN:
{
int i;
ND_PRINT((ndo," len=%d ", len));
for (i = 0; i < len; i++)
safeputchar(ndo, data[i]);
len = 0;
break;
}
case IPSECDOI_ID_IPV4_ADDR_SUBNET:
{
const u_char *mask;
if (len < 8)
ND_PRINT((ndo," len=%d [bad: < 8]", len));
else {
mask = data + sizeof(struct in_addr);
ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len,
ipaddr_string(ndo, data),
mask[0], mask[1], mask[2], mask[3]));
}
len = 0;
break;
}
case IPSECDOI_ID_IPV6_ADDR:
if (len < 16)
ND_PRINT((ndo," len=%d [bad: < 16]", len));
else
ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data)));
len = 0;
break;
case IPSECDOI_ID_IPV6_ADDR_SUBNET:
{
const u_char *mask;
if (len < 32)
ND_PRINT((ndo," len=%d [bad: < 32]", len));
else {
mask = (const u_char *)(data + sizeof(struct in6_addr));
/*XXX*/
ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len,
ip6addr_string(ndo, data),
mask[0], mask[1], mask[2], mask[3],
mask[4], mask[5], mask[6], mask[7],
mask[8], mask[9], mask[10], mask[11],
mask[12], mask[13], mask[14], mask[15]));
}
len = 0;
break;
}
case IPSECDOI_ID_IPV4_ADDR_RANGE:
if (len < 8)
ND_PRINT((ndo," len=%d [bad: < 8]", len));
else {
ND_PRINT((ndo," len=%d %s-%s", len,
ipaddr_string(ndo, data),
ipaddr_string(ndo, data + sizeof(struct in_addr))));
}
len = 0;
break;
case IPSECDOI_ID_IPV6_ADDR_RANGE:
if (len < 32)
ND_PRINT((ndo," len=%d [bad: < 32]", len));
else {
ND_PRINT((ndo," len=%d %s-%s", len,
ip6addr_string(ndo, data),
ip6addr_string(ndo, data + sizeof(struct in6_addr))));
}
len = 0;
break;
case IPSECDOI_ID_DER_ASN1_DN:
case IPSECDOI_ID_DER_ASN1_GN:
case IPSECDOI_ID_KEY_ID:
break;
}
break;
}
}
if (data && len) {
ND_PRINT((ndo," len=%d", len));
if (2 < ndo->ndo_vflag) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)data, len))
goto trunc;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID)));
return NULL;
}
static const u_char *
ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase _U_,
uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_cert *p;
struct ikev1_pl_cert cert;
static const char *certstr[] = {
"none", "pkcs7", "pgp", "dns",
"x509sign", "x509ke", "kerberos", "crl",
"arl", "spki", "x509attr",
};
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT)));
p = (const struct ikev1_pl_cert *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&cert, ext, sizeof(cert));
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT)));
return NULL;
}
static const u_char *
ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_cert *p;
struct ikev1_pl_cert cert;
static const char *certstr[] = {
"none", "pkcs7", "pgp", "dns",
"x509sign", "x509ke", "kerberos", "crl",
"arl", "spki", "x509attr",
};
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR)));
p = (const struct ikev1_pl_cert *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&cert, ext, sizeof(cert));
ND_PRINT((ndo," len=%d", item_len - 4));
ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr)));
if (2 < ndo->ndo_vflag && 4 < item_len) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4))
goto trunc;
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR)));
return NULL;
}
static const u_char *
ikev1_hash_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_HASH)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_HASH)));
return NULL;
}
static const u_char *
ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG)));
return NULL;
}
static const u_char *
ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_,
const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Our caller has ensured that the length is >= 4.
*/
ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4));
if (ntohs(e.len) > 4) {
if (ndo->ndo_vflag > 2) {
ND_PRINT((ndo, " "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
} else if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " "));
if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep))
goto trunc;
}
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE)));
return NULL;
}
static const u_char *
ikev1_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_n *p;
struct ikev1_pl_n n;
const u_char *cp;
const u_char *ep2;
uint32_t doi;
uint32_t proto;
static const char *notify_error_str[] = {
NULL, "INVALID-PAYLOAD-TYPE",
"DOI-NOT-SUPPORTED", "SITUATION-NOT-SUPPORTED",
"INVALID-COOKIE", "INVALID-MAJOR-VERSION",
"INVALID-MINOR-VERSION", "INVALID-EXCHANGE-TYPE",
"INVALID-FLAGS", "INVALID-MESSAGE-ID",
"INVALID-PROTOCOL-ID", "INVALID-SPI",
"INVALID-TRANSFORM-ID", "ATTRIBUTES-NOT-SUPPORTED",
"NO-PROPOSAL-CHOSEN", "BAD-PROPOSAL-SYNTAX",
"PAYLOAD-MALFORMED", "INVALID-KEY-INFORMATION",
"INVALID-ID-INFORMATION", "INVALID-CERT-ENCODING",
"INVALID-CERTIFICATE", "CERT-TYPE-UNSUPPORTED",
"INVALID-CERT-AUTHORITY", "INVALID-HASH-INFORMATION",
"AUTHENTICATION-FAILED", "INVALID-SIGNATURE",
"ADDRESS-NOTIFICATION", "NOTIFY-SA-LIFETIME",
"CERTIFICATE-UNAVAILABLE", "UNSUPPORTED-EXCHANGE-TYPE",
"UNEQUAL-PAYLOAD-LENGTHS",
};
static const char *ipsec_notify_error_str[] = {
"RESERVED",
};
static const char *notify_status_str[] = {
"CONNECTED",
};
static const char *ipsec_notify_status_str[] = {
"RESPONDER-LIFETIME", "REPLAY-STATUS",
"INITIAL-CONTACT",
};
/* NOTE: these macro must be called with x in proper range */
/* 0 - 8191 */
#define NOTIFY_ERROR_STR(x) \
STR_OR_ID((x), notify_error_str)
/* 8192 - 16383 */
#define IPSEC_NOTIFY_ERROR_STR(x) \
STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str)
/* 16384 - 24575 */
#define NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 16384), notify_status_str)
/* 24576 - 32767 */
#define IPSEC_NOTIFY_STATUS_STR(x) \
STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str)
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_N)));
p = (const struct ikev1_pl_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
doi = ntohl(n.doi);
proto = n.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%d", doi));
ND_PRINT((ndo," proto=%d", proto));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
return (const u_char *)(p + 1) + n.spi_size;
}
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
if (ntohs(n.type) < 8192)
ND_PRINT((ndo," type=%s", NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 16384)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type))));
else if (ntohs(n.type) < 24576)
ND_PRINT((ndo," type=%s", NOTIFY_STATUS_STR(ntohs(n.type))));
else if (ntohs(n.type) < 32768)
ND_PRINT((ndo," type=%s", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type))));
else
ND_PRINT((ndo," type=%s", numstr(ntohs(n.type))));
if (n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
ep2 = (const u_char *)p + item_len;
if (cp < ep) {
switch (ntohs(n.type)) {
case IPSECDOI_NTYPE_RESPONDER_LIFETIME:
{
const struct attrmap *map = oakley_t_map;
size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]);
ND_PRINT((ndo," attrs=("));
while (cp < ep && cp < ep2) {
cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);
if (cp == NULL) {
ND_PRINT((ndo,")"));
goto trunc;
}
}
ND_PRINT((ndo,")"));
break;
}
case IPSECDOI_NTYPE_REPLAY_STATUS:
ND_PRINT((ndo," status=("));
ND_PRINT((ndo,"replay detection %sabled",
EXTRACT_32BITS(cp) ? "en" : "dis"));
ND_PRINT((ndo,")"));
break;
default:
/*
* XXX - fill in more types here; see, for example,
* draft-ietf-ipsec-notifymsg-04.
*/
if (ndo->ndo_vflag > 3) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else {
if (!ike_show_somedata(ndo, cp, ep))
goto trunc;
}
break;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
static const u_char *
ikev1_d_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len _U_,
const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_,
uint32_t proto0 _U_, int depth _U_)
{
const struct ikev1_pl_d *p;
struct ikev1_pl_d d;
const uint8_t *q;
uint32_t doi;
uint32_t proto;
int i;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_D)));
p = (const struct ikev1_pl_d *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&d, ext, sizeof(d));
doi = ntohl(d.doi);
proto = d.prot_id;
if (doi != 1) {
ND_PRINT((ndo," doi=%u", doi));
ND_PRINT((ndo," proto=%u", proto));
} else {
ND_PRINT((ndo," doi=ipsec"));
ND_PRINT((ndo," proto=%s", PROTOIDSTR(proto)));
}
ND_PRINT((ndo," spilen=%u", d.spi_size));
ND_PRINT((ndo," nspi=%u", ntohs(d.num_spi)));
ND_PRINT((ndo," spi="));
q = (const uint8_t *)(p + 1);
for (i = 0; i < ntohs(d.num_spi); i++) {
if (i != 0)
ND_PRINT((ndo,","));
if (!rawprint(ndo, (const uint8_t *)q, d.spi_size))
goto trunc;
q += d.spi_size;
}
return q;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_D)));
return NULL;
}
static const u_char *
ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID)));
return NULL;
}
/************************************************************/
/* */
/* IKE v2 - rfc4306 - dissector */
/* */
/************************************************************/
static void
ikev2_pay_print(netdissect_options *ndo, const char *payname, int critical)
{
ND_PRINT((ndo,"%s%s:", payname, critical&0x80 ? "[C]" : ""));
}
static const u_char *
ikev2_gen_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext)
{
struct isakmp_gen e;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_t_print(netdissect_options *ndo, int tcount,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep)
{
const struct ikev2_t *p;
struct ikev2_t t;
uint16_t t_id;
const u_char *cp;
const char *idstr;
const struct attrmap *map;
size_t nmap;
const u_char *ep2;
p = (const struct ikev2_t *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&t, ext, sizeof(t));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_T), t.h.critical);
t_id = ntohs(t.t_id);
map = NULL;
nmap = 0;
switch (t.t_type) {
case IV2_T_ENCR:
idstr = STR_OR_ID(t_id, esp_p_map);
map = encr_t_map;
nmap = sizeof(encr_t_map)/sizeof(encr_t_map[0]);
break;
case IV2_T_PRF:
idstr = STR_OR_ID(t_id, prf_p_map);
break;
case IV2_T_INTEG:
idstr = STR_OR_ID(t_id, integ_p_map);
break;
case IV2_T_DH:
idstr = STR_OR_ID(t_id, dh_p_map);
break;
case IV2_T_ESN:
idstr = STR_OR_ID(t_id, esn_p_map);
break;
default:
idstr = NULL;
break;
}
if (idstr)
ND_PRINT((ndo," #%u type=%s id=%s ", tcount,
STR_OR_ID(t.t_type, ikev2_t_type_map),
idstr));
else
ND_PRINT((ndo," #%u type=%s id=%u ", tcount,
STR_OR_ID(t.t_type, ikev2_t_type_map),
t.t_id));
cp = (const u_char *)(p + 1);
ep2 = (const u_char *)p + item_len;
while (cp < ep && cp < ep2) {
if (map && nmap) {
cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap);
} else
cp = ikev1_attr_print(ndo, cp, ep2);
if (cp == NULL)
goto trunc;
}
if (ep < ep2)
ND_PRINT((ndo,"..."));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_T)));
return NULL;
}
static const u_char *
ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_,
const struct isakmp_gen *ext, u_int oprop_length,
const u_char *ep, int depth)
{
const struct ikev2_p *p;
struct ikev2_p prop;
u_int prop_length;
const u_char *cp;
int i;
int tcount;
u_char np;
struct isakmp_gen e;
u_int item_len;
p = (const struct ikev2_p *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&prop, ext, sizeof(prop));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical);
/*
* ikev2_sa_print() guarantees that this is >= 4.
*/
prop_length = oprop_length - 4;
ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u",
prop.p_no, PROTOIDSTR(prop.prot_id),
prop.num_t, oprop_length));
cp = (const u_char *)(p + 1);
if (prop.spi_size) {
if (prop_length < prop.spi_size)
goto toolong;
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size))
goto trunc;
cp += prop.spi_size;
prop_length -= prop.spi_size;
}
/*
* Print the transforms.
*/
tcount = 0;
for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) {
tcount++;
ext = (const struct isakmp_gen *)cp;
if (prop_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
goto trunc;
if (prop_length < item_len)
goto toolong;
ND_TCHECK2(*cp, item_len);
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
if (np == ISAKMP_NPTYPE_T) {
cp = ikev2_t_print(ndo, tcount, ext, item_len, ep);
if (cp == NULL) {
/* error, already reported */
return NULL;
}
} else {
ND_PRINT((ndo, "%s", NPSTR(np)));
cp += item_len;
}
ND_PRINT((ndo,")"));
depth--;
prop_length -= item_len;
}
return cp;
toolong:
/*
* Skip the rest of the proposal.
*/
cp += prop_length;
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return NULL;
}
static const u_char *
ikev2_sa_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext1,
u_int osa_length, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth)
{
const struct isakmp_gen *ext;
struct isakmp_gen e;
u_int sa_length;
const u_char *cp;
int i;
int pcount;
u_char np;
u_int item_len;
ND_TCHECK(*ext1);
UNALIGNED_MEMCPY(&e, ext1, sizeof(e));
ikev2_pay_print(ndo, "sa", e.critical);
/*
* ikev2_sub0_print() guarantees that this is >= 4.
*/
osa_length= ntohs(e.len);
sa_length = osa_length - 4;
ND_PRINT((ndo," len=%d", sa_length));
/*
* Print the payloads.
*/
cp = (const u_char *)(ext1 + 1);
pcount = 0;
for (np = ISAKMP_NPTYPE_P; np != 0; np = e.np) {
pcount++;
ext = (const struct isakmp_gen *)cp;
if (sa_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
goto trunc;
if (sa_length < item_len)
goto toolong;
ND_TCHECK2(*cp, item_len);
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
if (np == ISAKMP_NPTYPE_P) {
cp = ikev2_p_print(ndo, np, pcount, ext, item_len,
ep, depth);
if (cp == NULL) {
/* error, already reported */
return NULL;
}
} else {
ND_PRINT((ndo, "%s", NPSTR(np)));
cp += item_len;
}
ND_PRINT((ndo,")"));
depth--;
sa_length -= item_len;
}
return cp;
toolong:
/*
* Skip the rest of the SA.
*/
cp += sa_length;
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_ke_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_ke ke;
const struct ikev2_ke *k;
k = (const struct ikev2_ke *)ext;
ND_TCHECK(*k);
UNALIGNED_MEMCPY(&ke, ext, sizeof(ke));
ikev2_pay_print(ndo, NPSTR(tpay), ke.h.critical);
ND_PRINT((ndo," len=%u group=%s", ntohs(ke.h.len) - 8,
STR_OR_ID(ntohs(ke.ke_group), dh_p_map)));
if (2 < ndo->ndo_vflag && 8 < ntohs(ke.h.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(k + 1), ntohs(ke.h.len) - 8))
goto trunc;
}
return (const u_char *)ext + ntohs(ke.h.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_ID_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
const struct ikev2_id *idp;
struct ikev2_id id;
int id_len, idtype_len, i;
unsigned int dumpascii, dumphex;
const unsigned char *typedata;
idp = (const struct ikev2_id *)ext;
ND_TCHECK(*idp);
UNALIGNED_MEMCPY(&id, ext, sizeof(id));
ikev2_pay_print(ndo, NPSTR(tpay), id.h.critical);
id_len = ntohs(id.h.len);
ND_PRINT((ndo," len=%d", id_len - 4));
if (2 < ndo->ndo_vflag && 4 < id_len) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), id_len - 4))
goto trunc;
}
idtype_len =id_len - sizeof(struct ikev2_id);
dumpascii = 0;
dumphex = 0;
typedata = (const unsigned char *)(ext)+sizeof(struct ikev2_id);
switch(id.type) {
case ID_IPV4_ADDR:
ND_PRINT((ndo, " ipv4:"));
dumphex=1;
break;
case ID_FQDN:
ND_PRINT((ndo, " fqdn:"));
dumpascii=1;
break;
case ID_RFC822_ADDR:
ND_PRINT((ndo, " rfc822:"));
dumpascii=1;
break;
case ID_IPV6_ADDR:
ND_PRINT((ndo, " ipv6:"));
dumphex=1;
break;
case ID_DER_ASN1_DN:
ND_PRINT((ndo, " dn:"));
dumphex=1;
break;
case ID_DER_ASN1_GN:
ND_PRINT((ndo, " gn:"));
dumphex=1;
break;
case ID_KEY_ID:
ND_PRINT((ndo, " keyid:"));
dumphex=1;
break;
}
if(dumpascii) {
ND_TCHECK2(*typedata, idtype_len);
for(i=0; i<idtype_len; i++) {
if(ND_ISPRINT(typedata[i])) {
ND_PRINT((ndo, "%c", typedata[i]));
} else {
ND_PRINT((ndo, "."));
}
}
}
if(dumphex) {
if (!rawprint(ndo, (const uint8_t *)typedata, idtype_len))
goto trunc;
}
return (const u_char *)ext + id_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_cert_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_cr_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_auth_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct ikev2_auth a;
const char *v2_auth[]={ "invalid", "rsasig",
"shared-secret", "dsssig" };
const u_char *authdata = (const u_char*)ext + sizeof(a);
unsigned int len;
ND_TCHECK2(*ext, sizeof(a));
UNALIGNED_MEMCPY(&a, ext, sizeof(a));
ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical);
len = ntohs(a.h.len);
/*
* Our caller has ensured that the length is >= 4.
*/
ND_PRINT((ndo," len=%u method=%s", len-4,
STR_OR_ID(a.auth_method, v2_auth)));
if (len > 4) {
if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " authdata=("));
if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a)))
goto trunc;
ND_PRINT((ndo, ") "));
} else if (ndo->ndo_vflag) {
if (!ike_show_somedata(ndo, authdata, ep))
goto trunc;
}
}
return (const u_char *)ext + len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_nonce_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, "nonce", e.critical);
ND_PRINT((ndo," len=%d", ntohs(e.len) - 4));
if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," nonce=("));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
ND_PRINT((ndo,") "));
} else if(ndo->ndo_vflag && 4 < ntohs(e.len)) {
if(!ike_show_somedata(ndo, (const u_char *)(ext+1), ep)) goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
/* notify payloads */
static const u_char *
ikev2_n_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len, const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
const struct ikev2_n *p;
struct ikev2_n n;
const u_char *cp;
u_char showspi, showsomedata;
const char *notify_name;
uint32_t type;
p = (const struct ikev2_n *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&n, ext, sizeof(n));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_N), n.h.critical);
showspi = 1;
showsomedata=0;
notify_name=NULL;
ND_PRINT((ndo," prot_id=%s", PROTOIDSTR(n.prot_id)));
type = ntohs(n.type);
/* notify space is annoying sparse */
switch(type) {
case IV2_NOTIFY_UNSUPPORTED_CRITICAL_PAYLOAD:
notify_name = "unsupported_critical_payload";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_IKE_SPI:
notify_name = "invalid_ike_spi";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_MAJOR_VERSION:
notify_name = "invalid_major_version";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_SYNTAX:
notify_name = "invalid_syntax";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_MESSAGE_ID:
notify_name = "invalid_message_id";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_SPI:
notify_name = "invalid_spi";
showspi = 1;
break;
case IV2_NOTIFY_NO_PROPOSAL_CHOSEN:
notify_name = "no_protocol_chosen";
showspi = 1;
break;
case IV2_NOTIFY_INVALID_KE_PAYLOAD:
notify_name = "invalid_ke_payload";
showspi = 1;
break;
case IV2_NOTIFY_AUTHENTICATION_FAILED:
notify_name = "authentication_failed";
showspi = 1;
break;
case IV2_NOTIFY_SINGLE_PAIR_REQUIRED:
notify_name = "single_pair_required";
showspi = 1;
break;
case IV2_NOTIFY_NO_ADDITIONAL_SAS:
notify_name = "no_additional_sas";
showspi = 0;
break;
case IV2_NOTIFY_INTERNAL_ADDRESS_FAILURE:
notify_name = "internal_address_failure";
showspi = 0;
break;
case IV2_NOTIFY_FAILED_CP_REQUIRED:
notify_name = "failed:cp_required";
showspi = 0;
break;
case IV2_NOTIFY_INVALID_SELECTORS:
notify_name = "invalid_selectors";
showspi = 0;
break;
case IV2_NOTIFY_INITIAL_CONTACT:
notify_name = "initial_contact";
showspi = 0;
break;
case IV2_NOTIFY_SET_WINDOW_SIZE:
notify_name = "set_window_size";
showspi = 0;
break;
case IV2_NOTIFY_ADDITIONAL_TS_POSSIBLE:
notify_name = "additional_ts_possible";
showspi = 0;
break;
case IV2_NOTIFY_IPCOMP_SUPPORTED:
notify_name = "ipcomp_supported";
showspi = 0;
break;
case IV2_NOTIFY_NAT_DETECTION_SOURCE_IP:
notify_name = "nat_detection_source_ip";
showspi = 1;
break;
case IV2_NOTIFY_NAT_DETECTION_DESTINATION_IP:
notify_name = "nat_detection_destination_ip";
showspi = 1;
break;
case IV2_NOTIFY_COOKIE:
notify_name = "cookie";
showspi = 1;
showsomedata= 1;
break;
case IV2_NOTIFY_USE_TRANSPORT_MODE:
notify_name = "use_transport_mode";
showspi = 0;
break;
case IV2_NOTIFY_HTTP_CERT_LOOKUP_SUPPORTED:
notify_name = "http_cert_lookup_supported";
showspi = 0;
break;
case IV2_NOTIFY_REKEY_SA:
notify_name = "rekey_sa";
showspi = 1;
break;
case IV2_NOTIFY_ESP_TFC_PADDING_NOT_SUPPORTED:
notify_name = "tfc_padding_not_supported";
showspi = 0;
break;
case IV2_NOTIFY_NON_FIRST_FRAGMENTS_ALSO:
notify_name = "non_first_fragment_also";
showspi = 0;
break;
default:
if (type < 8192) {
notify_name="error";
} else if(type < 16384) {
notify_name="private-error";
} else if(type < 40960) {
notify_name="status";
} else {
notify_name="private-status";
}
}
if(notify_name) {
ND_PRINT((ndo," type=%u(%s)", type, notify_name));
}
if (showspi && n.spi_size) {
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size))
goto trunc;
}
cp = (const u_char *)(p + 1) + n.spi_size;
if (cp < ep) {
if (ndo->ndo_vflag > 3 || (showsomedata && ep-cp < 30)) {
ND_PRINT((ndo," data=("));
if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp))
goto trunc;
ND_PRINT((ndo,")"));
} else if (showsomedata) {
if (!ike_show_somedata(ndo, cp, ep))
goto trunc;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_N)));
return NULL;
}
static const u_char *
ikev2_d_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_vid_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
const u_char *vid;
int i, len;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4));
vid = (const u_char *)(ext+1);
len = ntohs(e.len) - 4;
ND_TCHECK2(*vid, len);
for(i=0; i<len; i++) {
if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i]));
else ND_PRINT((ndo, "."));
}
if (2 < ndo->ndo_vflag && 4 < len) {
/* Print the entire payload in hex */
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_TS_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_e_print(netdissect_options *ndo,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
struct isakmp *base,
u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
uint32_t phase,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
uint32_t doi,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
uint32_t proto,
#ifndef HAVE_LIBCRYPTO
_U_
#endif
int depth)
{
struct isakmp_gen e;
const u_char *dat;
volatile int dlen;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ikev2_pay_print(ndo, NPSTR(tpay), e.critical);
dlen = ntohs(e.len)-4;
ND_PRINT((ndo," len=%d", dlen));
if (2 < ndo->ndo_vflag && 4 < dlen) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), dlen))
goto trunc;
}
dat = (const u_char *)(ext+1);
ND_TCHECK2(*dat, dlen);
#ifdef HAVE_LIBCRYPTO
/* try to decypt it! */
if(esp_print_decrypt_buffer_by_ikev2(ndo,
base->flags & ISAKMP_FLAG_I,
base->i_ck, base->r_ck,
dat, dat+dlen)) {
ext = (const struct isakmp_gen *)ndo->ndo_packetp;
/* got it decrypted, print stuff inside. */
ikev2_sub_print(ndo, base, e.np, ext, ndo->ndo_snapend,
phase, doi, proto, depth+1);
}
#endif
/* always return NULL, because E must be at end, and NP refers
* to what was inside.
*/
return NULL;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(tpay)));
return NULL;
}
static const u_char *
ikev2_cp_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ikev2_eap_print(netdissect_options *ndo, u_char tpay,
const struct isakmp_gen *ext,
u_int item_len _U_, const u_char *ep _U_,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
return ikev2_gen_print(ndo, tpay, ext);
}
static const u_char *
ike_sub0_print(netdissect_options *ndo,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
struct isakmp_gen e;
u_int item_len;
cp = (const u_char *)ext;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
return NULL;
if (NPFUNC(np)) {
/*
* XXX - what if item_len is too short, or too long,
* for this payload type?
*/
cp = (*npfunc[np])(ndo, np, ext, item_len, ep, phase, doi, proto, depth);
} else {
ND_PRINT((ndo,"%s", NPSTR(np)));
cp += item_len;
}
return cp;
trunc:
ND_PRINT((ndo," [|isakmp]"));
return NULL;
}
static const u_char *
ikev1_sub_print(netdissect_options *ndo,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
int i;
struct isakmp_gen e;
cp = (const u_char *)ext;
while (np) {
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
cp = ike_sub0_print(ndo, np, ext, ep, phase, doi, proto, depth);
ND_PRINT((ndo,")"));
depth--;
if (cp == NULL) {
/* Zero-length subitem */
return NULL;
}
np = e.np;
ext = (const struct isakmp_gen *)cp;
}
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(np)));
return NULL;
}
static char *
numstr(int x)
{
static char buf[20];
snprintf(buf, sizeof(buf), "#%d", x);
return buf;
}
static void
ikev1_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2, struct isakmp *base)
{
const struct isakmp *p;
const u_char *ep;
u_char np;
int i;
int phase;
p = (const struct isakmp *)bp;
ep = ndo->ndo_snapend;
phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2;
if (phase == 1)
ND_PRINT((ndo," phase %d", phase));
else
ND_PRINT((ndo," phase %d/others", phase));
i = cookie_find(&base->i_ck);
if (i < 0) {
if (iszero((const u_char *)&base->r_ck, sizeof(base->r_ck))) {
/* the first packet */
ND_PRINT((ndo," I"));
if (bp2)
cookie_record(&base->i_ck, bp2);
} else
ND_PRINT((ndo," ?"));
} else {
if (bp2 && cookie_isinitiator(i, bp2))
ND_PRINT((ndo," I"));
else if (bp2 && cookie_isresponder(i, bp2))
ND_PRINT((ndo," R"));
else
ND_PRINT((ndo," ?"));
}
ND_PRINT((ndo," %s", ETYPESTR(base->etype)));
if (base->flags) {
ND_PRINT((ndo,"[%s%s]", base->flags & ISAKMP_FLAG_E ? "E" : "",
base->flags & ISAKMP_FLAG_C ? "C" : ""));
}
if (ndo->ndo_vflag) {
const struct isakmp_gen *ext;
ND_PRINT((ndo,":"));
/* regardless of phase... */
if (base->flags & ISAKMP_FLAG_E) {
/*
* encrypted, nothing we can do right now.
* we hope to decrypt the packet in the future...
*/
ND_PRINT((ndo," [encrypted %s]", NPSTR(base->np)));
goto done;
}
CHECKLEN(p + 1, base->np);
np = base->np;
ext = (const struct isakmp_gen *)(p + 1);
ikev1_sub_print(ndo, np, ext, ep, phase, 0, 0, 0);
}
done:
if (ndo->ndo_vflag) {
if (ntohl(base->len) != length) {
ND_PRINT((ndo," (len mismatch: isakmp %u/ip %u)",
(uint32_t)ntohl(base->len), length));
}
}
}
static const u_char *
ikev2_sub0_print(netdissect_options *ndo, struct isakmp *base,
u_char np,
const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
struct isakmp_gen e;
u_int item_len;
cp = (const u_char *)ext;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
return NULL;
if (np == ISAKMP_NPTYPE_v2E) {
cp = ikev2_e_print(ndo, base, np, ext, item_len,
ep, phase, doi, proto, depth);
} else if (NPFUNC(np)) {
/*
* XXX - what if item_len is too short, or too long,
* for this payload type?
*/
cp = (*npfunc[np])(ndo, np, ext, item_len,
ep, phase, doi, proto, depth);
} else {
ND_PRINT((ndo,"%s", NPSTR(np)));
cp += item_len;
}
return cp;
trunc:
ND_PRINT((ndo," [|isakmp]"));
return NULL;
}
static const u_char *
ikev2_sub_print(netdissect_options *ndo,
struct isakmp *base,
u_char np, const struct isakmp_gen *ext, const u_char *ep,
uint32_t phase, uint32_t doi, uint32_t proto, int depth)
{
const u_char *cp;
int i;
struct isakmp_gen e;
cp = (const u_char *)ext;
while (np) {
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_TCHECK2(*ext, ntohs(e.len));
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
cp = ikev2_sub0_print(ndo, base, np,
ext, ep, phase, doi, proto, depth);
ND_PRINT((ndo,")"));
depth--;
if (cp == NULL) {
/* Zero-length subitem */
return NULL;
}
np = e.np;
ext = (const struct isakmp_gen *)cp;
}
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(np)));
return NULL;
}
static void
ikev2_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2 _U_, struct isakmp *base)
{
const struct isakmp *p;
const u_char *ep;
u_char np;
int phase;
p = (const struct isakmp *)bp;
ep = ndo->ndo_snapend;
phase = (EXTRACT_32BITS(base->msgid) == 0) ? 1 : 2;
if (phase == 1)
ND_PRINT((ndo, " parent_sa"));
else
ND_PRINT((ndo, " child_sa "));
ND_PRINT((ndo, " %s", ETYPESTR(base->etype)));
if (base->flags) {
ND_PRINT((ndo, "[%s%s%s]",
base->flags & ISAKMP_FLAG_I ? "I" : "",
base->flags & ISAKMP_FLAG_V ? "V" : "",
base->flags & ISAKMP_FLAG_R ? "R" : ""));
}
if (ndo->ndo_vflag) {
const struct isakmp_gen *ext;
ND_PRINT((ndo, ":"));
/* regardless of phase... */
if (base->flags & ISAKMP_FLAG_E) {
/*
* encrypted, nothing we can do right now.
* we hope to decrypt the packet in the future...
*/
ND_PRINT((ndo, " [encrypted %s]", NPSTR(base->np)));
goto done;
}
CHECKLEN(p + 1, base->np)
np = base->np;
ext = (const struct isakmp_gen *)(p + 1);
ikev2_sub_print(ndo, base, np, ext, ep, phase, 0, 0, 0);
}
done:
if (ndo->ndo_vflag) {
if (ntohl(base->len) != length) {
ND_PRINT((ndo, " (len mismatch: isakmp %u/ip %u)",
(uint32_t)ntohl(base->len), length));
}
}
}
void
isakmp_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2)
{
const struct isakmp *p;
struct isakmp base;
const u_char *ep;
int major, minor;
#ifdef HAVE_LIBCRYPTO
/* initialize SAs */
if (ndo->ndo_sa_list_head == NULL) {
if (ndo->ndo_espsecret)
esp_print_decodesecret(ndo);
}
#endif
p = (const struct isakmp *)bp;
ep = ndo->ndo_snapend;
if ((const struct isakmp *)ep < p + 1) {
ND_PRINT((ndo,"[|isakmp]"));
return;
}
UNALIGNED_MEMCPY(&base, p, sizeof(base));
ND_PRINT((ndo,"isakmp"));
major = (base.vers & ISAKMP_VERS_MAJOR)
>> ISAKMP_VERS_MAJOR_SHIFT;
minor = (base.vers & ISAKMP_VERS_MINOR)
>> ISAKMP_VERS_MINOR_SHIFT;
if (ndo->ndo_vflag) {
ND_PRINT((ndo," %d.%d", major, minor));
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo," msgid "));
hexprint(ndo, (const uint8_t *)&base.msgid, sizeof(base.msgid));
}
if (1 < ndo->ndo_vflag) {
ND_PRINT((ndo," cookie "));
hexprint(ndo, (const uint8_t *)&base.i_ck, sizeof(base.i_ck));
ND_PRINT((ndo,"->"));
hexprint(ndo, (const uint8_t *)&base.r_ck, sizeof(base.r_ck));
}
ND_PRINT((ndo,":"));
switch(major) {
case IKEv1_MAJOR_VERSION:
ikev1_print(ndo, bp, length, bp2, &base);
break;
case IKEv2_MAJOR_VERSION:
ikev2_print(ndo, bp, length, bp2, &base);
break;
}
}
void
isakmp_rfc3948_print(netdissect_options *ndo,
const u_char *bp, u_int length,
const u_char *bp2)
{
ND_TCHECK(bp[0]);
if(length == 1 && bp[0]==0xff) {
ND_PRINT((ndo, "isakmp-nat-keep-alive"));
return;
}
if(length < 4) {
goto trunc;
}
ND_TCHECK(bp[3]);
/*
* see if this is an IKE packet
*/
if(bp[0]==0 && bp[1]==0 && bp[2]==0 && bp[3]==0) {
ND_PRINT((ndo, "NONESP-encap: "));
isakmp_print(ndo, bp+4, length-4, bp2);
return;
}
/* must be an ESP packet */
{
int nh, enh, padlen;
int advance;
ND_PRINT((ndo, "UDP-encap: "));
advance = esp_print(ndo, bp, length, bp2, &enh, &padlen);
if(advance <= 0)
return;
bp += advance;
length -= advance + padlen;
nh = enh & 0xff;
ip_print_inner(ndo, bp, length, nh, bp2);
return;
}
trunc:
ND_PRINT((ndo,"[|isakmp]"));
return;
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_267_0 |
crossvul-cpp_data_bad_801_0 | /*
* MPEG-4 decoder
* Copyright (c) 2000,2001 Fabrice Bellard
* Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define UNCHECKED_BITSTREAM_READER 1
#include "libavutil/internal.h"
#include "libavutil/opt.h"
#include "libavutil/pixdesc.h"
#include "error_resilience.h"
#include "hwaccel.h"
#include "idctdsp.h"
#include "internal.h"
#include "mpegutils.h"
#include "mpegvideo.h"
#include "mpegvideodata.h"
#include "mpeg4video.h"
#include "h263.h"
#include "profiles.h"
#include "thread.h"
#include "xvididct.h"
#include "unary.h"
/* The defines below define the number of bits that are read at once for
* reading vlc values. Changing these may improve speed and data cache needs
* be aware though that decreasing them may need the number of stages that is
* passed to get_vlc* to be increased. */
#define SPRITE_TRAJ_VLC_BITS 6
#define DC_VLC_BITS 9
#define MB_TYPE_B_VLC_BITS 4
#define STUDIO_INTRA_BITS 9
static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb);
static VLC dc_lum, dc_chrom;
static VLC sprite_trajectory;
static VLC mb_type_b_vlc;
static const int mb_type_b_map[4] = {
MB_TYPE_DIRECT2 | MB_TYPE_L0L1,
MB_TYPE_L0L1 | MB_TYPE_16x16,
MB_TYPE_L1 | MB_TYPE_16x16,
MB_TYPE_L0 | MB_TYPE_16x16,
};
/**
* Predict the ac.
* @param n block index (0-3 are luma, 4-5 are chroma)
* @param dir the ac prediction direction
*/
void ff_mpeg4_pred_ac(MpegEncContext *s, int16_t *block, int n, int dir)
{
int i;
int16_t *ac_val, *ac_val1;
int8_t *const qscale_table = s->current_picture.qscale_table;
/* find prediction */
ac_val = &s->ac_val[0][0][0] + s->block_index[n] * 16;
ac_val1 = ac_val;
if (s->ac_pred) {
if (dir == 0) {
const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride;
/* left prediction */
ac_val -= 16;
if (s->mb_x == 0 || s->qscale == qscale_table[xy] ||
n == 1 || n == 3) {
/* same qscale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i << 3]] += ac_val[i];
} else {
/* different qscale, we must rescale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i << 3]] += ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale);
}
} else {
const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride;
/* top prediction */
ac_val -= 16 * s->block_wrap[n];
if (s->mb_y == 0 || s->qscale == qscale_table[xy] ||
n == 2 || n == 3) {
/* same qscale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i]] += ac_val[i + 8];
} else {
/* different qscale, we must rescale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale);
}
}
}
/* left copy */
for (i = 1; i < 8; i++)
ac_val1[i] = block[s->idsp.idct_permutation[i << 3]];
/* top copy */
for (i = 1; i < 8; i++)
ac_val1[8 + i] = block[s->idsp.idct_permutation[i]];
}
/**
* check if the next stuff is a resync marker or the end.
* @return 0 if not
*/
static inline int mpeg4_is_resync(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int bits_count = get_bits_count(&s->gb);
int v = show_bits(&s->gb, 16);
if (s->workaround_bugs & FF_BUG_NO_PADDING && !ctx->resync_marker)
return 0;
while (v <= 0xFF) {
if (s->pict_type == AV_PICTURE_TYPE_B ||
(v >> (8 - s->pict_type) != 1) || s->partitioned_frame)
break;
skip_bits(&s->gb, 8 + s->pict_type);
bits_count += 8 + s->pict_type;
v = show_bits(&s->gb, 16);
}
if (bits_count + 8 >= s->gb.size_in_bits) {
v >>= 8;
v |= 0x7F >> (7 - (bits_count & 7));
if (v == 0x7F)
return s->mb_num;
} else {
if (v == ff_mpeg4_resync_prefix[bits_count & 7]) {
int len, mb_num;
int mb_num_bits = av_log2(s->mb_num - 1) + 1;
GetBitContext gb = s->gb;
skip_bits(&s->gb, 1);
align_get_bits(&s->gb);
for (len = 0; len < 32; len++)
if (get_bits1(&s->gb))
break;
mb_num = get_bits(&s->gb, mb_num_bits);
if (!mb_num || mb_num > s->mb_num || get_bits_count(&s->gb)+6 > s->gb.size_in_bits)
mb_num= -1;
s->gb = gb;
if (len >= ff_mpeg4_get_video_packet_prefix_length(s))
return mb_num;
}
}
return 0;
}
static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int a = 2 << s->sprite_warping_accuracy;
int rho = 3 - s->sprite_warping_accuracy;
int r = 16 / a;
int alpha = 1;
int beta = 0;
int w = s->width;
int h = s->height;
int min_ab, i, w2, h2, w3, h3;
int sprite_ref[4][2];
int virtual_ref[2][2];
int64_t sprite_offset[2][2];
int64_t sprite_delta[2][2];
// only true for rectangle shapes
const int vop_ref[4][2] = { { 0, 0 }, { s->width, 0 },
{ 0, s->height }, { s->width, s->height } };
int d[4][2] = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
if (w <= 0 || h <= 0)
return AVERROR_INVALIDDATA;
/* the decoder was not properly initialized and we cannot continue */
if (sprite_trajectory.table == NULL)
return AVERROR_INVALIDDATA;
for (i = 0; i < ctx->num_sprite_warping_points; i++) {
int length;
int x = 0, y = 0;
length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
if (length > 0)
x = get_xbits(gb, length);
if (!(ctx->divx_version == 500 && ctx->divx_build == 413))
check_marker(s->avctx, gb, "before sprite_trajectory");
length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
if (length > 0)
y = get_xbits(gb, length);
check_marker(s->avctx, gb, "after sprite_trajectory");
ctx->sprite_traj[i][0] = d[i][0] = x;
ctx->sprite_traj[i][1] = d[i][1] = y;
}
for (; i < 4; i++)
ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0;
while ((1 << alpha) < w)
alpha++;
while ((1 << beta) < h)
beta++; /* typo in the MPEG-4 std for the definition of w' and h' */
w2 = 1 << alpha;
h2 = 1 << beta;
// Note, the 4th point isn't used for GMC
if (ctx->divx_version == 500 && ctx->divx_build == 413) {
sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0];
sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1];
sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0];
sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1];
sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0];
sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1];
} else {
sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]);
sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]);
sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]);
sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]);
sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]);
sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]);
}
/* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
* sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
/* This is mostly identical to the MPEG-4 std (and is totally unreadable
* because of that...). Perhaps it should be reordered to be more readable.
* The idea behind this virtual_ref mess is to be able to use shifts later
* per pixel instead of divides so the distance between points is converted
* from w&h based to w2&h2 based which are of the 2^x form. */
virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) +
ROUNDED_DIV(((w - w2) *
(r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) +
w2 * (r * sprite_ref[1][0] - 16LL * vop_ref[1][0])), w);
virtual_ref[0][1] = 16 * vop_ref[0][1] +
ROUNDED_DIV(((w - w2) *
(r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) +
w2 * (r * sprite_ref[1][1] - 16LL * vop_ref[1][1])), w);
virtual_ref[1][0] = 16 * vop_ref[0][0] +
ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) +
h2 * (r * sprite_ref[2][0] - 16LL * vop_ref[2][0])), h);
virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) +
ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) +
h2 * (r * sprite_ref[2][1] - 16LL * vop_ref[2][1])), h);
switch (ctx->num_sprite_warping_points) {
case 0:
sprite_offset[0][0] =
sprite_offset[0][1] =
sprite_offset[1][0] =
sprite_offset[1][1] = 0;
sprite_delta[0][0] = a;
sprite_delta[0][1] =
sprite_delta[1][0] = 0;
sprite_delta[1][1] = a;
ctx->sprite_shift[0] =
ctx->sprite_shift[1] = 0;
break;
case 1: // GMC only
sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0];
sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1];
sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) -
a * (vop_ref[0][0] / 2);
sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) -
a * (vop_ref[0][1] / 2);
sprite_delta[0][0] = a;
sprite_delta[0][1] =
sprite_delta[1][0] = 0;
sprite_delta[1][1] = a;
ctx->sprite_shift[0] =
ctx->sprite_shift[1] = 0;
break;
case 2:
sprite_offset[0][0] = ((int64_t) sprite_ref[0][0] * (1 << alpha + rho)) +
((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t) -vop_ref[0][0]) +
((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) *
((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1));
sprite_offset[0][1] = ((int64_t) sprite_ref[0][1] * (1 << alpha + rho)) +
((int64_t) -r * sprite_ref[0][1] + virtual_ref[0][1]) *
((int64_t) -vop_ref[0][0]) +
((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1));
sprite_offset[1][0] = (((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t)-2 * vop_ref[0][0] + 1) +
((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) *
((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r *
(int64_t) sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1)));
sprite_offset[1][1] = (((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) *
((int64_t)-2 * vop_ref[0][0] + 1) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r *
(int64_t) sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1)));
sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]);
sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]);
sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
ctx->sprite_shift[0] = alpha + rho;
ctx->sprite_shift[1] = alpha + rho + 2;
break;
case 3:
min_ab = FFMIN(alpha, beta);
w3 = w2 >> min_ab;
h3 = h2 >> min_ab;
sprite_offset[0][0] = ((int64_t)sprite_ref[0][0] * (1 << (alpha + beta + rho - min_ab))) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-vop_ref[0][0]) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-vop_ref[0][1]) +
((int64_t)1 << (alpha + beta + rho - min_ab - 1));
sprite_offset[0][1] = ((int64_t)sprite_ref[0][1] * (1 << (alpha + beta + rho - min_ab))) +
((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-vop_ref[0][0]) +
((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-vop_ref[0][1]) +
((int64_t)1 << (alpha + beta + rho - min_ab - 1));
sprite_offset[1][0] = ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-2 * vop_ref[0][0] + 1) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-2 * vop_ref[0][1] + 1) +
(int64_t)2 * w2 * h3 * r * sprite_ref[0][0] - 16 * w2 * h3 +
((int64_t)1 << (alpha + beta + rho - min_ab + 1));
sprite_offset[1][1] = ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-2 * vop_ref[0][0] + 1) +
((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-2 * vop_ref[0][1] + 1) +
(int64_t)2 * w2 * h3 * r * sprite_ref[0][1] - 16 * w2 * h3 +
((int64_t)1 << (alpha + beta + rho - min_ab + 1));
sprite_delta[0][0] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[0][0]) * h3;
sprite_delta[0][1] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[1][0]) * w3;
sprite_delta[1][0] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[0][1]) * h3;
sprite_delta[1][1] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[1][1]) * w3;
ctx->sprite_shift[0] = alpha + beta + rho - min_ab;
ctx->sprite_shift[1] = alpha + beta + rho - min_ab + 2;
break;
}
/* try to simplify the situation */
if (sprite_delta[0][0] == a << ctx->sprite_shift[0] &&
sprite_delta[0][1] == 0 &&
sprite_delta[1][0] == 0 &&
sprite_delta[1][1] == a << ctx->sprite_shift[0]) {
sprite_offset[0][0] >>= ctx->sprite_shift[0];
sprite_offset[0][1] >>= ctx->sprite_shift[0];
sprite_offset[1][0] >>= ctx->sprite_shift[1];
sprite_offset[1][1] >>= ctx->sprite_shift[1];
sprite_delta[0][0] = a;
sprite_delta[0][1] = 0;
sprite_delta[1][0] = 0;
sprite_delta[1][1] = a;
ctx->sprite_shift[0] = 0;
ctx->sprite_shift[1] = 0;
s->real_sprite_warping_points = 1;
} else {
int shift_y = 16 - ctx->sprite_shift[0];
int shift_c = 16 - ctx->sprite_shift[1];
for (i = 0; i < 2; i++) {
if (shift_c < 0 || shift_y < 0 ||
FFABS( sprite_offset[0][i]) >= INT_MAX >> shift_y ||
FFABS( sprite_offset[1][i]) >= INT_MAX >> shift_c ||
FFABS( sprite_delta[0][i]) >= INT_MAX >> shift_y ||
FFABS( sprite_delta[1][i]) >= INT_MAX >> shift_y
) {
avpriv_request_sample(s->avctx, "Too large sprite shift, delta or offset");
goto overflow;
}
}
for (i = 0; i < 2; i++) {
sprite_offset[0][i] *= 1 << shift_y;
sprite_offset[1][i] *= 1 << shift_c;
sprite_delta[0][i] *= 1 << shift_y;
sprite_delta[1][i] *= 1 << shift_y;
ctx->sprite_shift[i] = 16;
}
for (i = 0; i < 2; i++) {
int64_t sd[2] = {
sprite_delta[i][0] - a * (1LL<<16),
sprite_delta[i][1] - a * (1LL<<16)
};
if (llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL) + sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
llabs(sprite_delta[i][0] * (w+16LL)) >= INT_MAX ||
llabs(sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
llabs(sd[0]) >= INT_MAX ||
llabs(sd[1]) >= INT_MAX ||
llabs(sprite_offset[0][i] + sd[0] * (w+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sd[1] * (h+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sd[0] * (w+16LL) + sd[1] * (h+16LL)) >= INT_MAX
) {
avpriv_request_sample(s->avctx, "Overflow on sprite points");
goto overflow;
}
}
s->real_sprite_warping_points = ctx->num_sprite_warping_points;
}
for (i = 0; i < 4; i++) {
s->sprite_offset[i&1][i>>1] = sprite_offset[i&1][i>>1];
s->sprite_delta [i&1][i>>1] = sprite_delta [i&1][i>>1];
}
return 0;
overflow:
memset(s->sprite_offset, 0, sizeof(s->sprite_offset));
memset(s->sprite_delta, 0, sizeof(s->sprite_delta));
return AVERROR_PATCHWELCOME;
}
static int decode_new_pred(Mpeg4DecContext *ctx, GetBitContext *gb) {
MpegEncContext *s = &ctx->m;
int len = FFMIN(ctx->time_increment_bits + 3, 15);
get_bits(gb, len);
if (get_bits1(gb))
get_bits(gb, len);
check_marker(s->avctx, gb, "after new_pred");
return 0;
}
/**
* Decode the next video packet.
* @return <0 if something went wrong
*/
int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int mb_num_bits = av_log2(s->mb_num - 1) + 1;
int header_extension = 0, mb_num, len;
/* is there enough space left for a video packet + header */
if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20)
return AVERROR_INVALIDDATA;
for (len = 0; len < 32; len++)
if (get_bits1(&s->gb))
break;
if (len != ff_mpeg4_get_video_packet_prefix_length(s)) {
av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");
return AVERROR_INVALIDDATA;
}
if (ctx->shape != RECT_SHAPE) {
header_extension = get_bits1(&s->gb);
// FIXME more stuff here
}
mb_num = get_bits(&s->gb, mb_num_bits);
if (mb_num >= s->mb_num || !mb_num) {
av_log(s->avctx, AV_LOG_ERROR,
"illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
return AVERROR_INVALIDDATA;
}
s->mb_x = mb_num % s->mb_width;
s->mb_y = mb_num / s->mb_width;
if (ctx->shape != BIN_ONLY_SHAPE) {
int qscale = get_bits(&s->gb, s->quant_precision);
if (qscale)
s->chroma_qscale = s->qscale = qscale;
}
if (ctx->shape == RECT_SHAPE)
header_extension = get_bits1(&s->gb);
if (header_extension) {
int time_incr = 0;
while (get_bits1(&s->gb) != 0)
time_incr++;
check_marker(s->avctx, &s->gb, "before time_increment in video packed header");
skip_bits(&s->gb, ctx->time_increment_bits); /* time_increment */
check_marker(s->avctx, &s->gb, "before vop_coding_type in video packed header");
skip_bits(&s->gb, 2); /* vop coding type */
// FIXME not rect stuff here
if (ctx->shape != BIN_ONLY_SHAPE) {
skip_bits(&s->gb, 3); /* intra dc vlc threshold */
// FIXME don't just ignore everything
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE) {
if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0)
return AVERROR_INVALIDDATA;
av_log(s->avctx, AV_LOG_ERROR, "untested\n");
}
// FIXME reduced res stuff here
if (s->pict_type != AV_PICTURE_TYPE_I) {
int f_code = get_bits(&s->gb, 3); /* fcode_for */
if (f_code == 0)
av_log(s->avctx, AV_LOG_ERROR,
"Error, video packet header damaged (f_code=0)\n");
}
if (s->pict_type == AV_PICTURE_TYPE_B) {
int b_code = get_bits(&s->gb, 3);
if (b_code == 0)
av_log(s->avctx, AV_LOG_ERROR,
"Error, video packet header damaged (b_code=0)\n");
}
}
}
if (ctx->new_pred)
decode_new_pred(ctx, &s->gb);
return 0;
}
static void reset_studio_dc_predictors(MpegEncContext *s)
{
/* Reset DC Predictors */
s->last_dc[0] =
s->last_dc[1] =
s->last_dc[2] = 1 << (s->avctx->bits_per_raw_sample + s->dct_precision + s->intra_dc_precision - 1);
}
/**
* Decode the next video packet.
* @return <0 if something went wrong
*/
int ff_mpeg4_decode_studio_slice_header(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
GetBitContext *gb = &s->gb;
unsigned vlc_len;
uint16_t mb_num;
if (get_bits_left(gb) >= 32 && get_bits_long(gb, 32) == SLICE_START_CODE) {
vlc_len = av_log2(s->mb_width * s->mb_height) + 1;
mb_num = get_bits(gb, vlc_len);
if (mb_num >= s->mb_num)
return AVERROR_INVALIDDATA;
s->mb_x = mb_num % s->mb_width;
s->mb_y = mb_num / s->mb_width;
if (ctx->shape != BIN_ONLY_SHAPE)
s->qscale = mpeg_get_qscale(s);
if (get_bits1(gb)) { /* slice_extension_flag */
skip_bits1(gb); /* intra_slice */
skip_bits1(gb); /* slice_VOP_id_enable */
skip_bits(gb, 6); /* slice_VOP_id */
while (get_bits1(gb)) /* extra_bit_slice */
skip_bits(gb, 8); /* extra_information_slice */
}
reset_studio_dc_predictors(s);
}
else {
return AVERROR_INVALIDDATA;
}
return 0;
}
/**
* Get the average motion vector for a GMC MB.
* @param n either 0 for the x component or 1 for y
* @return the average MV for a GMC MB
*/
static inline int get_amv(Mpeg4DecContext *ctx, int n)
{
MpegEncContext *s = &ctx->m;
int x, y, mb_v, sum, dx, dy, shift;
int len = 1 << (s->f_code + 4);
const int a = s->sprite_warping_accuracy;
if (s->workaround_bugs & FF_BUG_AMV)
len >>= s->quarter_sample;
if (s->real_sprite_warping_points == 1) {
if (ctx->divx_version == 500 && ctx->divx_build == 413 && a >= s->quarter_sample)
sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample));
else
sum = RSHIFT(s->sprite_offset[0][n] * (1 << s->quarter_sample), a);
} else {
dx = s->sprite_delta[n][0];
dy = s->sprite_delta[n][1];
shift = ctx->sprite_shift[0];
if (n)
dy -= 1 << (shift + a + 1);
else
dx -= 1 << (shift + a + 1);
mb_v = s->sprite_offset[0][n] + dx * s->mb_x * 16 + dy * s->mb_y * 16;
sum = 0;
for (y = 0; y < 16; y++) {
int v;
v = mb_v + dy * y;
// FIXME optimize
for (x = 0; x < 16; x++) {
sum += v >> shift;
v += dx;
}
}
sum = RSHIFT(sum, a + 8 - s->quarter_sample);
}
if (sum < -len)
sum = -len;
else if (sum >= len)
sum = len - 1;
return sum;
}
/**
* Decode the dc value.
* @param n block index (0-3 are luma, 4-5 are chroma)
* @param dir_ptr the prediction direction will be stored here
* @return the quantized dc
*/
static inline int mpeg4_decode_dc(MpegEncContext *s, int n, int *dir_ptr)
{
int level, code;
if (n < 4)
code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
else
code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
if (code < 0 || code > 9 /* && s->nbit < 9 */) {
av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n");
return AVERROR_INVALIDDATA;
}
if (code == 0) {
level = 0;
} else {
if (IS_3IV1) {
if (code == 1)
level = 2 * get_bits1(&s->gb) - 1;
else {
if (get_bits1(&s->gb))
level = get_bits(&s->gb, code - 1) + (1 << (code - 1));
else
level = -get_bits(&s->gb, code - 1) - (1 << (code - 1));
}
} else {
level = get_xbits(&s->gb, code);
}
if (code > 8) {
if (get_bits1(&s->gb) == 0) { /* marker */
if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)) {
av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n");
return AVERROR_INVALIDDATA;
}
}
}
}
return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0);
}
/**
* Decode first partition.
* @return number of MBs decoded or <0 if an error occurred
*/
static int mpeg4_decode_partition_a(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int mb_num = 0;
static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
/* decode first partition */
s->first_slice_line = 1;
for (; s->mb_y < s->mb_height; s->mb_y++) {
ff_init_block_index(s);
for (; s->mb_x < s->mb_width; s->mb_x++) {
const int xy = s->mb_x + s->mb_y * s->mb_stride;
int cbpc;
int dir = 0;
mb_num++;
ff_update_block_index(s);
if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
s->first_slice_line = 0;
if (s->pict_type == AV_PICTURE_TYPE_I) {
int i;
do {
if (show_bits_long(&s->gb, 19) == DC_MARKER)
return mb_num - 1;
cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} while (cbpc == 8);
s->cbp_table[xy] = cbpc & 3;
s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
s->mb_intra = 1;
if (cbpc & 4)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
s->current_picture.qscale_table[xy] = s->qscale;
s->mbintra_table[xy] = 1;
for (i = 0; i < 6; i++) {
int dc_pred_dir;
int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
if (dc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"DC corrupted at %d %d\n", s->mb_x, s->mb_y);
return dc;
}
dir <<= 1;
if (dc_pred_dir)
dir |= 1;
}
s->pred_dir_table[xy] = dir;
} else { /* P/S_TYPE */
int mx, my, pred_x, pred_y, bits;
int16_t *const mot_val = s->current_picture.motion_val[0][s->block_index[0]];
const int stride = s->b8_stride * 2;
try_again:
bits = show_bits(&s->gb, 17);
if (bits == MOTION_MARKER)
return mb_num - 1;
skip_bits1(&s->gb);
if (bits & 0x10000) {
/* skip mb */
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE) {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_GMC |
MB_TYPE_L0;
mx = get_amv(ctx, 0);
my = get_amv(ctx, 1);
} else {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_L0;
mx = my = 0;
}
mot_val[0] =
mot_val[2] =
mot_val[0 + stride] =
mot_val[2 + stride] = mx;
mot_val[1] =
mot_val[3] =
mot_val[1 + stride] =
mot_val[3 + stride] = my;
if (s->mbintra_table[xy])
ff_clean_intra_table_entries(s);
continue;
}
cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
if (cbpc == 20)
goto try_again;
s->cbp_table[xy] = cbpc & (8 + 3); // 8 is dquant
s->mb_intra = ((cbpc & 4) != 0);
if (s->mb_intra) {
s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
s->mbintra_table[xy] = 1;
mot_val[0] =
mot_val[2] =
mot_val[0 + stride] =
mot_val[2 + stride] = 0;
mot_val[1] =
mot_val[3] =
mot_val[1 + stride] =
mot_val[3 + stride] = 0;
} else {
if (s->mbintra_table[xy])
ff_clean_intra_table_entries(s);
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE &&
(cbpc & 16) == 0)
s->mcsel = get_bits1(&s->gb);
else
s->mcsel = 0;
if ((cbpc & 16) == 0) {
/* 16x16 motion prediction */
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
if (!s->mcsel) {
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->current_picture.mb_type[xy] = MB_TYPE_16x16 |
MB_TYPE_L0;
} else {
mx = get_amv(ctx, 0);
my = get_amv(ctx, 1);
s->current_picture.mb_type[xy] = MB_TYPE_16x16 |
MB_TYPE_GMC |
MB_TYPE_L0;
}
mot_val[0] =
mot_val[2] =
mot_val[0 + stride] =
mot_val[2 + stride] = mx;
mot_val[1] =
mot_val[3] =
mot_val[1 + stride] =
mot_val[3 + stride] = my;
} else {
int i;
s->current_picture.mb_type[xy] = MB_TYPE_8x8 |
MB_TYPE_L0;
for (i = 0; i < 4; i++) {
int16_t *mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
mot_val[0] = mx;
mot_val[1] = my;
}
}
}
}
}
s->mb_x = 0;
}
return mb_num;
}
/**
* decode second partition.
* @return <0 if an error occurred
*/
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count)
{
int mb_num = 0;
static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
s->mb_x = s->resync_mb_x;
s->first_slice_line = 1;
for (s->mb_y = s->resync_mb_y; mb_num < mb_count; s->mb_y++) {
ff_init_block_index(s);
for (; mb_num < mb_count && s->mb_x < s->mb_width; s->mb_x++) {
const int xy = s->mb_x + s->mb_y * s->mb_stride;
mb_num++;
ff_update_block_index(s);
if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
s->first_slice_line = 0;
if (s->pict_type == AV_PICTURE_TYPE_I) {
int ac_pred = get_bits1(&s->gb);
int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
s->cbp_table[xy] |= cbpy << 2;
s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
} else { /* P || S_TYPE */
if (IS_INTRA(s->current_picture.mb_type[xy])) {
int i;
int dir = 0;
int ac_pred = get_bits1(&s->gb);
int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
if (s->cbp_table[xy] & 8)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
s->current_picture.qscale_table[xy] = s->qscale;
for (i = 0; i < 6; i++) {
int dc_pred_dir;
int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
if (dc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"DC corrupted at %d %d\n", s->mb_x, s->mb_y);
return dc;
}
dir <<= 1;
if (dc_pred_dir)
dir |= 1;
}
s->cbp_table[xy] &= 3; // remove dquant
s->cbp_table[xy] |= cbpy << 2;
s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
s->pred_dir_table[xy] = dir;
} else if (IS_SKIP(s->current_picture.mb_type[xy])) {
s->current_picture.qscale_table[xy] = s->qscale;
s->cbp_table[xy] = 0;
} else {
int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
if (s->cbp_table[xy] & 8)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
s->current_picture.qscale_table[xy] = s->qscale;
s->cbp_table[xy] &= 3; // remove dquant
s->cbp_table[xy] |= (cbpy ^ 0xf) << 2;
}
}
}
if (mb_num >= mb_count)
return 0;
s->mb_x = 0;
}
return 0;
}
/**
* Decode the first and second partition.
* @return <0 if error (and sets error type in the error_status_table)
*/
int ff_mpeg4_decode_partitions(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int mb_num;
int ret;
const int part_a_error = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_ERROR | ER_MV_ERROR) : ER_MV_ERROR;
const int part_a_end = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_END | ER_MV_END) : ER_MV_END;
mb_num = mpeg4_decode_partition_a(ctx);
if (mb_num <= 0) {
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x, s->mb_y, part_a_error);
return mb_num ? mb_num : AVERROR_INVALIDDATA;
}
if (s->resync_mb_x + s->resync_mb_y * s->mb_width + mb_num > s->mb_num) {
av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x, s->mb_y, part_a_error);
return AVERROR_INVALIDDATA;
}
s->mb_num_left = mb_num;
if (s->pict_type == AV_PICTURE_TYPE_I) {
while (show_bits(&s->gb, 9) == 1)
skip_bits(&s->gb, 9);
if (get_bits_long(&s->gb, 19) != DC_MARKER) {
av_log(s->avctx, AV_LOG_ERROR,
"marker missing after first I partition at %d %d\n",
s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} else {
while (show_bits(&s->gb, 10) == 1)
skip_bits(&s->gb, 10);
if (get_bits(&s->gb, 17) != MOTION_MARKER) {
av_log(s->avctx, AV_LOG_ERROR,
"marker missing after first P partition at %d %d\n",
s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
}
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x - 1, s->mb_y, part_a_end);
ret = mpeg4_decode_partition_b(s, mb_num);
if (ret < 0) {
if (s->pict_type == AV_PICTURE_TYPE_P)
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x, s->mb_y, ER_DC_ERROR);
return ret;
} else {
if (s->pict_type == AV_PICTURE_TYPE_P)
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x - 1, s->mb_y, ER_DC_END);
}
return 0;
}
/**
* Decode a block.
* @return <0 if an error occurred
*/
static inline int mpeg4_decode_block(Mpeg4DecContext *ctx, int16_t *block,
int n, int coded, int intra, int rvlc)
{
MpegEncContext *s = &ctx->m;
int level, i, last, run, qmul, qadd;
int av_uninit(dc_pred_dir);
RLTable *rl;
RL_VLC_ELEM *rl_vlc;
const uint8_t *scan_table;
// Note intra & rvlc should be optimized away if this is inlined
if (intra) {
if (ctx->use_intra_dc_vlc) {
/* DC coef */
if (s->partitioned_frame) {
level = s->dc_val[0][s->block_index[n]];
if (n < 4)
level = FASTDIV((level + (s->y_dc_scale >> 1)), s->y_dc_scale);
else
level = FASTDIV((level + (s->c_dc_scale >> 1)), s->c_dc_scale);
dc_pred_dir = (s->pred_dir_table[s->mb_x + s->mb_y * s->mb_stride] << n) & 32;
} else {
level = mpeg4_decode_dc(s, n, &dc_pred_dir);
if (level < 0)
return level;
}
block[0] = level;
i = 0;
} else {
i = -1;
ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0);
}
if (!coded)
goto not_coded;
if (rvlc) {
rl = &ff_rvlc_rl_intra;
rl_vlc = ff_rvlc_rl_intra.rl_vlc[0];
} else {
rl = &ff_mpeg4_rl_intra;
rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0];
}
if (s->ac_pred) {
if (dc_pred_dir == 0)
scan_table = s->intra_v_scantable.permutated; /* left */
else
scan_table = s->intra_h_scantable.permutated; /* top */
} else {
scan_table = s->intra_scantable.permutated;
}
qmul = 1;
qadd = 0;
} else {
i = -1;
if (!coded) {
s->block_last_index[n] = i;
return 0;
}
if (rvlc)
rl = &ff_rvlc_rl_inter;
else
rl = &ff_h263_rl_inter;
scan_table = s->intra_scantable.permutated;
if (s->mpeg_quant) {
qmul = 1;
qadd = 0;
if (rvlc)
rl_vlc = ff_rvlc_rl_inter.rl_vlc[0];
else
rl_vlc = ff_h263_rl_inter.rl_vlc[0];
} else {
qmul = s->qscale << 1;
qadd = (s->qscale - 1) | 1;
if (rvlc)
rl_vlc = ff_rvlc_rl_inter.rl_vlc[s->qscale];
else
rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale];
}
}
{
OPEN_READER(re, &s->gb);
for (;;) {
UPDATE_CACHE(re, &s->gb);
GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0);
if (level == 0) {
/* escape */
if (rvlc) {
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"1. marker bit missing in rvlc esc\n");
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 1);
last = SHOW_UBITS(re, &s->gb, 1);
SKIP_CACHE(re, &s->gb, 1);
run = SHOW_UBITS(re, &s->gb, 6);
SKIP_COUNTER(re, &s->gb, 1 + 1 + 6);
UPDATE_CACHE(re, &s->gb);
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"2. marker bit missing in rvlc esc\n");
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 1);
level = SHOW_UBITS(re, &s->gb, 11);
SKIP_CACHE(re, &s->gb, 11);
if (SHOW_UBITS(re, &s->gb, 5) != 0x10) {
av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n");
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 5);
level = level * qmul + qadd;
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
SKIP_COUNTER(re, &s->gb, 1 + 11 + 5 + 1);
i += run + 1;
if (last)
i += 192;
} else {
int cache;
cache = GET_CACHE(re, &s->gb);
if (IS_3IV1)
cache ^= 0xC0000000;
if (cache & 0x80000000) {
if (cache & 0x40000000) {
/* third escape */
SKIP_CACHE(re, &s->gb, 2);
last = SHOW_UBITS(re, &s->gb, 1);
SKIP_CACHE(re, &s->gb, 1);
run = SHOW_UBITS(re, &s->gb, 6);
SKIP_COUNTER(re, &s->gb, 2 + 1 + 6);
UPDATE_CACHE(re, &s->gb);
if (IS_3IV1) {
level = SHOW_SBITS(re, &s->gb, 12);
LAST_SKIP_BITS(re, &s->gb, 12);
} else {
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"1. marker bit missing in 3. esc\n");
if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR))
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 1);
level = SHOW_SBITS(re, &s->gb, 12);
SKIP_CACHE(re, &s->gb, 12);
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"2. marker bit missing in 3. esc\n");
if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR))
return AVERROR_INVALIDDATA;
}
SKIP_COUNTER(re, &s->gb, 1 + 12 + 1);
}
#if 0
if (s->error_recognition >= FF_ER_COMPLIANT) {
const int abs_level= FFABS(level);
if (abs_level<=MAX_LEVEL && run<=MAX_RUN) {
const int run1= run - rl->max_run[last][abs_level] - 1;
if (abs_level <= rl->max_level[last][run]) {
av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");
return AVERROR_INVALIDDATA;
}
if (s->error_recognition > FF_ER_COMPLIANT) {
if (abs_level <= rl->max_level[last][run]*2) {
av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n");
return AVERROR_INVALIDDATA;
}
if (run1 >= 0 && abs_level <= rl->max_level[last][run1]) {
av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n");
return AVERROR_INVALIDDATA;
}
}
}
}
#endif
if (level > 0)
level = level * qmul + qadd;
else
level = level * qmul - qadd;
if ((unsigned)(level + 2048) > 4095) {
if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_AGGRESSIVE)) {
if (level > 2560 || level < -2560) {
av_log(s->avctx, AV_LOG_ERROR,
"|level| overflow in 3. esc, qp=%d\n",
s->qscale);
return AVERROR_INVALIDDATA;
}
}
level = level < 0 ? -2048 : 2047;
}
i += run + 1;
if (last)
i += 192;
} else {
/* second escape */
SKIP_BITS(re, &s->gb, 2);
GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
i += run + rl->max_run[run >> 7][level / qmul] + 1; // FIXME opt indexing
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
LAST_SKIP_BITS(re, &s->gb, 1);
}
} else {
/* first escape */
SKIP_BITS(re, &s->gb, 1);
GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
i += run;
level = level + rl->max_level[run >> 7][(run - 1) & 63] * qmul; // FIXME opt indexing
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
LAST_SKIP_BITS(re, &s->gb, 1);
}
}
} else {
i += run;
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
LAST_SKIP_BITS(re, &s->gb, 1);
}
ff_tlog(s->avctx, "dct[%d][%d] = %- 4d end?:%d\n", scan_table[i&63]&7, scan_table[i&63] >> 3, level, i>62);
if (i > 62) {
i -= 192;
if (i & (~63)) {
av_log(s->avctx, AV_LOG_ERROR,
"ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
block[scan_table[i]] = level;
break;
}
block[scan_table[i]] = level;
}
CLOSE_READER(re, &s->gb);
}
not_coded:
if (intra) {
if (!ctx->use_intra_dc_vlc) {
block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0);
i -= i >> 31; // if (i == -1) i = 0;
}
ff_mpeg4_pred_ac(s, block, n, dc_pred_dir);
if (s->ac_pred)
i = 63; // FIXME not optimal
}
s->block_last_index[n] = i;
return 0;
}
/**
* decode partition C of one MB.
* @return <0 if an error occurred
*/
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64])
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cbp, mb_type;
const int xy = s->mb_x + s->mb_y * s->mb_stride;
av_assert2(s == (void*)ctx);
mb_type = s->current_picture.mb_type[xy];
cbp = s->cbp_table[xy];
ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
if (s->current_picture.qscale_table[xy] != s->qscale)
ff_set_qscale(s, s->current_picture.qscale_table[xy]);
if (s->pict_type == AV_PICTURE_TYPE_P ||
s->pict_type == AV_PICTURE_TYPE_S) {
int i;
for (i = 0; i < 4; i++) {
s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
}
s->mb_intra = IS_INTRA(mb_type);
if (IS_SKIP(mb_type)) {
/* skip mb */
for (i = 0; i < 6; i++)
s->block_last_index[i] = -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
if (s->pict_type == AV_PICTURE_TYPE_S
&& ctx->vol_sprite_usage == GMC_SPRITE) {
s->mcsel = 1;
s->mb_skipped = 0;
} else {
s->mcsel = 0;
s->mb_skipped = 1;
}
} else if (s->mb_intra) {
s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
} else if (!s->mb_intra) {
// s->mcsel = 0; // FIXME do we need to init that?
s->mv_dir = MV_DIR_FORWARD;
if (IS_8X8(mb_type)) {
s->mv_type = MV_TYPE_8X8;
} else {
s->mv_type = MV_TYPE_16X16;
}
}
} else { /* I-Frame */
s->mb_intra = 1;
s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
}
if (!IS_SKIP(mb_type)) {
int i;
s->bdsp.clear_blocks(s->block[0]);
/* decode each block */
for (i = 0; i < 6; i++) {
if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra, ctx->rvlc) < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"texture corrupted at %d %d %d\n",
s->mb_x, s->mb_y, s->mb_intra);
return AVERROR_INVALIDDATA;
}
cbp += cbp;
}
}
/* per-MB end of slice check */
if (--s->mb_num_left <= 0) {
if (mpeg4_is_resync(ctx))
return SLICE_END;
else
return SLICE_NOEND;
} else {
if (mpeg4_is_resync(ctx)) {
const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1;
if (s->cbp_table[xy + delta])
return SLICE_END;
}
return SLICE_OK;
}
}
static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64])
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
int16_t *mot_val;
static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
const int xy = s->mb_x + s->mb_y * s->mb_stride;
av_assert2(s == (void*)ctx);
av_assert2(s->h263_pred);
if (s->pict_type == AV_PICTURE_TYPE_P ||
s->pict_type == AV_PICTURE_TYPE_S) {
do {
if (get_bits1(&s->gb)) {
/* skip mb */
s->mb_intra = 0;
for (i = 0; i < 6; i++)
s->block_last_index[i] = -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE) {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_GMC |
MB_TYPE_16x16 |
MB_TYPE_L0;
s->mcsel = 1;
s->mv[0][0][0] = get_amv(ctx, 0);
s->mv[0][0][1] = get_amv(ctx, 1);
s->mb_skipped = 0;
} else {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_L0;
s->mcsel = 0;
s->mv[0][0][0] = 0;
s->mv[0][0][1] = 0;
s->mb_skipped = 1;
}
goto end;
}
cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"mcbpc damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} while (cbpc == 20);
s->bdsp.clear_blocks(s->block[0]);
dquant = cbpc & 8;
s->mb_intra = ((cbpc & 4) != 0);
if (s->mb_intra)
goto intra;
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0)
s->mcsel = get_bits1(&s->gb);
else
s->mcsel = 0;
cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F;
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"P cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
cbp = (cbpc & 3) | (cbpy << 2);
if (dquant)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
if ((!s->progressive_sequence) &&
(cbp || (s->workaround_bugs & FF_BUG_XVID_ILACE)))
s->interlaced_dct = get_bits1(&s->gb);
s->mv_dir = MV_DIR_FORWARD;
if ((cbpc & 16) == 0) {
if (s->mcsel) {
s->current_picture.mb_type[xy] = MB_TYPE_GMC |
MB_TYPE_16x16 |
MB_TYPE_L0;
/* 16x16 global motion prediction */
s->mv_type = MV_TYPE_16X16;
mx = get_amv(ctx, 0);
my = get_amv(ctx, 1);
s->mv[0][0][0] = mx;
s->mv[0][0][1] = my;
} else if ((!s->progressive_sequence) && get_bits1(&s->gb)) {
s->current_picture.mb_type[xy] = MB_TYPE_16x8 |
MB_TYPE_L0 |
MB_TYPE_INTERLACED;
/* 16x8 field motion prediction */
s->mv_type = MV_TYPE_FIELD;
s->field_select[0][0] = get_bits1(&s->gb);
s->field_select[0][1] = get_bits1(&s->gb);
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
for (i = 0; i < 2; i++) {
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y / 2, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->mv[0][i][0] = mx;
s->mv[0][i][1] = my;
}
} else {
s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
/* 16x16 motion prediction */
s->mv_type = MV_TYPE_16X16;
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->mv[0][0][0] = mx;
s->mv[0][0][1] = my;
}
} else {
s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;
s->mv_type = MV_TYPE_8X8;
for (i = 0; i < 4; i++) {
mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->mv[0][i][0] = mx;
s->mv[0][i][1] = my;
mot_val[0] = mx;
mot_val[1] = my;
}
}
} else if (s->pict_type == AV_PICTURE_TYPE_B) {
int modb1; // first bit of modb
int modb2; // second bit of modb
int mb_type;
s->mb_intra = 0; // B-frames never contain intra blocks
s->mcsel = 0; // ... true gmc blocks
if (s->mb_x == 0) {
for (i = 0; i < 2; i++) {
s->last_mv[i][0][0] =
s->last_mv[i][0][1] =
s->last_mv[i][1][0] =
s->last_mv[i][1][1] = 0;
}
ff_thread_await_progress(&s->next_picture_ptr->tf, s->mb_y, 0);
}
/* if we skipped it in the future P-frame than skip it now too */
s->mb_skipped = s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]; // Note, skiptab=0 if last was GMC
if (s->mb_skipped) {
/* skip mb */
for (i = 0; i < 6; i++)
s->block_last_index[i] = -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
s->mv[0][0][0] =
s->mv[0][0][1] =
s->mv[1][0][0] =
s->mv[1][0][1] = 0;
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_L0;
goto end;
}
modb1 = get_bits1(&s->gb);
if (modb1) {
// like MB_TYPE_B_DIRECT but no vectors coded
mb_type = MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1;
cbp = 0;
} else {
modb2 = get_bits1(&s->gb);
mb_type = get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
if (mb_type < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");
return AVERROR_INVALIDDATA;
}
mb_type = mb_type_b_map[mb_type];
if (modb2) {
cbp = 0;
} else {
s->bdsp.clear_blocks(s->block[0]);
cbp = get_bits(&s->gb, 6);
}
if ((!IS_DIRECT(mb_type)) && cbp) {
if (get_bits1(&s->gb))
ff_set_qscale(s, s->qscale + get_bits1(&s->gb) * 4 - 2);
}
if (!s->progressive_sequence) {
if (cbp)
s->interlaced_dct = get_bits1(&s->gb);
if (!IS_DIRECT(mb_type) && get_bits1(&s->gb)) {
mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
mb_type &= ~MB_TYPE_16x16;
if (USES_LIST(mb_type, 0)) {
s->field_select[0][0] = get_bits1(&s->gb);
s->field_select[0][1] = get_bits1(&s->gb);
}
if (USES_LIST(mb_type, 1)) {
s->field_select[1][0] = get_bits1(&s->gb);
s->field_select[1][1] = get_bits1(&s->gb);
}
}
}
s->mv_dir = 0;
if ((mb_type & (MB_TYPE_DIRECT2 | MB_TYPE_INTERLACED)) == 0) {
s->mv_type = MV_TYPE_16X16;
if (USES_LIST(mb_type, 0)) {
s->mv_dir = MV_DIR_FORWARD;
mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
s->last_mv[0][1][0] =
s->last_mv[0][0][0] =
s->mv[0][0][0] = mx;
s->last_mv[0][1][1] =
s->last_mv[0][0][1] =
s->mv[0][0][1] = my;
}
if (USES_LIST(mb_type, 1)) {
s->mv_dir |= MV_DIR_BACKWARD;
mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
s->last_mv[1][1][0] =
s->last_mv[1][0][0] =
s->mv[1][0][0] = mx;
s->last_mv[1][1][1] =
s->last_mv[1][0][1] =
s->mv[1][0][1] = my;
}
} else if (!IS_DIRECT(mb_type)) {
s->mv_type = MV_TYPE_FIELD;
if (USES_LIST(mb_type, 0)) {
s->mv_dir = MV_DIR_FORWARD;
for (i = 0; i < 2; i++) {
mx = ff_h263_decode_motion(s, s->last_mv[0][i][0], s->f_code);
my = ff_h263_decode_motion(s, s->last_mv[0][i][1] / 2, s->f_code);
s->last_mv[0][i][0] =
s->mv[0][i][0] = mx;
s->last_mv[0][i][1] = (s->mv[0][i][1] = my) * 2;
}
}
if (USES_LIST(mb_type, 1)) {
s->mv_dir |= MV_DIR_BACKWARD;
for (i = 0; i < 2; i++) {
mx = ff_h263_decode_motion(s, s->last_mv[1][i][0], s->b_code);
my = ff_h263_decode_motion(s, s->last_mv[1][i][1] / 2, s->b_code);
s->last_mv[1][i][0] =
s->mv[1][i][0] = mx;
s->last_mv[1][i][1] = (s->mv[1][i][1] = my) * 2;
}
}
}
}
if (IS_DIRECT(mb_type)) {
if (IS_SKIP(mb_type)) {
mx =
my = 0;
} else {
mx = ff_h263_decode_motion(s, 0, 1);
my = ff_h263_decode_motion(s, 0, 1);
}
s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
mb_type |= ff_mpeg4_set_direct_mv(s, mx, my);
}
s->current_picture.mb_type[xy] = mb_type;
} else { /* I-Frame */
do {
cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} while (cbpc == 8);
dquant = cbpc & 4;
s->mb_intra = 1;
intra:
s->ac_pred = get_bits1(&s->gb);
if (s->ac_pred)
s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED;
else
s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
cbp = (cbpc & 3) | (cbpy << 2);
ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
if (dquant)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
if (!s->progressive_sequence)
s->interlaced_dct = get_bits1(&s->gb);
s->bdsp.clear_blocks(s->block[0]);
/* decode each block */
for (i = 0; i < 6; i++) {
if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 1, 0) < 0)
return AVERROR_INVALIDDATA;
cbp += cbp;
}
goto end;
}
/* decode each block */
for (i = 0; i < 6; i++) {
if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 0, 0) < 0)
return AVERROR_INVALIDDATA;
cbp += cbp;
}
end:
/* per-MB end of slice check */
if (s->codec_id == AV_CODEC_ID_MPEG4) {
int next = mpeg4_is_resync(ctx);
if (next) {
if (s->mb_x + s->mb_y*s->mb_width + 1 > next && (s->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
return AVERROR_INVALIDDATA;
} else if (s->mb_x + s->mb_y*s->mb_width + 1 >= next)
return SLICE_END;
if (s->pict_type == AV_PICTURE_TYPE_B) {
const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
ff_thread_await_progress(&s->next_picture_ptr->tf,
(s->mb_x + delta >= s->mb_width)
? FFMIN(s->mb_y + 1, s->mb_height - 1)
: s->mb_y, 0);
if (s->next_picture.mbskip_table[xy + delta])
return SLICE_OK;
}
return SLICE_END;
}
}
return SLICE_OK;
}
/* As per spec, studio start code search isn't the same as the old type of start code */
static void next_start_code_studio(GetBitContext *gb)
{
align_get_bits(gb);
while (get_bits_left(gb) >= 24 && show_bits_long(gb, 24) != 0x1) {
get_bits(gb, 8);
}
}
/* additional_code, vlc index */
static const uint8_t ac_state_tab[22][2] =
{
{0, 0},
{0, 1},
{1, 1},
{2, 1},
{3, 1},
{4, 1},
{5, 1},
{1, 2},
{2, 2},
{3, 2},
{4, 2},
{5, 2},
{6, 2},
{1, 3},
{2, 4},
{3, 5},
{4, 6},
{5, 7},
{6, 8},
{7, 9},
{8, 10},
{0, 11}
};
static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n)
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0,
additional_code_len, sign, mismatch;
VLC *cur_vlc = &ctx->studio_intra_tab[0];
uint8_t *const scantable = s->intra_scantable.permutated;
const uint16_t *quant_matrix;
uint32_t flc;
const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6));
const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1);
mismatch = 1;
memset(block, 0, 64 * sizeof(int32_t));
if (n < 4) {
cc = 0;
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->intra_matrix;
} else {
cc = (n & 1) + 1;
if (ctx->rgb)
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
else
dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->chroma_intra_matrix;
}
if (dct_dc_size < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n");
return AVERROR_INVALIDDATA;
} else if (dct_dc_size == 0) {
dct_diff = 0;
} else {
dct_diff = get_xbits(&s->gb, dct_dc_size);
if (dct_dc_size > 8) {
if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8"))
return AVERROR_INVALIDDATA;
}
}
s->last_dc[cc] += dct_diff;
if (s->mpeg_quant)
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision);
else
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision);
/* TODO: support mpeg_quant for AC coefficients */
block[0] = av_clip(block[0], min, max);
mismatch ^= block[0];
/* AC Coefficients */
while (1) {
group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2);
if (group < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n");
return AVERROR_INVALIDDATA;
}
additional_code_len = ac_state_tab[group][0];
cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]];
if (group == 0) {
/* End of Block */
break;
} else if (group >= 1 && group <= 6) {
/* Zero run length (Table B.47) */
run = 1 << additional_code_len;
if (additional_code_len)
run += get_bits(&s->gb, additional_code_len);
idx += run;
continue;
} else if (group >= 7 && group <= 12) {
/* Zero run length and +/-1 level (Table B.48) */
code = get_bits(&s->gb, additional_code_len);
sign = code & 1;
code >>= 1;
run = (1 << (additional_code_len - 1)) + code;
idx += run;
j = scantable[idx++];
block[j] = sign ? 1 : -1;
} else if (group >= 13 && group <= 20) {
/* Level value (Table B.49) */
j = scantable[idx++];
block[j] = get_xbits(&s->gb, additional_code_len);
} else if (group == 21) {
/* Escape */
j = scantable[idx++];
additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4;
flc = get_bits(&s->gb, additional_code_len);
if (flc >> (additional_code_len-1))
block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1);
else
block[j] = flc;
}
block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32;
block[j] = av_clip(block[j], min, max);
mismatch ^= block[j];
}
block[63] ^= mismatch & 1;
return 0;
}
static int mpeg4_decode_dpcm_macroblock(MpegEncContext *s, int16_t macroblock[256], int n)
{
int i, j, w, h, idx = 0;
int block_mean, rice_parameter, rice_prefix_code, rice_suffix_code,
dpcm_residual, left, top, topleft, min_left_top, max_left_top, p, p2, output;
h = 16 >> (n ? s->chroma_y_shift : 0);
w = 16 >> (n ? s->chroma_x_shift : 0);
block_mean = get_bits(&s->gb, s->avctx->bits_per_raw_sample);
if (block_mean == 0){
av_log(s->avctx, AV_LOG_ERROR, "Forbidden block_mean\n");
return AVERROR_INVALIDDATA;
}
s->last_dc[n] = block_mean * (1 << (s->dct_precision + s->intra_dc_precision));
rice_parameter = get_bits(&s->gb, 4);
if (rice_parameter == 0) {
av_log(s->avctx, AV_LOG_ERROR, "Forbidden rice_parameter\n");
return AVERROR_INVALIDDATA;
}
if (rice_parameter == 15)
rice_parameter = 0;
if (rice_parameter > 11) {
av_log(s->avctx, AV_LOG_ERROR, "Forbidden rice_parameter\n");
return AVERROR_INVALIDDATA;
}
for (i = 0; i < h; i++) {
output = 1 << (s->avctx->bits_per_raw_sample - 1);
top = 1 << (s->avctx->bits_per_raw_sample - 1);
for (j = 0; j < w; j++) {
left = output;
topleft = top;
rice_prefix_code = get_unary(&s->gb, 1, 12);
/* Escape */
if (rice_prefix_code == 11)
dpcm_residual = get_bits(&s->gb, s->avctx->bits_per_raw_sample);
else {
if (rice_prefix_code == 12) {
av_log(s->avctx, AV_LOG_ERROR, "Forbidden rice_prefix_code\n");
return AVERROR_INVALIDDATA;
}
rice_suffix_code = get_bitsz(&s->gb, rice_parameter);
dpcm_residual = (rice_prefix_code << rice_parameter) + rice_suffix_code;
}
/* Map to a signed residual */
if (dpcm_residual & 1)
dpcm_residual = (-1 * dpcm_residual) >> 1;
else
dpcm_residual = (dpcm_residual >> 1);
if (i != 0)
top = macroblock[idx-w];
p = left + top - topleft;
min_left_top = FFMIN(left, top);
if (p < min_left_top)
p = min_left_top;
max_left_top = FFMAX(left, top);
if (p > max_left_top)
p = max_left_top;
p2 = (FFMIN(min_left_top, topleft) + FFMAX(max_left_top, topleft)) >> 1;
if (p2 == p)
p2 = block_mean;
if (p2 > p)
dpcm_residual *= -1;
macroblock[idx++] = output = (dpcm_residual + p) & ((1 << s->avctx->bits_per_raw_sample) - 1);
}
}
return 0;
}
static int mpeg4_decode_studio_mb(MpegEncContext *s, int16_t block_[12][64])
{
int i;
s->dpcm_direction = 0;
/* StudioMacroblock */
/* Assumes I-VOP */
s->mb_intra = 1;
if (get_bits1(&s->gb)) { /* compression_mode */
/* DCT */
/* macroblock_type, 1 or 2-bit VLC */
if (!get_bits1(&s->gb)) {
skip_bits1(&s->gb);
s->qscale = mpeg_get_qscale(s);
}
for (i = 0; i < mpeg4_block_count[s->chroma_format]; i++) {
if (mpeg4_decode_studio_block(s, (*s->block32)[i], i) < 0)
return AVERROR_INVALIDDATA;
}
} else {
/* DPCM */
check_marker(s->avctx, &s->gb, "DPCM block start");
s->dpcm_direction = get_bits1(&s->gb) ? -1 : 1;
for (i = 0; i < 3; i++) {
if (mpeg4_decode_dpcm_macroblock(s, (*s->dpcm_macroblock)[i], i) < 0)
return AVERROR_INVALIDDATA;
}
}
if (get_bits_left(&s->gb) >= 24 && show_bits(&s->gb, 23) == 0) {
next_start_code_studio(&s->gb);
return SLICE_END;
}
//vcon-stp9L1.bits (first frame)
if (get_bits_left(&s->gb) == 0)
return SLICE_END;
//vcon-stp2L1.bits, vcon-stp3L1.bits, vcon-stp6L1.bits, vcon-stp7L1.bits, vcon-stp8L1.bits, vcon-stp10L1.bits (first frame)
if (get_bits_left(&s->gb) < 8U && show_bits(&s->gb, get_bits_left(&s->gb)) == 0)
return SLICE_END;
return SLICE_OK;
}
static int mpeg4_decode_gop_header(MpegEncContext *s, GetBitContext *gb)
{
int hours, minutes, seconds;
if (!show_bits(gb, 23)) {
av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n");
return AVERROR_INVALIDDATA;
}
hours = get_bits(gb, 5);
minutes = get_bits(gb, 6);
check_marker(s->avctx, gb, "in gop_header");
seconds = get_bits(gb, 6);
s->time_base = seconds + 60*(minutes + 60*hours);
skip_bits1(gb);
skip_bits1(gb);
return 0;
}
static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb, int *profile, int *level)
{
*profile = get_bits(gb, 4);
*level = get_bits(gb, 4);
// for Simple profile, level 0
if (*profile == 0 && *level == 8) {
*level = 0;
}
return 0;
}
static int mpeg4_decode_visual_object(MpegEncContext *s, GetBitContext *gb)
{
int visual_object_type;
int is_visual_object_identifier = get_bits1(gb);
if (is_visual_object_identifier) {
skip_bits(gb, 4+3);
}
visual_object_type = get_bits(gb, 4);
if (visual_object_type == VOT_VIDEO_ID ||
visual_object_type == VOT_STILL_TEXTURE_ID) {
int video_signal_type = get_bits1(gb);
if (video_signal_type) {
int video_range, color_description;
skip_bits(gb, 3); // video_format
video_range = get_bits1(gb);
color_description = get_bits1(gb);
s->avctx->color_range = video_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
if (color_description) {
s->avctx->color_primaries = get_bits(gb, 8);
s->avctx->color_trc = get_bits(gb, 8);
s->avctx->colorspace = get_bits(gb, 8);
}
}
}
return 0;
}
static void mpeg4_load_default_matrices(MpegEncContext *s)
{
int i, v;
/* load default matrices */
for (i = 0; i < 64; i++) {
int j = s->idsp.idct_permutation[i];
v = ff_mpeg4_default_intra_matrix[i];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
v = ff_mpeg4_default_non_intra_matrix[i];
s->inter_matrix[j] = v;
s->chroma_inter_matrix[j] = v;
}
}
static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int width, height, vo_ver_id;
/* vol header */
skip_bits(gb, 1); /* random access */
s->vo_type = get_bits(gb, 8);
/* If we are in studio profile (per vo_type), check if its all consistent
* and if so continue pass control to decode_studio_vol_header().
* elIf something is inconsistent, error out
* else continue with (non studio) vol header decpoding.
*/
if (s->vo_type == CORE_STUDIO_VO_TYPE ||
s->vo_type == SIMPLE_STUDIO_VO_TYPE) {
if (s->avctx->profile != FF_PROFILE_UNKNOWN && s->avctx->profile != FF_PROFILE_MPEG4_SIMPLE_STUDIO)
return AVERROR_INVALIDDATA;
s->studio_profile = 1;
s->avctx->profile = FF_PROFILE_MPEG4_SIMPLE_STUDIO;
return decode_studio_vol_header(ctx, gb);
} else if (s->studio_profile) {
return AVERROR_PATCHWELCOME;
}
if (get_bits1(gb) != 0) { /* is_ol_id */
vo_ver_id = get_bits(gb, 4); /* vo_ver_id */
skip_bits(gb, 3); /* vo_priority */
} else {
vo_ver_id = 1;
}
s->aspect_ratio_info = get_bits(gb, 4);
if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width
s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height
} else {
s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info];
}
if ((ctx->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */
int chroma_format = get_bits(gb, 2);
if (chroma_format != CHROMA_420)
av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
s->low_delay = get_bits1(gb);
if (get_bits1(gb)) { /* vbv parameters */
get_bits(gb, 15); /* first_half_bitrate */
check_marker(s->avctx, gb, "after first_half_bitrate");
get_bits(gb, 15); /* latter_half_bitrate */
check_marker(s->avctx, gb, "after latter_half_bitrate");
get_bits(gb, 15); /* first_half_vbv_buffer_size */
check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
get_bits(gb, 3); /* latter_half_vbv_buffer_size */
get_bits(gb, 11); /* first_half_vbv_occupancy */
check_marker(s->avctx, gb, "after first_half_vbv_occupancy");
get_bits(gb, 15); /* latter_half_vbv_occupancy */
check_marker(s->avctx, gb, "after latter_half_vbv_occupancy");
}
} else {
/* is setting low delay flag only once the smartest thing to do?
* low delay detection will not be overridden. */
if (s->picture_number == 0) {
switch(s->vo_type) {
case SIMPLE_VO_TYPE:
case ADV_SIMPLE_VO_TYPE:
s->low_delay = 1;
break;
default:
s->low_delay = 0;
}
}
}
ctx->shape = get_bits(gb, 2); /* vol shape */
if (ctx->shape != RECT_SHAPE)
av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n");
if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) {
av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n");
skip_bits(gb, 4); /* video_object_layer_shape_extension */
}
check_marker(s->avctx, gb, "before time_increment_resolution");
s->avctx->framerate.num = get_bits(gb, 16);
if (!s->avctx->framerate.num) {
av_log(s->avctx, AV_LOG_ERROR, "framerate==0\n");
return AVERROR_INVALIDDATA;
}
ctx->time_increment_bits = av_log2(s->avctx->framerate.num - 1) + 1;
if (ctx->time_increment_bits < 1)
ctx->time_increment_bits = 1;
check_marker(s->avctx, gb, "before fixed_vop_rate");
if (get_bits1(gb) != 0) /* fixed_vop_rate */
s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits);
else
s->avctx->framerate.den = 1;
s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
ctx->t_frame = 0;
if (ctx->shape != BIN_ONLY_SHAPE) {
if (ctx->shape == RECT_SHAPE) {
check_marker(s->avctx, gb, "before width");
width = get_bits(gb, 13);
check_marker(s->avctx, gb, "before height");
height = get_bits(gb, 13);
check_marker(s->avctx, gb, "after height");
if (width && height && /* they should be non zero but who knows */
!(s->width && s->codec_tag == AV_RL32("MP4S"))) {
if (s->width && s->height &&
(s->width != width || s->height != height))
s->context_reinit = 1;
s->width = width;
s->height = height;
}
}
s->progressive_sequence =
s->progressive_frame = get_bits1(gb) ^ 1;
s->interlaced_dct = 0;
if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO))
av_log(s->avctx, AV_LOG_INFO, /* OBMC Disable */
"MPEG-4 OBMC not supported (very likely buggy encoder)\n");
if (vo_ver_id == 1)
ctx->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */
else
ctx->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */
if (ctx->vol_sprite_usage == STATIC_SPRITE)
av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n");
if (ctx->vol_sprite_usage == STATIC_SPRITE ||
ctx->vol_sprite_usage == GMC_SPRITE) {
if (ctx->vol_sprite_usage == STATIC_SPRITE) {
skip_bits(gb, 13); // sprite_width
check_marker(s->avctx, gb, "after sprite_width");
skip_bits(gb, 13); // sprite_height
check_marker(s->avctx, gb, "after sprite_height");
skip_bits(gb, 13); // sprite_left
check_marker(s->avctx, gb, "after sprite_left");
skip_bits(gb, 13); // sprite_top
check_marker(s->avctx, gb, "after sprite_top");
}
ctx->num_sprite_warping_points = get_bits(gb, 6);
if (ctx->num_sprite_warping_points > 3) {
av_log(s->avctx, AV_LOG_ERROR,
"%d sprite_warping_points\n",
ctx->num_sprite_warping_points);
ctx->num_sprite_warping_points = 0;
return AVERROR_INVALIDDATA;
}
s->sprite_warping_accuracy = get_bits(gb, 2);
ctx->sprite_brightness_change = get_bits1(gb);
if (ctx->vol_sprite_usage == STATIC_SPRITE)
skip_bits1(gb); // low_latency_sprite
}
// FIXME sadct disable bit if verid!=1 && shape not rect
if (get_bits1(gb) == 1) { /* not_8_bit */
s->quant_precision = get_bits(gb, 4); /* quant_precision */
if (get_bits(gb, 4) != 8) /* bits_per_pixel */
av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n");
if (s->quant_precision != 5)
av_log(s->avctx, AV_LOG_ERROR,
"quant precision %d\n", s->quant_precision);
if (s->quant_precision<3 || s->quant_precision>9) {
s->quant_precision = 5;
}
} else {
s->quant_precision = 5;
}
// FIXME a bunch of grayscale shape things
if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */
int i, v;
mpeg4_load_default_matrices(s);
/* load custom intra matrix */
if (get_bits1(gb)) {
int last = 0;
for (i = 0; i < 64; i++) {
int j;
if (get_bits_left(gb) < 8) {
av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
return AVERROR_INVALIDDATA;
}
v = get_bits(gb, 8);
if (v == 0)
break;
last = v;
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = last;
s->chroma_intra_matrix[j] = last;
}
/* replicate last value */
for (; i < 64; i++) {
int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = last;
s->chroma_intra_matrix[j] = last;
}
}
/* load custom non intra matrix */
if (get_bits1(gb)) {
int last = 0;
for (i = 0; i < 64; i++) {
int j;
if (get_bits_left(gb) < 8) {
av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
return AVERROR_INVALIDDATA;
}
v = get_bits(gb, 8);
if (v == 0)
break;
last = v;
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->inter_matrix[j] = v;
s->chroma_inter_matrix[j] = v;
}
/* replicate last value */
for (; i < 64; i++) {
int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->inter_matrix[j] = last;
s->chroma_inter_matrix[j] = last;
}
}
// FIXME a bunch of grayscale shape things
}
if (vo_ver_id != 1)
s->quarter_sample = get_bits1(gb);
else
s->quarter_sample = 0;
if (get_bits_left(gb) < 4) {
av_log(s->avctx, AV_LOG_ERROR, "VOL Header truncated\n");
return AVERROR_INVALIDDATA;
}
if (!get_bits1(gb)) {
int pos = get_bits_count(gb);
int estimation_method = get_bits(gb, 2);
if (estimation_method < 2) {
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* opaque */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* transparent */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_cae */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* inter_cae */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* no_update */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* upsampling */
}
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_blocks */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter_blocks */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter4v_blocks */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* not coded blocks */
}
if (!check_marker(s->avctx, gb, "in complexity estimation part 1")) {
skip_bits_long(gb, pos - get_bits_count(gb));
goto no_cplx_est;
}
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_coeffs */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_lines */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* vlc_syms */
ctx->cplx_estimation_trash_i += 4 * get_bits1(gb); /* vlc_bits */
}
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* apm */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* npm */
ctx->cplx_estimation_trash_b += 8 * get_bits1(gb); /* interpolate_mc_q */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* forwback_mc_q */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel2 */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel4 */
}
if (!check_marker(s->avctx, gb, "in complexity estimation part 2")) {
skip_bits_long(gb, pos - get_bits_count(gb));
goto no_cplx_est;
}
if (estimation_method == 1) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* sadct */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* qpel */
}
} else
av_log(s->avctx, AV_LOG_ERROR,
"Invalid Complexity estimation method %d\n",
estimation_method);
} else {
no_cplx_est:
ctx->cplx_estimation_trash_i =
ctx->cplx_estimation_trash_p =
ctx->cplx_estimation_trash_b = 0;
}
ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */
s->data_partitioning = get_bits1(gb);
if (s->data_partitioning)
ctx->rvlc = get_bits1(gb);
if (vo_ver_id != 1) {
ctx->new_pred = get_bits1(gb);
if (ctx->new_pred) {
av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n");
skip_bits(gb, 2); /* requested upstream message type */
skip_bits1(gb); /* newpred segment type */
}
if (get_bits1(gb)) // reduced_res_vop
av_log(s->avctx, AV_LOG_ERROR,
"reduced resolution VOP not supported\n");
} else {
ctx->new_pred = 0;
}
ctx->scalability = get_bits1(gb);
if (ctx->scalability) {
GetBitContext bak = *gb;
int h_sampling_factor_n;
int h_sampling_factor_m;
int v_sampling_factor_n;
int v_sampling_factor_m;
skip_bits1(gb); // hierarchy_type
skip_bits(gb, 4); /* ref_layer_id */
skip_bits1(gb); /* ref_layer_sampling_dir */
h_sampling_factor_n = get_bits(gb, 5);
h_sampling_factor_m = get_bits(gb, 5);
v_sampling_factor_n = get_bits(gb, 5);
v_sampling_factor_m = get_bits(gb, 5);
ctx->enhancement_type = get_bits1(gb);
if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 ||
v_sampling_factor_n == 0 || v_sampling_factor_m == 0) {
/* illegal scalability header (VERY broken encoder),
* trying to workaround */
ctx->scalability = 0;
*gb = bak;
} else
av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n");
// bin shape stuff FIXME
}
}
if (s->avctx->debug&FF_DEBUG_PICT_INFO) {
av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d, low_delay:%d %s%s%s%s\n",
s->avctx->framerate.den, s->avctx->framerate.num,
ctx->time_increment_bits,
s->quant_precision,
s->progressive_sequence,
s->low_delay,
ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "",
s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : ""
);
}
return 0;
}
/**
* Decode the user data stuff in the header.
* Also initializes divx/xvid/lavc_version/build.
*/
static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
char buf[256];
int i;
int e;
int ver = 0, build = 0, ver2 = 0, ver3 = 0;
char last;
for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) {
if (show_bits(gb, 23) == 0)
break;
buf[i] = get_bits(gb, 8);
}
buf[i] = 0;
/* divx detection */
e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last);
if (e < 2)
e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last);
if (e >= 2) {
ctx->divx_version = ver;
ctx->divx_build = build;
s->divx_packed = e == 3 && last == 'p';
}
/* libavcodec detection */
e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3;
if (e != 4)
e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build);
if (e != 4) {
e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1;
if (e > 1) {
if (ver > 0xFFU || ver2 > 0xFFU || ver3 > 0xFFU) {
av_log(s->avctx, AV_LOG_WARNING,
"Unknown Lavc version string encountered, %d.%d.%d; "
"clamping sub-version values to 8-bits.\n",
ver, ver2, ver3);
}
build = ((ver & 0xFF) << 16) + ((ver2 & 0xFF) << 8) + (ver3 & 0xFF);
}
}
if (e != 4) {
if (strcmp(buf, "ffmpeg") == 0)
ctx->lavc_build = 4600;
}
if (e == 4)
ctx->lavc_build = build;
/* Xvid detection */
e = sscanf(buf, "XviD%d", &build);
if (e == 1)
ctx->xvid_build = build;
return 0;
}
int ff_mpeg4_workaround_bugs(AVCodecContext *avctx)
{
Mpeg4DecContext *ctx = avctx->priv_data;
MpegEncContext *s = &ctx->m;
if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) {
if (s->codec_tag == AV_RL32("XVID") ||
s->codec_tag == AV_RL32("XVIX") ||
s->codec_tag == AV_RL32("RMP4") ||
s->codec_tag == AV_RL32("ZMP4") ||
s->codec_tag == AV_RL32("SIPP"))
ctx->xvid_build = 0;
}
if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1)
if (s->codec_tag == AV_RL32("DIVX") && s->vo_type == 0 &&
ctx->vol_control_parameters == 0)
ctx->divx_version = 400; // divx 4
if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) {
ctx->divx_version =
ctx->divx_build = -1;
}
if (s->workaround_bugs & FF_BUG_AUTODETECT) {
if (s->codec_tag == AV_RL32("XVIX"))
s->workaround_bugs |= FF_BUG_XVID_ILACE;
if (s->codec_tag == AV_RL32("UMP4"))
s->workaround_bugs |= FF_BUG_UMP4;
if (ctx->divx_version >= 500 && ctx->divx_build < 1814)
s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
if (ctx->divx_version > 502 && ctx->divx_build < 1814)
s->workaround_bugs |= FF_BUG_QPEL_CHROMA2;
if (ctx->xvid_build <= 3U)
s->padding_bug_score = 256 * 256 * 256 * 64;
if (ctx->xvid_build <= 1U)
s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
if (ctx->xvid_build <= 12U)
s->workaround_bugs |= FF_BUG_EDGE;
if (ctx->xvid_build <= 32U)
s->workaround_bugs |= FF_BUG_DC_CLIP;
#define SET_QPEL_FUNC(postfix1, postfix2) \
s->qdsp.put_ ## postfix1 = ff_put_ ## postfix2; \
s->qdsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2; \
s->qdsp.avg_ ## postfix1 = ff_avg_ ## postfix2;
if (ctx->lavc_build < 4653U)
s->workaround_bugs |= FF_BUG_STD_QPEL;
if (ctx->lavc_build < 4655U)
s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
if (ctx->lavc_build < 4670U)
s->workaround_bugs |= FF_BUG_EDGE;
if (ctx->lavc_build <= 4712U)
s->workaround_bugs |= FF_BUG_DC_CLIP;
if ((ctx->lavc_build&0xFF) >= 100) {
if (ctx->lavc_build > 3621476 && ctx->lavc_build < 3752552 &&
(ctx->lavc_build < 3752037 || ctx->lavc_build > 3752191) // 3.2.1+
)
s->workaround_bugs |= FF_BUG_IEDGE;
}
if (ctx->divx_version >= 0)
s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
if (ctx->divx_version == 501 && ctx->divx_build == 20020416)
s->padding_bug_score = 256 * 256 * 256 * 64;
if (ctx->divx_version < 500U)
s->workaround_bugs |= FF_BUG_EDGE;
if (ctx->divx_version >= 0)
s->workaround_bugs |= FF_BUG_HPEL_CHROMA;
}
if (s->workaround_bugs & FF_BUG_STD_QPEL) {
SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c)
}
if (avctx->debug & FF_DEBUG_BUGS)
av_log(s->avctx, AV_LOG_DEBUG,
"bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n",
s->workaround_bugs, ctx->lavc_build, ctx->xvid_build,
ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : "");
if (CONFIG_MPEG4_DECODER && ctx->xvid_build >= 0 &&
s->codec_id == AV_CODEC_ID_MPEG4 &&
avctx->idct_algo == FF_IDCT_AUTO) {
avctx->idct_algo = FF_IDCT_XVID;
ff_mpv_idct_init(s);
return 1;
}
return 0;
}
static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int time_incr, time_increment;
int64_t pts;
s->mcsel = 0;
s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* pict type: I = 0 , P = 1 */
if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay &&
ctx->vol_control_parameters == 0 && !(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) {
av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set incorrectly, clearing it\n");
s->low_delay = 0;
}
s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;
if (s->partitioned_frame)
s->decode_mb = mpeg4_decode_partitioned_mb;
else
s->decode_mb = mpeg4_decode_mb;
time_incr = 0;
while (get_bits1(gb) != 0)
time_incr++;
check_marker(s->avctx, gb, "before time_increment");
if (ctx->time_increment_bits == 0 ||
!(show_bits(gb, ctx->time_increment_bits + 1) & 1)) {
av_log(s->avctx, AV_LOG_WARNING,
"time_increment_bits %d is invalid in relation to the current bitstream, this is likely caused by a missing VOL header\n", ctx->time_increment_bits);
for (ctx->time_increment_bits = 1;
ctx->time_increment_bits < 16;
ctx->time_increment_bits++) {
if (s->pict_type == AV_PICTURE_TYPE_P ||
(s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE)) {
if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30)
break;
} else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18)
break;
}
av_log(s->avctx, AV_LOG_WARNING,
"time_increment_bits set to %d bits, based on bitstream analysis\n", ctx->time_increment_bits);
if (s->avctx->framerate.num && 4*s->avctx->framerate.num < 1<<ctx->time_increment_bits) {
s->avctx->framerate.num = 1<<ctx->time_increment_bits;
s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
}
}
if (IS_3IV1)
time_increment = get_bits1(gb); // FIXME investigate further
else
time_increment = get_bits(gb, ctx->time_increment_bits);
if (s->pict_type != AV_PICTURE_TYPE_B) {
s->last_time_base = s->time_base;
s->time_base += time_incr;
s->time = s->time_base * (int64_t)s->avctx->framerate.num + time_increment;
if (s->workaround_bugs & FF_BUG_UMP4) {
if (s->time < s->last_non_b_time) {
/* header is not mpeg-4-compatible, broken encoder,
* trying to workaround */
s->time_base++;
s->time += s->avctx->framerate.num;
}
}
s->pp_time = s->time - s->last_non_b_time;
s->last_non_b_time = s->time;
} else {
s->time = (s->last_time_base + time_incr) * (int64_t)s->avctx->framerate.num + time_increment;
s->pb_time = s->pp_time - (s->last_non_b_time - s->time);
if (s->pp_time <= s->pb_time ||
s->pp_time <= s->pp_time - s->pb_time ||
s->pp_time <= 0) {
/* messed up order, maybe after seeking? skipping current B-frame */
return FRAME_SKIPPED;
}
ff_mpeg4_init_direct_mv(s);
if (ctx->t_frame == 0)
ctx->t_frame = s->pb_time;
if (ctx->t_frame == 0)
ctx->t_frame = 1; // 1/0 protection
s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) -
ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) -
ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1) {
s->pb_field_time = 2;
s->pp_field_time = 4;
if (!s->progressive_sequence)
return FRAME_SKIPPED;
}
}
if (s->avctx->framerate.den)
pts = ROUNDED_DIV(s->time, s->avctx->framerate.den);
else
pts = AV_NOPTS_VALUE;
ff_dlog(s->avctx, "MPEG4 PTS: %"PRId64"\n", pts);
check_marker(s->avctx, gb, "before vop_coded");
/* vop coded */
if (get_bits1(gb) != 1) {
if (s->avctx->debug & FF_DEBUG_PICT_INFO)
av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");
return FRAME_SKIPPED;
}
if (ctx->new_pred)
decode_new_pred(ctx, gb);
if (ctx->shape != BIN_ONLY_SHAPE &&
(s->pict_type == AV_PICTURE_TYPE_P ||
(s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE))) {
/* rounding type for motion estimation */
s->no_rounding = get_bits1(gb);
} else {
s->no_rounding = 0;
}
// FIXME reduced res stuff
if (ctx->shape != RECT_SHAPE) {
if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) {
skip_bits(gb, 13); /* width */
check_marker(s->avctx, gb, "after width");
skip_bits(gb, 13); /* height */
check_marker(s->avctx, gb, "after height");
skip_bits(gb, 13); /* hor_spat_ref */
check_marker(s->avctx, gb, "after hor_spat_ref");
skip_bits(gb, 13); /* ver_spat_ref */
}
skip_bits1(gb); /* change_CR_disable */
if (get_bits1(gb) != 0)
skip_bits(gb, 8); /* constant_alpha_value */
}
// FIXME complexity estimation stuff
if (ctx->shape != BIN_ONLY_SHAPE) {
skip_bits_long(gb, ctx->cplx_estimation_trash_i);
if (s->pict_type != AV_PICTURE_TYPE_I)
skip_bits_long(gb, ctx->cplx_estimation_trash_p);
if (s->pict_type == AV_PICTURE_TYPE_B)
skip_bits_long(gb, ctx->cplx_estimation_trash_b);
if (get_bits_left(gb) < 3) {
av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n");
return AVERROR_INVALIDDATA;
}
ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)];
if (!s->progressive_sequence) {
s->top_field_first = get_bits1(gb);
s->alternate_scan = get_bits1(gb);
} else
s->alternate_scan = 0;
}
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
if (s->pict_type == AV_PICTURE_TYPE_S) {
if((ctx->vol_sprite_usage == STATIC_SPRITE ||
ctx->vol_sprite_usage == GMC_SPRITE)) {
if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0)
return AVERROR_INVALIDDATA;
if (ctx->sprite_brightness_change)
av_log(s->avctx, AV_LOG_ERROR,
"sprite_brightness_change not supported\n");
if (ctx->vol_sprite_usage == STATIC_SPRITE)
av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");
} else {
memset(s->sprite_offset, 0, sizeof(s->sprite_offset));
memset(s->sprite_delta, 0, sizeof(s->sprite_delta));
}
}
if (ctx->shape != BIN_ONLY_SHAPE) {
s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision);
if (s->qscale == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Error, header damaged or not MPEG-4 header (qscale=0)\n");
return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then
}
if (s->pict_type != AV_PICTURE_TYPE_I) {
s->f_code = get_bits(gb, 3); /* fcode_for */
if (s->f_code == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Error, header damaged or not MPEG-4 header (f_code=0)\n");
s->f_code = 1;
return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then
}
} else
s->f_code = 1;
if (s->pict_type == AV_PICTURE_TYPE_B) {
s->b_code = get_bits(gb, 3);
if (s->b_code == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Error, header damaged or not MPEG4 header (b_code=0)\n");
s->b_code=1;
return AVERROR_INVALIDDATA; // makes no sense to continue, as the MV decoding will break very quickly
}
} else
s->b_code = 1;
if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
av_log(s->avctx, AV_LOG_DEBUG,
"qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d time:%"PRId64" tincr:%d\n",
s->qscale, s->f_code, s->b_code,
s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")),
gb->size_in_bits,s->progressive_sequence, s->alternate_scan,
s->top_field_first, s->quarter_sample ? "q" : "h",
s->data_partitioning, ctx->resync_marker,
ctx->num_sprite_warping_points, s->sprite_warping_accuracy,
1 - s->no_rounding, s->vo_type,
ctx->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold,
ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p,
ctx->cplx_estimation_trash_b,
s->time,
time_increment
);
}
if (!ctx->scalability) {
if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I)
skip_bits1(gb); // vop shape coding type
} else {
if (ctx->enhancement_type) {
int load_backward_shape = get_bits1(gb);
if (load_backward_shape)
av_log(s->avctx, AV_LOG_ERROR,
"load backward shape isn't supported\n");
}
skip_bits(gb, 2); // ref_select_code
}
}
/* detect buggy encoders which don't set the low_delay flag
* (divx4/xvid/opendivx). Note we cannot detect divx5 without B-frames
* easily (although it's buggy too) */
if (s->vo_type == 0 && ctx->vol_control_parameters == 0 &&
ctx->divx_version == -1 && s->picture_number == 0) {
av_log(s->avctx, AV_LOG_WARNING,
"looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
s->low_delay = 1;
}
s->picture_number++; // better than pic number==0 always ;)
// FIXME add short header support
s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table;
s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table;
if (s->workaround_bugs & FF_BUG_EDGE) {
s->h_edge_pos = s->width;
s->v_edge_pos = s->height;
}
return 0;
}
static int read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)
{
int i, j, v;
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* chroma_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* chroma_non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
next_start_code_studio(gb);
return 0;
}
static void extension_and_user_data(MpegEncContext *s, GetBitContext *gb, int id)
{
uint32_t startcode;
uint8_t extension_type;
startcode = show_bits_long(gb, 32);
if (startcode == USER_DATA_STARTCODE || startcode == EXT_STARTCODE) {
if ((id == 2 || id == 4) && startcode == EXT_STARTCODE) {
skip_bits_long(gb, 32);
extension_type = get_bits(gb, 4);
if (extension_type == QUANT_MATRIX_EXT_ID)
read_quant_matrix_ext(s, gb);
}
}
}
static void decode_smpte_tc(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
skip_bits(gb, 16); /* Time_code[63..48] */
check_marker(s->avctx, gb, "after Time_code[63..48]");
skip_bits(gb, 16); /* Time_code[47..32] */
check_marker(s->avctx, gb, "after Time_code[47..32]");
skip_bits(gb, 16); /* Time_code[31..16] */
check_marker(s->avctx, gb, "after Time_code[31..16]");
skip_bits(gb, 16); /* Time_code[15..0] */
check_marker(s->avctx, gb, "after Time_code[15..0]");
skip_bits(gb, 4); /* reserved_bits */
}
/**
* Decode the next studio vop header.
* @return <0 if something went wrong
*/
static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
if (get_bits_left(gb) <= 32)
return 0;
s->partitioned_frame = 0;
s->interlaced_dct = 0;
s->decode_mb = mpeg4_decode_studio_mb;
decode_smpte_tc(ctx, gb);
skip_bits(gb, 10); /* temporal_reference */
skip_bits(gb, 2); /* vop_structure */
s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */
if (get_bits1(gb)) { /* vop_coded */
skip_bits1(gb); /* top_field_first */
skip_bits1(gb); /* repeat_first_field */
s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */
}
if (s->pict_type == AV_PICTURE_TYPE_I) {
if (get_bits1(gb))
reset_studio_dc_predictors(s);
}
if (ctx->shape != BIN_ONLY_SHAPE) {
s->alternate_scan = get_bits1(gb);
s->frame_pred_frame_dct = get_bits1(gb);
s->dct_precision = get_bits(gb, 2);
s->intra_dc_precision = get_bits(gb, 2);
s->q_scale_type = get_bits1(gb);
}
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
mpeg4_load_default_matrices(s);
next_start_code_studio(gb);
extension_and_user_data(s, gb, 4);
return 0;
}
static int decode_studiovisualobject(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int visual_object_type;
skip_bits(gb, 4); /* visual_object_verid */
visual_object_type = get_bits(gb, 4);
if (visual_object_type != VOT_VIDEO_ID) {
avpriv_request_sample(s->avctx, "VO type %u", visual_object_type);
return AVERROR_PATCHWELCOME;
}
next_start_code_studio(gb);
extension_and_user_data(s, gb, 1);
return 0;
}
static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int width, height;
int bits_per_raw_sample;
// random_accessible_vol and video_object_type_indication have already
// been read by the caller decode_vol_header()
skip_bits(gb, 4); /* video_object_layer_verid */
ctx->shape = get_bits(gb, 2); /* video_object_layer_shape */
skip_bits(gb, 4); /* video_object_layer_shape_extension */
skip_bits1(gb); /* progressive_sequence */
if (ctx->shape != BIN_ONLY_SHAPE) {
ctx->rgb = get_bits1(gb); /* rgb_components */
s->chroma_format = get_bits(gb, 2); /* chroma_format */
if (!s->chroma_format) {
av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
return AVERROR_INVALIDDATA;
}
bits_per_raw_sample = get_bits(gb, 4); /* bit_depth */
if (bits_per_raw_sample == 10) {
if (ctx->rgb) {
s->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
}
else {
s->avctx->pix_fmt = s->chroma_format == CHROMA_422 ? AV_PIX_FMT_YUV422P10 : AV_PIX_FMT_YUV444P10;
}
}
else {
avpriv_request_sample(s->avctx, "MPEG-4 Studio profile bit-depth %u", bits_per_raw_sample);
return AVERROR_PATCHWELCOME;
}
s->avctx->bits_per_raw_sample = bits_per_raw_sample;
}
if (ctx->shape == RECT_SHAPE) {
check_marker(s->avctx, gb, "before video_object_layer_width");
width = get_bits(gb, 14); /* video_object_layer_width */
check_marker(s->avctx, gb, "before video_object_layer_height");
height = get_bits(gb, 14); /* video_object_layer_height */
check_marker(s->avctx, gb, "after video_object_layer_height");
/* Do the same check as non-studio profile */
if (width && height) {
if (s->width && s->height &&
(s->width != width || s->height != height))
s->context_reinit = 1;
s->width = width;
s->height = height;
}
}
s->aspect_ratio_info = get_bits(gb, 4);
if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width
s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height
} else {
s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info];
}
skip_bits(gb, 4); /* frame_rate_code */
skip_bits(gb, 15); /* first_half_bit_rate */
check_marker(s->avctx, gb, "after first_half_bit_rate");
skip_bits(gb, 15); /* latter_half_bit_rate */
check_marker(s->avctx, gb, "after latter_half_bit_rate");
skip_bits(gb, 15); /* first_half_vbv_buffer_size */
check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
skip_bits(gb, 3); /* latter_half_vbv_buffer_size */
skip_bits(gb, 11); /* first_half_vbv_buffer_size */
check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
skip_bits(gb, 15); /* latter_half_vbv_occupancy */
check_marker(s->avctx, gb, "after latter_half_vbv_occupancy");
s->low_delay = get_bits1(gb);
s->mpeg_quant = get_bits1(gb); /* mpeg2_stream */
next_start_code_studio(gb);
extension_and_user_data(s, gb, 2);
return 0;
}
/**
* Decode MPEG-4 headers.
*
* @param header If set the absence of a VOP is not treated as error; otherwise, it is treated as such.
* @return <0 if an error occured
* FRAME_SKIPPED if a not coded VOP is found
* 0 else
*/
int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb, int header)
{
MpegEncContext *s = &ctx->m;
unsigned startcode, v;
int ret;
int vol = 0;
/* search next start code */
align_get_bits(gb);
// If we have not switched to studio profile than we also did not switch bps
// that means something else (like a previous instance) outside set bps which
// would be inconsistant with the currect state, thus reset it
if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8)
s->avctx->bits_per_raw_sample = 0;
if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
skip_bits(gb, 24);
if (get_bits(gb, 8) == 0xF0)
goto end;
}
startcode = 0xff;
for (;;) {
if (get_bits_count(gb) >= gb->size_in_bits) {
if (gb->size_in_bits == 8 &&
(ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
return FRAME_SKIPPED; // divx bug
} else if (header && get_bits_count(gb) == gb->size_in_bits) {
return 0; // ordinary return value for parsing of extradata
} else
return AVERROR_INVALIDDATA; // end of stream
}
/* use the bits after the test */
v = get_bits(gb, 8);
startcode = ((startcode << 8) | v) & 0xffffffff;
if ((startcode & 0xFFFFFF00) != 0x100)
continue; // no startcode
if (s->avctx->debug & FF_DEBUG_STARTCODE) {
av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
if (startcode <= 0x11F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
else if (startcode <= 0x12F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
else if (startcode <= 0x13F)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode <= 0x15F)
av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
else if (startcode <= 0x1AF)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode == 0x1B0)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
else if (startcode == 0x1B1)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
else if (startcode == 0x1B2)
av_log(s->avctx, AV_LOG_DEBUG, "User Data");
else if (startcode == 0x1B3)
av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
else if (startcode == 0x1B4)
av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
else if (startcode == 0x1B5)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
else if (startcode == 0x1B6)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
else if (startcode == 0x1B7)
av_log(s->avctx, AV_LOG_DEBUG, "slice start");
else if (startcode == 0x1B8)
av_log(s->avctx, AV_LOG_DEBUG, "extension start");
else if (startcode == 0x1B9)
av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
else if (startcode == 0x1BA)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
else if (startcode == 0x1BB)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
else if (startcode == 0x1BC)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
else if (startcode == 0x1BD)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
else if (startcode == 0x1BE)
av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
else if (startcode == 0x1BF)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
else if (startcode == 0x1C0)
av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
else if (startcode == 0x1C1)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
else if (startcode == 0x1C2)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
else if (startcode == 0x1C3)
av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
else if (startcode <= 0x1C5)
av_log(s->avctx, AV_LOG_DEBUG, "reserved");
else if (startcode <= 0x1FF)
av_log(s->avctx, AV_LOG_DEBUG, "System start");
av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
}
if (startcode >= 0x120 && startcode <= 0x12F) {
if (vol) {
av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n");
continue;
}
vol++;
if ((ret = decode_vol_header(ctx, gb)) < 0)
return ret;
} else if (startcode == USER_DATA_STARTCODE) {
decode_user_data(ctx, gb);
} else if (startcode == GOP_STARTCODE) {
mpeg4_decode_gop_header(s, gb);
} else if (startcode == VOS_STARTCODE) {
int profile, level;
mpeg4_decode_profile_level(s, gb, &profile, &level);
if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&
(level > 0 && level < 9)) {
s->studio_profile = 1;
next_start_code_studio(gb);
extension_and_user_data(s, gb, 0);
} else if (s->studio_profile) {
avpriv_request_sample(s->avctx, "Mixes studio and non studio profile\n");
return AVERROR_PATCHWELCOME;
}
s->avctx->profile = profile;
s->avctx->level = level;
} else if (startcode == VISUAL_OBJ_STARTCODE) {
if (s->studio_profile) {
if ((ret = decode_studiovisualobject(ctx, gb)) < 0)
return ret;
} else
mpeg4_decode_visual_object(s, gb);
} else if (startcode == VOP_STARTCODE) {
break;
}
align_get_bits(gb);
startcode = 0xff;
}
end:
if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
s->low_delay = 1;
s->avctx->has_b_frames = !s->low_delay;
if (s->studio_profile) {
if (!s->avctx->bits_per_raw_sample) {
av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n");
return AVERROR_INVALIDDATA;
}
return decode_studio_vop_header(ctx, gb);
} else
return decode_vop_header(ctx, gb);
}
av_cold void ff_mpeg4videodec_static_init(void) {
static int done = 0;
if (!done) {
ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
ff_rl_init(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]);
ff_rl_init(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]);
INIT_VLC_RL(ff_mpeg4_rl_intra, 554);
INIT_VLC_RL(ff_rvlc_rl_inter, 1072);
INIT_VLC_RL(ff_rvlc_rl_intra, 1072);
INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
&ff_mpeg4_DCtab_lum[0][1], 2, 1,
&ff_mpeg4_DCtab_lum[0][0], 2, 1, 512);
INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
&ff_mpeg4_DCtab_chrom[0][1], 2, 1,
&ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512);
INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
&ff_sprite_trajectory_tab[0][1], 4, 2,
&ff_sprite_trajectory_tab[0][0], 4, 2, 128);
INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
&ff_mb_type_b_tab[0][1], 2, 1,
&ff_mb_type_b_tab[0][0], 2, 1, 16);
done = 1;
}
}
int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
{
Mpeg4DecContext *ctx = avctx->priv_data;
MpegEncContext *s = &ctx->m;
/* divx 5.01+ bitstream reorder stuff */
/* Since this clobbers the input buffer and hwaccel codecs still need the
* data during hwaccel->end_frame we should not do this any earlier */
if (s->divx_packed) {
int current_pos = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3);
int startcode_found = 0;
if (buf_size - current_pos > 7) {
int i;
for (i = current_pos; i < buf_size - 4; i++)
if (buf[i] == 0 &&
buf[i + 1] == 0 &&
buf[i + 2] == 1 &&
buf[i + 3] == 0xB6) {
startcode_found = !(buf[i + 4] & 0x40);
break;
}
}
if (startcode_found) {
if (!ctx->showed_packed_warning) {
av_log(s->avctx, AV_LOG_INFO, "Video uses a non-standard and "
"wasteful way to store B-frames ('packed B-frames'). "
"Consider using the mpeg4_unpack_bframes bitstream filter without encoding but stream copy to fix it.\n");
ctx->showed_packed_warning = 1;
}
av_fast_padded_malloc(&s->bitstream_buffer,
&s->allocated_bitstream_buffer_size,
buf_size - current_pos);
if (!s->bitstream_buffer) {
s->bitstream_buffer_size = 0;
return AVERROR(ENOMEM);
}
memcpy(s->bitstream_buffer, buf + current_pos,
buf_size - current_pos);
s->bitstream_buffer_size = buf_size - current_pos;
}
}
return 0;
}
#if HAVE_THREADS
static int mpeg4_update_thread_context(AVCodecContext *dst,
const AVCodecContext *src)
{
Mpeg4DecContext *s = dst->priv_data;
const Mpeg4DecContext *s1 = src->priv_data;
int init = s->m.context_initialized;
int ret = ff_mpeg_update_thread_context(dst, src);
if (ret < 0)
return ret;
memcpy(((uint8_t*)s) + sizeof(MpegEncContext), ((uint8_t*)s1) + sizeof(MpegEncContext), sizeof(Mpeg4DecContext) - sizeof(MpegEncContext));
if (CONFIG_MPEG4_DECODER && !init && s1->xvid_build >= 0)
ff_xvid_idct_init(&s->m.idsp, dst);
return 0;
}
#endif
static av_cold int init_studio_vlcs(Mpeg4DecContext *ctx)
{
int i, ret;
for (i = 0; i < 12; i++) {
ret = init_vlc(&ctx->studio_intra_tab[i], STUDIO_INTRA_BITS, 22,
&ff_mpeg4_studio_intra[i][0][1], 4, 2,
&ff_mpeg4_studio_intra[i][0][0], 4, 2,
0);
if (ret < 0)
return ret;
}
ret = init_vlc(&ctx->studio_luma_dc, STUDIO_INTRA_BITS, 19,
&ff_mpeg4_studio_dc_luma[0][1], 4, 2,
&ff_mpeg4_studio_dc_luma[0][0], 4, 2,
0);
if (ret < 0)
return ret;
ret = init_vlc(&ctx->studio_chroma_dc, STUDIO_INTRA_BITS, 19,
&ff_mpeg4_studio_dc_chroma[0][1], 4, 2,
&ff_mpeg4_studio_dc_chroma[0][0], 4, 2,
0);
if (ret < 0)
return ret;
return 0;
}
static av_cold int decode_init(AVCodecContext *avctx)
{
Mpeg4DecContext *ctx = avctx->priv_data;
MpegEncContext *s = &ctx->m;
int ret;
ctx->divx_version =
ctx->divx_build =
ctx->xvid_build =
ctx->lavc_build = -1;
if ((ret = ff_h263_decode_init(avctx)) < 0)
return ret;
ff_mpeg4videodec_static_init();
if ((ret = init_studio_vlcs(ctx)) < 0)
return ret;
s->h263_pred = 1;
s->low_delay = 0; /* default, might be overridden in the vol header during header parsing */
s->decode_mb = mpeg4_decode_mb;
ctx->time_increment_bits = 4; /* default value for broken headers */
avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
avctx->internal->allocate_progress = 1;
return 0;
}
static av_cold int decode_end(AVCodecContext *avctx)
{
Mpeg4DecContext *ctx = avctx->priv_data;
int i;
if (!avctx->internal->is_copy) {
for (i = 0; i < 12; i++)
ff_free_vlc(&ctx->studio_intra_tab[i]);
ff_free_vlc(&ctx->studio_luma_dc);
ff_free_vlc(&ctx->studio_chroma_dc);
}
return ff_h263_decode_end(avctx);
}
static const AVOption mpeg4_options[] = {
{"quarter_sample", "1/4 subpel MC", offsetof(MpegEncContext, quarter_sample), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
{"divx_packed", "divx style packed b frames", offsetof(MpegEncContext, divx_packed), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
{NULL}
};
static const AVClass mpeg4_class = {
.class_name = "MPEG4 Video Decoder",
.item_name = av_default_item_name,
.option = mpeg4_options,
.version = LIBAVUTIL_VERSION_INT,
};
AVCodec ff_mpeg4_decoder = {
.name = "mpeg4",
.long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_MPEG4,
.priv_data_size = sizeof(Mpeg4DecContext),
.init = decode_init,
.close = decode_end,
.decode = ff_h263_decode_frame,
.capabilities = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 |
AV_CODEC_CAP_TRUNCATED | AV_CODEC_CAP_DELAY |
AV_CODEC_CAP_FRAME_THREADS,
.caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM,
.flush = ff_mpeg_flush,
.max_lowres = 3,
.pix_fmts = ff_h263_hwaccel_pixfmt_list_420,
.profiles = NULL_IF_CONFIG_SMALL(ff_mpeg4_video_profiles),
.update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg4_update_thread_context),
.priv_class = &mpeg4_class,
.hw_configs = (const AVCodecHWConfigInternal*[]) {
#if CONFIG_MPEG4_NVDEC_HWACCEL
HWACCEL_NVDEC(mpeg4),
#endif
#if CONFIG_MPEG4_VAAPI_HWACCEL
HWACCEL_VAAPI(mpeg4),
#endif
#if CONFIG_MPEG4_VDPAU_HWACCEL
HWACCEL_VDPAU(mpeg4),
#endif
#if CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL
HWACCEL_VIDEOTOOLBOX(mpeg4),
#endif
NULL
},
};
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_801_0 |
crossvul-cpp_data_bad_486_5 | /* -*- c-basic-offset: 8 -*-
rdesktop: A Remote Desktop Protocol client.
Support for the Matrox "lspci" channel
Copyright (C) 2005 Matrox Graphics Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "rdesktop.h"
#include <sys/types.h>
#include <unistd.h>
static VCHANNEL *lspci_channel;
typedef struct _pci_device
{
uint16 klass;
uint16 vendor;
uint16 device;
uint16 subvendor;
uint16 subdevice;
uint8 revision;
uint8 progif;
} pci_device;
static pci_device current_device;
static void lspci_send(const char *output);
/* Handle one line of output from the lspci subprocess */
static RD_BOOL
handle_child_line(const char *line, void *data)
{
UNUSED(data);
const char *val;
char buf[1024];
if (str_startswith(line, "Class:"))
{
val = line + sizeof("Class:");
/* Skip whitespace and second Class: occurrence */
val += strspn(val, " \t") + sizeof("Class");
current_device.klass = strtol(val, NULL, 16);
}
else if (str_startswith(line, "Vendor:"))
{
val = line + sizeof("Vendor:");
current_device.vendor = strtol(val, NULL, 16);
}
else if (str_startswith(line, "Device:"))
{
val = line + sizeof("Device:");
/* Sigh, there are *two* lines tagged as Device:. We
are not interested in the domain/bus/slot/func */
if (!strchr(val, ':'))
current_device.device = strtol(val, NULL, 16);
}
else if (str_startswith(line, "SVendor:"))
{
val = line + sizeof("SVendor:");
current_device.subvendor = strtol(val, NULL, 16);
}
else if (str_startswith(line, "SDevice:"))
{
val = line + sizeof("SDevice:");
current_device.subdevice = strtol(val, NULL, 16);
}
else if (str_startswith(line, "Rev:"))
{
val = line + sizeof("Rev:");
current_device.revision = strtol(val, NULL, 16);
}
else if (str_startswith(line, "ProgIf:"))
{
val = line + sizeof("ProgIf:");
current_device.progif = strtol(val, NULL, 16);
}
else if (strspn(line, " \t") == strlen(line))
{
/* Blank line. Send collected information over channel */
snprintf(buf, sizeof(buf), "%04x,%04x,%04x,%04x,%04x,%02x,%02x\n",
current_device.klass, current_device.vendor,
current_device.device, current_device.subvendor,
current_device.subdevice, current_device.revision, current_device.progif);
lspci_send(buf);
memset(¤t_device, 0, sizeof(current_device));
}
else
{
logger(Core, Warning, "handle_child_line(), Unrecognized lspci line '%s'", line);
}
return True;
}
/* Process one line of input from virtual channel */
static RD_BOOL
lspci_process_line(const char *line, void *data)
{
UNUSED(data);
char *lspci_command[5] = { "lspci", "-m", "-n", "-v", NULL };
if (!strcmp(line, "LSPCI"))
{
memset(¤t_device, 0, sizeof(current_device));
subprocess(lspci_command, handle_child_line, NULL);
/* Send single dot to indicate end of enumeration */
lspci_send(".\n");
}
else
{
logger(Core, Error, "lspci_process_line(), invalid line '%s'", line);
}
return True;
}
/* Process new data from the virtual channel */
static void
lspci_process(STREAM s)
{
unsigned int pkglen;
static char *rest = NULL;
char *buf;
pkglen = s->end - s->p;
/* str_handle_lines requires null terminated strings */
buf = xmalloc(pkglen + 1);
STRNCPY(buf, (char *) s->p, pkglen + 1);
str_handle_lines(buf, &rest, lspci_process_line, NULL);
xfree(buf);
}
/* Initialize this module: Register the lspci channel */
RD_BOOL
lspci_init(void)
{
lspci_channel =
channel_register("lspci", CHANNEL_OPTION_INITIALIZED | CHANNEL_OPTION_ENCRYPT_RDP,
lspci_process);
return (lspci_channel != NULL);
}
/* Send data to channel */
static void
lspci_send(const char *output)
{
STREAM s;
size_t len;
len = strlen(output);
s = channel_init(lspci_channel, len);
out_uint8p(s, output, len) s_mark_end(s);
channel_send(s, lspci_channel);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_486_5 |
crossvul-cpp_data_bad_2588_1 | /*
* hmi.c -- Midi Wavetable Processing library
*
* Copyright (C) WildMIDI Developers 2001-2016
*
* This file is part of WildMIDI.
*
* WildMIDI is free software: you can redistribute and/or modify the player
* under the terms of the GNU General Public License and you can redistribute
* and/or modify the library under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either version 3 of
* the licenses, or(at your option) any later version.
*
* WildMIDI is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License and
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License and the
* GNU Lesser General Public License along with WildMIDI. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "common.h"
#include "wm_error.h"
#include "wildmidi_lib.h"
#include "internal_midi.h"
#include "reverb.h"
#include "f_hmi.h"
/*
Turns hmp file data into an event stream
*/
struct _mdi *
_WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) {
uint32_t hmi_tmp = 0;
uint8_t *hmi_base = hmi_data;
uint16_t hmi_bpm = 0;
uint16_t hmi_division = 0;
// uint32_t hmi_duration_secs = 0;
uint32_t hmi_track_cnt = 0;
uint32_t *hmi_track_offset = NULL;
uint32_t i = 0;
uint32_t j = 0;
uint8_t *hmi_addr = NULL;
uint32_t *hmi_track_header_length = NULL;
struct _mdi *hmi_mdi = NULL;
uint32_t tempo_f = 5000000.0;
uint32_t *hmi_track_end = NULL;
uint8_t hmi_tracks_ended = 0;
uint8_t *hmi_running_event = NULL;
uint32_t setup_ret = 0;
uint32_t *hmi_delta = NULL;
uint32_t smallest_delta = 0;
uint32_t subtract_delta = 0;
uint32_t sample_count = 0;
float sample_count_f = 0;
float sample_remainder = 0;
float samples_per_delta_f = 0.0;
struct _note {
uint32_t length;
uint8_t channel;
} *note;
//FIXME: This needs to be used for sanity check.
UNUSED(hmi_size);
if (memcmp(hmi_data, "HMI-MIDISONG061595", 18)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, NULL, 0);
return NULL;
}
//FIXME: Unsure if this is correct but it seems to be the only offset that plays the files at what appears to be the right speed.
hmi_bpm = hmi_data[212];
hmi_division = 60;
hmi_track_cnt = hmi_data[228];
hmi_mdi = _WM_initMDI();
_WM_midi_setup_divisions(hmi_mdi, hmi_division);
if ((_WM_MixerOptions & WM_MO_ROUNDTEMPO)) {
tempo_f = (float) (60000000 / hmi_bpm) + 0.5f;
} else {
tempo_f = (float) (60000000 / hmi_bpm);
}
samples_per_delta_f = _WM_GetSamplesPerTick(hmi_division, (uint32_t)tempo_f);
_WM_midi_setup_tempo(hmi_mdi, (uint32_t)tempo_f);
hmi_track_offset = (uint32_t *)malloc(sizeof(uint32_t) * hmi_track_cnt);
hmi_track_header_length = malloc(sizeof(uint32_t) * hmi_track_cnt);
hmi_track_end = malloc(sizeof(uint32_t) * hmi_track_cnt);
hmi_delta = malloc(sizeof(uint32_t) * hmi_track_cnt);
note = malloc(sizeof(struct _note) * 128 * hmi_track_cnt);
hmi_running_event = malloc(sizeof(uint8_t) * 128 * hmi_track_cnt);
hmi_data += 370;
smallest_delta = 0xffffffff;
if (hmi_size < (370 + (hmi_track_cnt * 17))) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, "file too short", 0);
goto _hmi_end;
}
hmi_track_offset[0] = *hmi_data; // To keep Xcode happy
for (i = 0; i < hmi_track_cnt; i++) {
hmi_track_offset[i] = *hmi_data++;
hmi_track_offset[i] += (*hmi_data++ << 8);
hmi_track_offset[i] += (*hmi_data++ << 16);
hmi_track_offset[i] += (*hmi_data++ << 24);
if (hmi_size < (hmi_track_offset[i] + 0x5a + 4)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, "file too short", 0);
goto _hmi_end;
}
hmi_addr = hmi_base + hmi_track_offset[i];
if (memcmp(hmi_addr, "HMI-MIDITRACK", 13)) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, NULL, 0);
goto _hmi_end;
}
hmi_track_header_length[i] = hmi_addr[0x57];
hmi_track_header_length[i] += (hmi_addr[0x58] << 8);
hmi_track_header_length[i] += (hmi_addr[0x59] << 16);
hmi_track_header_length[i] += (hmi_addr[0x5a] << 24);
hmi_addr += hmi_track_header_length[i];
hmi_track_offset[i] += hmi_track_header_length[i];
// Get tracks initial delta and set its samples_till_next;
hmi_delta[i] = 0;
if (*hmi_addr > 0x7f) {
do {
hmi_delta[i] = (hmi_delta[i] << 7) + (*hmi_addr & 0x7f);
hmi_addr++;
hmi_track_offset[i]++;
} while (*hmi_addr > 0x7f);
}
hmi_delta[i] = (hmi_delta[i] << 7) + (*hmi_addr & 0x7f);
hmi_track_offset[i]++;
hmi_addr++;
// Find smallest delta to work with
if (hmi_delta[i] < smallest_delta) {
smallest_delta = hmi_delta[i];
}
hmi_track_end[i] = 0;
hmi_running_event[i] = 0;
for (j = 0; j < 128; j++) {
hmi_tmp = (128 * i) + j;
note[hmi_tmp].length = 0;
note[hmi_tmp].channel = 0;
}
}
subtract_delta = smallest_delta;
sample_count_f= (((float) smallest_delta * samples_per_delta_f) + sample_remainder);
sample_count = (uint32_t) sample_count_f;
sample_remainder = sample_count_f - (float) sample_count;
hmi_mdi->events[hmi_mdi->event_count - 1].samples_to_next += sample_count;
hmi_mdi->extra_info.approx_total_samples += sample_count;
while (hmi_tracks_ended < hmi_track_cnt) {
smallest_delta = 0;
for (i = 0; i < hmi_track_cnt; i++) {
if (hmi_track_end[i]) continue;
// first check to see if any active notes need turning off.
for (j = 0; j < 128; j++) {
hmi_tmp = (128 * i) + j;
if (note[hmi_tmp].length) {
note[hmi_tmp].length -= subtract_delta;
if (note[hmi_tmp].length) {
if ((!smallest_delta) || (smallest_delta > note[hmi_tmp].length)) {
smallest_delta = note[hmi_tmp].length;
}
} else {
_WM_midi_setup_noteoff(hmi_mdi, note[hmi_tmp].channel, j, 0);
}
}
}
if (hmi_delta[i]) {
hmi_delta[i] -= subtract_delta;
if (hmi_delta[i]) {
if ((!smallest_delta) || (smallest_delta > hmi_delta[i])) {
smallest_delta = hmi_delta[i];
}
continue;
}
}
do {
hmi_data = hmi_base + hmi_track_offset[i];
hmi_delta[i] = 0;
if (hmi_data[0] == 0xfe) {
// HMI only event of some sort.
if (hmi_data[1] == 0x10) {
hmi_tmp = (hmi_data[4] + 5);
hmi_data += hmi_tmp;
hmi_track_offset[i] += hmi_tmp;
} else if (hmi_data[1] == 0x15) {
hmi_data += 4;
hmi_track_offset[i] += 4;
}
hmi_data += 4;
hmi_track_offset[i] += 4;
} else {
if ((setup_ret = _WM_SetupMidiEvent(hmi_mdi,hmi_data,hmi_running_event[i])) == 0) {
goto _hmi_end;
}
if ((hmi_data[0] == 0xff) && (hmi_data[1] == 0x2f) && (hmi_data[2] == 0x00)) {
hmi_track_end[i] = 1;
hmi_tracks_ended++;
for(j = 0; j < 128; j++) {
hmi_tmp = (128 * i) + j;
if (note[hmi_tmp].length) {
_WM_midi_setup_noteoff(hmi_mdi, note[hmi_tmp].channel, j, 0);
note[hmi_tmp].length = 0;
}
}
goto _hmi_next_track;
}
// Running event
// 0xff does not alter running event
if ((*hmi_data == 0xF0) || (*hmi_data == 0xF7)) {
// Sysex resets running event data
hmi_running_event[i] = 0;
} else if (*hmi_data < 0xF0) {
// MIDI events 0x80 to 0xEF set running event
if (*hmi_data >= 0x80) {
hmi_running_event[i] = *hmi_data;
}
}
if ((hmi_running_event[i] & 0xf0) == 0x90) {
// note on has extra data to specify how long the note is.
if (*hmi_data > 127) {
hmi_tmp = hmi_data[1];
} else {
hmi_tmp = *hmi_data;
}
hmi_tmp += (i * 128);
note[hmi_tmp].channel = hmi_running_event[i] & 0xf;
hmi_data += setup_ret;
hmi_track_offset[i] += setup_ret;
note[hmi_tmp].length = 0;
if (*hmi_data > 0x7f) {
do {
note[hmi_tmp].length = (note[hmi_tmp].length << 7) | (*hmi_data & 0x7F);
hmi_data++;
hmi_track_offset[i]++;
} while (*hmi_data > 0x7F);
}
note[hmi_tmp].length = (note[hmi_tmp].length << 7) | (*hmi_data & 0x7F);
hmi_data++;
hmi_track_offset[i]++;
if (note[hmi_tmp].length) {
if ((!smallest_delta) || (smallest_delta > note[hmi_tmp].length)) {
smallest_delta = note[hmi_tmp].length;
}
} else {
_WM_midi_setup_noteoff(hmi_mdi, note[hmi_tmp].channel, j, 0);
}
} else {
hmi_data += setup_ret;
hmi_track_offset[i] += setup_ret;
}
}
// get track delta
// hmi_delta[i] = 0; // set at start of loop
if (*hmi_data > 0x7f) {
do {
hmi_delta[i] = (hmi_delta[i] << 7) | (*hmi_data & 0x7F);
hmi_data++;
hmi_track_offset[i]++;
} while (*hmi_data > 0x7F);
}
hmi_delta[i] = (hmi_delta[i] << 7) | (*hmi_data & 0x7F);
hmi_data++;
hmi_track_offset[i]++;
} while (!hmi_delta[i]);
if ((!smallest_delta) || (smallest_delta > hmi_delta[i])) {
smallest_delta = hmi_delta[i];
}
_hmi_next_track:
hmi_tmp = 0;
UNUSED(hmi_tmp);
}
// convert smallest delta to samples till next
subtract_delta = smallest_delta;
sample_count_f= (((float) smallest_delta * samples_per_delta_f) + sample_remainder);
sample_count = (uint32_t) sample_count_f;
sample_remainder = sample_count_f - (float) sample_count;
hmi_mdi->events[hmi_mdi->event_count - 1].samples_to_next += sample_count;
hmi_mdi->extra_info.approx_total_samples += sample_count;
}
if ((hmi_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, "to init reverb", 0);
goto _hmi_end;
}
hmi_mdi->extra_info.current_sample = 0;
hmi_mdi->current_event = &hmi_mdi->events[0];
hmi_mdi->samples_to_mix = 0;
hmi_mdi->note = NULL;
_WM_ResetToStart(hmi_mdi);
_hmi_end:
free(hmi_track_offset);
free(hmi_track_header_length);
free(hmi_track_end);
free(hmi_delta);
free(note);
free(hmi_running_event);
if (hmi_mdi->reverb) return (hmi_mdi);
_WM_freeMDI(hmi_mdi);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2588_1 |
crossvul-cpp_data_bad_1277_0 | /**********************************************************************
regexec.c - Oniguruma (regular expression library)
**********************************************************************/
/*-
* Copyright (c) 2002-2019 K.Kosako
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
#include "regint.h"
#define IS_MBC_WORD_ASCII_MODE(enc,s,end,mode) \
((mode) == 0 ? ONIGENC_IS_MBC_WORD(enc,s,end) : ONIGENC_IS_MBC_WORD_ASCII(enc,s,end))
#ifdef USE_CRNL_AS_LINE_TERMINATOR
#define ONIGENC_IS_MBC_CRNL(enc,p,end) \
(ONIGENC_MBC_TO_CODE(enc,p,end) == 13 && \
ONIGENC_IS_MBC_NEWLINE(enc,(p+enclen(enc,p)),end))
#endif
#define CHECK_INTERRUPT_IN_MATCH
#ifdef USE_CALLOUT
typedef struct {
int last_match_at_call_counter;
struct {
OnigType type;
OnigValue val;
} slot[ONIG_CALLOUT_DATA_SLOT_NUM];
} CalloutData;
#endif
struct OnigMatchParamStruct {
unsigned int match_stack_limit;
unsigned long retry_limit_in_match;
#ifdef USE_CALLOUT
OnigCalloutFunc progress_callout_of_contents;
OnigCalloutFunc retraction_callout_of_contents;
int match_at_call_counter;
void* callout_user_data;
CalloutData* callout_data;
int callout_data_alloc_num;
#endif
};
extern int
onig_set_match_stack_limit_size_of_match_param(OnigMatchParam* param,
unsigned int limit)
{
param->match_stack_limit = limit;
return ONIG_NORMAL;
}
extern int
onig_set_retry_limit_in_match_of_match_param(OnigMatchParam* param,
unsigned long limit)
{
param->retry_limit_in_match = limit;
return ONIG_NORMAL;
}
extern int
onig_set_progress_callout_of_match_param(OnigMatchParam* param, OnigCalloutFunc f)
{
#ifdef USE_CALLOUT
param->progress_callout_of_contents = f;
return ONIG_NORMAL;
#else
return ONIG_NO_SUPPORT_CONFIG;
#endif
}
extern int
onig_set_retraction_callout_of_match_param(OnigMatchParam* param, OnigCalloutFunc f)
{
#ifdef USE_CALLOUT
param->retraction_callout_of_contents = f;
return ONIG_NORMAL;
#else
return ONIG_NO_SUPPORT_CONFIG;
#endif
}
extern int
onig_set_callout_user_data_of_match_param(OnigMatchParam* param, void* user_data)
{
#ifdef USE_CALLOUT
param->callout_user_data = user_data;
return ONIG_NORMAL;
#else
return ONIG_NO_SUPPORT_CONFIG;
#endif
}
typedef struct {
void* stack_p;
int stack_n;
OnigOptionType options;
OnigRegion* region;
int ptr_num;
const UChar* start; /* search start position (for \G: BEGIN_POSITION) */
unsigned int match_stack_limit;
unsigned long retry_limit_in_match;
OnigMatchParam* mp;
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
int best_len; /* for ONIG_OPTION_FIND_LONGEST */
UChar* best_s;
#endif
} MatchArg;
#ifdef ONIG_DEBUG
/* arguments type */
typedef enum {
ARG_SPECIAL = -1,
ARG_NON = 0,
ARG_RELADDR = 1,
ARG_ABSADDR = 2,
ARG_LENGTH = 3,
ARG_MEMNUM = 4,
ARG_OPTION = 5,
ARG_MODE = 6
} OpArgType;
typedef struct {
short int opcode;
char* name;
} OpInfoType;
static OpInfoType OpInfo[] = {
{ OP_FINISH, "finish" },
{ OP_END, "end" },
{ OP_EXACT1, "exact1" },
{ OP_EXACT2, "exact2" },
{ OP_EXACT3, "exact3" },
{ OP_EXACT4, "exact4" },
{ OP_EXACT5, "exact5" },
{ OP_EXACTN, "exactn" },
{ OP_EXACTMB2N1, "exactmb2-n1" },
{ OP_EXACTMB2N2, "exactmb2-n2" },
{ OP_EXACTMB2N3, "exactmb2-n3" },
{ OP_EXACTMB2N, "exactmb2-n" },
{ OP_EXACTMB3N, "exactmb3n" },
{ OP_EXACTMBN, "exactmbn" },
{ OP_EXACT1_IC, "exact1-ic" },
{ OP_EXACTN_IC, "exactn-ic" },
{ OP_CCLASS, "cclass" },
{ OP_CCLASS_MB, "cclass-mb" },
{ OP_CCLASS_MIX, "cclass-mix" },
{ OP_CCLASS_NOT, "cclass-not" },
{ OP_CCLASS_MB_NOT, "cclass-mb-not" },
{ OP_CCLASS_MIX_NOT, "cclass-mix-not" },
{ OP_ANYCHAR, "anychar" },
{ OP_ANYCHAR_ML, "anychar-ml" },
{ OP_ANYCHAR_STAR, "anychar*" },
{ OP_ANYCHAR_ML_STAR, "anychar-ml*" },
{ OP_ANYCHAR_STAR_PEEK_NEXT, "anychar*-peek-next" },
{ OP_ANYCHAR_ML_STAR_PEEK_NEXT, "anychar-ml*-peek-next" },
{ OP_WORD, "word" },
{ OP_WORD_ASCII, "word-ascii" },
{ OP_NO_WORD, "not-word" },
{ OP_NO_WORD_ASCII, "not-word-ascii" },
{ OP_WORD_BOUNDARY, "word-boundary" },
{ OP_NO_WORD_BOUNDARY, "not-word-boundary" },
{ OP_WORD_BEGIN, "word-begin" },
{ OP_WORD_END, "word-end" },
{ OP_TEXT_SEGMENT_BOUNDARY, "text-segment-boundary" },
{ OP_BEGIN_BUF, "begin-buf" },
{ OP_END_BUF, "end-buf" },
{ OP_BEGIN_LINE, "begin-line" },
{ OP_END_LINE, "end-line" },
{ OP_SEMI_END_BUF, "semi-end-buf" },
{ OP_BEGIN_POSITION, "begin-position" },
{ OP_BACKREF1, "backref1" },
{ OP_BACKREF2, "backref2" },
{ OP_BACKREF_N, "backref-n" },
{ OP_BACKREF_N_IC, "backref-n-ic" },
{ OP_BACKREF_MULTI, "backref_multi" },
{ OP_BACKREF_MULTI_IC, "backref_multi-ic" },
{ OP_BACKREF_WITH_LEVEL, "backref_with_level" },
{ OP_BACKREF_WITH_LEVEL_IC, "backref_with_level-c" },
{ OP_BACKREF_CHECK, "backref_check" },
{ OP_BACKREF_CHECK_WITH_LEVEL, "backref_check_with_level" },
{ OP_MEMORY_START_PUSH, "mem-start-push" },
{ OP_MEMORY_START, "mem-start" },
{ OP_MEMORY_END_PUSH, "mem-end-push" },
{ OP_MEMORY_END_PUSH_REC, "mem-end-push-rec" },
{ OP_MEMORY_END, "mem-end" },
{ OP_MEMORY_END_REC, "mem-end-rec" },
{ OP_FAIL, "fail" },
{ OP_JUMP, "jump" },
{ OP_PUSH, "push" },
{ OP_PUSH_SUPER, "push-super" },
{ OP_POP_OUT, "pop-out" },
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
{ OP_PUSH_OR_JUMP_EXACT1, "push-or-jump-e1" },
#endif
{ OP_PUSH_IF_PEEK_NEXT, "push-if-peek-next" },
{ OP_REPEAT, "repeat" },
{ OP_REPEAT_NG, "repeat-ng" },
{ OP_REPEAT_INC, "repeat-inc" },
{ OP_REPEAT_INC_NG, "repeat-inc-ng" },
{ OP_REPEAT_INC_SG, "repeat-inc-sg" },
{ OP_REPEAT_INC_NG_SG, "repeat-inc-ng-sg" },
{ OP_EMPTY_CHECK_START, "empty-check-start" },
{ OP_EMPTY_CHECK_END, "empty-check-end" },
{ OP_EMPTY_CHECK_END_MEMST, "empty-check-end-memst" },
{ OP_EMPTY_CHECK_END_MEMST_PUSH,"empty-check-end-memst-push" },
{ OP_PREC_READ_START, "push-pos" },
{ OP_PREC_READ_END, "pop-pos" },
{ OP_PREC_READ_NOT_START, "prec-read-not-start" },
{ OP_PREC_READ_NOT_END, "prec-read-not-end" },
{ OP_ATOMIC_START, "atomic-start" },
{ OP_ATOMIC_END, "atomic-end" },
{ OP_LOOK_BEHIND, "look-behind" },
{ OP_LOOK_BEHIND_NOT_START, "look-behind-not-start" },
{ OP_LOOK_BEHIND_NOT_END, "look-behind-not-end" },
{ OP_CALL, "call" },
{ OP_RETURN, "return" },
{ OP_PUSH_SAVE_VAL, "push-save-val" },
{ OP_UPDATE_VAR, "update-var" },
#ifdef USE_CALLOUT
{ OP_CALLOUT_CONTENTS, "callout-contents" },
{ OP_CALLOUT_NAME, "callout-name" },
#endif
{ -1, "" }
};
static char*
op2name(int opcode)
{
int i;
for (i = 0; OpInfo[i].opcode >= 0; i++) {
if (opcode == OpInfo[i].opcode) return OpInfo[i].name;
}
return "";
}
static void
p_string(FILE* f, int len, UChar* s)
{
fputs(":", f);
while (len-- > 0) { fputc(*s++, f); }
}
static void
p_len_string(FILE* f, LengthType len, int mb_len, UChar* s)
{
int x = len * mb_len;
fprintf(f, ":%d:", len);
while (x-- > 0) { fputc(*s++, f); }
}
static void
p_rel_addr(FILE* f, RelAddrType rel_addr, Operation* p, Operation* start)
{
RelAddrType curr = (RelAddrType )(p - start);
fprintf(f, "{%d/%d}", rel_addr, curr + rel_addr);
}
static int
bitset_on_num(BitSetRef bs)
{
int i, n;
n = 0;
for (i = 0; i < SINGLE_BYTE_SIZE; i++) {
if (BITSET_AT(bs, i)) n++;
}
return n;
}
static void
print_compiled_byte_code(FILE* f, regex_t* reg, int index,
Operation* start, OnigEncoding enc)
{
int i, n;
RelAddrType addr;
LengthType len;
MemNumType mem;
OnigCodePoint code;
ModeType mode;
UChar *q;
Operation* p;
enum OpCode opcode;
p = reg->ops + index;
#ifdef USE_DIRECT_THREADED_CODE
opcode = reg->ocs[index];
#else
opcode = p->opcode;
#endif
fprintf(f, "%s", op2name(opcode));
switch (opcode) {
case OP_EXACT1:
p_string(f, 1, p->exact.s); break;
case OP_EXACT2:
p_string(f, 2, p->exact.s); break;
case OP_EXACT3:
p_string(f, 3, p->exact.s); break;
case OP_EXACT4:
p_string(f, 4, p->exact.s); break;
case OP_EXACT5:
p_string(f, 5, p->exact.s); break;
case OP_EXACTN:
len = p->exact_n.n;
p_string(f, len, p->exact_n.s); break;
case OP_EXACTMB2N1:
p_string(f, 2, p->exact.s); break;
case OP_EXACTMB2N2:
p_string(f, 4, p->exact.s); break;
case OP_EXACTMB2N3:
p_string(f, 3, p->exact.s); break;
case OP_EXACTMB2N:
len = p->exact_n.n;
p_len_string(f, len, 2, p->exact_n.s); break;
case OP_EXACTMB3N:
len = p->exact_n.n;
p_len_string(f, len, 3, p->exact_n.s); break;
case OP_EXACTMBN:
{
int mb_len;
mb_len = p->exact_len_n.len;
len = p->exact_len_n.n;
q = p->exact_len_n.s;
fprintf(f, ":%d:%d:", mb_len, len);
n = len * mb_len;
while (n-- > 0) { fputc(*q++, f); }
}
break;
case OP_EXACT1_IC:
len = enclen(enc, p->exact.s);
p_string(f, len, p->exact.s);
break;
case OP_EXACTN_IC:
len = p->exact_n.n;
p_len_string(f, len, 1, p->exact_n.s);
break;
case OP_CCLASS:
case OP_CCLASS_NOT:
n = bitset_on_num(p->cclass.bsp);
fprintf(f, ":%d", n);
break;
case OP_CCLASS_MB:
case OP_CCLASS_MB_NOT:
{
OnigCodePoint ncode;
OnigCodePoint* codes;
codes = (OnigCodePoint* )p->cclass_mb.mb;
GET_CODE_POINT(ncode, codes);
codes++;
GET_CODE_POINT(code, codes);
fprintf(f, ":%u:%u", code, ncode);
}
break;
case OP_CCLASS_MIX:
case OP_CCLASS_MIX_NOT:
{
OnigCodePoint ncode;
OnigCodePoint* codes;
codes = (OnigCodePoint* )p->cclass_mix.mb;
n = bitset_on_num(p->cclass_mix.bsp);
GET_CODE_POINT(ncode, codes);
codes++;
GET_CODE_POINT(code, codes);
fprintf(f, ":%d:%u:%u", n, code, ncode);
}
break;
case OP_ANYCHAR_STAR_PEEK_NEXT:
case OP_ANYCHAR_ML_STAR_PEEK_NEXT:
p_string(f, 1, &(p->anychar_star_peek_next.c));
break;
case OP_WORD_BOUNDARY:
case OP_NO_WORD_BOUNDARY:
case OP_WORD_BEGIN:
case OP_WORD_END:
mode = p->word_boundary.mode;
fprintf(f, ":%d", mode);
break;
case OP_BACKREF_N:
case OP_BACKREF_N_IC:
mem = p->backref_n.n1;
fprintf(f, ":%d", mem);
break;
case OP_BACKREF_MULTI_IC:
case OP_BACKREF_MULTI:
case OP_BACKREF_CHECK:
fputs(" ", f);
n = p->backref_general.num;
for (i = 0; i < n; i++) {
mem = (n == 1) ? p->backref_general.n1 : p->backref_general.ns[i];
if (i > 0) fputs(", ", f);
fprintf(f, "%d", mem);
}
break;
case OP_BACKREF_WITH_LEVEL:
case OP_BACKREF_WITH_LEVEL_IC:
case OP_BACKREF_CHECK_WITH_LEVEL:
{
LengthType level;
level = p->backref_general.nest_level;
fprintf(f, ":%d", level);
fputs(" ", f);
n = p->backref_general.num;
for (i = 0; i < n; i++) {
mem = (n == 1) ? p->backref_general.n1 : p->backref_general.ns[i];
if (i > 0) fputs(", ", f);
fprintf(f, "%d", mem);
}
}
break;
case OP_MEMORY_START:
case OP_MEMORY_START_PUSH:
mem = p->memory_start.num;
fprintf(f, ":%d", mem);
break;
case OP_MEMORY_END_PUSH:
case OP_MEMORY_END_PUSH_REC:
case OP_MEMORY_END:
case OP_MEMORY_END_REC:
mem = p->memory_end.num;
fprintf(f, ":%d", mem);
break;
case OP_JUMP:
addr = p->jump.addr;
fputc(':', f);
p_rel_addr(f, addr, p, start);
break;
case OP_PUSH:
case OP_PUSH_SUPER:
addr = p->push.addr;
fputc(':', f);
p_rel_addr(f, addr, p, start);
break;
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
case OP_PUSH_OR_JUMP_EXACT1:
addr = p->push_or_jump_exact1.addr;
fputc(':', f);
p_rel_addr(f, addr, p, start);
p_string(f, 1, &(p->push_or_jump_exact1.c));
break;
#endif
case OP_PUSH_IF_PEEK_NEXT:
addr = p->push_if_peek_next.addr;
fputc(':', f);
p_rel_addr(f, addr, p, start);
p_string(f, 1, &(p->push_if_peek_next.c));
break;
case OP_REPEAT:
case OP_REPEAT_NG:
mem = p->repeat.id;
addr = p->repeat.addr;
fprintf(f, ":%d:", mem);
p_rel_addr(f, addr, p, start);
break;
case OP_REPEAT_INC:
case OP_REPEAT_INC_NG:
case OP_REPEAT_INC_SG:
case OP_REPEAT_INC_NG_SG:
mem = p->repeat.id;
fprintf(f, ":%d", mem);
break;
case OP_EMPTY_CHECK_START:
mem = p->empty_check_start.mem;
fprintf(f, ":%d", mem);
break;
case OP_EMPTY_CHECK_END:
case OP_EMPTY_CHECK_END_MEMST:
case OP_EMPTY_CHECK_END_MEMST_PUSH:
mem = p->empty_check_end.mem;
fprintf(f, ":%d", mem);
break;
case OP_PREC_READ_NOT_START:
addr = p->prec_read_not_start.addr;
fputc(':', f);
p_rel_addr(f, addr, p, start);
break;
case OP_LOOK_BEHIND:
len = p->look_behind.len;
fprintf(f, ":%d", len);
break;
case OP_LOOK_BEHIND_NOT_START:
addr = p->look_behind_not_start.addr;
len = p->look_behind_not_start.len;
fprintf(f, ":%d:", len);
p_rel_addr(f, addr, p, start);
break;
case OP_CALL:
addr = p->call.addr;
fprintf(f, ":{/%d}", addr);
break;
case OP_PUSH_SAVE_VAL:
{
SaveType type;
type = p->push_save_val.type;
mem = p->push_save_val.id;
fprintf(f, ":%d:%d", type, mem);
}
break;
case OP_UPDATE_VAR:
{
UpdateVarType type;
type = p->update_var.type;
mem = p->update_var.id;
fprintf(f, ":%d:%d", type, mem);
}
break;
#ifdef USE_CALLOUT
case OP_CALLOUT_CONTENTS:
mem = p->callout_contents.num;
fprintf(f, ":%d", mem);
break;
case OP_CALLOUT_NAME:
{
int id;
id = p->callout_name.id;
mem = p->callout_name.num;
fprintf(f, ":%d:%d", id, mem);
}
break;
#endif
case OP_TEXT_SEGMENT_BOUNDARY:
if (p->text_segment_boundary.not != 0)
fprintf(f, ":not");
break;
case OP_FINISH:
case OP_END:
case OP_ANYCHAR:
case OP_ANYCHAR_ML:
case OP_ANYCHAR_STAR:
case OP_ANYCHAR_ML_STAR:
case OP_WORD:
case OP_WORD_ASCII:
case OP_NO_WORD:
case OP_NO_WORD_ASCII:
case OP_BEGIN_BUF:
case OP_END_BUF:
case OP_BEGIN_LINE:
case OP_END_LINE:
case OP_SEMI_END_BUF:
case OP_BEGIN_POSITION:
case OP_BACKREF1:
case OP_BACKREF2:
case OP_FAIL:
case OP_POP_OUT:
case OP_PREC_READ_START:
case OP_PREC_READ_END:
case OP_PREC_READ_NOT_END:
case OP_ATOMIC_START:
case OP_ATOMIC_END:
case OP_LOOK_BEHIND_NOT_END:
case OP_RETURN:
break;
default:
fprintf(stderr, "print_compiled_byte_code: undefined code %d\n", opcode);
break;
}
}
#endif /* ONIG_DEBUG */
#ifdef ONIG_DEBUG_COMPILE
extern void
onig_print_compiled_byte_code_list(FILE* f, regex_t* reg)
{
Operation* bp;
Operation* start = reg->ops;
Operation* end = reg->ops + reg->ops_used;
fprintf(f, "bt_mem_start: 0x%x, bt_mem_end: 0x%x\n",
reg->bt_mem_start, reg->bt_mem_end);
fprintf(f, "code-length: %d\n", reg->ops_used);
bp = start;
while (bp < end) {
int pos = bp - start;
fprintf(f, "%4d: ", pos);
print_compiled_byte_code(f, reg, pos, start, reg->enc);
fprintf(f, "\n");
bp++;
}
fprintf(f, "\n");
}
#endif
#ifdef USE_CAPTURE_HISTORY
static void history_tree_free(OnigCaptureTreeNode* node);
static void
history_tree_clear(OnigCaptureTreeNode* node)
{
int i;
if (IS_NULL(node)) return ;
for (i = 0; i < node->num_childs; i++) {
if (IS_NOT_NULL(node->childs[i])) {
history_tree_free(node->childs[i]);
}
}
for (i = 0; i < node->allocated; i++) {
node->childs[i] = (OnigCaptureTreeNode* )0;
}
node->num_childs = 0;
node->beg = ONIG_REGION_NOTPOS;
node->end = ONIG_REGION_NOTPOS;
node->group = -1;
}
static void
history_tree_free(OnigCaptureTreeNode* node)
{
history_tree_clear(node);
if (IS_NOT_NULL(node->childs)) xfree(node->childs);
xfree(node);
}
static void
history_root_free(OnigRegion* r)
{
if (IS_NULL(r->history_root)) return ;
history_tree_free(r->history_root);
r->history_root = (OnigCaptureTreeNode* )0;
}
static OnigCaptureTreeNode*
history_node_new(void)
{
OnigCaptureTreeNode* node;
node = (OnigCaptureTreeNode* )xmalloc(sizeof(OnigCaptureTreeNode));
CHECK_NULL_RETURN(node);
node->childs = (OnigCaptureTreeNode** )0;
node->allocated = 0;
node->num_childs = 0;
node->group = -1;
node->beg = ONIG_REGION_NOTPOS;
node->end = ONIG_REGION_NOTPOS;
return node;
}
static int
history_tree_add_child(OnigCaptureTreeNode* parent, OnigCaptureTreeNode* child)
{
#define HISTORY_TREE_INIT_ALLOC_SIZE 8
if (parent->num_childs >= parent->allocated) {
int n, i;
if (IS_NULL(parent->childs)) {
n = HISTORY_TREE_INIT_ALLOC_SIZE;
parent->childs =
(OnigCaptureTreeNode** )xmalloc(sizeof(parent->childs[0]) * n);
}
else {
n = parent->allocated * 2;
parent->childs =
(OnigCaptureTreeNode** )xrealloc(parent->childs,
sizeof(parent->childs[0]) * n);
}
CHECK_NULL_RETURN_MEMERR(parent->childs);
for (i = parent->allocated; i < n; i++) {
parent->childs[i] = (OnigCaptureTreeNode* )0;
}
parent->allocated = n;
}
parent->childs[parent->num_childs] = child;
parent->num_childs++;
return 0;
}
static OnigCaptureTreeNode*
history_tree_clone(OnigCaptureTreeNode* node)
{
int i;
OnigCaptureTreeNode *clone, *child;
clone = history_node_new();
CHECK_NULL_RETURN(clone);
clone->beg = node->beg;
clone->end = node->end;
for (i = 0; i < node->num_childs; i++) {
child = history_tree_clone(node->childs[i]);
if (IS_NULL(child)) {
history_tree_free(clone);
return (OnigCaptureTreeNode* )0;
}
history_tree_add_child(clone, child);
}
return clone;
}
extern OnigCaptureTreeNode*
onig_get_capture_tree(OnigRegion* region)
{
return region->history_root;
}
#endif /* USE_CAPTURE_HISTORY */
extern void
onig_region_clear(OnigRegion* region)
{
int i;
for (i = 0; i < region->num_regs; i++) {
region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS;
}
#ifdef USE_CAPTURE_HISTORY
history_root_free(region);
#endif
}
extern int
onig_region_resize(OnigRegion* region, int n)
{
region->num_regs = n;
if (n < ONIG_NREGION)
n = ONIG_NREGION;
if (region->allocated == 0) {
region->beg = (int* )xmalloc(n * sizeof(int));
region->end = (int* )xmalloc(n * sizeof(int));
if (region->beg == 0 || region->end == 0)
return ONIGERR_MEMORY;
region->allocated = n;
}
else if (region->allocated < n) {
region->beg = (int* )xrealloc(region->beg, n * sizeof(int));
region->end = (int* )xrealloc(region->end, n * sizeof(int));
if (region->beg == 0 || region->end == 0)
return ONIGERR_MEMORY;
region->allocated = n;
}
return 0;
}
static int
onig_region_resize_clear(OnigRegion* region, int n)
{
int r;
r = onig_region_resize(region, n);
if (r != 0) return r;
onig_region_clear(region);
return 0;
}
extern int
onig_region_set(OnigRegion* region, int at, int beg, int end)
{
if (at < 0) return ONIGERR_INVALID_ARGUMENT;
if (at >= region->allocated) {
int r = onig_region_resize(region, at + 1);
if (r < 0) return r;
}
region->beg[at] = beg;
region->end[at] = end;
return 0;
}
extern void
onig_region_init(OnigRegion* region)
{
region->num_regs = 0;
region->allocated = 0;
region->beg = (int* )0;
region->end = (int* )0;
region->history_root = (OnigCaptureTreeNode* )0;
}
extern OnigRegion*
onig_region_new(void)
{
OnigRegion* r;
r = (OnigRegion* )xmalloc(sizeof(OnigRegion));
CHECK_NULL_RETURN(r);
onig_region_init(r);
return r;
}
extern void
onig_region_free(OnigRegion* r, int free_self)
{
if (r != 0) {
if (r->allocated > 0) {
if (r->beg) xfree(r->beg);
if (r->end) xfree(r->end);
r->allocated = 0;
}
#ifdef USE_CAPTURE_HISTORY
history_root_free(r);
#endif
if (free_self) xfree(r);
}
}
extern void
onig_region_copy(OnigRegion* to, OnigRegion* from)
{
#define RREGC_SIZE (sizeof(int) * from->num_regs)
int i;
if (to == from) return;
if (to->allocated == 0) {
if (from->num_regs > 0) {
to->beg = (int* )xmalloc(RREGC_SIZE);
if (IS_NULL(to->beg)) return;
to->end = (int* )xmalloc(RREGC_SIZE);
if (IS_NULL(to->end)) return;
to->allocated = from->num_regs;
}
}
else if (to->allocated < from->num_regs) {
to->beg = (int* )xrealloc(to->beg, RREGC_SIZE);
if (IS_NULL(to->beg)) return;
to->end = (int* )xrealloc(to->end, RREGC_SIZE);
if (IS_NULL(to->end)) return;
to->allocated = from->num_regs;
}
for (i = 0; i < from->num_regs; i++) {
to->beg[i] = from->beg[i];
to->end[i] = from->end[i];
}
to->num_regs = from->num_regs;
#ifdef USE_CAPTURE_HISTORY
history_root_free(to);
if (IS_NOT_NULL(from->history_root)) {
to->history_root = history_tree_clone(from->history_root);
}
#endif
}
#ifdef USE_CALLOUT
#define CALLOUT_BODY(func, ain, aname_id, anum, user, args, result) do { \
args.in = (ain);\
args.name_id = (aname_id);\
args.num = anum;\
args.regex = reg;\
args.string = str;\
args.string_end = end;\
args.start = sstart;\
args.right_range = right_range;\
args.current = s;\
args.retry_in_match_counter = retry_in_match_counter;\
args.msa = msa;\
args.stk_base = stk_base;\
args.stk = stk;\
args.mem_start_stk = mem_start_stk;\
args.mem_end_stk = mem_end_stk;\
result = (func)(&args, user);\
} while (0)
#define RETRACTION_CALLOUT(func, aname_id, anum, user) do {\
int result;\
OnigCalloutArgs args;\
CALLOUT_BODY(func, ONIG_CALLOUT_IN_RETRACTION, aname_id, anum, user, args, result);\
switch (result) {\
case ONIG_CALLOUT_FAIL:\
case ONIG_CALLOUT_SUCCESS:\
break;\
default:\
if (result > 0) {\
result = ONIGERR_INVALID_ARGUMENT;\
}\
best_len = result;\
goto finish;\
break;\
}\
} while(0)
#endif
/** stack **/
#define INVALID_STACK_INDEX -1
#define STK_ALT_FLAG 0x0001
/* stack type */
/* used by normal-POP */
#define STK_SUPER_ALT STK_ALT_FLAG
#define STK_ALT (0x0002 | STK_ALT_FLAG)
#define STK_ALT_PREC_READ_NOT (0x0004 | STK_ALT_FLAG)
#define STK_ALT_LOOK_BEHIND_NOT (0x0006 | STK_ALT_FLAG)
/* handled by normal-POP */
#define STK_MEM_START 0x0010
#define STK_MEM_END 0x8030
#define STK_REPEAT_INC 0x0050
#ifdef USE_CALLOUT
#define STK_CALLOUT 0x0070
#endif
/* avoided by normal-POP */
#define STK_VOID 0x0000 /* for fill a blank */
#define STK_EMPTY_CHECK_START 0x3000
#define STK_EMPTY_CHECK_END 0x5000 /* for recursive call */
#define STK_MEM_END_MARK 0x8100
#define STK_TO_VOID_START 0x1200 /* mark for "(?>...)" */
#define STK_REPEAT 0x0300
#define STK_CALL_FRAME 0x0400
#define STK_RETURN 0x0500
#define STK_SAVE_VAL 0x0600
#define STK_PREC_READ_START 0x0700
#define STK_PREC_READ_END 0x0800
/* stack type check mask */
#define STK_MASK_POP_USED STK_ALT_FLAG
#define STK_MASK_POP_HANDLED 0x0010
#define STK_MASK_POP_HANDLED_TIL (STK_MASK_POP_HANDLED | 0x0004)
#define STK_MASK_TO_VOID_TARGET 0x100e
#define STK_MASK_MEM_END_OR_MARK 0x8000 /* MEM_END or MEM_END_MARK */
typedef intptr_t StackIndex;
typedef struct _StackType {
unsigned int type;
int zid;
union {
struct {
Operation* pcode; /* byte code position */
UChar* pstr; /* string position */
UChar* pstr_prev; /* previous char position of pstr */
} state;
struct {
int count; /* for OP_REPEAT_INC, OP_REPEAT_INC_NG */
Operation* pcode; /* byte code position (head of repeated target) */
} repeat;
struct {
StackIndex si; /* index of stack */
} repeat_inc;
struct {
UChar *pstr; /* start/end position */
/* Following information is set, if this stack type is MEM-START */
StackIndex prev_start; /* prev. info (for backtrack "(...)*" ) */
StackIndex prev_end; /* prev. info (for backtrack "(...)*" ) */
} mem;
struct {
UChar *pstr; /* start position */
} empty_check;
#ifdef USE_CALL
struct {
Operation *ret_addr; /* byte code position */
UChar *pstr; /* string position */
} call_frame;
#endif
struct {
enum SaveType type;
UChar* v;
UChar* v2;
} val;
#ifdef USE_CALLOUT
struct {
int num;
OnigCalloutFunc func;
} callout;
#endif
} u;
} StackType;
#ifdef USE_CALLOUT
struct OnigCalloutArgsStruct {
OnigCalloutIn in;
int name_id; /* name id or ONIG_NON_NAME_ID */
int num;
OnigRegex regex;
const OnigUChar* string;
const OnigUChar* string_end;
const OnigUChar* start;
const OnigUChar* right_range;
const OnigUChar* current; /* current matching position */
unsigned long retry_in_match_counter;
/* invisible to users */
MatchArg* msa;
StackType* stk_base;
StackType* stk;
StackIndex* mem_start_stk;
StackIndex* mem_end_stk;
};
#endif
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
#define MATCH_ARG_INIT(msa, reg, arg_option, arg_region, arg_start, mp) do { \
(msa).stack_p = (void* )0;\
(msa).options = (arg_option);\
(msa).region = (arg_region);\
(msa).start = (arg_start);\
(msa).match_stack_limit = (mp)->match_stack_limit;\
(msa).retry_limit_in_match = (mp)->retry_limit_in_match;\
(msa).mp = mp;\
(msa).best_len = ONIG_MISMATCH;\
(msa).ptr_num = (reg)->num_repeat + ((reg)->num_mem + 1) * 2; \
} while(0)
#else
#define MATCH_ARG_INIT(msa, reg, arg_option, arg_region, arg_start, mp) do { \
(msa).stack_p = (void* )0;\
(msa).options = (arg_option);\
(msa).region = (arg_region);\
(msa).start = (arg_start);\
(msa).match_stack_limit = (mp)->match_stack_limit;\
(msa).retry_limit_in_match = (mp)->retry_limit_in_match;\
(msa).mp = mp;\
(msa).ptr_num = (reg)->num_repeat + ((reg)->num_mem + 1) * 2; \
} while(0)
#endif
#define MATCH_ARG_FREE(msa) if ((msa).stack_p) xfree((msa).stack_p)
#define ALLOCA_PTR_NUM_LIMIT 50
#define STACK_INIT(stack_num) do {\
if (msa->stack_p) {\
is_alloca = 0;\
alloc_base = msa->stack_p;\
stk_base = (StackType* )(alloc_base\
+ (sizeof(StackIndex) * msa->ptr_num));\
stk = stk_base;\
stk_end = stk_base + msa->stack_n;\
}\
else if (msa->ptr_num > ALLOCA_PTR_NUM_LIMIT) {\
is_alloca = 0;\
alloc_base = (char* )xmalloc(sizeof(StackIndex) * msa->ptr_num\
+ sizeof(StackType) * (stack_num));\
CHECK_NULL_RETURN_MEMERR(alloc_base);\
stk_base = (StackType* )(alloc_base\
+ (sizeof(StackIndex) * msa->ptr_num));\
stk = stk_base;\
stk_end = stk_base + (stack_num);\
}\
else {\
is_alloca = 1;\
alloc_base = (char* )xalloca(sizeof(StackIndex) * msa->ptr_num\
+ sizeof(StackType) * (stack_num));\
CHECK_NULL_RETURN_MEMERR(alloc_base);\
stk_base = (StackType* )(alloc_base\
+ (sizeof(StackIndex) * msa->ptr_num));\
stk = stk_base;\
stk_end = stk_base + (stack_num);\
}\
} while(0);
#define STACK_SAVE do{\
msa->stack_n = (int )(stk_end - stk_base);\
if (is_alloca != 0) {\
size_t size = sizeof(StackIndex) * msa->ptr_num \
+ sizeof(StackType) * msa->stack_n;\
msa->stack_p = xmalloc(size);\
CHECK_NULL_RETURN_MEMERR(msa->stack_p);\
xmemcpy(msa->stack_p, alloc_base, size);\
}\
else {\
msa->stack_p = alloc_base;\
};\
} while(0)
#define UPDATE_FOR_STACK_REALLOC do{\
repeat_stk = (StackIndex* )alloc_base;\
mem_start_stk = (StackIndex* )(repeat_stk + reg->num_repeat);\
mem_end_stk = mem_start_stk + num_mem + 1;\
} while(0)
static unsigned int MatchStackLimit = DEFAULT_MATCH_STACK_LIMIT_SIZE;
extern unsigned int
onig_get_match_stack_limit_size(void)
{
return MatchStackLimit;
}
extern int
onig_set_match_stack_limit_size(unsigned int size)
{
MatchStackLimit = size;
return 0;
}
#ifdef USE_RETRY_LIMIT_IN_MATCH
static unsigned long RetryLimitInMatch = DEFAULT_RETRY_LIMIT_IN_MATCH;
#define CHECK_RETRY_LIMIT_IN_MATCH do {\
if (retry_in_match_counter++ > retry_limit_in_match) goto retry_limit_in_match_over;\
} while (0)
#else
#define CHECK_RETRY_LIMIT_IN_MATCH
#endif /* USE_RETRY_LIMIT_IN_MATCH */
extern unsigned long
onig_get_retry_limit_in_match(void)
{
#ifdef USE_RETRY_LIMIT_IN_MATCH
return RetryLimitInMatch;
#else
/* return ONIG_NO_SUPPORT_CONFIG; */
return 0;
#endif
}
extern int
onig_set_retry_limit_in_match(unsigned long size)
{
#ifdef USE_RETRY_LIMIT_IN_MATCH
RetryLimitInMatch = size;
return 0;
#else
return ONIG_NO_SUPPORT_CONFIG;
#endif
}
#ifdef USE_CALLOUT
static OnigCalloutFunc DefaultProgressCallout;
static OnigCalloutFunc DefaultRetractionCallout;
#endif
extern OnigMatchParam*
onig_new_match_param(void)
{
OnigMatchParam* p;
p = (OnigMatchParam* )xmalloc(sizeof(*p));
if (IS_NOT_NULL(p)) {
onig_initialize_match_param(p);
}
return p;
}
extern void
onig_free_match_param_content(OnigMatchParam* p)
{
#ifdef USE_CALLOUT
if (IS_NOT_NULL(p->callout_data)) {
xfree(p->callout_data);
p->callout_data = 0;
}
#endif
}
extern void
onig_free_match_param(OnigMatchParam* p)
{
if (IS_NOT_NULL(p)) {
onig_free_match_param_content(p);
xfree(p);
}
}
extern int
onig_initialize_match_param(OnigMatchParam* mp)
{
mp->match_stack_limit = MatchStackLimit;
#ifdef USE_RETRY_LIMIT_IN_MATCH
mp->retry_limit_in_match = RetryLimitInMatch;
#endif
#ifdef USE_CALLOUT
mp->progress_callout_of_contents = DefaultProgressCallout;
mp->retraction_callout_of_contents = DefaultRetractionCallout;
mp->match_at_call_counter = 0;
mp->callout_user_data = 0;
mp->callout_data = 0;
mp->callout_data_alloc_num = 0;
#endif
return ONIG_NORMAL;
}
#ifdef USE_CALLOUT
static int
adjust_match_param(regex_t* reg, OnigMatchParam* mp)
{
RegexExt* ext = reg->extp;
mp->match_at_call_counter = 0;
if (IS_NULL(ext) || ext->callout_num == 0) return ONIG_NORMAL;
if (ext->callout_num > mp->callout_data_alloc_num) {
CalloutData* d;
size_t n = ext->callout_num * sizeof(*d);
if (IS_NOT_NULL(mp->callout_data))
d = (CalloutData* )xrealloc(mp->callout_data, n);
else
d = (CalloutData* )xmalloc(n);
CHECK_NULL_RETURN_MEMERR(d);
mp->callout_data = d;
mp->callout_data_alloc_num = ext->callout_num;
}
xmemset(mp->callout_data, 0, mp->callout_data_alloc_num * sizeof(CalloutData));
return ONIG_NORMAL;
}
#define ADJUST_MATCH_PARAM(reg, mp) \
r = adjust_match_param(reg, mp);\
if (r != ONIG_NORMAL) return r;
#define CALLOUT_DATA_AT_NUM(mp, num) ((mp)->callout_data + ((num) - 1))
extern int
onig_check_callout_data_and_clear_old_values(OnigCalloutArgs* args)
{
OnigMatchParam* mp;
int num;
CalloutData* d;
mp = args->msa->mp;
num = args->num;
d = CALLOUT_DATA_AT_NUM(mp, num);
if (d->last_match_at_call_counter != mp->match_at_call_counter) {
xmemset(d, 0, sizeof(*d));
d->last_match_at_call_counter = mp->match_at_call_counter;
return d->last_match_at_call_counter;
}
return 0;
}
extern int
onig_get_callout_data_dont_clear_old(regex_t* reg, OnigMatchParam* mp,
int callout_num, int slot,
OnigType* type, OnigValue* val)
{
OnigType t;
CalloutData* d;
if (callout_num <= 0) return ONIGERR_INVALID_ARGUMENT;
d = CALLOUT_DATA_AT_NUM(mp, callout_num);
t = d->slot[slot].type;
if (IS_NOT_NULL(type)) *type = t;
if (IS_NOT_NULL(val)) *val = d->slot[slot].val;
return (t == ONIG_TYPE_VOID ? 1 : ONIG_NORMAL);
}
extern int
onig_get_callout_data_by_callout_args_self_dont_clear_old(OnigCalloutArgs* args,
int slot, OnigType* type,
OnigValue* val)
{
return onig_get_callout_data_dont_clear_old(args->regex, args->msa->mp,
args->num, slot, type, val);
}
extern int
onig_get_callout_data(regex_t* reg, OnigMatchParam* mp,
int callout_num, int slot,
OnigType* type, OnigValue* val)
{
OnigType t;
CalloutData* d;
if (callout_num <= 0) return ONIGERR_INVALID_ARGUMENT;
d = CALLOUT_DATA_AT_NUM(mp, callout_num);
if (d->last_match_at_call_counter != mp->match_at_call_counter) {
xmemset(d, 0, sizeof(*d));
d->last_match_at_call_counter = mp->match_at_call_counter;
}
t = d->slot[slot].type;
if (IS_NOT_NULL(type)) *type = t;
if (IS_NOT_NULL(val)) *val = d->slot[slot].val;
return (t == ONIG_TYPE_VOID ? 1 : ONIG_NORMAL);
}
extern int
onig_get_callout_data_by_tag(regex_t* reg, OnigMatchParam* mp,
const UChar* tag, const UChar* tag_end, int slot,
OnigType* type, OnigValue* val)
{
int num;
num = onig_get_callout_num_by_tag(reg, tag, tag_end);
if (num < 0) return num;
if (num == 0) return ONIGERR_INVALID_CALLOUT_TAG_NAME;
return onig_get_callout_data(reg, mp, num, slot, type, val);
}
extern int
onig_get_callout_data_by_callout_args(OnigCalloutArgs* args,
int callout_num, int slot,
OnigType* type, OnigValue* val)
{
return onig_get_callout_data(args->regex, args->msa->mp, callout_num, slot,
type, val);
}
extern int
onig_get_callout_data_by_callout_args_self(OnigCalloutArgs* args,
int slot, OnigType* type, OnigValue* val)
{
return onig_get_callout_data(args->regex, args->msa->mp, args->num, slot,
type, val);
}
extern int
onig_set_callout_data(regex_t* reg, OnigMatchParam* mp,
int callout_num, int slot,
OnigType type, OnigValue* val)
{
CalloutData* d;
if (callout_num <= 0) return ONIGERR_INVALID_ARGUMENT;
d = CALLOUT_DATA_AT_NUM(mp, callout_num);
d->slot[slot].type = type;
d->slot[slot].val = *val;
d->last_match_at_call_counter = mp->match_at_call_counter;
return ONIG_NORMAL;
}
extern int
onig_set_callout_data_by_tag(regex_t* reg, OnigMatchParam* mp,
const UChar* tag, const UChar* tag_end, int slot,
OnigType type, OnigValue* val)
{
int num;
num = onig_get_callout_num_by_tag(reg, tag, tag_end);
if (num < 0) return num;
if (num == 0) return ONIGERR_INVALID_CALLOUT_TAG_NAME;
return onig_set_callout_data(reg, mp, num, slot, type, val);
}
extern int
onig_set_callout_data_by_callout_args(OnigCalloutArgs* args,
int callout_num, int slot,
OnigType type, OnigValue* val)
{
return onig_set_callout_data(args->regex, args->msa->mp, callout_num, slot,
type, val);
}
extern int
onig_set_callout_data_by_callout_args_self(OnigCalloutArgs* args,
int slot, OnigType type, OnigValue* val)
{
return onig_set_callout_data(args->regex, args->msa->mp, args->num, slot,
type, val);
}
#else
#define ADJUST_MATCH_PARAM(reg, mp)
#endif /* USE_CALLOUT */
static int
stack_double(int is_alloca, char** arg_alloc_base,
StackType** arg_stk_base, StackType** arg_stk_end, StackType** arg_stk,
MatchArg* msa)
{
unsigned int n;
int used;
size_t size;
size_t new_size;
char* alloc_base;
char* new_alloc_base;
StackType *stk_base, *stk_end, *stk;
alloc_base = *arg_alloc_base;
stk_base = *arg_stk_base;
stk_end = *arg_stk_end;
stk = *arg_stk;
n = (unsigned int )(stk_end - stk_base);
size = sizeof(StackIndex) * msa->ptr_num + sizeof(StackType) * n;
n *= 2;
new_size = sizeof(StackIndex) * msa->ptr_num + sizeof(StackType) * n;
if (is_alloca != 0) {
new_alloc_base = (char* )xmalloc(new_size);
if (IS_NULL(new_alloc_base)) {
STACK_SAVE;
return ONIGERR_MEMORY;
}
xmemcpy(new_alloc_base, alloc_base, size);
}
else {
if (msa->match_stack_limit != 0 && n > msa->match_stack_limit) {
if ((unsigned int )(stk_end - stk_base) == msa->match_stack_limit)
return ONIGERR_MATCH_STACK_LIMIT_OVER;
else
n = msa->match_stack_limit;
}
new_alloc_base = (char* )xrealloc(alloc_base, new_size);
if (IS_NULL(new_alloc_base)) {
STACK_SAVE;
return ONIGERR_MEMORY;
}
}
alloc_base = new_alloc_base;
used = (int )(stk - stk_base);
*arg_alloc_base = alloc_base;
*arg_stk_base = (StackType* )(alloc_base
+ (sizeof(StackIndex) * msa->ptr_num));
*arg_stk = *arg_stk_base + used;
*arg_stk_end = *arg_stk_base + n;
return 0;
}
#define STACK_ENSURE(n) do {\
if ((int )(stk_end - stk) < (n)) {\
int r = stack_double(is_alloca, &alloc_base, &stk_base, &stk_end, &stk, msa);\
if (r != 0) { STACK_SAVE; return r; } \
is_alloca = 0;\
UPDATE_FOR_STACK_REALLOC;\
}\
} while(0)
#define STACK_AT(index) (stk_base + (index))
#define GET_STACK_INDEX(stk) ((stk) - stk_base)
#define STACK_PUSH_TYPE(stack_type) do {\
STACK_ENSURE(1);\
stk->type = (stack_type);\
STACK_INC;\
} while(0)
#define IS_TO_VOID_TARGET(stk) (((stk)->type & STK_MASK_TO_VOID_TARGET) != 0)
#define STACK_PUSH(stack_type,pat,s,sprev) do {\
STACK_ENSURE(1);\
stk->type = (stack_type);\
stk->u.state.pcode = (pat);\
stk->u.state.pstr = (s);\
stk->u.state.pstr_prev = (sprev);\
STACK_INC;\
} while(0)
#define STACK_PUSH_ENSURED(stack_type,pat) do {\
stk->type = (stack_type);\
stk->u.state.pcode = (pat);\
STACK_INC;\
} while(0)
#ifdef ONIG_DEBUG_MATCH
#define STACK_PUSH_BOTTOM(stack_type,pat) do {\
stk->type = (stack_type);\
stk->u.state.pcode = (pat);\
stk->u.state.pstr = s;\
stk->u.state.pstr_prev = sprev;\
STACK_INC;\
} while (0)
#else
#define STACK_PUSH_BOTTOM(stack_type,pat) do {\
stk->type = (stack_type);\
stk->u.state.pcode = (pat);\
STACK_INC;\
} while (0)
#endif
#define STACK_PUSH_ALT(pat,s,sprev) STACK_PUSH(STK_ALT,pat,s,sprev)
#define STACK_PUSH_SUPER_ALT(pat,s,sprev) STACK_PUSH(STK_SUPER_ALT,pat,s,sprev)
#define STACK_PUSH_PREC_READ_START(s,sprev) \
STACK_PUSH(STK_PREC_READ_START,(Operation* )0,s,sprev)
#define STACK_PUSH_ALT_PREC_READ_NOT(pat,s,sprev) \
STACK_PUSH(STK_ALT_PREC_READ_NOT,pat,s,sprev)
#define STACK_PUSH_TO_VOID_START STACK_PUSH_TYPE(STK_TO_VOID_START)
#define STACK_PUSH_ALT_LOOK_BEHIND_NOT(pat,s,sprev) \
STACK_PUSH(STK_ALT_LOOK_BEHIND_NOT,pat,s,sprev)
#define STACK_PUSH_REPEAT(sid, pat) do {\
STACK_ENSURE(1);\
stk->type = STK_REPEAT;\
stk->zid = (sid);\
stk->u.repeat.pcode = (pat);\
stk->u.repeat.count = 0;\
STACK_INC;\
} while(0)
#define STACK_PUSH_REPEAT_INC(sindex) do {\
STACK_ENSURE(1);\
stk->type = STK_REPEAT_INC;\
stk->u.repeat_inc.si = (sindex);\
STACK_INC;\
} while(0)
#define STACK_PUSH_MEM_START(mnum, s) do {\
STACK_ENSURE(1);\
stk->type = STK_MEM_START;\
stk->zid = (mnum);\
stk->u.mem.pstr = (s);\
stk->u.mem.prev_start = mem_start_stk[mnum];\
stk->u.mem.prev_end = mem_end_stk[mnum];\
mem_start_stk[mnum] = GET_STACK_INDEX(stk);\
mem_end_stk[mnum] = INVALID_STACK_INDEX;\
STACK_INC;\
} while(0)
#define STACK_PUSH_MEM_END(mnum, s) do {\
STACK_ENSURE(1);\
stk->type = STK_MEM_END;\
stk->zid = (mnum);\
stk->u.mem.pstr = (s);\
stk->u.mem.prev_start = mem_start_stk[mnum];\
stk->u.mem.prev_end = mem_end_stk[mnum];\
mem_end_stk[mnum] = GET_STACK_INDEX(stk);\
STACK_INC;\
} while(0)
#define STACK_PUSH_MEM_END_MARK(mnum) do {\
STACK_ENSURE(1);\
stk->type = STK_MEM_END_MARK;\
stk->zid = (mnum);\
STACK_INC;\
} while(0)
#define STACK_GET_MEM_START(mnum, k) do {\
int level = 0;\
k = stk;\
while (k > stk_base) {\
k--;\
if ((k->type & STK_MASK_MEM_END_OR_MARK) != 0 \
&& k->zid == (mnum)) {\
level++;\
}\
else if (k->type == STK_MEM_START && k->zid == (mnum)) {\
if (level == 0) break;\
level--;\
}\
}\
} while(0)
#define STACK_GET_MEM_RANGE(k, mnum, start, end) do {\
int level = 0;\
while (k < stk) {\
if (k->type == STK_MEM_START && k->u.mem.num == (mnum)) {\
if (level == 0) (start) = k->u.mem.pstr;\
level++;\
}\
else if (k->type == STK_MEM_END && k->u.mem.num == (mnum)) {\
level--;\
if (level == 0) {\
(end) = k->u.mem.pstr;\
break;\
}\
}\
k++;\
}\
} while(0)
#define STACK_PUSH_EMPTY_CHECK_START(cnum, s) do {\
STACK_ENSURE(1);\
stk->type = STK_EMPTY_CHECK_START;\
stk->zid = (cnum);\
stk->u.empty_check.pstr = (s);\
STACK_INC;\
} while(0)
#define STACK_PUSH_EMPTY_CHECK_END(cnum) do {\
STACK_ENSURE(1);\
stk->type = STK_EMPTY_CHECK_END;\
stk->zid = (cnum);\
STACK_INC;\
} while(0)
#define STACK_PUSH_CALL_FRAME(pat) do {\
STACK_ENSURE(1);\
stk->type = STK_CALL_FRAME;\
stk->u.call_frame.ret_addr = (pat);\
STACK_INC;\
} while(0)
#define STACK_PUSH_RETURN do {\
STACK_ENSURE(1);\
stk->type = STK_RETURN;\
STACK_INC;\
} while(0)
#define STACK_PUSH_SAVE_VAL(sid, stype, sval) do {\
STACK_ENSURE(1);\
stk->type = STK_SAVE_VAL;\
stk->zid = (sid);\
stk->u.val.type = (stype);\
stk->u.val.v = (UChar* )(sval);\
STACK_INC;\
} while(0)
#define STACK_PUSH_SAVE_VAL_WITH_SPREV(sid, stype, sval) do {\
STACK_ENSURE(1);\
stk->type = STK_SAVE_VAL;\
stk->zid = (sid);\
stk->u.val.type = (stype);\
stk->u.val.v = (UChar* )(sval);\
stk->u.val.v2 = sprev;\
STACK_INC;\
} while(0)
#define STACK_GET_SAVE_VAL_TYPE_LAST(stype, sval) do {\
StackType *k = stk;\
while (k > stk_base) {\
k--;\
STACK_BASE_CHECK(k, "STACK_GET_SAVE_VAL_TYPE_LAST"); \
if (k->type == STK_SAVE_VAL && k->u.val.type == (stype)) {\
(sval) = k->u.val.v;\
break;\
}\
}\
} while (0)
#define STACK_GET_SAVE_VAL_TYPE_LAST_ID(stype, sid, sval) do { \
int level = 0;\
StackType *k = stk;\
while (k > stk_base) {\
k--;\
STACK_BASE_CHECK(k, "STACK_GET_SAVE_VAL_TYPE_LAST_ID"); \
if (k->type == STK_SAVE_VAL && k->u.val.type == (stype)\
&& k->zid == (sid)) {\
if (level == 0) {\
(sval) = k->u.val.v;\
break;\
}\
}\
else if (k->type == STK_CALL_FRAME)\
level--;\
else if (k->type == STK_RETURN)\
level++;\
}\
} while (0)
#define STACK_GET_SAVE_VAL_TYPE_LAST_ID_WITH_SPREV(stype, sid, sval) do { \
int level = 0;\
StackType *k = stk;\
while (k > stk_base) {\
k--;\
STACK_BASE_CHECK(k, "STACK_GET_SAVE_VAL_TYPE_LAST_ID"); \
if (k->type == STK_SAVE_VAL && k->u.val.type == (stype)\
&& k->zid == (sid)) {\
if (level == 0) {\
(sval) = k->u.val.v;\
sprev = k->u.val.v2;\
break;\
}\
}\
else if (k->type == STK_CALL_FRAME)\
level--;\
else if (k->type == STK_RETURN)\
level++;\
}\
} while (0)
#define STACK_GET_SAVE_VAL_TYPE_LAST_ID_FROM(stype, sid, sval, stk_from) do { \
int level = 0;\
StackType *k = (stk_from);\
while (k > stk_base) {\
STACK_BASE_CHECK(k, "STACK_GET_SAVE_VAL_TYPE_LAST_ID_FROM"); \
if (k->type == STK_SAVE_VAL && k->u.val.type == (stype)\
&& k->u.val.id == (sid)) {\
if (level == 0) {\
(sval) = k->u.val.v;\
break;\
}\
}\
else if (k->type == STK_CALL_FRAME)\
level--;\
else if (k->type == STK_RETURN)\
level++;\
k--;\
}\
} while (0)
#define STACK_PUSH_CALLOUT_CONTENTS(anum, func) do {\
STACK_ENSURE(1);\
stk->type = STK_CALLOUT;\
stk->zid = ONIG_NON_NAME_ID;\
stk->u.callout.num = (anum);\
stk->u.callout.func = (func);\
STACK_INC;\
} while(0)
#define STACK_PUSH_CALLOUT_NAME(aid, anum, func) do {\
STACK_ENSURE(1);\
stk->type = STK_CALLOUT;\
stk->zid = (aid);\
stk->u.callout.num = (anum);\
stk->u.callout.func = (func);\
STACK_INC;\
} while(0)
#ifdef ONIG_DEBUG
#define STACK_BASE_CHECK(p, at) \
if ((p) < stk_base) {\
fprintf(stderr, "at %s\n", at);\
goto stack_error;\
}
#else
#define STACK_BASE_CHECK(p, at)
#endif
#define STACK_POP_ONE do {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP_ONE"); \
} while(0)
#ifdef USE_CALLOUT
#define POP_CALLOUT_CASE \
else if (stk->type == STK_CALLOUT) {\
RETRACTION_CALLOUT(stk->u.callout.func, stk->zid, stk->u.callout.num, msa->mp->callout_user_data);\
}
#else
#define POP_CALLOUT_CASE
#endif
#define STACK_POP do {\
switch (pop_level) {\
case STACK_POP_LEVEL_FREE:\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP"); \
if ((stk->type & STK_MASK_POP_USED) != 0) break;\
}\
break;\
case STACK_POP_LEVEL_MEM_START:\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP 2"); \
if ((stk->type & STK_MASK_POP_USED) != 0) break;\
else if (stk->type == STK_MEM_START) {\
mem_start_stk[stk->zid] = stk->u.mem.prev_start;\
mem_end_stk[stk->zid] = stk->u.mem.prev_end;\
}\
}\
break;\
default:\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP 3"); \
if ((stk->type & STK_MASK_POP_USED) != 0) break;\
else if ((stk->type & STK_MASK_POP_HANDLED) != 0) {\
if (stk->type == STK_MEM_START) {\
mem_start_stk[stk->zid] = stk->u.mem.prev_start;\
mem_end_stk[stk->zid] = stk->u.mem.prev_end;\
}\
else if (stk->type == STK_REPEAT_INC) {\
STACK_AT(stk->u.repeat_inc.si)->u.repeat.count--;\
}\
else if (stk->type == STK_MEM_END) {\
mem_start_stk[stk->zid] = stk->u.mem.prev_start;\
mem_end_stk[stk->zid] = stk->u.mem.prev_end;\
}\
POP_CALLOUT_CASE\
}\
}\
break;\
}\
} while(0)
#define POP_TIL_BODY(aname, til_type) do {\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, (aname));\
if ((stk->type & STK_MASK_POP_HANDLED_TIL) != 0) {\
if (stk->type == (til_type)) break;\
else {\
if (stk->type == STK_MEM_START) {\
mem_start_stk[stk->zid] = stk->u.mem.prev_start;\
mem_end_stk[stk->zid] = stk->u.mem.prev_end;\
}\
else if (stk->type == STK_REPEAT_INC) {\
STACK_AT(stk->u.repeat_inc.si)->u.repeat.count--;\
}\
else if (stk->type == STK_MEM_END) {\
mem_start_stk[stk->zid] = stk->u.mem.prev_start;\
mem_end_stk[stk->zid] = stk->u.mem.prev_end;\
}\
/* Don't call callout here because negation of total success by (?!..) (?<!..) */\
}\
}\
}\
} while(0)
#define STACK_POP_TIL_ALT_PREC_READ_NOT do {\
POP_TIL_BODY("STACK_POP_TIL_ALT_PREC_READ_NOT", STK_ALT_PREC_READ_NOT);\
} while(0)
#define STACK_POP_TIL_ALT_LOOK_BEHIND_NOT do {\
POP_TIL_BODY("STACK_POP_TIL_ALT_LOOK_BEHIND_NOT", STK_ALT_LOOK_BEHIND_NOT);\
} while(0)
#define STACK_EXEC_TO_VOID(k) do {\
k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_EXEC_TO_VOID"); \
if (IS_TO_VOID_TARGET(k)) {\
if (k->type == STK_TO_VOID_START) {\
k->type = STK_VOID;\
break;\
}\
k->type = STK_VOID;\
}\
}\
} while(0)
#define STACK_GET_PREC_READ_START(k) do {\
int level = 0;\
k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_GET_PREC_READ_START");\
if (IS_TO_VOID_TARGET(k)) {\
k->type = STK_VOID;\
}\
else if (k->type == STK_PREC_READ_START) {\
if (level == 0) {\
break;\
}\
level--;\
}\
else if (k->type == STK_PREC_READ_END) {\
level++;\
}\
}\
} while(0)
#define STACK_EMPTY_CHECK(isnull,sid,s) do {\
StackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_EMPTY_CHECK"); \
if (k->type == STK_EMPTY_CHECK_START) {\
if (k->zid == (sid)) {\
(isnull) = (k->u.empty_check.pstr == (s));\
break;\
}\
}\
}\
} while(0)
#define STACK_MEM_START_GET_PREV_END_ADDR(k /* STK_MEM_START*/, reg, addr) do {\
if (k->u.mem.prev_end == INVALID_STACK_INDEX) {\
(addr) = 0;\
}\
else {\
if (MEM_STATUS_AT((reg)->bt_mem_end, k->zid))\
(addr) = STACK_AT(k->u.mem.prev_end)->u.mem.pstr;\
else\
(addr) = (UChar* )k->u.mem.prev_end;\
}\
} while (0)
#ifdef USE_STUBBORN_CHECK_CAPTURES_IN_EMPTY_REPEAT
#define STACK_EMPTY_CHECK_MEM(isnull,sid,s,reg) do {\
StackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_EMPTY_CHECK_MEM"); \
if (k->type == STK_EMPTY_CHECK_START) {\
if (k->zid == (sid)) {\
if (k->u.empty_check.pstr != (s)) {\
(isnull) = 0;\
break;\
}\
else {\
UChar* endp;\
int level = 0;\
(isnull) = 1;\
while (k < stk) {\
if (k->type == STK_MEM_START && level == 0) {\
STACK_MEM_START_GET_PREV_END_ADDR(k, reg, endp);\
if (endp == 0) {\
(isnull) = 0; break;\
}\
else if (STACK_AT(k->u.mem.prev_start)->u.mem.pstr != endp) {\
(isnull) = 0; break;\
}\
else if (endp != s) {\
(isnull) = -1; /* empty, but position changed */ \
}\
}\
else if (k->type == STK_PREC_READ_START) {\
level++;\
}\
else if (k->type == STK_PREC_READ_END) {\
level--;\
}\
k++;\
}\
break;\
}\
}\
}\
}\
} while(0)
#define STACK_EMPTY_CHECK_MEM_REC(isnull,sid,s,reg) do {\
int level = 0;\
StackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_EMPTY_CHECK_MEM_REC");\
if (k->type == STK_EMPTY_CHECK_START) {\
if (k->zid == (sid)) {\
if (level == 0) {\
if (k->u.empty_check.pstr != (s)) {\
(isnull) = 0;\
break;\
}\
else {\
UChar* endp;\
int prec_level = 0;\
(isnull) = 1;\
while (k < stk) {\
if (k->type == STK_MEM_START) {\
if (level == 0 && prec_level == 0) {\
STACK_MEM_START_GET_PREV_END_ADDR(k, reg, endp);\
if (endp == 0) {\
(isnull) = 0; break;\
}\
else if (STACK_AT(k->u.mem.prev_start)->u.mem.pstr != endp) { \
(isnull) = 0; break;\
}\
else if (endp != s) {\
(isnull) = -1; /* empty, but position changed */\
}\
}\
}\
else if (k->type == STK_EMPTY_CHECK_START) {\
if (k->zid == (sid)) level++;\
}\
else if (k->type == STK_EMPTY_CHECK_END) {\
if (k->zid == (sid)) level--;\
}\
else if (k->type == STK_PREC_READ_START) {\
prec_level++;\
}\
else if (k->type == STK_PREC_READ_END) {\
prec_level--;\
}\
k++;\
}\
break;\
}\
}\
else {\
level--;\
}\
}\
}\
else if (k->type == STK_EMPTY_CHECK_END) {\
if (k->zid == (sid)) level++;\
}\
}\
} while(0)
#else
#define STACK_EMPTY_CHECK_REC(isnull,id,s) do {\
int level = 0;\
StackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_EMPTY_CHECK_REC"); \
if (k->type == STK_EMPTY_CHECK_START) {\
if (k->u.empty_check.num == (id)) {\
if (level == 0) {\
(isnull) = (k->u.empty_check.pstr == (s));\
break;\
}\
}\
level--;\
}\
else if (k->type == STK_EMPTY_CHECK_END) {\
level++;\
}\
}\
} while(0)
#endif /* USE_STUBBORN_CHECK_CAPTURES_IN_EMPTY_REPEAT */
#define STACK_GET_REPEAT(sid, k) do {\
int level = 0;\
k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_GET_REPEAT"); \
if (k->type == STK_REPEAT) {\
if (level == 0) {\
if (k->zid == (sid)) {\
break;\
}\
}\
}\
else if (k->type == STK_CALL_FRAME) level--;\
else if (k->type == STK_RETURN) level++;\
}\
} while(0)
#define STACK_RETURN(addr) do {\
int level = 0;\
StackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_RETURN"); \
if (k->type == STK_CALL_FRAME) {\
if (level == 0) {\
(addr) = k->u.call_frame.ret_addr;\
break;\
}\
else level--;\
}\
else if (k->type == STK_RETURN)\
level++;\
}\
} while(0)
#define STRING_CMP(s1,s2,len) do {\
while (len-- > 0) {\
if (*s1++ != *s2++) goto fail;\
}\
} while(0)
#define STRING_CMP_IC(case_fold_flag,s1,ps2,len) do {\
if (string_cmp_ic(encode, case_fold_flag, s1, ps2, len) == 0) \
goto fail; \
} while(0)
static int string_cmp_ic(OnigEncoding enc, int case_fold_flag,
UChar* s1, UChar** ps2, int mblen)
{
UChar buf1[ONIGENC_MBC_CASE_FOLD_MAXLEN];
UChar buf2[ONIGENC_MBC_CASE_FOLD_MAXLEN];
UChar *p1, *p2, *end1, *s2, *end2;
int len1, len2;
s2 = *ps2;
end1 = s1 + mblen;
end2 = s2 + mblen;
while (s1 < end1) {
len1 = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &s1, end1, buf1);
len2 = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &s2, end2, buf2);
if (len1 != len2) return 0;
p1 = buf1;
p2 = buf2;
while (len1-- > 0) {
if (*p1 != *p2) return 0;
p1++;
p2++;
}
}
*ps2 = s2;
return 1;
}
#define STRING_CMP_VALUE(s1,s2,len,is_fail) do {\
is_fail = 0;\
while (len-- > 0) {\
if (*s1++ != *s2++) {\
is_fail = 1; break;\
}\
}\
} while(0)
#define STRING_CMP_VALUE_IC(case_fold_flag,s1,ps2,len,is_fail) do {\
if (string_cmp_ic(encode, case_fold_flag, s1, ps2, len) == 0) \
is_fail = 1; \
else \
is_fail = 0; \
} while(0)
#define IS_EMPTY_STR (str == end)
#define ON_STR_BEGIN(s) ((s) == str)
#define ON_STR_END(s) ((s) == end)
#define DATA_ENSURE_CHECK1 (s < right_range)
#define DATA_ENSURE_CHECK(n) (s + (n) <= right_range)
#define DATA_ENSURE(n) if (s + (n) > right_range) goto fail
#define INIT_RIGHT_RANGE right_range = (UChar* )in_right_range
#ifdef USE_CAPTURE_HISTORY
static int
make_capture_history_tree(OnigCaptureTreeNode* node, StackType** kp,
StackType* stk_top, UChar* str, regex_t* reg)
{
int n, r;
OnigCaptureTreeNode* child;
StackType* k = *kp;
while (k < stk_top) {
if (k->type == STK_MEM_START) {
n = k->zid;
if (n <= ONIG_MAX_CAPTURE_HISTORY_GROUP &&
MEM_STATUS_AT(reg->capture_history, n) != 0) {
child = history_node_new();
CHECK_NULL_RETURN_MEMERR(child);
child->group = n;
child->beg = (int )(k->u.mem.pstr - str);
r = history_tree_add_child(node, child);
if (r != 0) return r;
*kp = (k + 1);
r = make_capture_history_tree(child, kp, stk_top, str, reg);
if (r != 0) return r;
k = *kp;
child->end = (int )(k->u.mem.pstr - str);
}
}
else if (k->type == STK_MEM_END) {
if (k->zid == node->group) {
node->end = (int )(k->u.mem.pstr - str);
*kp = k;
return 0;
}
}
k++;
}
return 1; /* 1: root node ending. */
}
#endif
#ifdef USE_BACKREF_WITH_LEVEL
static int mem_is_in_memp(int mem, int num, MemNumType* memp)
{
int i;
for (i = 0; i < num; i++) {
if (mem == (int )memp[i]) return 1;
}
return 0;
}
static int
backref_match_at_nested_level(regex_t* reg,
StackType* top, StackType* stk_base,
int ignore_case, int case_fold_flag,
int nest, int mem_num, MemNumType* memp,
UChar** s, const UChar* send)
{
UChar *ss, *p, *pstart, *pend = NULL_UCHARP;
int level;
StackType* k;
level = 0;
k = top;
k--;
while (k >= stk_base) {
if (k->type == STK_CALL_FRAME) {
level--;
}
else if (k->type == STK_RETURN) {
level++;
}
else if (level == nest) {
if (k->type == STK_MEM_START) {
if (mem_is_in_memp(k->zid, mem_num, memp)) {
pstart = k->u.mem.pstr;
if (IS_NOT_NULL(pend)) {
if (pend - pstart > send - *s) return 0; /* or goto next_mem; */
p = pstart;
ss = *s;
if (ignore_case != 0) {
if (string_cmp_ic(reg->enc, case_fold_flag,
pstart, &ss, (int )(pend - pstart)) == 0)
return 0; /* or goto next_mem; */
}
else {
while (p < pend) {
if (*p++ != *ss++) return 0; /* or goto next_mem; */
}
}
*s = ss;
return 1;
}
}
}
else if (k->type == STK_MEM_END) {
if (mem_is_in_memp(k->zid, mem_num, memp)) {
pend = k->u.mem.pstr;
}
}
}
k--;
}
return 0;
}
static int
backref_check_at_nested_level(regex_t* reg,
StackType* top, StackType* stk_base,
int nest, int mem_num, MemNumType* memp)
{
int level;
StackType* k;
level = 0;
k = top;
k--;
while (k >= stk_base) {
if (k->type == STK_CALL_FRAME) {
level--;
}
else if (k->type == STK_RETURN) {
level++;
}
else if (level == nest) {
if (k->type == STK_MEM_END) {
if (mem_is_in_memp(k->zid, mem_num, memp)) {
return 1;
}
}
}
k--;
}
return 0;
}
#endif /* USE_BACKREF_WITH_LEVEL */
#ifdef ONIG_DEBUG_STATISTICS
#define USE_TIMEOFDAY
#ifdef USE_TIMEOFDAY
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
static struct timeval ts, te;
#define GETTIME(t) gettimeofday(&(t), (struct timezone* )0)
#define TIMEDIFF(te,ts) (((te).tv_usec - (ts).tv_usec) + \
(((te).tv_sec - (ts).tv_sec)*1000000))
#else
#ifdef HAVE_SYS_TIMES_H
#include <sys/times.h>
#endif
static struct tms ts, te;
#define GETTIME(t) times(&(t))
#define TIMEDIFF(te,ts) ((te).tms_utime - (ts).tms_utime)
#endif
static int OpCounter[256];
static int OpPrevCounter[256];
static unsigned long OpTime[256];
static int OpCurr = OP_FINISH;
static int OpPrevTarget = OP_FAIL;
static int MaxStackDepth = 0;
#define SOP_IN(opcode) do {\
if (opcode == OpPrevTarget) OpPrevCounter[OpCurr]++;\
OpCurr = opcode;\
OpCounter[opcode]++;\
GETTIME(ts);\
} while(0)
#define SOP_OUT do {\
GETTIME(te);\
OpTime[OpCurr] += TIMEDIFF(te, ts);\
} while(0)
extern void
onig_statistics_init(void)
{
int i;
for (i = 0; i < 256; i++) {
OpCounter[i] = OpPrevCounter[i] = 0; OpTime[i] = 0;
}
MaxStackDepth = 0;
}
extern int
onig_print_statistics(FILE* f)
{
int r;
int i;
r = fprintf(f, " count prev time\n");
if (r < 0) return -1;
for (i = 0; OpInfo[i].opcode >= 0; i++) {
r = fprintf(f, "%8d: %8d: %10ld: %s\n",
OpCounter[i], OpPrevCounter[i], OpTime[i], OpInfo[i].name);
if (r < 0) return -1;
}
r = fprintf(f, "\nmax stack depth: %d\n", MaxStackDepth);
if (r < 0) return -1;
return 0;
}
#define STACK_INC do {\
stk++;\
if (stk - stk_base > MaxStackDepth) \
MaxStackDepth = stk - stk_base;\
} while(0)
#else
#define STACK_INC stk++
#define SOP_IN(opcode)
#define SOP_OUT
#endif
/* matching region of POSIX API */
typedef int regoff_t;
typedef struct {
regoff_t rm_so;
regoff_t rm_eo;
} posix_regmatch_t;
#ifdef USE_THREADED_CODE
#define BYTECODE_INTERPRETER_START GOTO_OP;
#define BYTECODE_INTERPRETER_END
#define CASE_OP(x) L_##x: SOP_IN(OP_##x); sbegin = s; MATCH_DEBUG_OUT(0)
#define DEFAULT_OP /* L_DEFAULT: */
#define NEXT_OP sprev = sbegin; JUMP_OP
#define JUMP_OP GOTO_OP
#ifdef USE_DIRECT_THREADED_CODE
#define GOTO_OP goto *(p->opaddr)
#else
#define GOTO_OP goto *opcode_to_label[p->opcode]
#endif
#define BREAK_OP /* Nothing */
#else
#define BYTECODE_INTERPRETER_START \
while (1) {\
MATCH_DEBUG_OUT(0)\
sbegin = s;\
switch (p->opcode) {
#define BYTECODE_INTERPRETER_END } sprev = sbegin; }
#define CASE_OP(x) case OP_##x: SOP_IN(OP_##x);
#define DEFAULT_OP default:
#define NEXT_OP break
#define JUMP_OP GOTO_OP
#define GOTO_OP continue; break
#define BREAK_OP break
#endif /* USE_THREADED_CODE */
#define INC_OP p++
#define NEXT_OUT SOP_OUT; NEXT_OP
#define JUMP_OUT SOP_OUT; JUMP_OP
#define BREAK_OUT SOP_OUT; BREAK_OP
#define CHECK_INTERRUPT_JUMP_OUT SOP_OUT; CHECK_INTERRUPT_IN_MATCH; JUMP_OP
#ifdef ONIG_DEBUG_MATCH
#define MATCH_DEBUG_OUT(offset) do {\
Operation *xp;\
UChar *q, *bp, buf[50];\
int len, spos;\
spos = IS_NOT_NULL(s) ? (int )(s - str) : -1;\
xp = p - (offset);\
fprintf(stderr, "%7u: %7ld: %4d> \"",\
counter, GET_STACK_INDEX(stk), spos);\
counter++;\
bp = buf;\
if (IS_NOT_NULL(s)) {\
for (i = 0, q = s; i < 7 && q < end; i++) {\
len = enclen(encode, q);\
while (len-- > 0) *bp++ = *q++;\
}\
if (q < end) { xmemcpy(bp, "...\"", 4); bp += 4; }\
else { xmemcpy(bp, "\"", 1); bp += 1; }\
}\
else {\
xmemcpy(bp, "\"", 1); bp += 1;\
}\
*bp = 0;\
fputs((char* )buf, stderr);\
for (i = 0; i < 20 - (bp - buf); i++) fputc(' ', stderr);\
if (xp == FinishCode)\
fprintf(stderr, "----: finish");\
else {\
fprintf(stderr, "%4d: ", (int )(xp - reg->ops));\
print_compiled_byte_code(stderr, reg, (int )(xp - reg->ops), reg->ops, encode);\
}\
fprintf(stderr, "\n");\
} while(0);
#else
#define MATCH_DEBUG_OUT(offset)
#endif
/* match data(str - end) from position (sstart). */
/* if sstart == str then set sprev to NULL. */
static int
match_at(regex_t* reg, const UChar* str, const UChar* end,
const UChar* in_right_range, const UChar* sstart, UChar* sprev,
MatchArg* msa)
{
#if defined(USE_DIRECT_THREADED_CODE)
static Operation FinishCode[] = { { .opaddr=&&L_FINISH } };
#else
static Operation FinishCode[] = { { OP_FINISH } };
#endif
#ifdef USE_THREADED_CODE
static const void *opcode_to_label[] = {
&&L_FINISH,
&&L_END,
&&L_EXACT1,
&&L_EXACT2,
&&L_EXACT3,
&&L_EXACT4,
&&L_EXACT5,
&&L_EXACTN,
&&L_EXACTMB2N1,
&&L_EXACTMB2N2,
&&L_EXACTMB2N3,
&&L_EXACTMB2N,
&&L_EXACTMB3N,
&&L_EXACTMBN,
&&L_EXACT1_IC,
&&L_EXACTN_IC,
&&L_CCLASS,
&&L_CCLASS_MB,
&&L_CCLASS_MIX,
&&L_CCLASS_NOT,
&&L_CCLASS_MB_NOT,
&&L_CCLASS_MIX_NOT,
&&L_ANYCHAR,
&&L_ANYCHAR_ML,
&&L_ANYCHAR_STAR,
&&L_ANYCHAR_ML_STAR,
&&L_ANYCHAR_STAR_PEEK_NEXT,
&&L_ANYCHAR_ML_STAR_PEEK_NEXT,
&&L_WORD,
&&L_WORD_ASCII,
&&L_NO_WORD,
&&L_NO_WORD_ASCII,
&&L_WORD_BOUNDARY,
&&L_NO_WORD_BOUNDARY,
&&L_WORD_BEGIN,
&&L_WORD_END,
&&L_TEXT_SEGMENT_BOUNDARY,
&&L_BEGIN_BUF,
&&L_END_BUF,
&&L_BEGIN_LINE,
&&L_END_LINE,
&&L_SEMI_END_BUF,
&&L_BEGIN_POSITION,
&&L_BACKREF1,
&&L_BACKREF2,
&&L_BACKREF_N,
&&L_BACKREF_N_IC,
&&L_BACKREF_MULTI,
&&L_BACKREF_MULTI_IC,
&&L_BACKREF_WITH_LEVEL,
&&L_BACKREF_WITH_LEVEL_IC,
&&L_BACKREF_CHECK,
&&L_BACKREF_CHECK_WITH_LEVEL,
&&L_MEMORY_START,
&&L_MEMORY_START_PUSH,
&&L_MEMORY_END_PUSH,
&&L_MEMORY_END_PUSH_REC,
&&L_MEMORY_END,
&&L_MEMORY_END_REC,
&&L_FAIL,
&&L_JUMP,
&&L_PUSH,
&&L_PUSH_SUPER,
&&L_POP_OUT,
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
&&L_PUSH_OR_JUMP_EXACT1,
#endif
&&L_PUSH_IF_PEEK_NEXT,
&&L_REPEAT,
&&L_REPEAT_NG,
&&L_REPEAT_INC,
&&L_REPEAT_INC_NG,
&&L_REPEAT_INC_SG,
&&L_REPEAT_INC_NG_SG,
&&L_EMPTY_CHECK_START,
&&L_EMPTY_CHECK_END,
&&L_EMPTY_CHECK_END_MEMST,
&&L_EMPTY_CHECK_END_MEMST_PUSH,
&&L_PREC_READ_START,
&&L_PREC_READ_END,
&&L_PREC_READ_NOT_START,
&&L_PREC_READ_NOT_END,
&&L_ATOMIC_START,
&&L_ATOMIC_END,
&&L_LOOK_BEHIND,
&&L_LOOK_BEHIND_NOT_START,
&&L_LOOK_BEHIND_NOT_END,
&&L_CALL,
&&L_RETURN,
&&L_PUSH_SAVE_VAL,
&&L_UPDATE_VAR,
#ifdef USE_CALLOUT
&&L_CALLOUT_CONTENTS,
&&L_CALLOUT_NAME,
#endif
};
#endif
int i, n, num_mem, best_len, pop_level;
LengthType tlen, tlen2;
MemNumType mem;
RelAddrType addr;
UChar *s, *q, *ps, *sbegin;
UChar *right_range;
int is_alloca;
char *alloc_base;
StackType *stk_base, *stk, *stk_end;
StackType *stkp; /* used as any purpose. */
StackIndex si;
StackIndex *repeat_stk;
StackIndex *mem_start_stk, *mem_end_stk;
UChar* keep;
#ifdef USE_RETRY_LIMIT_IN_MATCH
unsigned long retry_limit_in_match;
unsigned long retry_in_match_counter;
#endif
#ifdef USE_CALLOUT
int of;
#endif
Operation* p = reg->ops;
OnigOptionType option = reg->options;
OnigEncoding encode = reg->enc;
OnigCaseFoldType case_fold_flag = reg->case_fold_flag;
#ifdef ONIG_DEBUG_MATCH
static unsigned int counter = 1;
#endif
#ifdef USE_DIRECT_THREADED_CODE
if (IS_NULL(msa)) {
for (i = 0; i < reg->ops_used; i++) {
const void* addr;
addr = opcode_to_label[reg->ocs[i]];
p->opaddr = addr;
p++;
}
return ONIG_NORMAL;
}
#endif
#ifdef USE_CALLOUT
msa->mp->match_at_call_counter++;
#endif
#ifdef USE_RETRY_LIMIT_IN_MATCH
retry_limit_in_match = msa->retry_limit_in_match;
#endif
pop_level = reg->stack_pop_level;
num_mem = reg->num_mem;
STACK_INIT(INIT_MATCH_STACK_SIZE);
UPDATE_FOR_STACK_REALLOC;
for (i = 1; i <= num_mem; i++) {
mem_start_stk[i] = mem_end_stk[i] = INVALID_STACK_INDEX;
}
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "match_at: str: %p, end: %p, start: %p, sprev: %p\n",
str, end, sstart, sprev);
fprintf(stderr, "size: %d, start offset: %d\n",
(int )(end - str), (int )(sstart - str));
#endif
best_len = ONIG_MISMATCH;
keep = s = (UChar* )sstart;
STACK_PUSH_BOTTOM(STK_ALT, FinishCode); /* bottom stack */
INIT_RIGHT_RANGE;
#ifdef USE_RETRY_LIMIT_IN_MATCH
retry_in_match_counter = 0;
#endif
BYTECODE_INTERPRETER_START {
CASE_OP(END)
n = (int )(s - sstart);
if (n > best_len) {
OnigRegion* region;
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
if (IS_FIND_LONGEST(option)) {
if (n > msa->best_len) {
msa->best_len = n;
msa->best_s = (UChar* )sstart;
}
else
goto end_best_len;
}
#endif
best_len = n;
region = msa->region;
if (region) {
if (keep > s) keep = s;
#ifdef USE_POSIX_API_REGION_OPTION
if (IS_POSIX_REGION(msa->options)) {
posix_regmatch_t* rmt = (posix_regmatch_t* )region;
rmt[0].rm_so = (regoff_t )(keep - str);
rmt[0].rm_eo = (regoff_t )(s - str);
for (i = 1; i <= num_mem; i++) {
if (mem_end_stk[i] != INVALID_STACK_INDEX) {
if (MEM_STATUS_AT(reg->bt_mem_start, i))
rmt[i].rm_so = (regoff_t )(STACK_AT(mem_start_stk[i])->u.mem.pstr - str);
else
rmt[i].rm_so = (regoff_t )((UChar* )((void* )(mem_start_stk[i])) - str);
rmt[i].rm_eo = (regoff_t )((MEM_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[i]))
- str);
}
else {
rmt[i].rm_so = rmt[i].rm_eo = ONIG_REGION_NOTPOS;
}
}
}
else {
#endif /* USE_POSIX_API_REGION_OPTION */
region->beg[0] = (int )(keep - str);
region->end[0] = (int )(s - str);
for (i = 1; i <= num_mem; i++) {
if (mem_end_stk[i] != INVALID_STACK_INDEX) {
if (MEM_STATUS_AT(reg->bt_mem_start, i))
region->beg[i] = (int )(STACK_AT(mem_start_stk[i])->u.mem.pstr - str);
else
region->beg[i] = (int )((UChar* )((void* )mem_start_stk[i]) - str);
region->end[i] = (int )((MEM_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[i])) - str);
}
else {
region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS;
}
}
#ifdef USE_CAPTURE_HISTORY
if (reg->capture_history != 0) {
int r;
OnigCaptureTreeNode* node;
if (IS_NULL(region->history_root)) {
region->history_root = node = history_node_new();
CHECK_NULL_RETURN_MEMERR(node);
}
else {
node = region->history_root;
history_tree_clear(node);
}
node->group = 0;
node->beg = (int )(keep - str);
node->end = (int )(s - str);
stkp = stk_base;
r = make_capture_history_tree(region->history_root, &stkp,
stk, (UChar* )str, reg);
if (r < 0) {
best_len = r; /* error code */
goto finish;
}
}
#endif /* USE_CAPTURE_HISTORY */
#ifdef USE_POSIX_API_REGION_OPTION
} /* else IS_POSIX_REGION() */
#endif
} /* if (region) */
} /* n > best_len */
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
end_best_len:
#endif
SOP_OUT;
if (IS_FIND_CONDITION(option)) {
if (IS_FIND_NOT_EMPTY(option) && s == sstart) {
best_len = ONIG_MISMATCH;
goto fail; /* for retry */
}
if (IS_FIND_LONGEST(option) && DATA_ENSURE_CHECK1) {
goto fail; /* for retry */
}
}
/* default behavior: return first-matching result. */
goto finish;
CASE_OP(EXACT1)
DATA_ENSURE(1);
ps = p->exact.s;
if (*ps != *s) goto fail;
s++;
INC_OP;
NEXT_OUT;
CASE_OP(EXACT1_IC)
{
int len;
UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
DATA_ENSURE(1);
len = ONIGENC_MBC_CASE_FOLD(encode,
/* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */
case_fold_flag,
&s, end, lowbuf);
DATA_ENSURE(0);
q = lowbuf;
ps = p->exact.s;
while (len-- > 0) {
if (*ps != *q) goto fail;
ps++; q++;
}
}
INC_OP;
NEXT_OUT;
CASE_OP(EXACT2)
DATA_ENSURE(2);
ps = p->exact.s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
sprev = s;
s++;
INC_OP;
JUMP_OUT;
CASE_OP(EXACT3)
DATA_ENSURE(3);
ps = p->exact.s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
sprev = s;
s++;
INC_OP;
JUMP_OUT;
CASE_OP(EXACT4)
DATA_ENSURE(4);
ps = p->exact.s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
sprev = s;
s++;
INC_OP;
JUMP_OUT;
CASE_OP(EXACT5)
DATA_ENSURE(5);
ps = p->exact.s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
sprev = s;
s++;
INC_OP;
JUMP_OUT;
CASE_OP(EXACTN)
tlen = p->exact_n.n;
DATA_ENSURE(tlen);
ps = p->exact_n.s;
while (tlen-- > 0) {
if (*ps++ != *s++) goto fail;
}
sprev = s - 1;
INC_OP;
JUMP_OUT;
CASE_OP(EXACTN_IC)
{
int len;
UChar *q, *endp, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
tlen = p->exact_n.n;
ps = p->exact_n.s;
endp = ps + tlen;
while (ps < endp) {
sprev = s;
DATA_ENSURE(1);
len = ONIGENC_MBC_CASE_FOLD(encode,
/* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */
case_fold_flag,
&s, end, lowbuf);
DATA_ENSURE(0);
q = lowbuf;
while (len-- > 0) {
if (*ps != *q) goto fail;
ps++; q++;
}
}
}
INC_OP;
JUMP_OUT;
CASE_OP(EXACTMB2N1)
DATA_ENSURE(2);
ps = p->exact.s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
s++;
INC_OP;
NEXT_OUT;
CASE_OP(EXACTMB2N2)
DATA_ENSURE(4);
ps = p->exact.s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
sprev = s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
s++;
INC_OP;
JUMP_OUT;
CASE_OP(EXACTMB2N3)
DATA_ENSURE(6);
ps = p->exact.s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
sprev = s;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
INC_OP;
JUMP_OUT;
CASE_OP(EXACTMB2N)
tlen = p->exact_n.n;
DATA_ENSURE(tlen * 2);
ps = p->exact_n.s;
while (tlen-- > 0) {
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
}
sprev = s - 2;
INC_OP;
JUMP_OUT;
CASE_OP(EXACTMB3N)
tlen = p->exact_n.n;
DATA_ENSURE(tlen * 3);
ps = p->exact_n.s;
while (tlen-- > 0) {
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
if (*ps != *s) goto fail;
ps++; s++;
}
sprev = s - 3;
INC_OP;
JUMP_OUT;
CASE_OP(EXACTMBN)
tlen = p->exact_len_n.len; /* mb byte len */
tlen2 = p->exact_len_n.n; /* number of chars */
tlen2 *= tlen;
DATA_ENSURE(tlen2);
ps = p->exact_len_n.s;
while (tlen2-- > 0) {
if (*ps != *s) goto fail;
ps++; s++;
}
sprev = s - tlen;
INC_OP;
JUMP_OUT;
CASE_OP(CCLASS)
DATA_ENSURE(1);
if (BITSET_AT(p->cclass.bsp, *s) == 0) goto fail;
s++;
INC_OP;
NEXT_OUT;
CASE_OP(CCLASS_MB)
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_HEAD(encode, s)) goto fail;
cclass_mb:
{
OnigCodePoint code;
UChar *ss;
int mb_len;
DATA_ENSURE(1);
mb_len = enclen(encode, s);
DATA_ENSURE(mb_len);
ss = s;
s += mb_len;
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
if (! onig_is_in_code_range(p->cclass_mb.mb, code)) goto fail;
}
INC_OP;
NEXT_OUT;
CASE_OP(CCLASS_MIX)
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_HEAD(encode, s)) {
goto cclass_mb;
}
else {
if (BITSET_AT(p->cclass_mix.bsp, *s) == 0)
goto fail;
s++;
}
INC_OP;
NEXT_OUT;
CASE_OP(CCLASS_NOT)
DATA_ENSURE(1);
if (BITSET_AT(p->cclass.bsp, *s) != 0) goto fail;
s += enclen(encode, s);
INC_OP;
NEXT_OUT;
CASE_OP(CCLASS_MB_NOT)
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_HEAD(encode, s)) {
s++;
goto cc_mb_not_success;
}
cclass_mb_not:
{
OnigCodePoint code;
UChar *ss;
int mb_len = enclen(encode, s);
if (! DATA_ENSURE_CHECK(mb_len)) {
DATA_ENSURE(1);
s = (UChar* )end;
goto cc_mb_not_success;
}
ss = s;
s += mb_len;
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
if (onig_is_in_code_range(p->cclass_mb.mb, code)) goto fail;
}
cc_mb_not_success:
INC_OP;
NEXT_OUT;
CASE_OP(CCLASS_MIX_NOT)
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_HEAD(encode, s)) {
goto cclass_mb_not;
}
else {
if (BITSET_AT(p->cclass_mix.bsp, *s) != 0)
goto fail;
s++;
}
INC_OP;
NEXT_OUT;
CASE_OP(ANYCHAR)
DATA_ENSURE(1);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
s += n;
INC_OP;
NEXT_OUT;
CASE_OP(ANYCHAR_ML)
DATA_ENSURE(1);
n = enclen(encode, s);
DATA_ENSURE(n);
s += n;
INC_OP;
NEXT_OUT;
CASE_OP(ANYCHAR_STAR)
INC_OP;
while (DATA_ENSURE_CHECK1) {
STACK_PUSH_ALT(p, s, sprev);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
JUMP_OUT;
CASE_OP(ANYCHAR_ML_STAR)
INC_OP;
while (DATA_ENSURE_CHECK1) {
STACK_PUSH_ALT(p, s, sprev);
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
JUMP_OUT;
CASE_OP(ANYCHAR_STAR_PEEK_NEXT)
{
UChar c;
c = p->anychar_star_peek_next.c;
INC_OP;
while (DATA_ENSURE_CHECK1) {
if (c == *s) {
STACK_PUSH_ALT(p, s, sprev);
}
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
}
NEXT_OUT;
CASE_OP(ANYCHAR_ML_STAR_PEEK_NEXT)
{
UChar c;
c = p->anychar_star_peek_next.c;
INC_OP;
while (DATA_ENSURE_CHECK1) {
if (c == *s) {
STACK_PUSH_ALT(p, s, sprev);
}
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
}
NEXT_OUT;
CASE_OP(WORD)
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
s += enclen(encode, s);
INC_OP;
NEXT_OUT;
CASE_OP(WORD_ASCII)
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_WORD_ASCII(encode, s, end))
goto fail;
s += enclen(encode, s);
INC_OP;
NEXT_OUT;
CASE_OP(NO_WORD)
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
s += enclen(encode, s);
INC_OP;
NEXT_OUT;
CASE_OP(NO_WORD_ASCII)
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_WORD_ASCII(encode, s, end))
goto fail;
s += enclen(encode, s);
INC_OP;
NEXT_OUT;
CASE_OP(WORD_BOUNDARY)
{
ModeType mode;
mode = p->word_boundary.mode;
if (ON_STR_BEGIN(s)) {
DATA_ENSURE(1);
if (! IS_MBC_WORD_ASCII_MODE(encode, s, end, mode))
goto fail;
}
else if (ON_STR_END(s)) {
if (! IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode))
goto fail;
}
else {
if (IS_MBC_WORD_ASCII_MODE(encode, s, end, mode)
== IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode))
goto fail;
}
}
INC_OP;
JUMP_OUT;
CASE_OP(NO_WORD_BOUNDARY)
{
ModeType mode;
mode = p->word_boundary.mode;
if (ON_STR_BEGIN(s)) {
if (DATA_ENSURE_CHECK1 && IS_MBC_WORD_ASCII_MODE(encode, s, end, mode))
goto fail;
}
else if (ON_STR_END(s)) {
if (IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode))
goto fail;
}
else {
if (IS_MBC_WORD_ASCII_MODE(encode, s, end, mode)
!= IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode))
goto fail;
}
}
INC_OP;
JUMP_OUT;
#ifdef USE_WORD_BEGIN_END
CASE_OP(WORD_BEGIN)
{
ModeType mode;
mode = p->word_boundary.mode;
if (DATA_ENSURE_CHECK1 && IS_MBC_WORD_ASCII_MODE(encode, s, end, mode)) {
if (ON_STR_BEGIN(s) || !IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode)) {
INC_OP;
JUMP_OUT;
}
}
}
goto fail;
CASE_OP(WORD_END)
{
ModeType mode;
mode = p->word_boundary.mode;
if (!ON_STR_BEGIN(s) && IS_MBC_WORD_ASCII_MODE(encode, sprev, end, mode)) {
if (ON_STR_END(s) || ! IS_MBC_WORD_ASCII_MODE(encode, s, end, mode)) {
INC_OP;
JUMP_OUT;
}
}
}
goto fail;
#endif
CASE_OP(TEXT_SEGMENT_BOUNDARY)
{
int is_break;
switch (p->text_segment_boundary.type) {
case EXTENDED_GRAPHEME_CLUSTER_BOUNDARY:
is_break = onigenc_egcb_is_break_position(encode, s, sprev, str, end);
break;
#ifdef USE_UNICODE_WORD_BREAK
case WORD_BOUNDARY:
is_break = onigenc_wb_is_break_position(encode, s, sprev, str, end);
break;
#endif
default:
goto bytecode_error;
break;
}
if (p->text_segment_boundary.not != 0)
is_break = ! is_break;
if (is_break != 0) {
INC_OP;
JUMP_OUT;
}
else {
goto fail;
}
}
CASE_OP(BEGIN_BUF)
if (! ON_STR_BEGIN(s)) goto fail;
INC_OP;
JUMP_OUT;
CASE_OP(END_BUF)
if (! ON_STR_END(s)) goto fail;
INC_OP;
JUMP_OUT;
CASE_OP(BEGIN_LINE)
if (ON_STR_BEGIN(s)) {
if (IS_NOTBOL(msa->options)) goto fail;
INC_OP;
JUMP_OUT;
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, sprev, end) && !ON_STR_END(s)) {
INC_OP;
JUMP_OUT;
}
goto fail;
CASE_OP(END_LINE)
if (ON_STR_END(s)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) {
#endif
if (IS_NOTEOL(msa->options)) goto fail;
INC_OP;
JUMP_OUT;
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
}
#endif
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) {
INC_OP;
JUMP_OUT;
}
#ifdef USE_CRNL_AS_LINE_TERMINATOR
else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) {
INC_OP;
JUMP_OUT;
}
#endif
goto fail;
CASE_OP(SEMI_END_BUF)
if (ON_STR_END(s)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) {
#endif
if (IS_NOTEOL(msa->options)) goto fail;
INC_OP;
JUMP_OUT;
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
}
#endif
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end) &&
ON_STR_END(s + enclen(encode, s))) {
INC_OP;
JUMP_OUT;
}
#ifdef USE_CRNL_AS_LINE_TERMINATOR
else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) {
UChar* ss = s + enclen(encode, s);
ss += enclen(encode, ss);
if (ON_STR_END(ss)) {
INC_OP;
JUMP_OUT;
}
}
#endif
goto fail;
CASE_OP(BEGIN_POSITION)
if (s != msa->start)
goto fail;
INC_OP;
JUMP_OUT;
CASE_OP(MEMORY_START_PUSH)
mem = p->memory_start.num;
STACK_PUSH_MEM_START(mem, s);
INC_OP;
JUMP_OUT;
CASE_OP(MEMORY_START)
mem = p->memory_start.num;
mem_start_stk[mem] = (StackIndex )((void* )s);
INC_OP;
JUMP_OUT;
CASE_OP(MEMORY_END_PUSH)
mem = p->memory_end.num;
STACK_PUSH_MEM_END(mem, s);
INC_OP;
JUMP_OUT;
CASE_OP(MEMORY_END)
mem = p->memory_end.num;
mem_end_stk[mem] = (StackIndex )((void* )s);
INC_OP;
JUMP_OUT;
#ifdef USE_CALL
CASE_OP(MEMORY_END_PUSH_REC)
mem = p->memory_end.num;
STACK_GET_MEM_START(mem, stkp); /* should be before push mem-end. */
si = GET_STACK_INDEX(stkp);
STACK_PUSH_MEM_END(mem, s);
mem_start_stk[mem] = si;
INC_OP;
JUMP_OUT;
CASE_OP(MEMORY_END_REC)
mem = p->memory_end.num;
mem_end_stk[mem] = (StackIndex )((void* )s);
STACK_GET_MEM_START(mem, stkp);
if (MEM_STATUS_AT(reg->bt_mem_start, mem))
mem_start_stk[mem] = GET_STACK_INDEX(stkp);
else
mem_start_stk[mem] = (StackIndex )((void* )stkp->u.mem.pstr);
STACK_PUSH_MEM_END_MARK(mem);
INC_OP;
JUMP_OUT;
#endif
CASE_OP(BACKREF1)
mem = 1;
goto backref;
CASE_OP(BACKREF2)
mem = 2;
goto backref;
CASE_OP(BACKREF_N)
mem = p->backref_n.n1;
backref:
{
int len;
UChar *pstart, *pend;
if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (MEM_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (MEM_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = (int )(pend - pstart);
if (n != 0) {
DATA_ENSURE(n);
sprev = s;
STRING_CMP(s, pstart, n);
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
}
}
INC_OP;
JUMP_OUT;
CASE_OP(BACKREF_N_IC)
mem = p->backref_n.n1;
{
int len;
UChar *pstart, *pend;
if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (MEM_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (MEM_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = (int )(pend - pstart);
if (n != 0) {
DATA_ENSURE(n);
sprev = s;
STRING_CMP_IC(case_fold_flag, pstart, &s, n);
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
}
}
INC_OP;
JUMP_OUT;
CASE_OP(BACKREF_MULTI)
{
int len, is_fail;
UChar *pstart, *pend, *swork;
tlen = p->backref_general.num;
for (i = 0; i < tlen; i++) {
mem = tlen == 1 ? p->backref_general.n1 : p->backref_general.ns[i];
if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue;
if (MEM_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (MEM_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = (int )(pend - pstart);
if (n != 0) {
DATA_ENSURE(n);
sprev = s;
swork = s;
STRING_CMP_VALUE(swork, pstart, n, is_fail);
if (is_fail) continue;
s = swork;
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
}
break; /* success */
}
if (i == tlen) goto fail;
}
INC_OP;
JUMP_OUT;
CASE_OP(BACKREF_MULTI_IC)
{
int len, is_fail;
UChar *pstart, *pend, *swork;
tlen = p->backref_general.num;
for (i = 0; i < tlen; i++) {
mem = tlen == 1 ? p->backref_general.n1 : p->backref_general.ns[i];
if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue;
if (MEM_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (MEM_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = (int )(pend - pstart);
if (n != 0) {
DATA_ENSURE(n);
sprev = s;
swork = s;
STRING_CMP_VALUE_IC(case_fold_flag, pstart, &swork, n, is_fail);
if (is_fail) continue;
s = swork;
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
}
break; /* success */
}
if (i == tlen) goto fail;
}
INC_OP;
JUMP_OUT;
#ifdef USE_BACKREF_WITH_LEVEL
CASE_OP(BACKREF_WITH_LEVEL_IC)
n = 1; /* ignore case */
goto backref_with_level;
CASE_OP(BACKREF_WITH_LEVEL)
{
int len;
int level;
MemNumType* mems;
UChar* ssave;
n = 0;
backref_with_level:
level = p->backref_general.nest_level;
tlen = p->backref_general.num;
mems = tlen == 1 ? &(p->backref_general.n1) : p->backref_general.ns;
ssave = s;
if (backref_match_at_nested_level(reg, stk, stk_base, n,
case_fold_flag, level, (int )tlen, mems, &s, end)) {
if (ssave != s) {
sprev = ssave;
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
}
}
else
goto fail;
}
INC_OP;
JUMP_OUT;
#endif
CASE_OP(BACKREF_CHECK)
{
MemNumType* mems;
tlen = p->backref_general.num;
mems = tlen == 1 ? &(p->backref_general.n1) : p->backref_general.ns;
for (i = 0; i < tlen; i++) {
mem = mems[i];
if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue;
break; /* success */
}
if (i == tlen) goto fail;
}
INC_OP;
JUMP_OUT;
#ifdef USE_BACKREF_WITH_LEVEL
CASE_OP(BACKREF_CHECK_WITH_LEVEL)
{
LengthType level;
MemNumType* mems;
level = p->backref_general.nest_level;
tlen = p->backref_general.num;
mems = tlen == 1 ? &(p->backref_general.n1) : p->backref_general.ns;
if (backref_check_at_nested_level(reg, stk, stk_base,
(int )level, (int )tlen, mems) == 0)
goto fail;
}
INC_OP;
JUMP_OUT;
#endif
CASE_OP(EMPTY_CHECK_START)
mem = p->empty_check_start.mem; /* mem: null check id */
STACK_PUSH_EMPTY_CHECK_START(mem, s);
INC_OP;
JUMP_OUT;
CASE_OP(EMPTY_CHECK_END)
{
int is_empty;
mem = p->empty_check_end.mem; /* mem: null check id */
STACK_EMPTY_CHECK(is_empty, mem, s);
INC_OP;
if (is_empty) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "EMPTY_CHECK_END: skip id:%d, s:%p\n", (int )mem, s);
#endif
empty_check_found:
/* empty loop founded, skip next instruction */
#if defined(ONIG_DEBUG) && !defined(USE_DIRECT_THREADED_CODE)
switch (p->opcode) {
case OP_JUMP:
case OP_PUSH:
case OP_REPEAT_INC:
case OP_REPEAT_INC_NG:
case OP_REPEAT_INC_SG:
case OP_REPEAT_INC_NG_SG:
INC_OP;
break;
default:
goto unexpected_bytecode_error;
break;
}
#else
INC_OP;
#endif
}
}
JUMP_OUT;
#ifdef USE_STUBBORN_CHECK_CAPTURES_IN_EMPTY_REPEAT
CASE_OP(EMPTY_CHECK_END_MEMST)
{
int is_empty;
mem = p->empty_check_end.mem; /* mem: null check id */
STACK_EMPTY_CHECK_MEM(is_empty, mem, s, reg);
INC_OP;
if (is_empty) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "EMPTY_CHECK_END_MEM: skip id:%d, s:%p\n", (int)mem, s);
#endif
if (is_empty == -1) goto fail;
goto empty_check_found;
}
}
JUMP_OUT;
#endif
#ifdef USE_CALL
CASE_OP(EMPTY_CHECK_END_MEMST_PUSH)
{
int is_empty;
mem = p->empty_check_end.mem; /* mem: null check id */
#ifdef USE_STUBBORN_CHECK_CAPTURES_IN_EMPTY_REPEAT
STACK_EMPTY_CHECK_MEM_REC(is_empty, mem, s, reg);
#else
STACK_EMPTY_CHECK_REC(is_empty, mem, s);
#endif
INC_OP;
if (is_empty) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "EMPTY_CHECK_END_MEM_PUSH: skip id:%d, s:%p\n",
(int )mem, s);
#endif
if (is_empty == -1) goto fail;
goto empty_check_found;
}
else {
STACK_PUSH_EMPTY_CHECK_END(mem);
}
}
JUMP_OUT;
#endif
CASE_OP(JUMP)
addr = p->jump.addr;
p += addr;
CHECK_INTERRUPT_JUMP_OUT;
CASE_OP(PUSH)
addr = p->push.addr;
STACK_PUSH_ALT(p + addr, s, sprev);
INC_OP;
JUMP_OUT;
CASE_OP(PUSH_SUPER)
addr = p->push.addr;
STACK_PUSH_SUPER_ALT(p + addr, s, sprev);
INC_OP;
JUMP_OUT;
CASE_OP(POP_OUT)
STACK_POP_ONE;
/* for stop backtrack */
/* CHECK_RETRY_LIMIT_IN_MATCH; */
INC_OP;
JUMP_OUT;
#ifdef USE_OP_PUSH_OR_JUMP_EXACT
CASE_OP(PUSH_OR_JUMP_EXACT1)
{
UChar c;
addr = p->push_or_jump_exact1.addr;
c = p->push_or_jump_exact1.c;
if (DATA_ENSURE_CHECK1 && c == *s) {
STACK_PUSH_ALT(p + addr, s, sprev);
INC_OP;
JUMP_OUT;
}
}
p += addr;
JUMP_OUT;
#endif
CASE_OP(PUSH_IF_PEEK_NEXT)
{
UChar c;
addr = p->push_if_peek_next.addr;
c = p->push_if_peek_next.c;
if (c == *s) {
STACK_PUSH_ALT(p + addr, s, sprev);
INC_OP;
JUMP_OUT;
}
}
INC_OP;
JUMP_OUT;
CASE_OP(REPEAT)
mem = p->repeat.id; /* mem: OP_REPEAT ID */
addr = p->repeat.addr;
STACK_ENSURE(1);
repeat_stk[mem] = GET_STACK_INDEX(stk);
STACK_PUSH_REPEAT(mem, p + 1);
if (reg->repeat_range[mem].lower == 0) {
STACK_PUSH_ALT(p + addr, s, sprev);
}
INC_OP;
JUMP_OUT;
CASE_OP(REPEAT_NG)
mem = p->repeat.id; /* mem: OP_REPEAT ID */
addr = p->repeat.addr;
STACK_ENSURE(1);
repeat_stk[mem] = GET_STACK_INDEX(stk);
STACK_PUSH_REPEAT(mem, p + 1);
if (reg->repeat_range[mem].lower == 0) {
STACK_PUSH_ALT(p + 1, s, sprev);
p += addr;
}
else
INC_OP;
JUMP_OUT;
CASE_OP(REPEAT_INC)
mem = p->repeat_inc.id; /* mem: OP_REPEAT ID */
si = repeat_stk[mem];
stkp = STACK_AT(si);
repeat_inc:
stkp->u.repeat.count++;
if (stkp->u.repeat.count >= reg->repeat_range[mem].upper) {
/* end of repeat. Nothing to do. */
INC_OP;
}
else if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) {
INC_OP;
STACK_PUSH_ALT(p, s, sprev);
p = STACK_AT(si)->u.repeat.pcode; /* Don't use stkp after PUSH. */
}
else {
p = stkp->u.repeat.pcode;
}
STACK_PUSH_REPEAT_INC(si);
CHECK_INTERRUPT_JUMP_OUT;
CASE_OP(REPEAT_INC_SG)
mem = p->repeat_inc.id; /* mem: OP_REPEAT ID */
STACK_GET_REPEAT(mem, stkp);
si = GET_STACK_INDEX(stkp);
goto repeat_inc;
CASE_OP(REPEAT_INC_NG)
mem = p->repeat_inc.id; /* mem: OP_REPEAT ID */
si = repeat_stk[mem];
stkp = STACK_AT(si);
repeat_inc_ng:
stkp->u.repeat.count++;
if (stkp->u.repeat.count < reg->repeat_range[mem].upper) {
if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) {
Operation* pcode = stkp->u.repeat.pcode;
STACK_PUSH_REPEAT_INC(si);
STACK_PUSH_ALT(pcode, s, sprev);
INC_OP;
}
else {
p = stkp->u.repeat.pcode;
STACK_PUSH_REPEAT_INC(si);
}
}
else if (stkp->u.repeat.count == reg->repeat_range[mem].upper) {
STACK_PUSH_REPEAT_INC(si);
INC_OP;
}
CHECK_INTERRUPT_JUMP_OUT;
CASE_OP(REPEAT_INC_NG_SG)
mem = p->repeat_inc.id; /* mem: OP_REPEAT ID */
STACK_GET_REPEAT(mem, stkp);
si = GET_STACK_INDEX(stkp);
goto repeat_inc_ng;
CASE_OP(PREC_READ_START)
STACK_PUSH_PREC_READ_START(s, sprev);
INC_OP;
JUMP_OUT;
CASE_OP(PREC_READ_END)
STACK_GET_PREC_READ_START(stkp);
s = stkp->u.state.pstr;
sprev = stkp->u.state.pstr_prev;
STACK_PUSH(STK_PREC_READ_END,0,0,0);
INC_OP;
JUMP_OUT;
CASE_OP(PREC_READ_NOT_START)
addr = p->prec_read_not_start.addr;
STACK_PUSH_ALT_PREC_READ_NOT(p + addr, s, sprev);
INC_OP;
JUMP_OUT;
CASE_OP(PREC_READ_NOT_END)
STACK_POP_TIL_ALT_PREC_READ_NOT;
goto fail;
CASE_OP(ATOMIC_START)
STACK_PUSH_TO_VOID_START;
INC_OP;
JUMP_OUT;
CASE_OP(ATOMIC_END)
STACK_EXEC_TO_VOID(stkp);
INC_OP;
JUMP_OUT;
CASE_OP(LOOK_BEHIND)
tlen = p->look_behind.len;
s = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen);
if (IS_NULL(s)) goto fail;
sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s);
INC_OP;
JUMP_OUT;
CASE_OP(LOOK_BEHIND_NOT_START)
addr = p->look_behind_not_start.addr;
tlen = p->look_behind_not_start.len;
q = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen);
if (IS_NULL(q)) {
/* too short case -> success. ex. /(?<!XXX)a/.match("a")
If you want to change to fail, replace following line. */
p += addr;
/* goto fail; */
}
else {
STACK_PUSH_ALT_LOOK_BEHIND_NOT(p + addr, s, sprev);
s = q;
sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s);
INC_OP;
}
JUMP_OUT;
CASE_OP(LOOK_BEHIND_NOT_END)
STACK_POP_TIL_ALT_LOOK_BEHIND_NOT;
INC_OP;
goto fail;
#ifdef USE_CALL
CASE_OP(CALL)
addr = p->call.addr;
INC_OP; STACK_PUSH_CALL_FRAME(p);
p = reg->ops + addr;
JUMP_OUT;
CASE_OP(RETURN)
STACK_RETURN(p);
STACK_PUSH_RETURN;
JUMP_OUT;
#endif
CASE_OP(PUSH_SAVE_VAL)
{
SaveType type;
type = p->push_save_val.type;
mem = p->push_save_val.id; /* mem: save id */
switch ((enum SaveType )type) {
case SAVE_KEEP:
STACK_PUSH_SAVE_VAL(mem, type, s);
break;
case SAVE_S:
STACK_PUSH_SAVE_VAL_WITH_SPREV(mem, type, s);
break;
case SAVE_RIGHT_RANGE:
STACK_PUSH_SAVE_VAL(mem, SAVE_RIGHT_RANGE, right_range);
break;
}
}
INC_OP;
JUMP_OUT;
CASE_OP(UPDATE_VAR)
{
UpdateVarType type;
enum SaveType save_type;
type = p->update_var.type;
mem = p->update_var.id; /* mem: save id */
switch ((enum UpdateVarType )type) {
case UPDATE_VAR_KEEP_FROM_STACK_LAST:
STACK_GET_SAVE_VAL_TYPE_LAST(SAVE_KEEP, keep);
break;
case UPDATE_VAR_S_FROM_STACK:
STACK_GET_SAVE_VAL_TYPE_LAST_ID_WITH_SPREV(SAVE_S, mem, s);
break;
case UPDATE_VAR_RIGHT_RANGE_FROM_S_STACK:
save_type = SAVE_S;
goto get_save_val_type_last_id;
break;
case UPDATE_VAR_RIGHT_RANGE_FROM_STACK:
save_type = SAVE_RIGHT_RANGE;
get_save_val_type_last_id:
STACK_GET_SAVE_VAL_TYPE_LAST_ID(save_type, mem, right_range);
break;
case UPDATE_VAR_RIGHT_RANGE_INIT:
INIT_RIGHT_RANGE;
break;
}
}
INC_OP;
JUMP_OUT;
#ifdef USE_CALLOUT
CASE_OP(CALLOUT_CONTENTS)
of = ONIG_CALLOUT_OF_CONTENTS;
mem = p->callout_contents.num;
goto callout_common_entry;
BREAK_OUT;
CASE_OP(CALLOUT_NAME)
{
int call_result;
int name_id;
int in;
CalloutListEntry* e;
OnigCalloutFunc func;
OnigCalloutArgs args;
of = ONIG_CALLOUT_OF_NAME;
name_id = p->callout_name.id;
mem = p->callout_name.num;
callout_common_entry:
e = onig_reg_callout_list_at(reg, mem);
in = e->in;
if (of == ONIG_CALLOUT_OF_NAME) {
func = onig_get_callout_start_func(reg, mem);
}
else {
name_id = ONIG_NON_NAME_ID;
func = msa->mp->progress_callout_of_contents;
}
if (IS_NOT_NULL(func) && (in & ONIG_CALLOUT_IN_PROGRESS) != 0) {
CALLOUT_BODY(func, ONIG_CALLOUT_IN_PROGRESS, name_id,
(int )mem, msa->mp->callout_user_data, args, call_result);
switch (call_result) {
case ONIG_CALLOUT_FAIL:
goto fail;
break;
case ONIG_CALLOUT_SUCCESS:
goto retraction_callout2;
break;
default: /* error code */
if (call_result > 0) {
call_result = ONIGERR_INVALID_ARGUMENT;
}
best_len = call_result;
goto finish;
break;
}
}
else {
retraction_callout2:
if ((in & ONIG_CALLOUT_IN_RETRACTION) != 0) {
if (of == ONIG_CALLOUT_OF_NAME) {
if (IS_NOT_NULL(func)) {
STACK_PUSH_CALLOUT_NAME(name_id, mem, func);
}
}
else {
func = msa->mp->retraction_callout_of_contents;
if (IS_NOT_NULL(func)) {
STACK_PUSH_CALLOUT_CONTENTS(mem, func);
}
}
}
}
}
INC_OP;
JUMP_OUT;
#endif
CASE_OP(FINISH)
goto finish;
#ifdef ONIG_DEBUG_STATISTICS
fail:
SOP_OUT;
goto fail2;
#endif
CASE_OP(FAIL)
#ifdef ONIG_DEBUG_STATISTICS
fail2:
#else
fail:
#endif
STACK_POP;
p = stk->u.state.pcode;
s = stk->u.state.pstr;
sprev = stk->u.state.pstr_prev;
CHECK_RETRY_LIMIT_IN_MATCH;
JUMP_OUT;
DEFAULT_OP
goto bytecode_error;
} BYTECODE_INTERPRETER_END;
finish:
STACK_SAVE;
return best_len;
#ifdef ONIG_DEBUG
stack_error:
STACK_SAVE;
return ONIGERR_STACK_BUG;
#endif
bytecode_error:
STACK_SAVE;
return ONIGERR_UNDEFINED_BYTECODE;
#if defined(ONIG_DEBUG) && !defined(USE_DIRECT_THREADED_CODE)
unexpected_bytecode_error:
STACK_SAVE;
return ONIGERR_UNEXPECTED_BYTECODE;
#endif
#ifdef USE_RETRY_LIMIT_IN_MATCH
retry_limit_in_match_over:
STACK_SAVE;
return ONIGERR_RETRY_LIMIT_IN_MATCH_OVER;
#endif
}
static UChar*
slow_search(OnigEncoding enc, UChar* target, UChar* target_end,
const UChar* text, const UChar* text_end, UChar* text_range)
{
UChar *t, *p, *s, *end;
end = (UChar* )text_end;
end -= target_end - target - 1;
if (end > text_range)
end = text_range;
s = (UChar* )text;
while (s < end) {
if (*s == *target) {
p = s + 1;
t = target + 1;
while (t < target_end) {
if (*t != *p++)
break;
t++;
}
if (t == target_end)
return s;
}
s += enclen(enc, s);
}
return (UChar* )NULL;
}
static int
str_lower_case_match(OnigEncoding enc, int case_fold_flag,
const UChar* t, const UChar* tend,
const UChar* p, const UChar* end)
{
int lowlen;
UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
while (t < tend) {
lowlen = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &p, end, lowbuf);
q = lowbuf;
while (lowlen > 0) {
if (*t++ != *q++) return 0;
lowlen--;
}
}
return 1;
}
static UChar*
slow_search_ic(OnigEncoding enc, int case_fold_flag,
UChar* target, UChar* target_end,
const UChar* text, const UChar* text_end, UChar* text_range)
{
UChar *s, *end;
end = (UChar* )text_end;
end -= target_end - target - 1;
if (end > text_range)
end = text_range;
s = (UChar* )text;
while (s < end) {
if (str_lower_case_match(enc, case_fold_flag, target, target_end,
s, text_end))
return s;
s += enclen(enc, s);
}
return (UChar* )NULL;
}
static UChar*
slow_search_backward(OnigEncoding enc, UChar* target, UChar* target_end,
const UChar* text, const UChar* adjust_text,
const UChar* text_end, const UChar* text_start)
{
UChar *t, *p, *s;
s = (UChar* )text_end;
s -= (target_end - target);
if (s > text_start)
s = (UChar* )text_start;
else
s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, adjust_text, s);
while (s >= text) {
if (*s == *target) {
p = s + 1;
t = target + 1;
while (t < target_end) {
if (*t != *p++)
break;
t++;
}
if (t == target_end)
return s;
}
s = (UChar* )onigenc_get_prev_char_head(enc, adjust_text, s);
}
return (UChar* )NULL;
}
static UChar*
slow_search_backward_ic(OnigEncoding enc, int case_fold_flag,
UChar* target, UChar* target_end,
const UChar* text, const UChar* adjust_text,
const UChar* text_end, const UChar* text_start)
{
UChar *s;
s = (UChar* )text_end;
s -= (target_end - target);
if (s > text_start)
s = (UChar* )text_start;
else
s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, adjust_text, s);
while (s >= text) {
if (str_lower_case_match(enc, case_fold_flag,
target, target_end, s, text_end))
return s;
s = (UChar* )onigenc_get_prev_char_head(enc, adjust_text, s);
}
return (UChar* )NULL;
}
static UChar*
sunday_quick_search_step_forward(regex_t* reg,
const UChar* target, const UChar* target_end,
const UChar* text, const UChar* text_end,
const UChar* text_range)
{
const UChar *s, *se, *t, *p, *end;
const UChar *tail;
int skip, tlen1;
int map_offset;
OnigEncoding enc;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"sunday_quick_search_step_forward: text: %p, text_end: %p, text_range: %p\n", text, text_end, text_range);
#endif
enc = reg->enc;
tail = target_end - 1;
tlen1 = (int )(tail - target);
end = text_range;
if (end + tlen1 > text_end)
end = text_end - tlen1;
map_offset = reg->map_offset;
s = text;
while (s < end) {
p = se = s + tlen1;
t = tail;
while (*p == *t) {
if (t == target) return (UChar* )s;
p--; t--;
}
if (se + map_offset >= text_end) break;
skip = reg->map[*(se + map_offset)];
#if 0
t = s;
do {
s += enclen(enc, s);
} while ((s - t) < skip && s < end);
#else
s += skip;
if (s < end)
s = onigenc_get_right_adjust_char_head(enc, text, s);
#endif
}
return (UChar* )NULL;
}
static UChar*
sunday_quick_search(regex_t* reg, const UChar* target, const UChar* target_end,
const UChar* text, const UChar* text_end,
const UChar* text_range)
{
const UChar *s, *t, *p, *end;
const UChar *tail;
int map_offset;
end = text_range + (target_end - target);
if (end > text_end)
end = text_end;
map_offset = reg->map_offset;
tail = target_end - 1;
s = text + (tail - target);
while (s < end) {
p = s;
t = tail;
while (*p == *t) {
if (t == target) return (UChar* )p;
p--; t--;
}
if (s + map_offset >= text_end) break;
s += reg->map[*(s + map_offset)];
}
return (UChar* )NULL;
}
static UChar*
sunday_quick_search_case_fold(regex_t* reg,
const UChar* target, const UChar* target_end,
const UChar* text, const UChar* text_end,
const UChar* text_range)
{
const UChar *s, *se, *end;
const UChar *tail;
int skip, tlen1;
int map_offset;
int case_fold_flag;
OnigEncoding enc;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"sunday_quick_search_case_fold: text: %p, text_end: %p, text_range: %p\n", text, text_end, text_range);
#endif
enc = reg->enc;
case_fold_flag = reg->case_fold_flag;
tail = target_end - 1;
tlen1 = (int )(tail - target);
end = text_range;
if (end + tlen1 > text_end)
end = text_end - tlen1;
map_offset = reg->map_offset;
s = text;
while (s < end) {
if (str_lower_case_match(enc, case_fold_flag, target, target_end,
s, text_end))
return (UChar* )s;
se = s + tlen1;
if (se + map_offset >= text_end) break;
skip = reg->map[*(se + map_offset)];
#if 0
p = s;
do {
s += enclen(enc, s);
} while ((s - p) < skip && s < end);
#else
/* This is faster than prev code for long text. ex: /(?i)Twain/ */
s += skip;
if (s < end)
s = onigenc_get_right_adjust_char_head(enc, text, s);
#endif
}
return (UChar* )NULL;
}
static UChar*
map_search(OnigEncoding enc, UChar map[],
const UChar* text, const UChar* text_range)
{
const UChar *s = text;
while (s < text_range) {
if (map[*s]) return (UChar* )s;
s += enclen(enc, s);
}
return (UChar* )NULL;
}
static UChar*
map_search_backward(OnigEncoding enc, UChar map[],
const UChar* text, const UChar* adjust_text,
const UChar* text_start)
{
const UChar *s = text_start;
while (s >= text) {
if (map[*s]) return (UChar* )s;
s = onigenc_get_prev_char_head(enc, adjust_text, s);
}
return (UChar* )NULL;
}
extern int
onig_match(regex_t* reg, const UChar* str, const UChar* end, const UChar* at,
OnigRegion* region, OnigOptionType option)
{
int r;
OnigMatchParam mp;
onig_initialize_match_param(&mp);
r = onig_match_with_param(reg, str, end, at, region, option, &mp);
onig_free_match_param_content(&mp);
return r;
}
extern int
onig_match_with_param(regex_t* reg, const UChar* str, const UChar* end,
const UChar* at, OnigRegion* region, OnigOptionType option,
OnigMatchParam* mp)
{
int r;
UChar *prev;
MatchArg msa;
ADJUST_MATCH_PARAM(reg, mp);
MATCH_ARG_INIT(msa, reg, option, region, at, mp);
if (region
#ifdef USE_POSIX_API_REGION_OPTION
&& !IS_POSIX_REGION(option)
#endif
) {
r = onig_region_resize_clear(region, reg->num_mem + 1);
}
else
r = 0;
if (r == 0) {
if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) {
if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end)) {
r = ONIGERR_INVALID_WIDE_CHAR_VALUE;
goto end;
}
}
prev = (UChar* )onigenc_get_prev_char_head(reg->enc, str, at);
r = match_at(reg, str, end, end, at, prev, &msa);
}
end:
MATCH_ARG_FREE(msa);
return r;
}
static int
forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,
UChar* range, UChar** low, UChar** high, UChar** low_prev)
{
UChar *p, *pprev = (UChar* )NULL;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "forward_search_range: str: %p, end: %p, s: %p, range: %p\n",
str, end, s, range);
#endif
p = s;
if (reg->dmin > 0) {
if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {
p += reg->dmin;
}
else {
UChar *q = p + reg->dmin;
if (q >= end) return 0; /* fail */
while (p < q) p += enclen(reg->enc, p);
}
}
retry:
switch (reg->optimize) {
case OPTIMIZE_STR:
p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);
break;
case OPTIMIZE_STR_CASE_FOLD:
p = slow_search_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end, p, end, range);
break;
case OPTIMIZE_STR_CASE_FOLD_FAST:
p = sunday_quick_search_case_fold(reg, reg->exact, reg->exact_end, p, end,
range);
break;
case OPTIMIZE_STR_FAST:
p = sunday_quick_search(reg, reg->exact, reg->exact_end, p, end, range);
break;
case OPTIMIZE_STR_FAST_STEP_FORWARD:
p = sunday_quick_search_step_forward(reg, reg->exact, reg->exact_end,
p, end, range);
break;
case OPTIMIZE_MAP:
p = map_search(reg->enc, reg->map, p, range);
break;
}
if (p && p < range) {
if (p - reg->dmin < s) {
retry_gate:
pprev = p;
p += enclen(reg->enc, p);
goto retry;
}
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
}
break;
case ANCR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = (UChar* )onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
)
goto retry_gate;
break;
}
}
if (reg->dmax == 0) {
*low = p;
if (low_prev) {
if (*low > s)
*low_prev = onigenc_get_prev_char_head(reg->enc, s, p);
else
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
}
}
else {
if (reg->dmax != INFINITE_LEN) {
if (p - str < reg->dmax) {
*low = (UChar* )str;
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc, str, *low);
}
else {
*low = p - reg->dmax;
if (*low > s) {
*low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
*low, (const UChar** )low_prev);
if (low_prev && IS_NULL(*low_prev))
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : s), *low);
}
else {
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), *low);
}
}
}
}
/* no needs to adjust *high, *high is used as range check only */
*high = p - reg->dmin;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n",
(int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);
#endif
return 1; /* success */
}
return 0; /* fail */
}
static int
backward_search_range(regex_t* reg, const UChar* str, const UChar* end,
UChar* s, const UChar* range, UChar* adjrange,
UChar** low, UChar** high)
{
UChar *p;
if (range == 0) goto fail;
range += reg->dmin;
p = s;
retry:
switch (reg->optimize) {
case OPTIMIZE_STR:
exact_method:
p = slow_search_backward(reg->enc, reg->exact, reg->exact_end,
range, adjrange, end, p);
break;
case OPTIMIZE_STR_CASE_FOLD:
case OPTIMIZE_STR_CASE_FOLD_FAST:
p = slow_search_backward_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end,
range, adjrange, end, p);
break;
case OPTIMIZE_STR_FAST:
case OPTIMIZE_STR_FAST_STEP_FORWARD:
goto exact_method;
break;
case OPTIMIZE_MAP:
p = map_search_backward(reg->enc, reg->map, range, adjrange, p);
break;
}
if (p) {
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc, str, p);
if (IS_NOT_NULL(prev) && !ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) {
p = prev;
goto retry;
}
}
break;
case ANCR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = onigenc_get_prev_char_head(reg->enc, adjrange, p);
if (IS_NULL(prev)) goto fail;
if (ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) {
p = prev;
goto retry;
}
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
) {
p = onigenc_get_prev_char_head(reg->enc, adjrange, p);
if (IS_NULL(p)) goto fail;
goto retry;
}
break;
}
}
/* no needs to adjust *high, *high is used as range check only */
if (reg->dmax != INFINITE_LEN) {
*low = p - reg->dmax;
*high = p - reg->dmin;
*high = onigenc_get_right_adjust_char_head(reg->enc, adjrange, *high);
}
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "backward_search_range: low: %d, high: %d\n",
(int )(*low - str), (int )(*high - str));
#endif
return 1; /* success */
}
fail:
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "backward_search_range: fail.\n");
#endif
return 0; /* fail */
}
extern int
onig_search(regex_t* reg, const UChar* str, const UChar* end,
const UChar* start, const UChar* range, OnigRegion* region,
OnigOptionType option)
{
int r;
OnigMatchParam mp;
onig_initialize_match_param(&mp);
r = onig_search_with_param(reg, str, end, start, range, region, option, &mp);
onig_free_match_param_content(&mp);
return r;
}
extern int
onig_search_with_param(regex_t* reg, const UChar* str, const UChar* end,
const UChar* start, const UChar* range, OnigRegion* region,
OnigOptionType option, OnigMatchParam* mp)
{
int r;
UChar *s, *prev;
MatchArg msa;
const UChar *orig_start = start;
const UChar *orig_range = range;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"onig_search (entry point): str: %p, end: %d, start: %d, range: %d\n",
str, (int )(end - str), (int )(start - str), (int )(range - str));
#endif
ADJUST_MATCH_PARAM(reg, mp);
if (region
#ifdef USE_POSIX_API_REGION_OPTION
&& !IS_POSIX_REGION(option)
#endif
) {
r = onig_region_resize_clear(region, reg->num_mem + 1);
if (r != 0) goto finish_no_msa;
}
if (start > end || start < str) goto mismatch_no_msa;
if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) {
if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end)) {
r = ONIGERR_INVALID_WIDE_CHAR_VALUE;
goto finish_no_msa;
}
}
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
#define MATCH_AND_RETURN_CHECK(upper_range) \
r = match_at(reg, str, end, (upper_range), s, prev, &msa); \
if (r != ONIG_MISMATCH) {\
if (r >= 0) {\
if (! IS_FIND_LONGEST(reg->options)) {\
goto match;\
}\
}\
else goto finish; /* error */ \
}
#else
#define MATCH_AND_RETURN_CHECK(upper_range) \
r = match_at(reg, str, end, (upper_range), s, prev, &msa); \
if (r != ONIG_MISMATCH) {\
if (r >= 0) {\
goto match;\
}\
else goto finish; /* error */ \
}
#endif /* USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE */
/* anchor optimize: resume search range */
if (reg->anchor != 0 && str < end) {
UChar *min_semi_end, *max_semi_end;
if (reg->anchor & ANCR_BEGIN_POSITION) {
/* search start-position only */
begin_position:
if (range > start)
range = start + 1;
else
range = start;
}
else if (reg->anchor & ANCR_BEGIN_BUF) {
/* search str-position only */
if (range > start) {
if (start != str) goto mismatch_no_msa;
range = str + 1;
}
else {
if (range <= str) {
start = str;
range = str;
}
else
goto mismatch_no_msa;
}
}
else if (reg->anchor & ANCR_END_BUF) {
min_semi_end = max_semi_end = (UChar* )end;
end_buf:
if ((OnigLen )(max_semi_end - str) < reg->anchor_dmin)
goto mismatch_no_msa;
if (range > start) {
if ((OnigLen )(min_semi_end - start) > reg->anchor_dmax) {
start = min_semi_end - reg->anchor_dmax;
if (start < end)
start = onigenc_get_right_adjust_char_head(reg->enc, str, start);
}
if ((OnigLen )(max_semi_end - (range - 1)) < reg->anchor_dmin) {
range = max_semi_end - reg->anchor_dmin + 1;
}
if (start > range) goto mismatch_no_msa;
/* If start == range, match with empty at end.
Backward search is used. */
}
else {
if ((OnigLen )(min_semi_end - range) > reg->anchor_dmax) {
range = min_semi_end - reg->anchor_dmax;
}
if ((OnigLen )(max_semi_end - start) < reg->anchor_dmin) {
start = max_semi_end - reg->anchor_dmin;
start = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, str, start);
}
if (range > start) goto mismatch_no_msa;
}
}
else if (reg->anchor & ANCR_SEMI_END_BUF) {
UChar* pre_end = ONIGENC_STEP_BACK(reg->enc, str, end, 1);
max_semi_end = (UChar* )end;
if (ONIGENC_IS_MBC_NEWLINE(reg->enc, pre_end, end)) {
min_semi_end = pre_end;
#ifdef USE_CRNL_AS_LINE_TERMINATOR
pre_end = ONIGENC_STEP_BACK(reg->enc, str, pre_end, 1);
if (IS_NOT_NULL(pre_end) &&
ONIGENC_IS_MBC_CRNL(reg->enc, pre_end, end)) {
min_semi_end = pre_end;
}
#endif
if (min_semi_end > str && start <= min_semi_end) {
goto end_buf;
}
}
else {
min_semi_end = (UChar* )end;
goto end_buf;
}
}
else if ((reg->anchor & ANCR_ANYCHAR_INF_ML)) {
goto begin_position;
}
}
else if (str == end) { /* empty string */
static const UChar* address_for_empty_string = (UChar* )"";
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "onig_search: empty string.\n");
#endif
if (reg->threshold_len == 0) {
start = end = str = address_for_empty_string;
s = (UChar* )start;
prev = (UChar* )NULL;
MATCH_ARG_INIT(msa, reg, option, region, start, mp);
MATCH_AND_RETURN_CHECK(end);
goto mismatch;
}
goto mismatch_no_msa;
}
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "onig_search(apply anchor): end: %d, start: %d, range: %d\n",
(int )(end - str), (int )(start - str), (int )(range - str));
#endif
MATCH_ARG_INIT(msa, reg, option, region, orig_start, mp);
s = (UChar* )start;
if (range > start) { /* forward search */
if (s > str)
prev = onigenc_get_prev_char_head(reg->enc, str, s);
else
prev = (UChar* )NULL;
if (reg->optimize != OPTIMIZE_NONE) {
UChar *sch_range, *low, *high, *low_prev;
sch_range = (UChar* )range;
if (reg->dmax != 0) {
if (reg->dmax == INFINITE_LEN)
sch_range = (UChar* )end;
else {
sch_range += reg->dmax;
if (sch_range > end) sch_range = (UChar* )end;
}
}
if ((end - start) < reg->threshold_len)
goto mismatch;
if (reg->dmax != INFINITE_LEN) {
do {
if (! forward_search_range(reg, str, end, s, sch_range,
&low, &high, &low_prev)) goto mismatch;
if (s < low) {
s = low;
prev = low_prev;
}
while (s <= high) {
MATCH_AND_RETURN_CHECK(orig_range);
prev = s;
s += enclen(reg->enc, s);
}
} while (s < range);
goto mismatch;
}
else { /* check only. */
if (! forward_search_range(reg, str, end, s, sch_range,
&low, &high, (UChar** )NULL)) goto mismatch;
if ((reg->anchor & ANCR_ANYCHAR_INF) != 0) {
do {
MATCH_AND_RETURN_CHECK(orig_range);
prev = s;
s += enclen(reg->enc, s);
if ((reg->anchor & (ANCR_LOOK_BEHIND | ANCR_PREC_READ_NOT)) == 0) {
while (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end) && s < range) {
prev = s;
s += enclen(reg->enc, s);
}
}
} while (s < range);
goto mismatch;
}
}
}
do {
MATCH_AND_RETURN_CHECK(orig_range);
prev = s;
s += enclen(reg->enc, s);
} while (s < range);
if (s == range) { /* because empty match with /$/. */
MATCH_AND_RETURN_CHECK(orig_range);
}
}
else { /* backward search */
if (range < str) goto mismatch;
if (orig_start < end)
orig_start += enclen(reg->enc, orig_start); /* is upper range */
if (reg->optimize != OPTIMIZE_NONE) {
UChar *low, *high, *adjrange, *sch_start;
if (range < end)
adjrange = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, str, range);
else
adjrange = (UChar* )end;
if (reg->dmax != INFINITE_LEN &&
(end - range) >= reg->threshold_len) {
do {
sch_start = s + reg->dmax;
if (sch_start > end) sch_start = (UChar* )end;
if (backward_search_range(reg, str, end, sch_start, range, adjrange,
&low, &high) <= 0)
goto mismatch;
if (s > high)
s = high;
while (s >= low) {
prev = onigenc_get_prev_char_head(reg->enc, str, s);
MATCH_AND_RETURN_CHECK(orig_start);
s = prev;
}
} while (s >= range);
goto mismatch;
}
else { /* check only. */
if ((end - range) < reg->threshold_len) goto mismatch;
sch_start = s;
if (reg->dmax != 0) {
if (reg->dmax == INFINITE_LEN)
sch_start = (UChar* )end;
else {
sch_start += reg->dmax;
if (sch_start > end) sch_start = (UChar* )end;
else
sch_start = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc,
start, sch_start);
}
}
if (backward_search_range(reg, str, end, sch_start, range, adjrange,
&low, &high) <= 0) goto mismatch;
}
}
do {
prev = onigenc_get_prev_char_head(reg->enc, str, s);
MATCH_AND_RETURN_CHECK(orig_start);
s = prev;
} while (s >= range);
}
mismatch:
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
if (IS_FIND_LONGEST(reg->options)) {
if (msa.best_len >= 0) {
s = msa.best_s;
goto match;
}
}
#endif
r = ONIG_MISMATCH;
finish:
MATCH_ARG_FREE(msa);
/* If result is mismatch and no FIND_NOT_EMPTY option,
then the region is not set in match_at(). */
if (IS_FIND_NOT_EMPTY(reg->options) && region
#ifdef USE_POSIX_API_REGION_OPTION
&& !IS_POSIX_REGION(option)
#endif
) {
onig_region_clear(region);
}
#ifdef ONIG_DEBUG
if (r != ONIG_MISMATCH)
fprintf(stderr, "onig_search: error %d\n", r);
#endif
return r;
mismatch_no_msa:
r = ONIG_MISMATCH;
finish_no_msa:
#ifdef ONIG_DEBUG
if (r != ONIG_MISMATCH)
fprintf(stderr, "onig_search: error %d\n", r);
#endif
return r;
match:
MATCH_ARG_FREE(msa);
return (int )(s - str);
}
extern int
onig_scan(regex_t* reg, const UChar* str, const UChar* end,
OnigRegion* region, OnigOptionType option,
int (*scan_callback)(int, int, OnigRegion*, void*),
void* callback_arg)
{
int r;
int n;
int rs;
const UChar* start;
if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) {
if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end))
return ONIGERR_INVALID_WIDE_CHAR_VALUE;
ONIG_OPTION_OFF(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING);
}
n = 0;
start = str;
while (1) {
r = onig_search(reg, str, end, start, end, region, option);
if (r >= 0) {
rs = scan_callback(n, r, region, callback_arg);
n++;
if (rs != 0)
return rs;
if (region->end[0] == start - str) {
if (start >= end) break;
start += enclen(reg->enc, start);
}
else
start = str + region->end[0];
if (start > end)
break;
}
else if (r == ONIG_MISMATCH) {
break;
}
else { /* error */
return r;
}
}
return n;
}
extern OnigEncoding
onig_get_encoding(regex_t* reg)
{
return reg->enc;
}
extern OnigOptionType
onig_get_options(regex_t* reg)
{
return reg->options;
}
extern OnigCaseFoldType
onig_get_case_fold_flag(regex_t* reg)
{
return reg->case_fold_flag;
}
extern OnigSyntaxType*
onig_get_syntax(regex_t* reg)
{
return reg->syntax;
}
extern int
onig_number_of_captures(regex_t* reg)
{
return reg->num_mem;
}
extern int
onig_number_of_capture_histories(regex_t* reg)
{
#ifdef USE_CAPTURE_HISTORY
int i, n;
n = 0;
for (i = 0; i <= ONIG_MAX_CAPTURE_HISTORY_GROUP; i++) {
if (MEM_STATUS_AT(reg->capture_history, i) != 0)
n++;
}
return n;
#else
return 0;
#endif
}
extern void
onig_copy_encoding(OnigEncoding to, OnigEncoding from)
{
*to = *from;
}
#ifdef USE_DIRECT_THREADED_CODE
extern int
onig_init_for_match_at(regex_t* reg)
{
return match_at(reg, (const UChar* )NULL, (const UChar* )NULL,
(const UChar* )NULL, (const UChar* )NULL, (UChar* )NULL,
(MatchArg* )NULL);
}
#endif
/* for callout functions */
#ifdef USE_CALLOUT
extern OnigCalloutFunc
onig_get_progress_callout(void)
{
return DefaultProgressCallout;
}
extern int
onig_set_progress_callout(OnigCalloutFunc f)
{
DefaultProgressCallout = f;
return ONIG_NORMAL;
}
extern OnigCalloutFunc
onig_get_retraction_callout(void)
{
return DefaultRetractionCallout;
}
extern int
onig_set_retraction_callout(OnigCalloutFunc f)
{
DefaultRetractionCallout = f;
return ONIG_NORMAL;
}
extern int
onig_get_callout_num_by_callout_args(OnigCalloutArgs* args)
{
return args->num;
}
extern OnigCalloutIn
onig_get_callout_in_by_callout_args(OnigCalloutArgs* args)
{
return args->in;
}
extern int
onig_get_name_id_by_callout_args(OnigCalloutArgs* args)
{
return args->name_id;
}
extern const UChar*
onig_get_contents_by_callout_args(OnigCalloutArgs* args)
{
int num;
CalloutListEntry* e;
num = args->num;
e = onig_reg_callout_list_at(args->regex, num);
if (IS_NULL(e)) return 0;
if (e->of == ONIG_CALLOUT_OF_CONTENTS) {
return e->u.content.start;
}
return 0;
}
extern const UChar*
onig_get_contents_end_by_callout_args(OnigCalloutArgs* args)
{
int num;
CalloutListEntry* e;
num = args->num;
e = onig_reg_callout_list_at(args->regex, num);
if (IS_NULL(e)) return 0;
if (e->of == ONIG_CALLOUT_OF_CONTENTS) {
return e->u.content.end;
}
return 0;
}
extern int
onig_get_args_num_by_callout_args(OnigCalloutArgs* args)
{
int num;
CalloutListEntry* e;
num = args->num;
e = onig_reg_callout_list_at(args->regex, num);
if (IS_NULL(e)) return ONIGERR_INVALID_ARGUMENT;
if (e->of == ONIG_CALLOUT_OF_NAME) {
return e->u.arg.num;
}
return ONIGERR_INVALID_ARGUMENT;
}
extern int
onig_get_passed_args_num_by_callout_args(OnigCalloutArgs* args)
{
int num;
CalloutListEntry* e;
num = args->num;
e = onig_reg_callout_list_at(args->regex, num);
if (IS_NULL(e)) return ONIGERR_INVALID_ARGUMENT;
if (e->of == ONIG_CALLOUT_OF_NAME) {
return e->u.arg.passed_num;
}
return ONIGERR_INVALID_ARGUMENT;
}
extern int
onig_get_arg_by_callout_args(OnigCalloutArgs* args, int index,
OnigType* type, OnigValue* val)
{
int num;
CalloutListEntry* e;
num = args->num;
e = onig_reg_callout_list_at(args->regex, num);
if (IS_NULL(e)) return ONIGERR_INVALID_ARGUMENT;
if (e->of == ONIG_CALLOUT_OF_NAME) {
if (IS_NOT_NULL(type)) *type = e->u.arg.types[index];
if (IS_NOT_NULL(val)) *val = e->u.arg.vals[index];
return ONIG_NORMAL;
}
return ONIGERR_INVALID_ARGUMENT;
}
extern const UChar*
onig_get_string_by_callout_args(OnigCalloutArgs* args)
{
return args->string;
}
extern const UChar*
onig_get_string_end_by_callout_args(OnigCalloutArgs* args)
{
return args->string_end;
}
extern const UChar*
onig_get_start_by_callout_args(OnigCalloutArgs* args)
{
return args->start;
}
extern const UChar*
onig_get_right_range_by_callout_args(OnigCalloutArgs* args)
{
return args->right_range;
}
extern const UChar*
onig_get_current_by_callout_args(OnigCalloutArgs* args)
{
return args->current;
}
extern OnigRegex
onig_get_regex_by_callout_args(OnigCalloutArgs* args)
{
return args->regex;
}
extern unsigned long
onig_get_retry_counter_by_callout_args(OnigCalloutArgs* args)
{
return args->retry_in_match_counter;
}
extern int
onig_get_capture_range_in_callout(OnigCalloutArgs* a, int mem_num, int* begin, int* end)
{
OnigRegex reg;
const UChar* str;
StackType* stk_base;
int i;
i = mem_num;
reg = a->regex;
str = a->string;
stk_base = a->stk_base;
if (i > 0) {
if (a->mem_end_stk[i] != INVALID_STACK_INDEX) {
if (MEM_STATUS_AT(reg->bt_mem_start, i))
*begin = (int )(STACK_AT(a->mem_start_stk[i])->u.mem.pstr - str);
else
*begin = (int )((UChar* )((void* )a->mem_start_stk[i]) - str);
*end = (int )((MEM_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(a->mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )a->mem_end_stk[i])) - str);
}
else {
*begin = *end = ONIG_REGION_NOTPOS;
}
}
else
return ONIGERR_INVALID_ARGUMENT;
return ONIG_NORMAL;
}
extern int
onig_get_used_stack_size_in_callout(OnigCalloutArgs* a, int* used_num, int* used_bytes)
{
int n;
n = (int )(a->stk - a->stk_base);
if (used_num != 0)
*used_num = n;
if (used_bytes != 0)
*used_bytes = n * sizeof(StackType);
return ONIG_NORMAL;
}
/* builtin callout functions */
extern int
onig_builtin_fail(OnigCalloutArgs* args ARG_UNUSED, void* user_data ARG_UNUSED)
{
return ONIG_CALLOUT_FAIL;
}
extern int
onig_builtin_mismatch(OnigCalloutArgs* args ARG_UNUSED, void* user_data ARG_UNUSED)
{
return ONIG_MISMATCH;
}
extern int
onig_builtin_error(OnigCalloutArgs* args, void* user_data ARG_UNUSED)
{
int r;
int n;
OnigValue val;
r = onig_get_arg_by_callout_args(args, 0, 0, &val);
if (r != ONIG_NORMAL) return r;
n = (int )val.l;
if (n >= 0) {
n = ONIGERR_INVALID_CALLOUT_BODY;
}
else if (onig_is_error_code_needs_param(n)) {
n = ONIGERR_INVALID_CALLOUT_BODY;
}
return n;
}
extern int
onig_builtin_count(OnigCalloutArgs* args, void* user_data)
{
(void )onig_check_callout_data_and_clear_old_values(args);
return onig_builtin_total_count(args, user_data);
}
extern int
onig_builtin_total_count(OnigCalloutArgs* args, void* user_data ARG_UNUSED)
{
int r;
int slot;
OnigType type;
OnigValue val;
OnigValue aval;
OnigCodePoint count_type;
r = onig_get_arg_by_callout_args(args, 0, &type, &aval);
if (r != ONIG_NORMAL) return r;
count_type = aval.c;
if (count_type != '>' && count_type != 'X' && count_type != '<')
return ONIGERR_INVALID_CALLOUT_ARG;
r = onig_get_callout_data_by_callout_args_self_dont_clear_old(args, 0,
&type, &val);
if (r < ONIG_NORMAL)
return r;
else if (r > ONIG_NORMAL) {
/* type == void: initial state */
val.l = 0;
}
if (args->in == ONIG_CALLOUT_IN_RETRACTION) {
slot = 2;
if (count_type == '<')
val.l++;
else if (count_type == 'X')
val.l--;
}
else {
slot = 1;
if (count_type != '<')
val.l++;
}
r = onig_set_callout_data_by_callout_args_self(args, 0, ONIG_TYPE_LONG, &val);
if (r != ONIG_NORMAL) return r;
/* slot 1: in progress counter, slot 2: in retraction counter */
r = onig_get_callout_data_by_callout_args_self_dont_clear_old(args, slot,
&type, &val);
if (r < ONIG_NORMAL)
return r;
else if (r > ONIG_NORMAL) {
val.l = 0;
}
val.l++;
r = onig_set_callout_data_by_callout_args_self(args, slot, ONIG_TYPE_LONG, &val);
if (r != ONIG_NORMAL) return r;
return ONIG_CALLOUT_SUCCESS;
}
extern int
onig_builtin_max(OnigCalloutArgs* args, void* user_data ARG_UNUSED)
{
int r;
int slot;
long max_val;
OnigCodePoint count_type;
OnigType type;
OnigValue val;
OnigValue aval;
(void )onig_check_callout_data_and_clear_old_values(args);
slot = 0;
r = onig_get_callout_data_by_callout_args_self(args, slot, &type, &val);
if (r < ONIG_NORMAL)
return r;
else if (r > ONIG_NORMAL) {
/* type == void: initial state */
type = ONIG_TYPE_LONG;
val.l = 0;
}
r = onig_get_arg_by_callout_args(args, 0, &type, &aval);
if (r != ONIG_NORMAL) return r;
if (type == ONIG_TYPE_TAG) {
r = onig_get_callout_data_by_callout_args(args, aval.tag, 0, &type, &aval);
if (r < ONIG_NORMAL) return r;
else if (r > ONIG_NORMAL)
max_val = 0L;
else
max_val = aval.l;
}
else { /* LONG */
max_val = aval.l;
}
r = onig_get_arg_by_callout_args(args, 1, &type, &aval);
if (r != ONIG_NORMAL) return r;
count_type = aval.c;
if (count_type != '>' && count_type != 'X' && count_type != '<')
return ONIGERR_INVALID_CALLOUT_ARG;
if (args->in == ONIG_CALLOUT_IN_RETRACTION) {
if (count_type == '<') {
if (val.l >= max_val) return ONIG_CALLOUT_FAIL;
val.l++;
}
else if (count_type == 'X')
val.l--;
}
else {
if (count_type != '<') {
if (val.l >= max_val) return ONIG_CALLOUT_FAIL;
val.l++;
}
}
r = onig_set_callout_data_by_callout_args_self(args, slot, ONIG_TYPE_LONG, &val);
if (r != ONIG_NORMAL) return r;
return ONIG_CALLOUT_SUCCESS;
}
enum OP_CMP {
OP_EQ,
OP_NE,
OP_LT,
OP_GT,
OP_LE,
OP_GE
};
extern int
onig_builtin_cmp(OnigCalloutArgs* args, void* user_data ARG_UNUSED)
{
int r;
int slot;
long lv;
long rv;
OnigType type;
OnigValue val;
regex_t* reg;
enum OP_CMP op;
reg = args->regex;
r = onig_get_arg_by_callout_args(args, 0, &type, &val);
if (r != ONIG_NORMAL) return r;
if (type == ONIG_TYPE_TAG) {
r = onig_get_callout_data_by_callout_args(args, val.tag, 0, &type, &val);
if (r < ONIG_NORMAL) return r;
else if (r > ONIG_NORMAL)
lv = 0L;
else
lv = val.l;
}
else { /* ONIG_TYPE_LONG */
lv = val.l;
}
r = onig_get_arg_by_callout_args(args, 2, &type, &val);
if (r != ONIG_NORMAL) return r;
if (type == ONIG_TYPE_TAG) {
r = onig_get_callout_data_by_callout_args(args, val.tag, 0, &type, &val);
if (r < ONIG_NORMAL) return r;
else if (r > ONIG_NORMAL)
rv = 0L;
else
rv = val.l;
}
else { /* ONIG_TYPE_LONG */
rv = val.l;
}
slot = 0;
r = onig_get_callout_data_by_callout_args_self(args, slot, &type, &val);
if (r < ONIG_NORMAL)
return r;
else if (r > ONIG_NORMAL) {
/* type == void: initial state */
OnigCodePoint c1, c2;
UChar* p;
r = onig_get_arg_by_callout_args(args, 1, &type, &val);
if (r != ONIG_NORMAL) return r;
p = val.s.start;
c1 = ONIGENC_MBC_TO_CODE(reg->enc, p, val.s.end);
p += ONIGENC_MBC_ENC_LEN(reg->enc, p);
if (p < val.s.end) {
c2 = ONIGENC_MBC_TO_CODE(reg->enc, p, val.s.end);
p += ONIGENC_MBC_ENC_LEN(reg->enc, p);
if (p != val.s.end) return ONIGERR_INVALID_CALLOUT_ARG;
}
else
c2 = 0;
switch (c1) {
case '=':
if (c2 != '=') return ONIGERR_INVALID_CALLOUT_ARG;
op = OP_EQ;
break;
case '!':
if (c2 != '=') return ONIGERR_INVALID_CALLOUT_ARG;
op = OP_NE;
break;
case '<':
if (c2 == '=') op = OP_LE;
else if (c2 == 0) op = OP_LT;
else return ONIGERR_INVALID_CALLOUT_ARG;
break;
case '>':
if (c2 == '=') op = OP_GE;
else if (c2 == 0) op = OP_GT;
else return ONIGERR_INVALID_CALLOUT_ARG;
break;
default:
return ONIGERR_INVALID_CALLOUT_ARG;
break;
}
val.l = (long )op;
r = onig_set_callout_data_by_callout_args_self(args, slot, ONIG_TYPE_LONG, &val);
if (r != ONIG_NORMAL) return r;
}
else {
op = (enum OP_CMP )val.l;
}
switch (op) {
case OP_EQ: r = (lv == rv); break;
case OP_NE: r = (lv != rv); break;
case OP_LT: r = (lv < rv); break;
case OP_GT: r = (lv > rv); break;
case OP_LE: r = (lv <= rv); break;
case OP_GE: r = (lv >= rv); break;
}
return r == 0 ? ONIG_CALLOUT_FAIL : ONIG_CALLOUT_SUCCESS;
}
#include <stdio.h>
static FILE* OutFp;
/* name start with "onig_" for macros. */
static int
onig_builtin_monitor(OnigCalloutArgs* args, void* user_data)
{
int r;
int num;
size_t tag_len;
const UChar* start;
const UChar* right;
const UChar* current;
const UChar* string;
const UChar* strend;
const UChar* tag_start;
const UChar* tag_end;
regex_t* reg;
OnigCalloutIn in;
OnigType type;
OnigValue val;
char buf[20];
FILE* fp;
fp = OutFp;
r = onig_get_arg_by_callout_args(args, 0, &type, &val);
if (r != ONIG_NORMAL) return r;
in = onig_get_callout_in_by_callout_args(args);
if (in == ONIG_CALLOUT_IN_PROGRESS) {
if (val.c == '<')
return ONIG_CALLOUT_SUCCESS;
}
else {
if (val.c != 'X' && val.c != '<')
return ONIG_CALLOUT_SUCCESS;
}
num = onig_get_callout_num_by_callout_args(args);
start = onig_get_start_by_callout_args(args);
right = onig_get_right_range_by_callout_args(args);
current = onig_get_current_by_callout_args(args);
string = onig_get_string_by_callout_args(args);
strend = onig_get_string_end_by_callout_args(args);
reg = onig_get_regex_by_callout_args(args);
tag_start = onig_get_callout_tag_start(reg, num);
tag_end = onig_get_callout_tag_end(reg, num);
if (tag_start == 0)
xsnprintf(buf, sizeof(buf), "#%d", num);
else {
/* CAUTION: tag string is not terminated with NULL. */
int i;
tag_len = tag_end - tag_start;
if (tag_len >= sizeof(buf)) tag_len = sizeof(buf) - 1;
for (i = 0; i < tag_len; i++) buf[i] = tag_start[i];
buf[tag_len] = '\0';
}
fprintf(fp, "ONIG-MONITOR: %-4s %s at: %d [%d - %d] len: %d\n",
buf,
in == ONIG_CALLOUT_IN_PROGRESS ? "=>" : "<=",
(int )(current - string),
(int )(start - string),
(int )(right - string),
(int )(strend - string));
fflush(fp);
return ONIG_CALLOUT_SUCCESS;
}
extern int
onig_setup_builtin_monitors_by_ascii_encoded_name(void* fp /* FILE* */)
{
int id;
char* name;
OnigEncoding enc;
unsigned int ts[4];
OnigValue opts[4];
if (IS_NOT_NULL(fp))
OutFp = (FILE* )fp;
else
OutFp = stdout;
enc = ONIG_ENCODING_ASCII;
name = "MON";
ts[0] = ONIG_TYPE_CHAR;
opts[0].c = '>';
BC_B_O(name, monitor, 1, ts, 1, opts);
return ONIG_NORMAL;
}
#endif /* USE_CALLOUT */
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_1277_0 |
crossvul-cpp_data_bad_351_12 | /*
* card-rtecp.c: Support for Rutoken ECP cards
*
* Copyright (C) 2009 Aleksey Samsonov <samsonov@guardant.ru>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <assert.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
static const struct sc_card_operations *iso_ops = NULL;
static struct sc_card_operations rtecp_ops;
static struct sc_card_driver rtecp_drv = {
"Rutoken ECP driver",
"rutoken_ecp",
&rtecp_ops,
NULL, 0, NULL
};
static struct sc_atr_table rtecp_atrs[] = {
/* Rutoken ECP */
{ "3B:8B:01:52:75:74:6F:6B:65:6E:20:45:43:50:A0",
NULL, "Rutoken ECP", SC_CARD_TYPE_GENERIC_BASE, 0, NULL },
/* Rutoken ECP (DS) */
{ "3B:8B:01:52:75:74:6F:6B:65:6E:20:44:53:20:C1",
NULL, "Rutoken ECP (DS)", SC_CARD_TYPE_GENERIC_BASE, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
static int rtecp_match_card(sc_card_t *card)
{
int i = -1;
i = _sc_match_atr(card, rtecp_atrs, &card->type);
if (i >= 0) {
card->name = rtecp_atrs[i].name;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, 1);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, 0);
}
static int rtecp_init(sc_card_t *card)
{
sc_algorithm_info_t info;
unsigned long flags;
assert(card && card->ctx);
card->caps |= SC_CARD_CAP_RNG;
card->cla = 0;
flags = SC_ALGORITHM_RSA_RAW | SC_ALGORITHM_ONBOARD_KEY_GEN
| SC_ALGORITHM_RSA_PAD_NONE | SC_ALGORITHM_RSA_HASH_NONE;
_sc_card_add_rsa_alg(card, 256, flags, 0);
_sc_card_add_rsa_alg(card, 512, flags, 0);
_sc_card_add_rsa_alg(card, 768, flags, 0);
_sc_card_add_rsa_alg(card, 1024, flags, 0);
_sc_card_add_rsa_alg(card, 1280, flags, 0);
_sc_card_add_rsa_alg(card, 1536, flags, 0);
_sc_card_add_rsa_alg(card, 1792, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
memset(&info, 0, sizeof(info));
info.algorithm = SC_ALGORITHM_GOSTR3410;
info.key_length = 256;
info.flags = SC_ALGORITHM_GOSTR3410_RAW | SC_ALGORITHM_ONBOARD_KEY_GEN
| SC_ALGORITHM_GOSTR3410_HASH_NONE;
_sc_card_add_algorithm(card, &info);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, 0);
}
static void reverse(unsigned char *buf, size_t len)
{
unsigned char tmp;
size_t i;
assert(buf || len == 0);
for (i = 0; i < len / 2; ++i)
{
tmp = buf[i];
buf[i] = buf[len - 1 - i];
buf[len - 1 - i] = tmp;
}
}
static unsigned int sec_attr_to_method(unsigned int attr)
{
if (attr == 0xFF)
return SC_AC_NEVER;
else if (attr == 0)
return SC_AC_NONE;
else if (attr & 0x03)
return SC_AC_CHV;
else
return SC_AC_UNKNOWN;
}
static unsigned long sec_attr_to_key_ref(unsigned int attr)
{
if (attr == 1 || attr == 2)
return attr;
return 0;
}
static unsigned int to_sec_attr(unsigned int method, unsigned int key_ref)
{
if (method == SC_AC_NEVER || method == SC_AC_NONE)
return method;
if (method == SC_AC_CHV && (key_ref == 1 || key_ref == 2))
return key_ref;
return 0;
}
static void set_acl_from_sec_attr(sc_card_t *card, sc_file_t *file)
{
unsigned int method;
unsigned long key_ref;
assert(card && card->ctx && file);
assert(file->sec_attr && file->sec_attr_len == SC_RTECP_SEC_ATTR_SIZE);
assert(1 + 6 < SC_RTECP_SEC_ATTR_SIZE);
sc_file_add_acl_entry(file, SC_AC_OP_SELECT, SC_AC_NONE, SC_AC_KEY_REF_NONE);
if (file->sec_attr[0] & 0x40) /* if AccessMode.6 */
{
method = sec_attr_to_method(file->sec_attr[1 + 6]);
key_ref = sec_attr_to_key_ref(file->sec_attr[1 + 6]);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"SC_AC_OP_DELETE %i %lu\n",
(int)method, key_ref);
sc_file_add_acl_entry(file, SC_AC_OP_DELETE, method, key_ref);
}
if (file->sec_attr[0] & 0x01) /* if AccessMode.0 */
{
method = sec_attr_to_method(file->sec_attr[1 + 0]);
key_ref = sec_attr_to_key_ref(file->sec_attr[1 + 0]);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
(file->type == SC_FILE_TYPE_DF) ?
"SC_AC_OP_CREATE %i %lu\n"
: "SC_AC_OP_READ %i %lu\n",
(int)method, key_ref);
sc_file_add_acl_entry(file, (file->type == SC_FILE_TYPE_DF) ?
SC_AC_OP_CREATE : SC_AC_OP_READ, method, key_ref);
}
if (file->type == SC_FILE_TYPE_DF)
{
sc_file_add_acl_entry(file, SC_AC_OP_LIST_FILES,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
}
else
if (file->sec_attr[0] & 0x02) /* if AccessMode.1 */
{
method = sec_attr_to_method(file->sec_attr[1 + 1]);
key_ref = sec_attr_to_key_ref(file->sec_attr[1 + 1]);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"SC_AC_OP_UPDATE %i %lu\n",
(int)method, key_ref);
sc_file_add_acl_entry(file, SC_AC_OP_UPDATE, method, key_ref);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"SC_AC_OP_WRITE %i %lu\n",
(int)method, key_ref);
sc_file_add_acl_entry(file, SC_AC_OP_WRITE, method, key_ref);
}
}
static int set_sec_attr_from_acl(sc_card_t *card, sc_file_t *file)
{
const sc_acl_entry_t *entry;
u8 sec_attr[SC_RTECP_SEC_ATTR_SIZE] = { 0 };
int r;
assert(card && card->ctx && file);
assert(!file->sec_attr && file->sec_attr_len == 0);
assert(1 + 6 < sizeof(sec_attr));
entry = sc_file_get_acl_entry(file, SC_AC_OP_DELETE);
if (entry)
{
sec_attr[0] |= 0x40;
sec_attr[1 + 6] = to_sec_attr(entry->method, entry->key_ref);
}
if (file->type == SC_FILE_TYPE_DF)
{
entry = sc_file_get_acl_entry(file, SC_AC_OP_CREATE);
if (entry)
{
/* ATTR: Create DF/EF file */
sec_attr[0] |= 0x01;
sec_attr[1 + 0] = to_sec_attr(entry->method, entry->key_ref);
/* ATTR: Create Internal EF (RSF) file */
sec_attr[0] |= 0x02;
sec_attr[1 + 1] = to_sec_attr(entry->method, entry->key_ref);
}
}
else
{
entry = sc_file_get_acl_entry(file, SC_AC_OP_READ);
if (entry)
{
sec_attr[0] |= 0x01;
sec_attr[1 + 0] = to_sec_attr(entry->method, entry->key_ref);
}
entry = sc_file_get_acl_entry(file, SC_AC_OP_WRITE);
if (entry)
{
sec_attr[0] |= 0x02;
sec_attr[1 + 1] = to_sec_attr(entry->method, entry->key_ref);
}
entry = sc_file_get_acl_entry(file, SC_AC_OP_UPDATE);
if (entry)
{
/* rewrite if sec_attr[1 + 1] already set */
sec_attr[0] |= 0x02;
sec_attr[1 + 1] = to_sec_attr(entry->method, entry->key_ref);
}
}
/* FIXME: Find the best solution */
if (file->path.len == 2 && !memcmp(file->path.value, "\x3F\x00", 2))
{
/* ATTR: Put data */
sec_attr[0] |= 0x04;
sec_attr[1 + 2] = 1; /* so-pin reference */
}
r = sc_file_set_sec_attr(file, sec_attr, sizeof(sec_attr));
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int rtecp_select_file(sc_card_t *card,
const sc_path_t *in_path, sc_file_t **file_out)
{
sc_file_t **file_out_copy, *file;
int r;
assert(card && card->ctx && in_path);
switch (in_path->type)
{
case SC_PATH_TYPE_DF_NAME:
case SC_PATH_TYPE_FROM_CURRENT:
case SC_PATH_TYPE_PARENT:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED);
}
assert(iso_ops && iso_ops->select_file);
file_out_copy = file_out;
r = iso_ops->select_file(card, in_path, file_out_copy);
if (r || file_out_copy == NULL)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
assert(file_out_copy);
file = *file_out_copy;
assert(file);
if (file->sec_attr && file->sec_attr_len == SC_RTECP_SEC_ATTR_SIZE)
set_acl_from_sec_attr(card, file);
else
r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
if (r)
sc_file_free(file);
else
{
assert(file_out);
*file_out = file;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int rtecp_verify(sc_card_t *card, unsigned int type, int ref_qualifier,
const u8 *data, size_t data_len, int *tries_left)
{
sc_apdu_t apdu;
int r, send_logout = 0;
(void)type; /* no warning */
assert(card && card->ctx && data);
for (;;)
{
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT,
0x20, 0, ref_qualifier);
apdu.lc = data_len;
apdu.data = data;
apdu.datalen = data_len;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (send_logout++ == 0 && apdu.sw1 == 0x6F && apdu.sw2 == 0x86)
{
r = sc_logout(card);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Logout failed");
}
else
break;
}
if (apdu.sw1 == 0x63 && apdu.sw2 == 0)
{
/* Verification failed */
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x20, 0, ref_qualifier);
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (r == SC_ERROR_PIN_CODE_INCORRECT && tries_left)
*tries_left = (int)(apdu.sw2 & 0x0F);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int rtecp_logout(sc_card_t *card)
{
sc_apdu_t apdu;
int r;
assert(card && card->ctx);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x40, 0, 0);
apdu.cla = 0x80;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int rtecp_cipher(sc_card_t *card, const u8 *data, size_t data_len,
u8 *out, size_t out_len, int sign)
{
sc_apdu_t apdu;
u8 *buf, *buf_out;
size_t i;
int r;
assert(card && card->ctx && data && out);
buf_out = malloc(out_len + 2);
buf = malloc(data_len);
if (!buf || !buf_out)
{
free(buf);
free(buf_out);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
}
for (i = 0; i < data_len; ++i)
buf[i] = data[data_len - 1 - i];
if (sign)
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x9E, 0x9A);
else
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);
apdu.lc = data_len;
apdu.data = buf;
apdu.datalen = data_len;
apdu.resp = buf_out;
apdu.resplen = out_len + 2;
apdu.le = out_len > 256 ? 256 : out_len;
if (apdu.lc > 255)
apdu.flags |= SC_APDU_FLAGS_CHAINING;
r = sc_transmit_apdu(card, &apdu);
if (!sign)
{
assert(buf);
sc_mem_clear(buf, data_len);
}
assert(buf);
free(buf);
if (r)
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "APDU transmit failed: %s\n", sc_strerror(r));
else
{
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00)
{
assert(buf_out);
for (i = 0; i < apdu.resplen; ++i)
out[i] = buf_out[apdu.resplen - 1 - i];
r = (i > 0) ? (int)i : SC_ERROR_INTERNAL;
}
else
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
}
if (!sign)
{
assert(buf_out);
sc_mem_clear(buf_out, out_len + 2);
}
assert(buf_out);
free(buf_out);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int rtecp_decipher(sc_card_t *card,
const u8 *data, size_t data_len, u8 *out, size_t out_len)
{
int r;
assert(card && card->ctx && data && out);
/* decipher */
r = rtecp_cipher(card, data, data_len, out, out_len, 0);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int rtecp_compute_signature(sc_card_t *card,
const u8 *data, size_t data_len, u8 *out, size_t out_len)
{
int r;
assert(card && card->ctx && data && out);
/* compute digital signature */
r = rtecp_cipher(card, data, data_len, out, out_len, 1);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int rtecp_change_reference_data(sc_card_t *card, unsigned int type,
int ref_qualifier, const u8 *old, size_t oldlen,
const u8 *newref, size_t newlen, int *tries_left)
{
sc_apdu_t apdu;
u8 rsf_length[2], *buf, *buf_end, *p;
size_t val_length, buf_length, max_transmit_length;
int transmits_num, r;
assert(card && card->ctx && newref);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"newlen = %"SC_FORMAT_LEN_SIZE_T"u\n", newlen);
if (newlen > 0xFFFF)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
if (type == SC_AC_CHV && old && oldlen != 0)
{
r = sc_verify(card, type, ref_qualifier, old, oldlen, tries_left);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Verify old pin failed");
}
max_transmit_length = sc_get_max_send_size(card);
assert(max_transmit_length > 2);
/*
* (2 + sizeof(rsf_length) + newlen) - total length of data we need to transfer,
* (max_transmit_length - 2) - amount of useful data we can transfer in one transmit (2 bytes for 0xA5 tag)
*/
transmits_num = (2 + sizeof(rsf_length) + newlen) / (max_transmit_length - 2) + 1;
/* buffer length = size of 0x80 TLV + size of RSF-file + (size of Tag and Length)*(number of APDUs) */
buf_length = (2 + sizeof(rsf_length)) + newlen + 2*(transmits_num);
p = buf = (u8 *)malloc(buf_length);
if (buf == NULL)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY);
buf_end = buf + buf_length;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x24, 0x01, ref_qualifier);
/* put 0x80 TLV */
rsf_length[0] = (newlen >> 8) & 0xFF;
rsf_length[1] = newlen & 0xFF;
assert(buf_end - p >= (int)(2 + sizeof(rsf_length)));
sc_asn1_put_tag(0x80, rsf_length, sizeof(rsf_length), p, buf_end - p, &p);
/* put 0xA5 TLVs (one or more); each transmit must begin with 0xA5 TLV */
while (newlen)
{
assert(buf_end - p >= (int)(newlen + 2));
if ((p - buf) % max_transmit_length + newlen + 2 > max_transmit_length)
val_length = max_transmit_length - (p - buf) % max_transmit_length - 2;
else
val_length = newlen;
/* not using sc_asn1_put_tag(...) because rtecp do not support asn1 properly (when val_length > 127) */
*p++ = 0xA5;
*p++ = (u8)val_length;
assert(val_length <= newlen);
memcpy(p, newref, val_length);
p += val_length;
newref += val_length;
newlen -= val_length;
if (newlen)
apdu.flags |= SC_APDU_FLAGS_CHAINING;
}
apdu.lc = p - buf;
apdu.data = buf;
apdu.datalen = p - buf;
r = sc_transmit_apdu(card, &apdu);
sc_mem_clear(buf, buf_length);
free(buf);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int rtecp_reset_retry_counter(sc_card_t *card, unsigned int type,
int ref_qualifier, const u8 *puk, size_t puklen,
const u8 *newref, size_t newlen)
{
sc_apdu_t apdu;
int r;
(void)type, (void)puk, (void)puklen; /* no warning */
assert(card && card->ctx);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x2C, 0x03, ref_qualifier);
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Unblock card failed");
if (newref && newlen) {
u8 tmp[2], buf[SC_MAX_APDU_BUFFER_SIZE];
u8 *p = buf;
tmp[0] = (newlen >> 8) & 0xFF;
tmp[1] = newlen & 0xFF;
sc_asn1_put_tag(0x80, tmp, sizeof(tmp), p, sizeof(buf) - (p - buf), &p);
r = sc_asn1_put_tag(0xA5, newref, newlen, p, sizeof(buf) - (p - buf), &p);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Invalid new PIN length");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x24, 0x01, ref_qualifier);
apdu.lc = p - buf;
apdu.data = buf;
apdu.datalen = p - buf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Set PIN failed");
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int rtecp_create_file(sc_card_t *card, sc_file_t *file)
{
int r;
assert(card && card->ctx && file);
if (file->sec_attr_len == 0)
{
r = set_sec_attr_from_acl(card, file);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Set sec_attr from ACL failed");
}
assert(iso_ops && iso_ops->create_file);
r = iso_ops->create_file(card, file);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int rtecp_list_files(sc_card_t *card, u8 *buf, size_t buflen)
{
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE], previd[2];
const u8 *tag;
size_t taglen, len = 0;
int r;
assert(card && card->ctx && buf);
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xA4, 0, 0);
for (;;)
{
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1 == 0x6A && apdu.sw2 == 0x82)
break; /* Next file not found */
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "");
if (apdu.resplen <= 2)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_WRONG_LENGTH);
/* save first file(dir) ID */
tag = sc_asn1_find_tag(card->ctx, apdu.resp + 2, apdu.resplen - 2,
0x83, &taglen);
if (!tag || taglen != sizeof(previd))
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_UNKNOWN_DATA_RECEIVED);
memcpy(previd, tag, sizeof(previd));
if (len + sizeof(previd) <= buflen)
{
memcpy(&buf[len], previd, sizeof(previd));
len += sizeof(previd);
}
tag = sc_asn1_find_tag(card->ctx, apdu.resp + 2, apdu.resplen - 2,
0x82, &taglen);
if (!tag || taglen != 2)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_UNKNOWN_DATA_RECEIVED);
if (tag[0] == 0x38)
{
/* Select parent DF of the current DF */
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xA4, 0x03, 0);
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "");
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x02);
apdu.lc = sizeof(previd);
apdu.data = previd;
apdu.datalen = sizeof(previd);
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, len);
}
static int rtecp_card_ctl(sc_card_t *card, unsigned long request, void *data)
{
sc_apdu_t apdu;
u8 buf[SC_MAX_APDU_BUFFER_SIZE];
sc_rtecp_genkey_data_t *genkey_data = data;
sc_serial_number_t *serial = data;
int r;
assert(card && card->ctx);
switch (request)
{
case SC_CARDCTL_RTECP_INIT:
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x8A, 0, 0);
apdu.cla = 0x80;
break;
case SC_CARDCTL_RTECP_INIT_END:
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x84, 0x4E, 0x19);
apdu.cla = 0x80;
break;
case SC_CARDCTL_GET_SERIALNR:
if (!serial)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xCA, 0x01, 0x81);
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 256;
serial->len = sizeof(serial->value);
break;
case SC_CARDCTL_RTECP_GENERATE_KEY:
if (!genkey_data)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_INVALID_ARGUMENTS);
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0x46, 0x80,
genkey_data->key_id);
apdu.resp = buf;
apdu.resplen = sizeof(buf);
apdu.le = 256;
break;
case SC_CARDCTL_LIFECYCLE_SET:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "%s\n",
"SC_CARDCTL_LIFECYCLE_SET not supported");
/* no call sc_debug (SC_FUNC_RETURN) */
return SC_ERROR_NOT_SUPPORTED;
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"request = 0x%lx\n", request);
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED);
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (!r && request == SC_CARDCTL_RTECP_GENERATE_KEY)
{
if (genkey_data->type == SC_ALGORITHM_RSA &&
genkey_data->u.rsa.modulus_len >= apdu.resplen &&
genkey_data->u.rsa.exponent_len >= 3)
{
memcpy(genkey_data->u.rsa.modulus, apdu.resp, apdu.resplen);
genkey_data->u.rsa.modulus_len = apdu.resplen;
reverse(genkey_data->u.rsa.modulus,
genkey_data->u.rsa.modulus_len);
memcpy(genkey_data->u.rsa.exponent, "\x01\x00\x01", 3);
genkey_data->u.rsa.exponent_len = 3;
}
else if (genkey_data->type == SC_ALGORITHM_GOSTR3410 &&
genkey_data->u.gostr3410.xy_len >= apdu.resplen)
{
memcpy(genkey_data->u.gostr3410.xy, apdu.resp, apdu.resplen);
genkey_data->u.gostr3410.xy_len = apdu.resplen;
}
else
r = SC_ERROR_BUFFER_TOO_SMALL;
}
else if (!r && request == SC_CARDCTL_GET_SERIALNR)
{
if (serial->len >= apdu.resplen)
{
memcpy(serial->value, apdu.resp, apdu.resplen);
serial->len = apdu.resplen;
}
else
r = SC_ERROR_BUFFER_TOO_SMALL;
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
static int rtecp_construct_fci(sc_card_t *card, const sc_file_t *file,
u8 *out, size_t *outlen)
{
u8 buf[64], *p = out;
assert(card && card->ctx && file && out && outlen);
assert(*outlen >= (size_t)(p - out) + 2);
*p++ = 0x6F; /* FCI template */
p++; /* for length */
/* 0x80 - Number of data bytes in the file, excluding structural information */
buf[0] = (file->size >> 8) & 0xFF;
buf[1] = file->size & 0xFF;
sc_asn1_put_tag(0x80, buf, 2, p, *outlen - (p - out), &p);
/* 0x82 - File descriptor byte */
if (file->type_attr_len)
{
assert(sizeof(buf) >= file->type_attr_len);
memcpy(buf, file->type_attr, file->type_attr_len);
sc_asn1_put_tag(0x82, buf, file->type_attr_len,
p, *outlen - (p - out), &p);
}
else
{
switch (file->type)
{
case SC_FILE_TYPE_WORKING_EF:
buf[0] = 0x01;
break;
case SC_FILE_TYPE_DF:
buf[0] = 0x38;
break;
case SC_FILE_TYPE_INTERNAL_EF:
default:
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_NOT_SUPPORTED);
}
buf[1] = 0;
sc_asn1_put_tag(0x82, buf, 2, p, *outlen - (p - out), &p);
}
/* 0x83 - File identifier */
buf[0] = (file->id >> 8) & 0xFF;
buf[1] = file->id & 0xFF;
sc_asn1_put_tag(0x83, buf, 2, p, *outlen - (p - out), &p);
if (file->prop_attr_len)
{
assert(sizeof(buf) >= file->prop_attr_len);
memcpy(buf, file->prop_attr, file->prop_attr_len);
sc_asn1_put_tag(0x85, buf, file->prop_attr_len,
p, *outlen - (p - out), &p);
}
if (file->sec_attr_len)
{
assert(sizeof(buf) >= file->sec_attr_len);
memcpy(buf, file->sec_attr, file->sec_attr_len);
sc_asn1_put_tag(0x86, buf, file->sec_attr_len,
p, *outlen - (p - out), &p);
}
out[1] = p - out - 2; /* length */
*outlen = p - out;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, 0);
}
struct sc_card_driver * sc_get_rtecp_driver(void)
{
if (iso_ops == NULL)
iso_ops = sc_get_iso7816_driver()->ops;
rtecp_ops = *iso_ops;
rtecp_ops.match_card = rtecp_match_card;
rtecp_ops.init = rtecp_init;
/* read_binary */
rtecp_ops.write_binary = NULL;
/* update_binary */
rtecp_ops.read_record = NULL;
rtecp_ops.write_record = NULL;
rtecp_ops.append_record = NULL;
rtecp_ops.update_record = NULL;
rtecp_ops.select_file = rtecp_select_file;
rtecp_ops.get_response = NULL;
/* get_challenge */
rtecp_ops.verify = rtecp_verify;
rtecp_ops.logout = rtecp_logout;
/* restore_security_env */
/* set_security_env */
rtecp_ops.decipher = rtecp_decipher;
rtecp_ops.compute_signature = rtecp_compute_signature;
rtecp_ops.change_reference_data = rtecp_change_reference_data;
rtecp_ops.reset_retry_counter = rtecp_reset_retry_counter;
rtecp_ops.create_file = rtecp_create_file;
/* delete_file */
rtecp_ops.list_files = rtecp_list_files;
/* check_sw */
rtecp_ops.card_ctl = rtecp_card_ctl;
/* process_fci */
rtecp_ops.construct_fci = rtecp_construct_fci;
rtecp_ops.pin_cmd = NULL;
return &rtecp_drv;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_351_12 |
crossvul-cpp_data_good_700_0 | /*
* SSLv3/TLSv1 client-side functions
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_SSL_CLI_C)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
#include "mbedtls/debug.h"
#include "mbedtls/ssl.h"
#include "mbedtls/ssl_internal.h"
#include <string.h>
#include <stdint.h>
#if defined(MBEDTLS_HAVE_TIME)
#include "mbedtls/platform_time.h"
#endif
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
/* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = v; while( n-- ) *p++ = 0;
}
#endif
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
static void ssl_write_hostname_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t hostname_len;
*olen = 0;
if( ssl->hostname == NULL )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding server name extension: %s",
ssl->hostname ) );
hostname_len = strlen( ssl->hostname );
if( end < p || (size_t)( end - p ) < hostname_len + 9 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
/*
* Sect. 3, RFC 6066 (TLS Extensions Definitions)
*
* In order to provide any of the server names, clients MAY include an
* extension of type "server_name" in the (extended) client hello. The
* "extension_data" field of this extension SHALL contain
* "ServerNameList" where:
*
* struct {
* NameType name_type;
* select (name_type) {
* case host_name: HostName;
* } name;
* } ServerName;
*
* enum {
* host_name(0), (255)
* } NameType;
*
* opaque HostName<1..2^16-1>;
*
* struct {
* ServerName server_name_list<1..2^16-1>
* } ServerNameList;
*
*/
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 5) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 5) ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 3) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( (hostname_len + 3) ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME ) & 0xFF );
*p++ = (unsigned char)( ( hostname_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( hostname_len ) & 0xFF );
memcpy( p, ssl->hostname, hostname_len );
*olen = hostname_len + 9;
}
#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
#if defined(MBEDTLS_SSL_RENEGOTIATION)
static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
/* We're always including an TLS_EMPTY_RENEGOTIATION_INFO_SCSV in the
* initial ClientHello, in which case also adding the renegotiation
* info extension is NOT RECOMMENDED as per RFC 5746 Section 3.4. */
if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding renegotiation extension" ) );
if( end < p || (size_t)( end - p ) < 5 + ssl->verify_data_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
/*
* Secure renegotiation
*/
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO ) & 0xFF );
*p++ = 0x00;
*p++ = ( ssl->verify_data_len + 1 ) & 0xFF;
*p++ = ssl->verify_data_len & 0xFF;
memcpy( p, ssl->own_verify_data, ssl->verify_data_len );
*olen = 5 + ssl->verify_data_len;
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
/*
* Only if we handle at least one key exchange that needs signatures.
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
static void ssl_write_signature_algorithms_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t sig_alg_len = 0;
const int *md;
#if defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C)
unsigned char *sig_alg_list = buf + 6;
#endif
*olen = 0;
if( ssl->conf->max_minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding signature_algorithms extension" ) );
for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
{
#if defined(MBEDTLS_ECDSA_C)
sig_alg_len += 2;
#endif
#if defined(MBEDTLS_RSA_C)
sig_alg_len += 2;
#endif
}
if( end < p || (size_t)( end - p ) < sig_alg_len + 6 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
/*
* Prepare signature_algorithms extension (TLS 1.2)
*/
sig_alg_len = 0;
for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
{
#if defined(MBEDTLS_ECDSA_C)
sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );
sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_ECDSA;
#endif
#if defined(MBEDTLS_RSA_C)
sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );
sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_RSA;
#endif
}
/*
* enum {
* none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5),
* sha512(6), (255)
* } HashAlgorithm;
*
* enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }
* SignatureAlgorithm;
*
* struct {
* HashAlgorithm hash;
* SignatureAlgorithm signature;
* } SignatureAndHashAlgorithm;
*
* SignatureAndHashAlgorithm
* supported_signature_algorithms<2..2^16-2>;
*/
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG ) & 0xFF );
*p++ = (unsigned char)( ( ( sig_alg_len + 2 ) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ( sig_alg_len + 2 ) ) & 0xFF );
*p++ = (unsigned char)( ( sig_alg_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( sig_alg_len ) & 0xFF );
*olen = 6 + sig_alg_len;
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static void ssl_write_supported_elliptic_curves_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
unsigned char *elliptic_curve_list = p + 6;
size_t elliptic_curve_len = 0;
const mbedtls_ecp_curve_info *info;
#if defined(MBEDTLS_ECP_C)
const mbedtls_ecp_group_id *grp_id;
#else
((void) ssl);
#endif
*olen = 0;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_elliptic_curves extension" ) );
#if defined(MBEDTLS_ECP_C)
for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ )
#else
for( info = mbedtls_ecp_curve_list(); info->grp_id != MBEDTLS_ECP_DP_NONE; info++ )
#endif
{
#if defined(MBEDTLS_ECP_C)
info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );
#endif
if( info == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid curve in ssl configuration" ) );
return;
}
elliptic_curve_len += 2;
}
if( end < p || (size_t)( end - p ) < 6 + elliptic_curve_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
elliptic_curve_len = 0;
#if defined(MBEDTLS_ECP_C)
for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ )
#else
for( info = mbedtls_ecp_curve_list(); info->grp_id != MBEDTLS_ECP_DP_NONE; info++ )
#endif
{
#if defined(MBEDTLS_ECP_C)
info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );
#endif
elliptic_curve_list[elliptic_curve_len++] = info->tls_id >> 8;
elliptic_curve_list[elliptic_curve_len++] = info->tls_id & 0xFF;
}
if( elliptic_curve_len == 0 )
return;
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len ) >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ( elliptic_curve_len ) ) & 0xFF );
*olen = 6 + elliptic_curve_len;
}
static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_point_formats extension" ) );
if( end < p || (size_t)( end - p ) < 6 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS ) & 0xFF );
*p++ = 0x00;
*p++ = 2;
*p++ = 1;
*p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
*olen = 6;
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
int ret;
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t kkpp_len;
*olen = 0;
/* Skip costly extension if we can't use EC J-PAKE anyway */
if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding ecjpake_kkpp extension" ) );
if( end - p < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP ) & 0xFF );
/*
* We may need to send ClientHello multiple times for Hello verification.
* We don't want to compute fresh values every time (both for performance
* and consistency reasons), so cache the extension content.
*/
if( ssl->handshake->ecjpake_cache == NULL ||
ssl->handshake->ecjpake_cache_len == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "generating new ecjpake parameters" ) );
ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx,
p + 2, end - p - 2, &kkpp_len,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret );
return;
}
ssl->handshake->ecjpake_cache = mbedtls_calloc( 1, kkpp_len );
if( ssl->handshake->ecjpake_cache == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "allocation failed" ) );
return;
}
memcpy( ssl->handshake->ecjpake_cache, p + 2, kkpp_len );
ssl->handshake->ecjpake_cache_len = kkpp_len;
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "re-using cached ecjpake parameters" ) );
kkpp_len = ssl->handshake->ecjpake_cache_len;
if( (size_t)( end - p - 2 ) < kkpp_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
memcpy( p + 2, ssl->handshake->ecjpake_cache, kkpp_len );
}
*p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( kkpp_len ) & 0xFF );
*olen = kkpp_len + 4;
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ) {
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding max_fragment_length extension" ) );
if( end < p || (size_t)( end - p ) < 5 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH ) & 0xFF );
*p++ = 0x00;
*p++ = 1;
*p++ = ssl->conf->mfl_code;
*olen = 5;
}
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
static void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding truncated_hmac extension" ) );
if( end < p || (size_t)( end - p ) < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
static void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding encrypt_then_mac "
"extension" ) );
if( end < p || (size_t)( end - p ) < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
static void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
*olen = 0;
if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding extended_master_secret "
"extension" ) );
if( end < p || (size_t)( end - p ) < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t tlen = ssl->session_negotiate->ticket_len;
*olen = 0;
if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding session ticket extension" ) );
if( end < p || (size_t)( end - p ) < 4 + tlen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET ) & 0xFF );
*p++ = (unsigned char)( ( tlen >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( tlen ) & 0xFF );
*olen = 4;
if( ssl->session_negotiate->ticket == NULL || tlen == 0 )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "sending session ticket of length %d", tlen ) );
memcpy( p, ssl->session_negotiate->ticket, tlen );
*olen += tlen;
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_SSL_ALPN)
static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
size_t alpnlen = 0;
const char **cur;
*olen = 0;
if( ssl->conf->alpn_list == NULL )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding alpn extension" ) );
for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
alpnlen += (unsigned char)( strlen( *cur ) & 0xFF ) + 1;
if( end < p || (size_t)( end - p ) < 6 + alpnlen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN ) & 0xFF );
/*
* opaque ProtocolName<1..2^8-1>;
*
* struct {
* ProtocolName protocol_name_list<2..2^16-1>
* } ProtocolNameList;
*/
/* Skip writing extension and list length for now */
p += 4;
for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
{
*p = (unsigned char)( strlen( *cur ) & 0xFF );
memcpy( p + 1, *cur, *p );
p += 1 + *p;
}
*olen = p - buf;
/* List length = olen - 2 (ext_type) - 2 (ext_len) - 2 (list_len) */
buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF );
buf[5] = (unsigned char)( ( ( *olen - 6 ) ) & 0xFF );
/* Extension length = olen - 2 (ext_type) - 2 (ext_len) */
buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF );
buf[3] = (unsigned char)( ( ( *olen - 4 ) ) & 0xFF );
}
#endif /* MBEDTLS_SSL_ALPN */
/*
* Generate random bytes for ClientHello
*/
static int ssl_generate_random( mbedtls_ssl_context *ssl )
{
int ret;
unsigned char *p = ssl->handshake->randbytes;
#if defined(MBEDTLS_HAVE_TIME)
mbedtls_time_t t;
#endif
/*
* When responding to a verify request, MUST reuse random (RFC 6347 4.2.1)
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
ssl->handshake->verify_cookie != NULL )
{
return( 0 );
}
#endif
#if defined(MBEDTLS_HAVE_TIME)
t = mbedtls_time( NULL );
*p++ = (unsigned char)( t >> 24 );
*p++ = (unsigned char)( t >> 16 );
*p++ = (unsigned char)( t >> 8 );
*p++ = (unsigned char)( t );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, current time: %lu", t ) );
#else
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 )
return( ret );
p += 4;
#endif /* MBEDTLS_HAVE_TIME */
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 )
return( ret );
return( 0 );
}
static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
{
int ret;
size_t i, n, olen, ext_len = 0;
unsigned char *buf;
unsigned char *p, *q;
unsigned char offer_compress;
const int *ciphersuites;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client hello" ) );
if( ssl->conf->f_rng == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") );
return( MBEDTLS_ERR_SSL_NO_RNG );
}
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
ssl->major_ver = ssl->conf->min_major_ver;
ssl->minor_ver = ssl->conf->min_minor_ver;
}
if( ssl->conf->max_major_ver == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "configured max major version is invalid, "
"consider using mbedtls_ssl_config_defaults()" ) );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
/*
* 0 . 0 handshake type
* 1 . 3 handshake length
* 4 . 5 highest version supported
* 6 . 9 current UNIX time
* 10 . 37 random bytes
*/
buf = ssl->out_msg;
p = buf + 4;
mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,
ssl->conf->transport, p );
p += 2;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, max version: [%d:%d]",
buf[4], buf[5] ) );
if( ( ret = ssl_generate_random( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_generate_random", ret );
return( ret );
}
memcpy( p, ssl->handshake->randbytes, 32 );
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", p, 32 );
p += 32;
/*
* 38 . 38 session id length
* 39 . 39+n session id
* 39+n . 39+n DTLS only: cookie length (1 byte)
* 40+n . .. DTSL only: cookie
* .. . .. ciphersuitelist length (2 bytes)
* .. . .. ciphersuitelist
* .. . .. compression methods length (1 byte)
* .. . .. compression methods
* .. . .. extensions length (2 bytes)
* .. . .. extensions
*/
n = ssl->session_negotiate->id_len;
if( n < 16 || n > 32 ||
#if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
#endif
ssl->handshake->resume == 0 )
{
n = 0;
}
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
/*
* RFC 5077 section 3.4: "When presenting a ticket, the client MAY
* generate and include a Session ID in the TLS ClientHello."
*/
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
if( ssl->session_negotiate->ticket != NULL &&
ssl->session_negotiate->ticket_len != 0 )
{
ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id, 32 );
if( ret != 0 )
return( ret );
ssl->session_negotiate->id_len = n = 32;
}
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
*p++ = (unsigned char) n;
for( i = 0; i < n; i++ )
*p++ = ssl->session_negotiate->id[i];
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, session id len.: %d", n ) );
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 39, n );
/*
* DTLS cookie
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
{
if( ssl->handshake->verify_cookie == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "no verify cookie to send" ) );
*p++ = 0;
}
else
{
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie",
ssl->handshake->verify_cookie,
ssl->handshake->verify_cookie_len );
*p++ = ssl->handshake->verify_cookie_len;
memcpy( p, ssl->handshake->verify_cookie,
ssl->handshake->verify_cookie_len );
p += ssl->handshake->verify_cookie_len;
}
}
#endif
/*
* Ciphersuite list
*/
ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
/* Skip writing ciphersuite length for now */
n = 0;
q = p;
p += 2;
for( i = 0; ciphersuites[i] != 0; i++ )
{
ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuites[i] );
if( ciphersuite_info == NULL )
continue;
if( ciphersuite_info->min_minor_ver > ssl->conf->max_minor_ver ||
ciphersuite_info->max_minor_ver < ssl->conf->min_minor_ver )
continue;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
( ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )
continue;
#endif
#if defined(MBEDTLS_ARC4_C)
if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&
ciphersuite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
continue;
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
continue;
#endif
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, add ciphersuite: %04x",
ciphersuites[i] ) );
n++;
*p++ = (unsigned char)( ciphersuites[i] >> 8 );
*p++ = (unsigned char)( ciphersuites[i] );
}
/*
* Add TLS_EMPTY_RENEGOTIATION_INFO_SCSV
*/
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
*p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO >> 8 );
*p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO );
n++;
}
/* Some versions of OpenSSL don't handle it correctly if not at end */
#if defined(MBEDTLS_SSL_FALLBACK_SCSV)
if( ssl->conf->fallback == MBEDTLS_SSL_IS_FALLBACK )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding FALLBACK_SCSV" ) );
*p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 );
*p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE );
n++;
}
#endif
*q++ = (unsigned char)( n >> 7 );
*q++ = (unsigned char)( n << 1 );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, got %d ciphersuites", n ) );
#if defined(MBEDTLS_ZLIB_SUPPORT)
offer_compress = 1;
#else
offer_compress = 0;
#endif
/*
* We don't support compression with DTLS right now: is many records come
* in the same datagram, uncompressing one could overwrite the next one.
* We don't want to add complexity for handling that case unless there is
* an actual need for it.
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
offer_compress = 0;
#endif
if( offer_compress )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 2 ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d %d",
MBEDTLS_SSL_COMPRESS_DEFLATE, MBEDTLS_SSL_COMPRESS_NULL ) );
*p++ = 2;
*p++ = MBEDTLS_SSL_COMPRESS_DEFLATE;
*p++ = MBEDTLS_SSL_COMPRESS_NULL;
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 1 ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d",
MBEDTLS_SSL_COMPRESS_NULL ) );
*p++ = 1;
*p++ = MBEDTLS_SSL_COMPRESS_NULL;
}
// First write extensions, then the total length
//
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
ssl_write_hostname_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
/* Note that TLS_EMPTY_RENEGOTIATION_INFO_SCSV is always added
* even if MBEDTLS_SSL_RENEGOTIATION is not defined. */
#if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
ssl_write_signature_algorithms_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_supported_elliptic_curves_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_ALPN)
ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
/* olen unused if all extensions are disabled */
((void) olen);
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, total extension length: %d",
ext_len ) );
if( ext_len > 0 )
{
*p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ext_len ) & 0xFF );
p += ext_len;
}
ssl->out_msglen = p - buf;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_CLIENT_HELLO;
ssl->state++;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
mbedtls_ssl_send_flight_completed( ssl );
#endif
if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client hello" ) );
return( 0 );
}
static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
{
/* Check verify-data in constant-time. The length OTOH is no secret */
if( len != 1 + ssl->verify_data_len * 2 ||
buf[0] != ssl->verify_data_len * 2 ||
mbedtls_ssl_safer_memcmp( buf + 1,
ssl->own_verify_data, ssl->verify_data_len ) != 0 ||
mbedtls_ssl_safer_memcmp( buf + 1 + ssl->verify_data_len,
ssl->peer_verify_data, ssl->verify_data_len ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
}
else
#endif /* MBEDTLS_SSL_RENEGOTIATION */
{
if( len != 1 || buf[0] != 0x00 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
}
return( 0 );
}
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
/*
* server should use the extension only if we did,
* and if so the server's value should match ours (and len is always 1)
*/
if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ||
len != 1 ||
buf[0] != ssl->conf->mfl_code )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching max fragment length extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
return( 0 );
}
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching truncated HMAC extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED;
return( 0 );
}
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching encrypt-then-MAC extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
return( 0 );
}
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching extended master secret extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
return( 0 );
}
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED ||
len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching session ticket extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
((void) buf);
ssl->handshake->new_session_ticket = 1;
return( 0 );
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
size_t list_size;
const unsigned char *p;
list_size = buf[0];
if( list_size + 1 != len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
p = buf + 1;
while( list_size > 0 )
{
if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
p[0] == MBEDTLS_ECP_PF_COMPRESSED )
{
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
ssl->handshake->ecdh_ctx.point_format = p[0];
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl->handshake->ecjpake_ctx.point_format = p[0];
#endif
MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) );
return( 0 );
}
list_size--;
p++;
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "no point format in common" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
int ret;
if( ssl->transform_negotiate->ciphersuite_info->key_exchange !=
MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) );
return( 0 );
}
/* If we got here, we no longer need our cached extension */
mbedtls_free( ssl->handshake->ecjpake_cache );
ssl->handshake->ecjpake_cache = NULL;
ssl->handshake->ecjpake_cache_len = 0;
if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx,
buf, len ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( ret );
}
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_ALPN)
static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf, size_t len )
{
size_t list_len, name_len;
const char **p;
/* If we didn't send it, the server shouldn't send it */
if( ssl->conf->alpn_list == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching ALPN extension" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/*
* opaque ProtocolName<1..2^8-1>;
*
* struct {
* ProtocolName protocol_name_list<2..2^16-1>
* } ProtocolNameList;
*
* the "ProtocolNameList" MUST contain exactly one "ProtocolName"
*/
/* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
if( len < 4 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
list_len = ( buf[0] << 8 ) | buf[1];
if( list_len != len - 2 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
name_len = buf[2];
if( name_len != list_len - 1 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/* Check that the server chosen protocol was in our list and save it */
for( p = ssl->conf->alpn_list; *p != NULL; p++ )
{
if( name_len == strlen( *p ) &&
memcmp( buf + 3, *p, name_len ) == 0 )
{
ssl->alpn_chosen = *p;
return( 0 );
}
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ALPN extension: no matching protocol" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
#endif /* MBEDTLS_SSL_ALPN */
/*
* Parse HelloVerifyRequest. Only called after verifying the HS type.
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
static int ssl_parse_hello_verify_request( mbedtls_ssl_context *ssl )
{
const unsigned char *p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
int major_ver, minor_ver;
unsigned char cookie_len;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse hello verify request" ) );
/*
* struct {
* ProtocolVersion server_version;
* opaque cookie<0..2^8-1>;
* } HelloVerifyRequest;
*/
MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 );
mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, p );
p += 2;
/*
* Since the RFC is not clear on this point, accept DTLS 1.0 (TLS 1.1)
* even is lower than our min version.
*/
if( major_ver < MBEDTLS_SSL_MAJOR_VERSION_3 ||
minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ||
major_ver > ssl->conf->max_major_ver ||
minor_ver > ssl->conf->max_minor_ver )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server version" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
}
cookie_len = *p++;
MBEDTLS_SSL_DEBUG_BUF( 3, "cookie", p, cookie_len );
if( ( ssl->in_msg + ssl->in_msglen ) - p < cookie_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1,
( "cookie length does not match incoming message size" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
mbedtls_free( ssl->handshake->verify_cookie );
ssl->handshake->verify_cookie = mbedtls_calloc( 1, cookie_len );
if( ssl->handshake->verify_cookie == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", cookie_len ) );
return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
}
memcpy( ssl->handshake->verify_cookie, p, cookie_len );
ssl->handshake->verify_cookie_len = cookie_len;
/* Start over at ClientHello */
ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
mbedtls_ssl_reset_checksum( ssl );
mbedtls_ssl_recv_flight_completed( ssl );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse hello verify request" ) );
return( 0 );
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
static int ssl_parse_server_hello( mbedtls_ssl_context *ssl )
{
int ret, i;
size_t n;
size_t ext_len;
unsigned char *buf, *ext;
unsigned char comp;
#if defined(MBEDTLS_ZLIB_SUPPORT)
int accept_comp;
#endif
#if defined(MBEDTLS_SSL_RENEGOTIATION)
int renegotiation_info_seen = 0;
#endif
int handshake_failure = 0;
const mbedtls_ssl_ciphersuite_t *suite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello" ) );
buf = ssl->in_msg;
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
/* No alert on a read error. */
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
{
ssl->renego_records_seen++;
if( ssl->conf->renego_max_records >= 0 &&
ssl->renego_records_seen > ssl->conf->renego_max_records )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
"but not honored by server" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-handshake message during renego" ) );
ssl->keep_current_message = 1;
return( MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO );
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
{
if( buf[0] == MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "received hello verify request" ) );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
return( ssl_parse_hello_verify_request( ssl ) );
}
else
{
/* We made it through the verification process */
mbedtls_free( ssl->handshake->verify_cookie );
ssl->handshake->verify_cookie = NULL;
ssl->handshake->verify_cookie_len = 0;
}
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
if( ssl->in_hslen < 38 + mbedtls_ssl_hs_hdr_len( ssl ) ||
buf[0] != MBEDTLS_SSL_HS_SERVER_HELLO )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/*
* 0 . 1 server_version
* 2 . 33 random (maybe including 4 bytes of Unix time)
* 34 . 34 session_id length = n
* 35 . 34+n session_id
* 35+n . 36+n cipher_suite
* 37+n . 37+n compression_method
*
* 38+n . 39+n extensions length (optional)
* 40+n . .. extensions
*/
buf += mbedtls_ssl_hs_hdr_len( ssl );
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, version", buf + 0, 2 );
mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver,
ssl->conf->transport, buf + 0 );
if( ssl->major_ver < ssl->conf->min_major_ver ||
ssl->minor_ver < ssl->conf->min_minor_ver ||
ssl->major_ver > ssl->conf->max_major_ver ||
ssl->minor_ver > ssl->conf->max_minor_ver )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server version out of bounds - "
" min: [%d:%d], server: [%d:%d], max: [%d:%d]",
ssl->conf->min_major_ver, ssl->conf->min_minor_ver,
ssl->major_ver, ssl->minor_ver,
ssl->conf->max_major_ver, ssl->conf->max_minor_ver ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu",
( (uint32_t) buf[2] << 24 ) |
( (uint32_t) buf[3] << 16 ) |
( (uint32_t) buf[4] << 8 ) |
( (uint32_t) buf[5] ) ) );
memcpy( ssl->handshake->randbytes + 32, buf + 2, 32 );
n = buf[34];
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", buf + 2, 32 );
if( n > 32 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
if( ssl->in_hslen > mbedtls_ssl_hs_hdr_len( ssl ) + 39 + n )
{
ext_len = ( ( buf[38 + n] << 8 )
| ( buf[39 + n] ) );
if( ( ext_len > 0 && ext_len < 4 ) ||
ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 40 + n + ext_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
}
else if( ssl->in_hslen == mbedtls_ssl_hs_hdr_len( ssl ) + 38 + n )
{
ext_len = 0;
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
/* ciphersuite (used later) */
i = ( buf[35 + n] << 8 ) | buf[36 + n];
/*
* Read and check compression
*/
comp = buf[37 + n];
#if defined(MBEDTLS_ZLIB_SUPPORT)
/* See comments in ssl_write_client_hello() */
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
accept_comp = 0;
else
#endif
accept_comp = 1;
if( comp != MBEDTLS_SSL_COMPRESS_NULL &&
( comp != MBEDTLS_SSL_COMPRESS_DEFLATE || accept_comp == 0 ) )
#else /* MBEDTLS_ZLIB_SUPPORT */
if( comp != MBEDTLS_SSL_COMPRESS_NULL )
#endif/* MBEDTLS_ZLIB_SUPPORT */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server hello, bad compression: %d", comp ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
}
/*
* Initialize update checksum functions
*/
ssl->transform_negotiate->ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( i );
if( ssl->transform_negotiate->ciphersuite_info == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ciphersuite info for %04x not found", i ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
mbedtls_ssl_optimize_checksum( ssl, ssl->transform_negotiate->ciphersuite_info );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %d", n ) );
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, session id", buf + 35, n );
/*
* Check if the session can be resumed
*/
if( ssl->handshake->resume == 0 || n == 0 ||
#if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
#endif
ssl->session_negotiate->ciphersuite != i ||
ssl->session_negotiate->compression != comp ||
ssl->session_negotiate->id_len != n ||
memcmp( ssl->session_negotiate->id, buf + 35, n ) != 0 )
{
ssl->state++;
ssl->handshake->resume = 0;
#if defined(MBEDTLS_HAVE_TIME)
ssl->session_negotiate->start = mbedtls_time( NULL );
#endif
ssl->session_negotiate->ciphersuite = i;
ssl->session_negotiate->compression = comp;
ssl->session_negotiate->id_len = n;
memcpy( ssl->session_negotiate->id, buf + 35, n );
}
else
{
ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
return( ret );
}
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed",
ssl->handshake->resume ? "a" : "no" ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %04x", i ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: %d", buf[37 + n] ) );
suite_info = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite );
if( suite_info == NULL
#if defined(MBEDTLS_ARC4_C)
|| ( ssl->conf->arc4_disabled &&
suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
#endif
)
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", suite_info->name ) );
i = 0;
while( 1 )
{
if( ssl->conf->ciphersuite_list[ssl->minor_ver][i] == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
if( ssl->conf->ciphersuite_list[ssl->minor_ver][i++] ==
ssl->session_negotiate->ciphersuite )
{
break;
}
}
if( comp != MBEDTLS_SSL_COMPRESS_NULL
#if defined(MBEDTLS_ZLIB_SUPPORT)
&& comp != MBEDTLS_SSL_COMPRESS_DEFLATE
#endif
)
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
ssl->session_negotiate->compression = comp;
ext = buf + 40 + n;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "server hello, total extension length: %d", ext_len ) );
while( ext_len )
{
unsigned int ext_id = ( ( ext[0] << 8 )
| ( ext[1] ) );
unsigned int ext_size = ( ( ext[2] << 8 )
| ( ext[3] ) );
if( ext_size + 4 > ext_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
switch( ext_id )
{
case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) );
#if defined(MBEDTLS_SSL_RENEGOTIATION)
renegotiation_info_seen = 1;
#endif
if( ( ret = ssl_parse_renegotiation_info( ssl, ext + 4,
ext_size ) ) != 0 )
return( ret );
break;
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max_fragment_length extension" ) );
if( ( ret = ssl_parse_max_fragment_length_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found truncated_hmac extension" ) );
if( ( ret = ssl_parse_truncated_hmac_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt_then_mac extension" ) );
if( ( ret = ssl_parse_encrypt_then_mac_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended_master_secret extension" ) );
if( ( ret = ssl_parse_extended_ms_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
case MBEDTLS_TLS_EXT_SESSION_TICKET:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session_ticket extension" ) );
if( ( ret = ssl_parse_session_ticket_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported_point_formats extension" ) );
if( ( ret = ssl_parse_supported_point_formats_ext( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake_kkpp extension" ) );
if( ( ret = ssl_parse_ecjpake_kkpp( ssl,
ext + 4, ext_size ) ) != 0 )
{
return( ret );
}
break;
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_ALPN)
case MBEDTLS_TLS_EXT_ALPN:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) );
if( ( ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ) ) != 0 )
return( ret );
break;
#endif /* MBEDTLS_SSL_ALPN */
default:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %d (ignoring)",
ext_id ) );
}
ext_len -= 4 + ext_size;
ext += 4 + ext_size;
if( ext_len > 0 && ext_len < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
}
/*
* Renegotiation security checks
*/
if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) );
handshake_failure = 1;
}
#if defined(MBEDTLS_SSL_RENEGOTIATION)
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
renegotiation_info_seen == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) );
handshake_failure = 1;
}
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) );
handshake_failure = 1;
}
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
renegotiation_info_seen == 1 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) );
handshake_failure = 1;
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
if( handshake_failure == 1 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
return( 0 );
}
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
static int ssl_parse_server_dh_params( mbedtls_ssl_context *ssl, unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
/*
* Ephemeral DH parameters:
*
* struct {
* opaque dh_p<1..2^16-1>;
* opaque dh_g<1..2^16-1>;
* opaque dh_Ys<1..2^16-1>;
* } ServerDHParams;
*/
if( ( ret = mbedtls_dhm_read_params( &ssl->handshake->dhm_ctx, p, end ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 2, ( "mbedtls_dhm_read_params" ), ret );
return( ret );
}
if( ssl->handshake->dhm_ctx.len * 8 < ssl->conf->dhm_min_bitlen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "DHM prime too short: %d < %d",
ssl->handshake->dhm_ctx.len * 8,
ssl->conf->dhm_min_bitlen ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY );
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
static int ssl_check_server_ecdh_params( const mbedtls_ssl_context *ssl )
{
const mbedtls_ecp_curve_info *curve_info;
curve_info = mbedtls_ecp_curve_info_from_grp_id( ssl->handshake->ecdh_ctx.grp.id );
if( curve_info == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDH curve: %s", curve_info->name ) );
#if defined(MBEDTLS_ECP_C)
if( mbedtls_ssl_check_curve( ssl, ssl->handshake->ecdh_ctx.grp.id ) != 0 )
#else
if( ssl->handshake->ecdh_ctx.grp.nbits < 163 ||
ssl->handshake->ecdh_ctx.grp.nbits > 521 )
#endif
return( -1 );
MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Qp", &ssl->handshake->ecdh_ctx.Qp );
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
static int ssl_parse_server_ecdh_params( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
/*
* Ephemeral ECDH parameters:
*
* struct {
* ECParameters curve_params;
* ECPoint public;
* } ServerECDHParams;
*/
if( ( ret = mbedtls_ecdh_read_params( &ssl->handshake->ecdh_ctx,
(const unsigned char **) p, end ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_read_params" ), ret );
return( ret );
}
if( ssl_check_server_ecdh_params( ssl ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message (ECDHE curve)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t len;
((void) ssl);
/*
* PSK parameters:
*
* opaque psk_identity_hint<0..2^16-1>;
*/
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) + len > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Note: we currently ignore the PKS identity hint, as we only allow one
* PSK to be provisionned on the client. This could be changed later if
* someone needs that feature.
*/
*p += len;
ret = 0;
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
/*
* Generate a pre-master secret and encrypt it with the server's RSA key
*/
static int ssl_write_encrypted_pms( mbedtls_ssl_context *ssl,
size_t offset, size_t *olen,
size_t pms_offset )
{
int ret;
size_t len_bytes = ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ? 0 : 2;
unsigned char *p = ssl->handshake->premaster + pms_offset;
if( offset + len_bytes > MBEDTLS_SSL_MAX_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small for encrypted pms" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
/*
* Generate (part of) the pre-master as
* struct {
* ProtocolVersion client_version;
* opaque random[46];
* } PreMasterSecret;
*/
mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,
ssl->conf->transport, p );
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p + 2, 46 ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "f_rng", ret );
return( ret );
}
ssl->handshake->pmslen = 48;
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* Now write it out, encrypted
*/
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
MBEDTLS_PK_RSA ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate key type mismatch" ) );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
if( ( ret = mbedtls_pk_encrypt( &ssl->session_negotiate->peer_cert->pk,
p, ssl->handshake->pmslen,
ssl->out_msg + offset + len_bytes, olen,
MBEDTLS_SSL_MAX_CONTENT_LEN - offset - len_bytes,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_rsa_pkcs1_encrypt", ret );
return( ret );
}
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( len_bytes == 2 )
{
ssl->out_msg[offset+0] = (unsigned char)( *olen >> 8 );
ssl->out_msg[offset+1] = (unsigned char)( *olen );
*olen += 2;
}
#endif
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
static int ssl_parse_signature_algorithm( mbedtls_ssl_context *ssl,
unsigned char **p,
unsigned char *end,
mbedtls_md_type_t *md_alg,
mbedtls_pk_type_t *pk_alg )
{
((void) ssl);
*md_alg = MBEDTLS_MD_NONE;
*pk_alg = MBEDTLS_PK_NONE;
/* Only in TLS 1.2 */
if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
{
return( 0 );
}
if( (*p) + 2 > end )
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
/*
* Get hash algorithm
*/
if( ( *md_alg = mbedtls_ssl_md_alg_from_hash( (*p)[0] ) ) == MBEDTLS_MD_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "Server used unsupported "
"HashAlgorithm %d", *(p)[0] ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Get signature algorithm
*/
if( ( *pk_alg = mbedtls_ssl_pk_alg_from_sig( (*p)[1] ) ) == MBEDTLS_PK_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used unsupported "
"SignatureAlgorithm %d", (*p)[1] ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
/*
* Check if the hash is acceptable
*/
if( mbedtls_ssl_check_sig_hash( ssl, *md_alg ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used HashAlgorithm %d that was not offered",
*(p)[0] ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used SignatureAlgorithm %d", (*p)[1] ) );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used HashAlgorithm %d", (*p)[0] ) );
*p += 2;
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
{
int ret;
const mbedtls_ecp_keypair *peer_key;
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
MBEDTLS_PK_ECKEY ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
peer_key = mbedtls_pk_ec( ssl->session_negotiate->peer_cert->pk );
if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx, peer_key,
MBEDTLS_ECDH_THEIRS ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret );
return( ret );
}
if( ssl_check_server_ecdh_params( ssl ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server certificate (ECDH curve)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
}
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
{
int ret;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
unsigned char *p = NULL, *end = NULL;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
{
if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
ssl->state++;
return( 0 );
}
((void) p);
((void) end);
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* ServerKeyExchange may be skipped with PSK and RSA-PSK when the server
* doesn't use a psk_identity_hint
*/
if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )
{
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
{
/* Current message is probably either
* CertificateRequest or ServerHelloDone */
ssl->keep_current_message = 1;
goto exit;
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key exchange message must "
"not be skipped" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
end = ssl->in_msg + ssl->in_hslen;
MBEDTLS_SSL_DEBUG_BUF( 3, "server key exchange", p, end - p );
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
} /* FALLTROUGH */
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
; /* nothing more to do */
else
#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
{
if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
{
if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
p, end - p );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
{
size_t sig_len, hashlen;
unsigned char hash[64];
mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
size_t params_len = p - params;
/*
* Handle the digitally-signed structure
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
if( ssl_parse_signature_algorithm( ssl, &p, end,
&md_alg, &pk_alg ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
{
pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
/* Default hash for ECDSA is SHA-1 */
if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE )
md_alg = MBEDTLS_MD_SHA1;
}
else
#endif
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
/*
* Read signature
*/
if( p > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
sig_len = ( p[0] << 8 ) | p[1];
p += 2;
if( end != p + sig_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len );
/*
* Compute the hash that has been signed
*/
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( md_alg == MBEDTLS_MD_NONE )
{
hashlen = 36;
ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params,
params_len );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( md_alg != MBEDTLS_MD_NONE )
{
/* Info from md_alg will be used instead */
hashlen = 0;
ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, params,
params_len, md_alg );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen != 0 ? hashlen :
(unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) );
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* Verify signature
*/
if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,
md_alg, hash, hashlen, p, sig_len ) ) != 0 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
return( ret );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
exit:
ssl->state++;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) );
return( 0 );
}
#if ! defined(MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED)
static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
{
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
ssl->state++;
return( 0 );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#else /* MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED */
static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
{
int ret;
unsigned char *buf;
size_t n = 0;
size_t cert_type_len = 0, dn_len = 0;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
ssl->state++;
return( 0 );
}
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
ssl->state++;
ssl->client_auth = ( ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE_REQUEST );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "got %s certificate request",
ssl->client_auth ? "a" : "no" ) );
if( ssl->client_auth == 0 )
{
/* Current message is probably the ServerHelloDone */
ssl->keep_current_message = 1;
goto exit;
}
/*
* struct {
* ClientCertificateType certificate_types<1..2^8-1>;
* SignatureAndHashAlgorithm
* supported_signature_algorithms<2^16-1>; -- TLS 1.2 only
* DistinguishedName certificate_authorities<0..2^16-1>;
* } CertificateRequest;
*
* Since we only support a single certificate on clients, let's just
* ignore all the information that's supposed to help us pick a
* certificate.
*
* We could check that our certificate matches the request, and bail out
* if it doesn't, but it's simpler to just send the certificate anyway,
* and give the server the opportunity to decide if it should terminate
* the connection when it doesn't like our certificate.
*
* Same goes for the hash in TLS 1.2's signature_algorithms: at this
* point we only have one hash available (see comments in
* write_certificate_verify), so let's just use what we have.
*
* However, we still minimally parse the message to check it is at least
* superficially sane.
*/
buf = ssl->in_msg;
/* certificate_types */
cert_type_len = buf[mbedtls_ssl_hs_hdr_len( ssl )];
n = cert_type_len;
if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
/* supported_signature_algorithms */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
size_t sig_alg_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 )
| ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) );
#if defined(MBEDTLS_DEBUG_C)
unsigned char* sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n;
size_t i;
for( i = 0; i < sig_alg_len; i += 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "Supported Signature Algorithm found: %d"
",%d", sig_alg[i], sig_alg[i + 1] ) );
}
#endif
n += 2 + sig_alg_len;
if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
/* certificate_authorities */
dn_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 )
| ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) );
n += dn_len;
if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
exit:
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate request" ) );
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED */
static int ssl_parse_server_hello_done( mbedtls_ssl_context *ssl )
{
int ret;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello done" ) );
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) ||
ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_HELLO_DONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE );
}
ssl->state++;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
mbedtls_ssl_recv_flight_completed( ssl );
#endif
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello done" ) );
return( 0 );
}
static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl )
{
int ret;
size_t i, n;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client key exchange" ) );
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA )
{
/*
* DHM key exchange -- send G^X mod P
*/
n = ssl->handshake->dhm_ctx.len;
ssl->out_msg[4] = (unsigned char)( n >> 8 );
ssl->out_msg[5] = (unsigned char)( n );
i = 6;
ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
(int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
&ssl->out_msg[i], n,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX );
if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
ssl->handshake->premaster,
MBEDTLS_PREMASTER_SIZE,
&ssl->handshake->pmslen,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
{
/*
* ECDH key exchange -- send client public value
*/
i = 4;
ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx,
&n,
&ssl->out_msg[i], 1000,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q );
if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx,
&ssl->handshake->pmslen,
ssl->handshake->premaster,
MBEDTLS_MPI_MAX_SIZE,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
if( mbedtls_ssl_ciphersuite_uses_psk( ciphersuite_info ) )
{
/*
* opaque psk_identity<0..2^16-1>;
*/
if( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for PSK" ) );
return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
}
i = 4;
n = ssl->conf->psk_identity_len;
if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity too long or "
"SSL buffer too short" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
ssl->out_msg[i++] = (unsigned char)( n >> 8 );
ssl->out_msg[i++] = (unsigned char)( n );
memcpy( ssl->out_msg + i, ssl->conf->psk_identity, ssl->conf->psk_identity_len );
i += ssl->conf->psk_identity_len;
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK )
{
n = 0;
}
else
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
{
if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 2 ) ) != 0 )
return( ret );
}
else
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
{
/*
* ClientDiffieHellmanPublic public (DHM send G^X mod P)
*/
n = ssl->handshake->dhm_ctx.len;
if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity or DHM size too long"
" or SSL buffer too short" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
ssl->out_msg[i++] = (unsigned char)( n >> 8 );
ssl->out_msg[i++] = (unsigned char)( n );
ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
(int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
&ssl->out_msg[i], n,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
/*
* ClientECDiffieHellmanPublic public;
*/
ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx, &n,
&ssl->out_msg[i], MBEDTLS_SSL_MAX_CONTENT_LEN - i,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
ciphersuite_info->key_exchange ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
{
i = 4;
if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 0 ) ) != 0 )
return( ret );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
i = 4;
ret = mbedtls_ecjpake_write_round_two( &ssl->handshake->ecjpake_ctx,
ssl->out_msg + i, MBEDTLS_SSL_MAX_CONTENT_LEN - i, &n,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret );
return( ret );
}
ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx,
ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
{
((void) ciphersuite_info);
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
ssl->out_msglen = i + n;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE;
ssl->state++;
if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client key exchange" ) );
return( 0 );
}
#if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
!defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)&& \
!defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
{
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
int ret;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
return( ret );
}
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
ssl->state++;
return( 0 );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#else
static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->transform_negotiate->ciphersuite_info;
size_t n = 0, offset = 0;
unsigned char hash[48];
unsigned char *hash_start = hash;
mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
unsigned int hashlen;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
return( ret );
}
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
ssl->state++;
return( 0 );
}
if( ssl->client_auth == 0 || mbedtls_ssl_own_cert( ssl ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
ssl->state++;
return( 0 );
}
if( mbedtls_ssl_own_key( ssl ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for certificate" ) );
return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
}
/*
* Make an RSA signature of the handshake digests
*/
ssl->handshake->calc_verify( ssl, hash );
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
{
/*
* digitally-signed struct {
* opaque md5_hash[16];
* opaque sha_hash[20];
* };
*
* md5_hash
* MD5(handshake_messages);
*
* sha_hash
* SHA(handshake_messages);
*/
hashlen = 36;
md_alg = MBEDTLS_MD_NONE;
/*
* For ECDSA, default hash is SHA-1 only
*/
if( mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECDSA ) )
{
hash_start += 16;
hashlen -= 16;
md_alg = MBEDTLS_MD_SHA1;
}
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
/*
* digitally-signed struct {
* opaque handshake_messages[handshake_messages_length];
* };
*
* Taking shortcut here. We assume that the server always allows the
* PRF Hash function and has sent it in the allowed signature
* algorithms list received in the Certificate Request message.
*
* Until we encounter a server that does not, we will take this
* shortcut.
*
* Reason: Otherwise we should have running hashes for SHA512 and SHA224
* in order to satisfy 'weird' needs from the server side.
*/
if( ssl->transform_negotiate->ciphersuite_info->mac ==
MBEDTLS_MD_SHA384 )
{
md_alg = MBEDTLS_MD_SHA384;
ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA384;
}
else
{
md_alg = MBEDTLS_MD_SHA256;
ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA256;
}
ssl->out_msg[5] = mbedtls_ssl_sig_from_pk( mbedtls_ssl_own_key( ssl ) );
/* Info from md_alg will be used instead */
hashlen = 0;
offset = 2;
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ), md_alg, hash_start, hashlen,
ssl->out_msg + 6 + offset, &n,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret );
return( ret );
}
ssl->out_msg[4 + offset] = (unsigned char)( n >> 8 );
ssl->out_msg[5 + offset] = (unsigned char)( n );
ssl->out_msglen = 6 + n + offset;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE_VERIFY;
ssl->state++;
if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate verify" ) );
return( ret );
}
#endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED &&
!MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl )
{
int ret;
uint32_t lifetime;
size_t ticket_len;
unsigned char *ticket;
const unsigned char *msg;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse new session ticket" ) );
if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
}
/*
* struct {
* uint32 ticket_lifetime_hint;
* opaque ticket<0..2^16-1>;
* } NewSessionTicket;
*
* 0 . 3 ticket_lifetime_hint
* 4 . 5 ticket_len (n)
* 6 . 5+n ticket content
*/
if( ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET ||
ssl->in_hslen < 6 + mbedtls_ssl_hs_hdr_len( ssl ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
}
msg = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
lifetime = ( msg[0] << 24 ) | ( msg[1] << 16 ) |
( msg[2] << 8 ) | ( msg[3] );
ticket_len = ( msg[4] << 8 ) | ( msg[5] );
if( ticket_len + 6 + mbedtls_ssl_hs_hdr_len( ssl ) != ssl->in_hslen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %d", ticket_len ) );
/* We're not waiting for a NewSessionTicket message any more */
ssl->handshake->new_session_ticket = 0;
ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
/*
* Zero-length ticket means the server changed his mind and doesn't want
* to send a ticket after all, so just forget it
*/
if( ticket_len == 0 )
return( 0 );
mbedtls_zeroize( ssl->session_negotiate->ticket,
ssl->session_negotiate->ticket_len );
mbedtls_free( ssl->session_negotiate->ticket );
ssl->session_negotiate->ticket = NULL;
ssl->session_negotiate->ticket_len = 0;
if( ( ticket = mbedtls_calloc( 1, ticket_len ) ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ticket alloc failed" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
}
memcpy( ticket, msg + 6, ticket_len );
ssl->session_negotiate->ticket = ticket;
ssl->session_negotiate->ticket_len = ticket_len;
ssl->session_negotiate->ticket_lifetime = lifetime;
/*
* RFC 5077 section 3.4:
* "If the client receives a session ticket from the server, then it
* discards any Session ID that was sent in the ServerHello."
*/
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket in use, discarding session id" ) );
ssl->session_negotiate->id_len = 0;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse new session ticket" ) );
return( 0 );
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
/*
* SSL handshake -- client side -- single step
*/
int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl )
{
int ret = 0;
if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL )
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "client state: %d", ssl->state ) );
if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
return( ret );
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
{
if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
return( ret );
}
#endif
/* Change state now, so that it is right in mbedtls_ssl_read_record(), used
* by DTLS for dropping out-of-sequence ChangeCipherSpec records */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
if( ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC &&
ssl->handshake->new_session_ticket != 0 )
{
ssl->state = MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET;
}
#endif
switch( ssl->state )
{
case MBEDTLS_SSL_HELLO_REQUEST:
ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
break;
/*
* ==> ClientHello
*/
case MBEDTLS_SSL_CLIENT_HELLO:
ret = ssl_write_client_hello( ssl );
break;
/*
* <== ServerHello
* Certificate
* ( ServerKeyExchange )
* ( CertificateRequest )
* ServerHelloDone
*/
case MBEDTLS_SSL_SERVER_HELLO:
ret = ssl_parse_server_hello( ssl );
break;
case MBEDTLS_SSL_SERVER_CERTIFICATE:
ret = mbedtls_ssl_parse_certificate( ssl );
break;
case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
ret = ssl_parse_server_key_exchange( ssl );
break;
case MBEDTLS_SSL_CERTIFICATE_REQUEST:
ret = ssl_parse_certificate_request( ssl );
break;
case MBEDTLS_SSL_SERVER_HELLO_DONE:
ret = ssl_parse_server_hello_done( ssl );
break;
/*
* ==> ( Certificate/Alert )
* ClientKeyExchange
* ( CertificateVerify )
* ChangeCipherSpec
* Finished
*/
case MBEDTLS_SSL_CLIENT_CERTIFICATE:
ret = mbedtls_ssl_write_certificate( ssl );
break;
case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
ret = ssl_write_client_key_exchange( ssl );
break;
case MBEDTLS_SSL_CERTIFICATE_VERIFY:
ret = ssl_write_certificate_verify( ssl );
break;
case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
ret = mbedtls_ssl_write_change_cipher_spec( ssl );
break;
case MBEDTLS_SSL_CLIENT_FINISHED:
ret = mbedtls_ssl_write_finished( ssl );
break;
/*
* <== ( NewSessionTicket )
* ChangeCipherSpec
* Finished
*/
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
case MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET:
ret = ssl_parse_new_session_ticket( ssl );
break;
#endif
case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
ret = mbedtls_ssl_parse_change_cipher_spec( ssl );
break;
case MBEDTLS_SSL_SERVER_FINISHED:
ret = mbedtls_ssl_parse_finished( ssl );
break;
case MBEDTLS_SSL_FLUSH_BUFFERS:
MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) );
ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
break;
case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
mbedtls_ssl_handshake_wrapup( ssl );
break;
default:
MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
return( ret );
}
#endif /* MBEDTLS_SSL_CLI_C */
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_700_0 |
crossvul-cpp_data_bad_3946_3 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Serial Port Device Service Virtual Channel
*
* Copyright 2011 O.S. Systems Software Ltda.
* Copyright 2011 Eduardo Fiss Beloni <beloni@ossystems.com.br>
* Copyright 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <winpr/collections.h>
#include <winpr/comm.h>
#include <winpr/crt.h>
#include <winpr/stream.h>
#include <winpr/synch.h>
#include <winpr/thread.h>
#include <winpr/wlog.h>
#include <freerdp/freerdp.h>
#include <freerdp/channels/rdpdr.h>
#include <freerdp/channels/log.h>
#define TAG CHANNELS_TAG("serial.client")
/* TODO: all #ifdef __linux__ could be removed once only some generic
* functions will be used. Replace CommReadFile by ReadFile,
* CommWriteFile by WriteFile etc.. */
#if defined __linux__ && !defined ANDROID
#define MAX_IRP_THREADS 5
typedef struct _SERIAL_DEVICE SERIAL_DEVICE;
struct _SERIAL_DEVICE
{
DEVICE device;
BOOL permissive;
SERIAL_DRIVER_ID ServerSerialDriverId;
HANDLE* hComm;
wLog* log;
HANDLE MainThread;
wMessageQueue* MainIrpQueue;
/* one thread per pending IRP and indexed according their CompletionId */
wListDictionary* IrpThreads;
UINT32 IrpThreadToBeTerminatedCount;
CRITICAL_SECTION TerminatingIrpThreadsLock;
rdpContext* rdpcontext;
};
typedef struct _IRP_THREAD_DATA IRP_THREAD_DATA;
struct _IRP_THREAD_DATA
{
SERIAL_DEVICE* serial;
IRP* irp;
};
static UINT32 _GetLastErrorToIoStatus(SERIAL_DEVICE* serial)
{
/* http://msdn.microsoft.com/en-us/library/ff547466%28v=vs.85%29.aspx#generic_status_values_for_serial_device_control_requests
*/
switch (GetLastError())
{
case ERROR_BAD_DEVICE:
return STATUS_INVALID_DEVICE_REQUEST;
case ERROR_CALL_NOT_IMPLEMENTED:
return STATUS_NOT_IMPLEMENTED;
case ERROR_CANCELLED:
return STATUS_CANCELLED;
case ERROR_INSUFFICIENT_BUFFER:
return STATUS_BUFFER_TOO_SMALL; /* NB: STATUS_BUFFER_SIZE_TOO_SMALL not defined */
case ERROR_INVALID_DEVICE_OBJECT_PARAMETER: /* eg: SerCx2.sys' _purge() */
return STATUS_INVALID_DEVICE_STATE;
case ERROR_INVALID_HANDLE:
return STATUS_INVALID_DEVICE_REQUEST;
case ERROR_INVALID_PARAMETER:
return STATUS_INVALID_PARAMETER;
case ERROR_IO_DEVICE:
return STATUS_IO_DEVICE_ERROR;
case ERROR_IO_PENDING:
return STATUS_PENDING;
case ERROR_NOT_SUPPORTED:
return STATUS_NOT_SUPPORTED;
case ERROR_TIMEOUT:
return STATUS_TIMEOUT;
/* no default */
}
WLog_Print(serial->log, WLOG_DEBUG, "unexpected last-error: 0x%08" PRIX32 "", GetLastError());
return STATUS_UNSUCCESSFUL;
}
static UINT serial_process_irp_create(SERIAL_DEVICE* serial, IRP* irp)
{
DWORD DesiredAccess;
DWORD SharedAccess;
DWORD CreateDisposition;
UINT32 PathLength;
if (Stream_GetRemainingLength(irp->input) < 32)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, DesiredAccess); /* DesiredAccess (4 bytes) */
Stream_Seek_UINT64(irp->input); /* AllocationSize (8 bytes) */
Stream_Seek_UINT32(irp->input); /* FileAttributes (4 bytes) */
Stream_Read_UINT32(irp->input, SharedAccess); /* SharedAccess (4 bytes) */
Stream_Read_UINT32(irp->input, CreateDisposition); /* CreateDisposition (4 bytes) */
Stream_Seek_UINT32(irp->input); /* CreateOptions (4 bytes) */
Stream_Read_UINT32(irp->input, PathLength); /* PathLength (4 bytes) */
if (Stream_GetRemainingLength(irp->input) < PathLength)
return ERROR_INVALID_DATA;
Stream_Seek(irp->input, PathLength); /* Path (variable) */
assert(PathLength == 0); /* MS-RDPESP 2.2.2.2 */
#ifndef _WIN32
/* Windows 2012 server sends on a first call :
* DesiredAccess = 0x00100080: SYNCHRONIZE | FILE_READ_ATTRIBUTES
* SharedAccess = 0x00000007: FILE_SHARE_DELETE | FILE_SHARE_WRITE | FILE_SHARE_READ
* CreateDisposition = 0x00000001: CREATE_NEW
*
* then Windows 2012 sends :
* DesiredAccess = 0x00120089: SYNCHRONIZE | READ_CONTROL | FILE_READ_ATTRIBUTES |
* FILE_READ_EA | FILE_READ_DATA SharedAccess = 0x00000007: FILE_SHARE_DELETE |
* FILE_SHARE_WRITE | FILE_SHARE_READ CreateDisposition = 0x00000001: CREATE_NEW
*
* assert(DesiredAccess == (GENERIC_READ | GENERIC_WRITE));
* assert(SharedAccess == 0);
* assert(CreateDisposition == OPEN_EXISTING);
*
*/
WLog_Print(serial->log, WLOG_DEBUG,
"DesiredAccess: 0x%" PRIX32 ", SharedAccess: 0x%" PRIX32
", CreateDisposition: 0x%" PRIX32 "",
DesiredAccess, SharedAccess, CreateDisposition);
/* FIXME: As of today only the flags below are supported by CommCreateFileA: */
DesiredAccess = GENERIC_READ | GENERIC_WRITE;
SharedAccess = 0;
CreateDisposition = OPEN_EXISTING;
#endif
serial->hComm =
CreateFile(serial->device.name, DesiredAccess, SharedAccess, NULL, /* SecurityAttributes */
CreateDisposition, 0, /* FlagsAndAttributes */
NULL); /* TemplateFile */
if (!serial->hComm || (serial->hComm == INVALID_HANDLE_VALUE))
{
WLog_Print(serial->log, WLOG_WARN, "CreateFile failure: %s last-error: 0x%08" PRIX32 "",
serial->device.name, GetLastError());
irp->IoStatus = STATUS_UNSUCCESSFUL;
goto error_handle;
}
_comm_setServerSerialDriver(serial->hComm, serial->ServerSerialDriverId);
_comm_set_permissive(serial->hComm, serial->permissive);
/* NOTE: binary mode/raw mode required for the redirection. On
* Linux, CommCreateFileA forces this setting.
*/
/* ZeroMemory(&dcb, sizeof(DCB)); */
/* dcb.DCBlength = sizeof(DCB); */
/* GetCommState(serial->hComm, &dcb); */
/* dcb.fBinary = TRUE; */
/* SetCommState(serial->hComm, &dcb); */
assert(irp->FileId == 0);
irp->FileId = irp->devman->id_sequence++; /* FIXME: why not ((WINPR_COMM*)hComm)->fd? */
irp->IoStatus = STATUS_SUCCESS;
WLog_Print(serial->log, WLOG_DEBUG, "%s (DeviceId: %" PRIu32 ", FileId: %" PRIu32 ") created.",
serial->device.name, irp->device->id, irp->FileId);
error_handle:
Stream_Write_UINT32(irp->output, irp->FileId); /* FileId (4 bytes) */
Stream_Write_UINT8(irp->output, 0); /* Information (1 byte) */
return CHANNEL_RC_OK;
}
static UINT serial_process_irp_close(SERIAL_DEVICE* serial, IRP* irp)
{
if (Stream_GetRemainingLength(irp->input) < 32)
return ERROR_INVALID_DATA;
Stream_Seek(irp->input, 32); /* Padding (32 bytes) */
if (!CloseHandle(serial->hComm))
{
WLog_Print(serial->log, WLOG_WARN, "CloseHandle failure: %s (%" PRIu32 ") closed.",
serial->device.name, irp->device->id);
irp->IoStatus = STATUS_UNSUCCESSFUL;
goto error_handle;
}
WLog_Print(serial->log, WLOG_DEBUG, "%s (DeviceId: %" PRIu32 ", FileId: %" PRIu32 ") closed.",
serial->device.name, irp->device->id, irp->FileId);
serial->hComm = NULL;
irp->IoStatus = STATUS_SUCCESS;
error_handle:
Stream_Zero(irp->output, 5); /* Padding (5 bytes) */
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT serial_process_irp_read(SERIAL_DEVICE* serial, IRP* irp)
{
UINT32 Length;
UINT64 Offset;
BYTE* buffer = NULL;
DWORD nbRead = 0;
if (Stream_GetRemainingLength(irp->input) < 32)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */
Stream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */
Stream_Seek(irp->input, 20); /* Padding (20 bytes) */
buffer = (BYTE*)calloc(Length, sizeof(BYTE));
if (buffer == NULL)
{
irp->IoStatus = STATUS_NO_MEMORY;
goto error_handle;
}
/* MS-RDPESP 3.2.5.1.4: If the Offset field is not set to 0, the value MUST be ignored
* assert(Offset == 0);
*/
WLog_Print(serial->log, WLOG_DEBUG, "reading %" PRIu32 " bytes from %s", Length,
serial->device.name);
/* FIXME: CommReadFile to be replaced by ReadFile */
if (CommReadFile(serial->hComm, buffer, Length, &nbRead, NULL))
{
irp->IoStatus = STATUS_SUCCESS;
}
else
{
WLog_Print(serial->log, WLOG_DEBUG,
"read failure to %s, nbRead=%" PRIu32 ", last-error: 0x%08" PRIX32 "",
serial->device.name, nbRead, GetLastError());
irp->IoStatus = _GetLastErrorToIoStatus(serial);
}
WLog_Print(serial->log, WLOG_DEBUG, "%" PRIu32 " bytes read from %s", nbRead,
serial->device.name);
error_handle:
Stream_Write_UINT32(irp->output, nbRead); /* Length (4 bytes) */
if (nbRead > 0)
{
if (!Stream_EnsureRemainingCapacity(irp->output, nbRead))
{
WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!");
free(buffer);
return CHANNEL_RC_NO_MEMORY;
}
Stream_Write(irp->output, buffer, nbRead); /* ReadData */
}
free(buffer);
return CHANNEL_RC_OK;
}
static UINT serial_process_irp_write(SERIAL_DEVICE* serial, IRP* irp)
{
UINT32 Length;
UINT64 Offset;
DWORD nbWritten = 0;
if (Stream_GetRemainingLength(irp->input) < 32)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */
Stream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */
Stream_Seek(irp->input, 20); /* Padding (20 bytes) */
/* MS-RDPESP 3.2.5.1.5: The Offset field is ignored
* assert(Offset == 0);
*
* Using a serial printer, noticed though this field could be
* set.
*/
WLog_Print(serial->log, WLOG_DEBUG, "writing %" PRIu32 " bytes to %s", Length,
serial->device.name);
/* FIXME: CommWriteFile to be replaced by WriteFile */
if (CommWriteFile(serial->hComm, Stream_Pointer(irp->input), Length, &nbWritten, NULL))
{
irp->IoStatus = STATUS_SUCCESS;
}
else
{
WLog_Print(serial->log, WLOG_DEBUG,
"write failure to %s, nbWritten=%" PRIu32 ", last-error: 0x%08" PRIX32 "",
serial->device.name, nbWritten, GetLastError());
irp->IoStatus = _GetLastErrorToIoStatus(serial);
}
WLog_Print(serial->log, WLOG_DEBUG, "%" PRIu32 " bytes written to %s", nbWritten,
serial->device.name);
Stream_Write_UINT32(irp->output, nbWritten); /* Length (4 bytes) */
Stream_Write_UINT8(irp->output, 0); /* Padding (1 byte) */
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT serial_process_irp_device_control(SERIAL_DEVICE* serial, IRP* irp)
{
UINT32 IoControlCode;
UINT32 InputBufferLength;
BYTE* InputBuffer = NULL;
UINT32 OutputBufferLength;
BYTE* OutputBuffer = NULL;
DWORD BytesReturned = 0;
if (Stream_GetRemainingLength(irp->input) < 32)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, OutputBufferLength); /* OutputBufferLength (4 bytes) */
Stream_Read_UINT32(irp->input, InputBufferLength); /* InputBufferLength (4 bytes) */
Stream_Read_UINT32(irp->input, IoControlCode); /* IoControlCode (4 bytes) */
Stream_Seek(irp->input, 20); /* Padding (20 bytes) */
if (Stream_GetRemainingLength(irp->input) < InputBufferLength)
return ERROR_INVALID_DATA;
OutputBuffer = (BYTE*)calloc(OutputBufferLength, sizeof(BYTE));
if (OutputBuffer == NULL)
{
irp->IoStatus = STATUS_NO_MEMORY;
goto error_handle;
}
InputBuffer = (BYTE*)calloc(InputBufferLength, sizeof(BYTE));
if (InputBuffer == NULL)
{
irp->IoStatus = STATUS_NO_MEMORY;
goto error_handle;
}
Stream_Read(irp->input, InputBuffer, InputBufferLength);
WLog_Print(serial->log, WLOG_DEBUG,
"CommDeviceIoControl: CompletionId=%" PRIu32 ", IoControlCode=[0x%" PRIX32 "] %s",
irp->CompletionId, IoControlCode, _comm_serial_ioctl_name(IoControlCode));
/* FIXME: CommDeviceIoControl to be replaced by DeviceIoControl() */
if (CommDeviceIoControl(serial->hComm, IoControlCode, InputBuffer, InputBufferLength,
OutputBuffer, OutputBufferLength, &BytesReturned, NULL))
{
/* WLog_Print(serial->log, WLOG_DEBUG, "CommDeviceIoControl: CompletionId=%"PRIu32",
* IoControlCode=[0x%"PRIX32"] %s done", irp->CompletionId, IoControlCode,
* _comm_serial_ioctl_name(IoControlCode)); */
irp->IoStatus = STATUS_SUCCESS;
}
else
{
WLog_Print(serial->log, WLOG_DEBUG,
"CommDeviceIoControl failure: IoControlCode=[0x%" PRIX32
"] %s, last-error: 0x%08" PRIX32 "",
IoControlCode, _comm_serial_ioctl_name(IoControlCode), GetLastError());
irp->IoStatus = _GetLastErrorToIoStatus(serial);
}
error_handle:
/* FIXME: find out whether it's required or not to get
* BytesReturned == OutputBufferLength when
* CommDeviceIoControl returns FALSE */
assert(OutputBufferLength == BytesReturned);
Stream_Write_UINT32(irp->output, BytesReturned); /* OutputBufferLength (4 bytes) */
if (BytesReturned > 0)
{
if (!Stream_EnsureRemainingCapacity(irp->output, BytesReturned))
{
WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!");
free(InputBuffer);
free(OutputBuffer);
return CHANNEL_RC_NO_MEMORY;
}
Stream_Write(irp->output, OutputBuffer, BytesReturned); /* OutputBuffer */
}
/* FIXME: Why at least Windows 2008R2 gets lost with this
* extra byte and likely on a IOCTL_SERIAL_SET_BAUD_RATE? The
* extra byte is well required according MS-RDPEFS
* 2.2.1.5.5 */
/* else */
/* { */
/* Stream_Write_UINT8(irp->output, 0); /\* Padding (1 byte) *\/ */
/* } */
free(InputBuffer);
free(OutputBuffer);
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT serial_process_irp(SERIAL_DEVICE* serial, IRP* irp)
{
UINT error = CHANNEL_RC_OK;
WLog_Print(serial->log, WLOG_DEBUG,
"IRP MajorFunction: 0x%08" PRIX32 " MinorFunction: 0x%08" PRIX32 "\n",
irp->MajorFunction, irp->MinorFunction);
switch (irp->MajorFunction)
{
case IRP_MJ_CREATE:
error = serial_process_irp_create(serial, irp);
break;
case IRP_MJ_CLOSE:
error = serial_process_irp_close(serial, irp);
break;
case IRP_MJ_READ:
if ((error = serial_process_irp_read(serial, irp)))
WLog_ERR(TAG, "serial_process_irp_read failed with error %" PRIu32 "!", error);
break;
case IRP_MJ_WRITE:
error = serial_process_irp_write(serial, irp);
break;
case IRP_MJ_DEVICE_CONTROL:
if ((error = serial_process_irp_device_control(serial, irp)))
WLog_ERR(TAG, "serial_process_irp_device_control failed with error %" PRIu32 "!",
error);
break;
default:
irp->IoStatus = STATUS_NOT_SUPPORTED;
break;
}
return error;
}
static DWORD WINAPI irp_thread_func(LPVOID arg)
{
IRP_THREAD_DATA* data = (IRP_THREAD_DATA*)arg;
UINT error;
/* blocks until the end of the request */
if ((error = serial_process_irp(data->serial, data->irp)))
{
WLog_ERR(TAG, "serial_process_irp failed with error %" PRIu32 "", error);
goto error_out;
}
EnterCriticalSection(&data->serial->TerminatingIrpThreadsLock);
data->serial->IrpThreadToBeTerminatedCount++;
error = data->irp->Complete(data->irp);
LeaveCriticalSection(&data->serial->TerminatingIrpThreadsLock);
error_out:
if (error && data->serial->rdpcontext)
setChannelError(data->serial->rdpcontext, error, "irp_thread_func reported an error");
/* NB: At this point, the server might already being reusing
* the CompletionId whereas the thread is not yet
* terminated */
free(data);
ExitThread(error);
return error;
}
static void create_irp_thread(SERIAL_DEVICE* serial, IRP* irp)
{
IRP_THREAD_DATA* data = NULL;
HANDLE irpThread;
HANDLE previousIrpThread;
uintptr_t key;
/* for a test/debug purpose, uncomment the code below to get a
* single thread for all IRPs. NB: two IRPs could not be
* processed at the same time, typically two concurent
* Read/Write operations could block each other. */
/* serial_process_irp(serial, irp); */
/* irp->Complete(irp); */
/* return; */
/* NOTE: for good or bad, this implementation relies on the
* server to avoid a flooding of requests. see also _purge().
*/
EnterCriticalSection(&serial->TerminatingIrpThreadsLock);
while (serial->IrpThreadToBeTerminatedCount > 0)
{
/* Cleaning up termitating and pending irp
* threads. See also: irp_thread_func() */
HANDLE irpThread;
ULONG_PTR* ids;
int i, nbIds;
nbIds = ListDictionary_GetKeys(serial->IrpThreads, &ids);
for (i = 0; i < nbIds; i++)
{
/* Checking if ids[i] is terminating or pending */
DWORD waitResult;
ULONG_PTR id = ids[i];
irpThread = ListDictionary_GetItemValue(serial->IrpThreads, (void*)id);
/* FIXME: not quite sure a zero timeout is a good thing to check whether a thread is
* stil alived or not */
waitResult = WaitForSingleObject(irpThread, 0);
if (waitResult == WAIT_OBJECT_0)
{
/* terminating thread */
/* WLog_Print(serial->log, WLOG_DEBUG, "IRP thread with CompletionId=%"PRIuz"
* naturally died", id); */
CloseHandle(irpThread);
ListDictionary_Remove(serial->IrpThreads, (void*)id);
serial->IrpThreadToBeTerminatedCount--;
}
else if (waitResult != WAIT_TIMEOUT)
{
/* unexpected thread state */
WLog_Print(serial->log, WLOG_WARN,
"WaitForSingleObject, got an unexpected result=0x%" PRIX32 "\n",
waitResult);
assert(FALSE);
}
/* pending thread (but not yet terminating thread) if waitResult == WAIT_TIMEOUT */
}
if (serial->IrpThreadToBeTerminatedCount > 0)
{
WLog_Print(serial->log, WLOG_DEBUG, "%" PRIu32 " IRP thread(s) not yet terminated",
serial->IrpThreadToBeTerminatedCount);
Sleep(1); /* 1 ms */
}
free(ids);
}
LeaveCriticalSection(&serial->TerminatingIrpThreadsLock);
/* NB: At this point and thanks to the synchronization we're
* sure that the incoming IRP uses well a recycled
* CompletionId or the server sent again an IRP already posted
* which didn't get yet a response (this later server behavior
* at least observed with IOCTL_SERIAL_WAIT_ON_MASK and
* mstsc.exe).
*
* FIXME: behavior documented somewhere? behavior not yet
* observed with FreeRDP).
*/
key = irp->CompletionId;
previousIrpThread = ListDictionary_GetItemValue(serial->IrpThreads, (void*)key);
if (previousIrpThread)
{
/* Thread still alived <=> Request still pending */
WLog_Print(serial->log, WLOG_DEBUG,
"IRP recall: IRP with the CompletionId=%" PRIu32 " not yet completed!",
irp->CompletionId);
assert(FALSE); /* unimplemented */
/* TODO: asserts that previousIrpThread handles well
* the same request by checking more details. Need an
* access to the IRP object used by previousIrpThread
*/
/* TODO: taking over the pending IRP or sending a kind
* of wake up signal to accelerate the pending
* request
*
* To be considered:
* if (IoControlCode == IOCTL_SERIAL_WAIT_ON_MASK) {
* pComm->PendingEvents |= SERIAL_EV_FREERDP_*;
* }
*/
irp->Discard(irp);
return;
}
if (ListDictionary_Count(serial->IrpThreads) >= MAX_IRP_THREADS)
{
WLog_Print(serial->log, WLOG_WARN,
"Number of IRP threads threshold reached: %d, keep on anyway",
ListDictionary_Count(serial->IrpThreads));
assert(FALSE); /* unimplemented */
/* TODO: MAX_IRP_THREADS has been thought to avoid a
* flooding of pending requests. Use
* WaitForMultipleObjects() when available in winpr
* for threads.
*/
}
/* error_handle to be used ... */
data = (IRP_THREAD_DATA*)calloc(1, sizeof(IRP_THREAD_DATA));
if (data == NULL)
{
WLog_Print(serial->log, WLOG_WARN, "Could not allocate a new IRP_THREAD_DATA.");
goto error_handle;
}
data->serial = serial;
data->irp = irp;
/* data freed by irp_thread_func */
irpThread = CreateThread(NULL, 0, irp_thread_func, (void*)data, 0, NULL);
if (irpThread == INVALID_HANDLE_VALUE)
{
WLog_Print(serial->log, WLOG_WARN, "Could not allocate a new IRP thread.");
goto error_handle;
}
key = irp->CompletionId;
if (!ListDictionary_Add(serial->IrpThreads, (void*)key, irpThread))
{
WLog_ERR(TAG, "ListDictionary_Add failed!");
goto error_handle;
}
return;
error_handle:
irp->IoStatus = STATUS_NO_MEMORY;
irp->Complete(irp);
free(data);
}
static void terminate_pending_irp_threads(SERIAL_DEVICE* serial)
{
ULONG_PTR* ids;
int i, nbIds;
nbIds = ListDictionary_GetKeys(serial->IrpThreads, &ids);
WLog_Print(serial->log, WLOG_DEBUG, "Terminating %d IRP thread(s)", nbIds);
for (i = 0; i < nbIds; i++)
{
HANDLE irpThread;
ULONG_PTR id = ids[i];
irpThread = ListDictionary_GetItemValue(serial->IrpThreads, (void*)id);
TerminateThread(irpThread, 0);
if (WaitForSingleObject(irpThread, INFINITE) == WAIT_FAILED)
{
WLog_ERR(TAG, "WaitForSingleObject failed!");
continue;
}
CloseHandle(irpThread);
WLog_Print(serial->log, WLOG_DEBUG, "IRP thread terminated, CompletionId %p", (void*)id);
}
ListDictionary_Clear(serial->IrpThreads);
free(ids);
}
static DWORD WINAPI serial_thread_func(LPVOID arg)
{
IRP* irp;
wMessage message;
SERIAL_DEVICE* serial = (SERIAL_DEVICE*)arg;
UINT error = CHANNEL_RC_OK;
while (1)
{
if (!MessageQueue_Wait(serial->MainIrpQueue))
{
WLog_ERR(TAG, "MessageQueue_Wait failed!");
error = ERROR_INTERNAL_ERROR;
break;
}
if (!MessageQueue_Peek(serial->MainIrpQueue, &message, TRUE))
{
WLog_ERR(TAG, "MessageQueue_Peek failed!");
error = ERROR_INTERNAL_ERROR;
break;
}
if (message.id == WMQ_QUIT)
{
terminate_pending_irp_threads(serial);
break;
}
irp = (IRP*)message.wParam;
if (irp)
create_irp_thread(serial, irp);
}
if (error && serial->rdpcontext)
setChannelError(serial->rdpcontext, error, "serial_thread_func reported an error");
ExitThread(error);
return error;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT serial_irp_request(DEVICE* device, IRP* irp)
{
SERIAL_DEVICE* serial = (SERIAL_DEVICE*)device;
assert(irp != NULL);
if (irp == NULL)
return CHANNEL_RC_OK;
/* NB: ENABLE_ASYNCIO is set, (MS-RDPEFS 2.2.2.7.2) this
* allows the server to send multiple simultaneous read or
* write requests.
*/
if (!MessageQueue_Post(serial->MainIrpQueue, NULL, 0, (void*)irp, NULL))
{
WLog_ERR(TAG, "MessageQueue_Post failed!");
return ERROR_INTERNAL_ERROR;
}
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT serial_free(DEVICE* device)
{
UINT error;
SERIAL_DEVICE* serial = (SERIAL_DEVICE*)device;
WLog_Print(serial->log, WLOG_DEBUG, "freeing");
MessageQueue_PostQuit(serial->MainIrpQueue, 0);
if (WaitForSingleObject(serial->MainThread, INFINITE) == WAIT_FAILED)
{
error = GetLastError();
WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "!", error);
return error;
}
CloseHandle(serial->MainThread);
if (serial->hComm)
CloseHandle(serial->hComm);
/* Clean up resources */
Stream_Free(serial->device.data, TRUE);
MessageQueue_Free(serial->MainIrpQueue);
ListDictionary_Free(serial->IrpThreads);
DeleteCriticalSection(&serial->TerminatingIrpThreadsLock);
free(serial);
return CHANNEL_RC_OK;
}
#endif /* __linux__ */
#ifdef BUILTIN_CHANNELS
#define DeviceServiceEntry serial_DeviceServiceEntry
#else
#define DeviceServiceEntry FREERDP_API DeviceServiceEntry
#endif
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
UINT DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints)
{
char* name;
char* path;
char* driver;
RDPDR_SERIAL* device;
#if defined __linux__ && !defined ANDROID
size_t i, len;
SERIAL_DEVICE* serial;
#endif /* __linux__ */
UINT error = CHANNEL_RC_OK;
device = (RDPDR_SERIAL*)pEntryPoints->device;
name = device->Name;
path = device->Path;
driver = device->Driver;
if (!name || (name[0] == '*'))
{
/* TODO: implement auto detection of serial ports */
return CHANNEL_RC_OK;
}
if ((name && name[0]) && (path && path[0]))
{
wLog* log;
log = WLog_Get("com.freerdp.channel.serial.client");
WLog_Print(log, WLOG_DEBUG, "initializing");
#ifndef __linux__ /* to be removed */
WLog_Print(log, WLOG_WARN, "Serial ports redirection not supported on this platform.");
return CHANNEL_RC_INITIALIZATION_ERROR;
#else /* __linux __ */
WLog_Print(log, WLOG_DEBUG, "Defining %s as %s", name, path);
if (!DefineCommDevice(name /* eg: COM1 */, path /* eg: /dev/ttyS0 */))
{
DWORD status = GetLastError();
WLog_ERR(TAG, "DefineCommDevice failed with %08" PRIx32, status);
return ERROR_INTERNAL_ERROR;
}
serial = (SERIAL_DEVICE*)calloc(1, sizeof(SERIAL_DEVICE));
if (!serial)
{
WLog_ERR(TAG, "calloc failed!");
return CHANNEL_RC_NO_MEMORY;
}
serial->log = log;
serial->device.type = RDPDR_DTYP_SERIAL;
serial->device.name = name;
serial->device.IRPRequest = serial_irp_request;
serial->device.Free = serial_free;
serial->rdpcontext = pEntryPoints->rdpcontext;
len = strlen(name);
serial->device.data = Stream_New(NULL, len + 1);
if (!serial->device.data)
{
WLog_ERR(TAG, "calloc failed!");
error = CHANNEL_RC_NO_MEMORY;
goto error_out;
}
for (i = 0; i <= len; i++)
Stream_Write_UINT8(serial->device.data, name[i] < 0 ? '_' : name[i]);
if (driver != NULL)
{
if (_stricmp(driver, "Serial") == 0)
serial->ServerSerialDriverId = SerialDriverSerialSys;
else if (_stricmp(driver, "SerCx") == 0)
serial->ServerSerialDriverId = SerialDriverSerCxSys;
else if (_stricmp(driver, "SerCx2") == 0)
serial->ServerSerialDriverId = SerialDriverSerCx2Sys;
else
{
assert(FALSE);
WLog_Print(serial->log, WLOG_DEBUG,
"Unknown server's serial driver: %s. SerCx2 will be used", driver);
serial->ServerSerialDriverId = SerialDriverSerialSys;
}
}
else
{
/* default driver */
serial->ServerSerialDriverId = SerialDriverSerialSys;
}
if (device->Permissive != NULL)
{
if (_stricmp(device->Permissive, "permissive") == 0)
{
serial->permissive = TRUE;
}
else
{
WLog_Print(serial->log, WLOG_DEBUG, "Unknown flag: %s", device->Permissive);
assert(FALSE);
}
}
WLog_Print(serial->log, WLOG_DEBUG, "Server's serial driver: %s (id: %d)", driver,
serial->ServerSerialDriverId);
/* TODO: implement auto detection of the server's serial driver */
serial->MainIrpQueue = MessageQueue_New(NULL);
if (!serial->MainIrpQueue)
{
WLog_ERR(TAG, "MessageQueue_New failed!");
error = CHANNEL_RC_NO_MEMORY;
goto error_out;
}
/* IrpThreads content only modified by create_irp_thread() */
serial->IrpThreads = ListDictionary_New(FALSE);
if (!serial->IrpThreads)
{
WLog_ERR(TAG, "ListDictionary_New failed!");
error = CHANNEL_RC_NO_MEMORY;
goto error_out;
}
serial->IrpThreadToBeTerminatedCount = 0;
InitializeCriticalSection(&serial->TerminatingIrpThreadsLock);
if ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*)serial)))
{
WLog_ERR(TAG, "EntryPoints->RegisterDevice failed with error %" PRIu32 "!", error);
goto error_out;
}
if (!(serial->MainThread =
CreateThread(NULL, 0, serial_thread_func, (void*)serial, 0, NULL)))
{
WLog_ERR(TAG, "CreateThread failed!");
error = ERROR_INTERNAL_ERROR;
goto error_out;
}
#endif /* __linux __ */
}
return error;
error_out:
#ifdef __linux__ /* to be removed */
ListDictionary_Free(serial->IrpThreads);
MessageQueue_Free(serial->MainIrpQueue);
Stream_Free(serial->device.data, TRUE);
free(serial);
#endif /* __linux __ */
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3946_3 |
crossvul-cpp_data_bad_1282_1 | /*
* This file includes functions to transform a concrete syntax tree (CST) to
* an abstract syntax tree (AST). The main function is Ta27AST_FromNode().
*
*/
#include "Python.h"
#include "Python-ast.h"
#include "grammar.h"
#include "node.h"
#include "pyarena.h"
#include "ast.h"
#include "token.h"
#include "parsetok.h"
#include "graminit.h"
#include "unicodeobject.h"
#include <assert.h>
/* Data structure used internally */
struct compiling {
char *c_encoding; /* source encoding */
int c_future_unicode; /* __future__ unicode literals flag */
PyArena *c_arena; /* arena for allocating memeory */
const char *c_filename; /* filename */
};
static asdl_seq *seq_for_testlist(struct compiling *, const node *);
static expr_ty ast_for_expr(struct compiling *, const node *);
static stmt_ty ast_for_stmt(struct compiling *, const node *);
static asdl_seq *ast_for_suite(struct compiling *, const node *);
static asdl_seq *ast_for_exprlist(struct compiling *, const node *,
expr_context_ty);
static expr_ty ast_for_testlist(struct compiling *, const node *);
static stmt_ty ast_for_classdef(struct compiling *, const node *, asdl_seq *);
static expr_ty ast_for_testlist_comp(struct compiling *, const node *);
/* Note different signature for ast_for_call */
static expr_ty ast_for_call(struct compiling *, const node *, expr_ty);
static PyObject *parsenumber(struct compiling *, const char *);
static PyObject *parsestr(struct compiling *, const node *n, const char *);
static PyObject *parsestrplus(struct compiling *, const node *n);
static int Py_Py3kWarningFlag = 0;
static int Py_UnicodeFlag = 0;
extern long Ta27OS_strtol(char *str, char **ptr, int base);
#ifndef LINENO
#define LINENO(n) ((n)->n_lineno)
#endif
#define COMP_GENEXP 0
#define COMP_SETCOMP 1
static identifier
new_identifier(const char* n, PyArena *arena) {
PyObject* id = PyUnicode_InternFromString(n);
if (id != NULL)
PyArena_AddPyObject(arena, id);
return id;
}
#define NEW_IDENTIFIER(n) new_identifier(STR(n), c->c_arena)
static string
new_type_comment(const char *s, struct compiling *c)
{
return PyUnicode_DecodeUTF8(s, strlen(s), NULL);
}
#define NEW_TYPE_COMMENT(n) new_type_comment(STR(n), c)
/* This routine provides an invalid object for the syntax error.
The outermost routine must unpack this error and create the
proper object. We do this so that we don't have to pass
the filename to everything function.
XXX Maybe we should just pass the filename...
*/
static int
ast_error(const node *n, const char *errstr)
{
PyObject *u = Py_BuildValue("zi", errstr, LINENO(n));
if (!u)
return 0;
PyErr_SetObject(PyExc_SyntaxError, u);
Py_DECREF(u);
return 0;
}
static void
ast_error_finish(const char *filename)
{
PyObject *type, *value, *tback, *errstr, *loc, *tmp;
long lineno;
assert(PyErr_Occurred());
if (!PyErr_ExceptionMatches(PyExc_SyntaxError))
return;
PyErr_Fetch(&type, &value, &tback);
errstr = PyTuple_GetItem(value, 0);
if (!errstr)
return;
Py_INCREF(errstr);
lineno = PyLong_AsLong(PyTuple_GetItem(value, 1));
if (lineno == -1) {
Py_DECREF(errstr);
return;
}
Py_DECREF(value);
loc = PyErr_ProgramText(filename, lineno);
if (!loc) {
Py_INCREF(Py_None);
loc = Py_None;
}
tmp = Py_BuildValue("(zlOO)", filename, lineno, Py_None, loc);
Py_DECREF(loc);
if (!tmp) {
Py_DECREF(errstr);
return;
}
value = PyTuple_Pack(2, errstr, tmp);
Py_DECREF(errstr);
Py_DECREF(tmp);
if (!value)
return;
PyErr_Restore(type, value, tback);
}
static int
ast_warn(struct compiling *c, const node *n, char *msg)
{
if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename, LINENO(n),
NULL, NULL) < 0) {
/* if -Werr, change it to a SyntaxError */
if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_SyntaxWarning))
ast_error(n, msg);
return 0;
}
return 1;
}
static int
forbidden_check(struct compiling *c, const node *n, const char *x)
{
if (!strcmp(x, "None"))
return ast_error(n, "cannot assign to None");
if (!strcmp(x, "__debug__"))
return ast_error(n, "cannot assign to __debug__");
if (Py_Py3kWarningFlag) {
if (!(strcmp(x, "True") && strcmp(x, "False")) &&
!ast_warn(c, n, "assignment to True or False is forbidden in 3.x"))
return 0;
if (!strcmp(x, "nonlocal") &&
!ast_warn(c, n, "nonlocal is a keyword in 3.x"))
return 0;
}
return 1;
}
/* num_stmts() returns number of contained statements.
Use this routine to determine how big a sequence is needed for
the statements in a parse tree. Its raison d'etre is this bit of
grammar:
stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
A simple_stmt can contain multiple small_stmt elements joined
by semicolons. If the arg is a simple_stmt, the number of
small_stmt elements is returned.
*/
static int
num_stmts(const node *n)
{
int i, l;
node *ch;
switch (TYPE(n)) {
case single_input:
if (TYPE(CHILD(n, 0)) == NEWLINE)
return 0;
else
return num_stmts(CHILD(n, 0));
case file_input:
l = 0;
for (i = 0; i < NCH(n); i++) {
ch = CHILD(n, i);
if (TYPE(ch) == stmt)
l += num_stmts(ch);
}
return l;
case stmt:
return num_stmts(CHILD(n, 0));
case compound_stmt:
return 1;
case simple_stmt:
return NCH(n) / 2; /* Divide by 2 to remove count of semi-colons */
case suite:
/* suite: simple_stmt | NEWLINE [TYPE_COMMENT NEWLINE] INDENT stmt+ DEDENT */
if (NCH(n) == 1)
return num_stmts(CHILD(n, 0));
else {
i = 2;
l = 0;
if (TYPE(CHILD(n, 1)) == TYPE_COMMENT)
i += 2;
for (; i < (NCH(n) - 1); i++)
l += num_stmts(CHILD(n, i));
return l;
}
default: {
char buf[128];
sprintf(buf, "Non-statement found: %d %d",
TYPE(n), NCH(n));
Py_FatalError(buf);
}
}
assert(0);
return 0;
}
/* Transform the CST rooted at node * to the appropriate AST
*/
mod_ty
Ta27AST_FromNode(const node *n, PyCompilerFlags *flags, const char *filename,
PyArena *arena)
{
int i, j, k, num;
asdl_seq *stmts = NULL;
asdl_seq *type_ignores = NULL;
stmt_ty s;
node *ch;
struct compiling c;
asdl_seq *argtypes = NULL;
expr_ty ret, arg;
if (flags && flags->cf_flags & PyCF_SOURCE_IS_UTF8) {
c.c_encoding = "utf-8";
if (TYPE(n) == encoding_decl) {
ast_error(n, "encoding declaration in Unicode string");
goto error;
}
} else if (TYPE(n) == encoding_decl) {
c.c_encoding = STR(n);
n = CHILD(n, 0);
} else {
c.c_encoding = NULL;
}
c.c_future_unicode = flags && flags->cf_flags & CO_FUTURE_UNICODE_LITERALS;
c.c_arena = arena;
c.c_filename = filename;
k = 0;
switch (TYPE(n)) {
case file_input:
stmts = asdl_seq_new(num_stmts(n), arena);
if (!stmts)
return NULL;
for (i = 0; i < NCH(n) - 1; i++) {
ch = CHILD(n, i);
if (TYPE(ch) == NEWLINE)
continue;
REQ(ch, stmt);
num = num_stmts(ch);
if (num == 1) {
s = ast_for_stmt(&c, ch);
if (!s)
goto error;
asdl_seq_SET(stmts, k++, s);
}
else {
ch = CHILD(ch, 0);
REQ(ch, simple_stmt);
for (j = 0; j < num; j++) {
s = ast_for_stmt(&c, CHILD(ch, j * 2));
if (!s)
goto error;
asdl_seq_SET(stmts, k++, s);
}
}
}
/* Type ignores are stored under the ENDMARKER in file_input. */
ch = CHILD(n, NCH(n) - 1);
REQ(ch, ENDMARKER);
num = NCH(ch);
type_ignores = _Py_asdl_seq_new(num, arena);
if (!type_ignores)
goto error;
for (i = 0; i < num; i++) {
type_ignore_ty ti = TypeIgnore(LINENO(CHILD(ch, i)), arena);
if (!ti)
goto error;
asdl_seq_SET(type_ignores, i, ti);
}
return Module(stmts, type_ignores, arena);
case eval_input: {
expr_ty testlist_ast;
/* XXX Why not comp_for here? */
testlist_ast = ast_for_testlist(&c, CHILD(n, 0));
if (!testlist_ast)
goto error;
return Expression(testlist_ast, arena);
}
case single_input:
if (TYPE(CHILD(n, 0)) == NEWLINE) {
stmts = asdl_seq_new(1, arena);
if (!stmts)
goto error;
asdl_seq_SET(stmts, 0, Pass(n->n_lineno, n->n_col_offset,
arena));
if (!asdl_seq_GET(stmts, 0))
goto error;
return Interactive(stmts, arena);
}
else {
n = CHILD(n, 0);
num = num_stmts(n);
stmts = asdl_seq_new(num, arena);
if (!stmts)
goto error;
if (num == 1) {
s = ast_for_stmt(&c, n);
if (!s)
goto error;
asdl_seq_SET(stmts, 0, s);
}
else {
/* Only a simple_stmt can contain multiple statements. */
REQ(n, simple_stmt);
for (i = 0; i < NCH(n); i += 2) {
if (TYPE(CHILD(n, i)) == NEWLINE)
break;
s = ast_for_stmt(&c, CHILD(n, i));
if (!s)
goto error;
asdl_seq_SET(stmts, i / 2, s);
}
}
return Interactive(stmts, arena);
}
case func_type_input:
n = CHILD(n, 0);
REQ(n, func_type);
if (TYPE(CHILD(n, 1)) == typelist) {
ch = CHILD(n, 1);
/* this is overly permissive -- we don't pay any attention to
* stars on the args -- just parse them into an ordered list */
num = 0;
for (i = 0; i < NCH(ch); i++) {
if (TYPE(CHILD(ch, i)) == test)
num++;
}
argtypes = _Py_asdl_seq_new(num, arena);
j = 0;
for (i = 0; i < NCH(ch); i++) {
if (TYPE(CHILD(ch, i)) == test) {
arg = ast_for_expr(&c, CHILD(ch, i));
if (!arg)
goto error;
asdl_seq_SET(argtypes, j++, arg);
}
}
}
else
argtypes = _Py_asdl_seq_new(0, arena);
ret = ast_for_expr(&c, CHILD(n, NCH(n) - 1));
if (!ret)
goto error;
return FunctionType(argtypes, ret, arena);
default:
PyErr_Format(PyExc_SystemError,
"invalid node %d for Ta27AST_FromNode", TYPE(n));
goto error;
}
error:
ast_error_finish(filename);
return NULL;
}
/* Return the AST repr. of the operator represented as syntax (|, ^, etc.)
*/
static operator_ty
get_operator(const node *n)
{
switch (TYPE(n)) {
case VBAR:
return BitOr;
case CIRCUMFLEX:
return BitXor;
case AMPER:
return BitAnd;
case LEFTSHIFT:
return LShift;
case RIGHTSHIFT:
return RShift;
case PLUS:
return Add;
case MINUS:
return Sub;
case STAR:
return Mult;
case SLASH:
return Div;
case DOUBLESLASH:
return FloorDiv;
case PERCENT:
return Mod;
default:
return (operator_ty)0;
}
}
/* Set the context ctx for expr_ty e, recursively traversing e.
Only sets context for expr kinds that "can appear in assignment context"
(according to ../Parser/Python.asdl). For other expr kinds, it sets
an appropriate syntax error and returns false.
*/
static int
set_context(struct compiling *c, expr_ty e, expr_context_ty ctx, const node *n)
{
asdl_seq *s = NULL;
/* If a particular expression type can't be used for assign / delete,
set expr_name to its name and an error message will be generated.
*/
const char* expr_name = NULL;
/* The ast defines augmented store and load contexts, but the
implementation here doesn't actually use them. The code may be
a little more complex than necessary as a result. It also means
that expressions in an augmented assignment have a Store context.
Consider restructuring so that augmented assignment uses
set_context(), too.
*/
assert(ctx != AugStore && ctx != AugLoad);
switch (e->kind) {
case Attribute_kind:
if (ctx == Store && !forbidden_check(c, n,
PyUnicode_AsUTF8(e->v.Attribute.attr)))
return 0;
e->v.Attribute.ctx = ctx;
break;
case Subscript_kind:
e->v.Subscript.ctx = ctx;
break;
case Name_kind:
if (ctx == Store && !forbidden_check(c, n,
PyUnicode_AsUTF8(e->v.Name.id)))
return 0;
e->v.Name.ctx = ctx;
break;
case List_kind:
e->v.List.ctx = ctx;
s = e->v.List.elts;
break;
case Tuple_kind:
if (asdl_seq_LEN(e->v.Tuple.elts)) {
e->v.Tuple.ctx = ctx;
s = e->v.Tuple.elts;
}
else {
expr_name = "()";
}
break;
case Lambda_kind:
expr_name = "lambda";
break;
case Call_kind:
expr_name = "function call";
break;
case BoolOp_kind:
case BinOp_kind:
case UnaryOp_kind:
expr_name = "operator";
break;
case GeneratorExp_kind:
expr_name = "generator expression";
break;
case Yield_kind:
expr_name = "yield expression";
break;
case ListComp_kind:
expr_name = "list comprehension";
break;
case SetComp_kind:
expr_name = "set comprehension";
break;
case DictComp_kind:
expr_name = "dict comprehension";
break;
case Dict_kind:
case Set_kind:
case Num_kind:
case Str_kind:
expr_name = "literal";
break;
case Compare_kind:
expr_name = "comparison";
break;
case Repr_kind:
expr_name = "repr";
break;
case IfExp_kind:
expr_name = "conditional expression";
break;
default:
PyErr_Format(PyExc_SystemError,
"unexpected expression in assignment %d (line %d)",
e->kind, e->lineno);
return 0;
}
/* Check for error string set by switch */
if (expr_name) {
char buf[300];
PyOS_snprintf(buf, sizeof(buf),
"can't %s %s",
ctx == Store ? "assign to" : "delete",
expr_name);
return ast_error(n, buf);
}
/* If the LHS is a list or tuple, we need to set the assignment
context for all the contained elements.
*/
if (s) {
int i;
for (i = 0; i < asdl_seq_LEN(s); i++) {
if (!set_context(c, (expr_ty)asdl_seq_GET(s, i), ctx, n))
return 0;
}
}
return 1;
}
static operator_ty
ast_for_augassign(struct compiling *c, const node *n)
{
REQ(n, augassign);
n = CHILD(n, 0);
switch (STR(n)[0]) {
case '+':
return Add;
case '-':
return Sub;
case '/':
if (STR(n)[1] == '/')
return FloorDiv;
else
return Div;
case '%':
return Mod;
case '<':
return LShift;
case '>':
return RShift;
case '&':
return BitAnd;
case '^':
return BitXor;
case '|':
return BitOr;
case '*':
if (STR(n)[1] == '*')
return Pow;
else
return Mult;
default:
PyErr_Format(PyExc_SystemError, "invalid augassign: %s", STR(n));
return (operator_ty)0;
}
}
static cmpop_ty
ast_for_comp_op(struct compiling *c, const node *n)
{
/* comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'
|'is' 'not'
*/
REQ(n, comp_op);
if (NCH(n) == 1) {
n = CHILD(n, 0);
switch (TYPE(n)) {
case LESS:
return Lt;
case GREATER:
return Gt;
case EQEQUAL: /* == */
return Eq;
case LESSEQUAL:
return LtE;
case GREATEREQUAL:
return GtE;
case NOTEQUAL:
return NotEq;
case NAME:
if (strcmp(STR(n), "in") == 0)
return In;
if (strcmp(STR(n), "is") == 0)
return Is;
default:
PyErr_Format(PyExc_SystemError, "invalid comp_op: %s",
STR(n));
return (cmpop_ty)0;
}
}
else if (NCH(n) == 2) {
/* handle "not in" and "is not" */
switch (TYPE(CHILD(n, 0))) {
case NAME:
if (strcmp(STR(CHILD(n, 1)), "in") == 0)
return NotIn;
if (strcmp(STR(CHILD(n, 0)), "is") == 0)
return IsNot;
default:
PyErr_Format(PyExc_SystemError, "invalid comp_op: %s %s",
STR(CHILD(n, 0)), STR(CHILD(n, 1)));
return (cmpop_ty)0;
}
}
PyErr_Format(PyExc_SystemError, "invalid comp_op: has %d children",
NCH(n));
return (cmpop_ty)0;
}
static asdl_seq *
seq_for_testlist(struct compiling *c, const node *n)
{
/* testlist: test (',' test)* [','] */
asdl_seq *seq;
expr_ty expression;
int i;
assert(TYPE(n) == testlist ||
TYPE(n) == listmaker ||
TYPE(n) == testlist_comp ||
TYPE(n) == testlist_safe ||
TYPE(n) == testlist1);
seq = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!seq)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
assert(TYPE(CHILD(n, i)) == test || TYPE(CHILD(n, i)) == old_test);
expression = ast_for_expr(c, CHILD(n, i));
if (!expression)
return NULL;
assert(i / 2 < seq->size);
asdl_seq_SET(seq, i / 2, expression);
}
return seq;
}
static expr_ty
compiler_complex_args(struct compiling *c, const node *n)
{
int i, len = (NCH(n) + 1) / 2;
expr_ty result;
asdl_seq *args = asdl_seq_new(len, c->c_arena);
if (!args)
return NULL;
/* fpdef: NAME | '(' fplist ')'
fplist: fpdef (',' fpdef)* [',']
*/
REQ(n, fplist);
for (i = 0; i < len; i++) {
PyObject *arg_id;
const node *fpdef_node = CHILD(n, 2*i);
const node *child;
expr_ty arg;
set_name:
/* fpdef_node is either a NAME or an fplist */
child = CHILD(fpdef_node, 0);
if (TYPE(child) == NAME) {
if (!forbidden_check(c, n, STR(child)))
return NULL;
arg_id = NEW_IDENTIFIER(child);
if (!arg_id)
return NULL;
arg = Name(arg_id, Store, LINENO(child), child->n_col_offset,
c->c_arena);
}
else {
assert(TYPE(fpdef_node) == fpdef);
/* fpdef_node[0] is not a name, so it must be '(', get CHILD[1] */
child = CHILD(fpdef_node, 1);
assert(TYPE(child) == fplist);
/* NCH == 1 means we have (x), we need to elide the extra parens */
if (NCH(child) == 1) {
fpdef_node = CHILD(child, 0);
assert(TYPE(fpdef_node) == fpdef);
goto set_name;
}
arg = compiler_complex_args(c, child);
}
asdl_seq_SET(args, i, arg);
}
result = Tuple(args, Store, LINENO(n), n->n_col_offset, c->c_arena);
if (!set_context(c, result, Store, n))
return NULL;
return result;
}
/* Create AST for argument list. */
static arguments_ty
ast_for_arguments(struct compiling *c, const node *n)
{
/* parameters: '(' [varargslist] ')'
varargslist: ((fpdef ['=' test] ',' [TYPE_COMMENT])*
('*' NAME [',' [TYPE_COMMENT] '**' NAME] [TYPE_COMMENT] | '**' NAME [TYPE_COMMENT]) |
fpdef ['=' test] (',' [TYPE_COMMENT] fpdef ['=' test])* [','] [TYPE_COMMENT])
*/
int i, j, k, l, n_args = 0, n_all_args = 0, n_defaults = 0, found_default = 0;
asdl_seq *args, *defaults, *type_comments = NULL;
identifier vararg = NULL, kwarg = NULL;
node *ch;
if (TYPE(n) == parameters) {
if (NCH(n) == 2) /* () as argument list */
return arguments(NULL, NULL, NULL, NULL, NULL, c->c_arena);
n = CHILD(n, 1);
}
REQ(n, varargslist);
/* first count the number of normal args & defaults */
for (i = 0; i < NCH(n); i++) {
ch = CHILD(n, i);
if (TYPE(ch) == fpdef)
n_args++;
if (TYPE(ch) == EQUAL)
n_defaults++;
if (TYPE(ch) == STAR || TYPE(ch) == DOUBLESTAR)
n_all_args++;
}
n_all_args += n_args;
args = (n_args ? asdl_seq_new(n_args, c->c_arena) : NULL);
if (!args && n_args)
return NULL;
defaults = (n_defaults ? asdl_seq_new(n_defaults, c->c_arena) : NULL);
if (!defaults && n_defaults)
return NULL;
/* type_comments will be lazily initialized if needed. If there are no
per-argument type comments, it will remain NULL. Otherwise, it will be
an asdl_seq with length equal to the number of args (including varargs
and kwargs, if present) and with members set to the string of each arg's
type comment, if present, or NULL otherwise.
*/
/* fpdef: NAME | '(' fplist ')'
fplist: fpdef (',' fpdef)* [',']
*/
i = 0;
j = 0; /* index for defaults */
k = 0; /* index for args */
l = 0; /* index for type comments */
while (i < NCH(n)) {
ch = CHILD(n, i);
switch (TYPE(ch)) {
case fpdef: {
int complex_args = 0, parenthesized = 0;
handle_fpdef:
/* XXX Need to worry about checking if TYPE(CHILD(n, i+1)) is
anything other than EQUAL or a comma? */
/* XXX Should NCH(n) check be made a separate check? */
if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) {
expr_ty expression = ast_for_expr(c, CHILD(n, i + 2));
if (!expression)
return NULL;
assert(defaults != NULL);
asdl_seq_SET(defaults, j++, expression);
i += 2;
found_default = 1;
}
else if (found_default) {
/* def f((x)=4): pass should raise an error.
def f((x, (y))): pass will just incur the tuple unpacking warning. */
if (parenthesized && !complex_args) {
ast_error(n, "parenthesized arg with default");
return NULL;
}
ast_error(n,
"non-default argument follows default argument");
return NULL;
}
if (NCH(ch) == 3) {
ch = CHILD(ch, 1);
/* def foo((x)): is not complex, special case. */
if (NCH(ch) != 1) {
/* We have complex arguments, setup for unpacking. */
if (Py_Py3kWarningFlag && !ast_warn(c, ch,
"tuple parameter unpacking has been removed in 3.x"))
return NULL;
complex_args = 1;
asdl_seq_SET(args, k++, compiler_complex_args(c, ch));
if (!asdl_seq_GET(args, k-1))
return NULL;
} else {
/* def foo((x)): setup for checking NAME below. */
/* Loop because there can be many parens and tuple
unpacking mixed in. */
parenthesized = 1;
ch = CHILD(ch, 0);
assert(TYPE(ch) == fpdef);
goto handle_fpdef;
}
}
if (TYPE(CHILD(ch, 0)) == NAME) {
PyObject *id;
expr_ty name;
if (!forbidden_check(c, n, STR(CHILD(ch, 0))))
return NULL;
id = NEW_IDENTIFIER(CHILD(ch, 0));
if (!id)
return NULL;
name = Name(id, Param, LINENO(ch), ch->n_col_offset,
c->c_arena);
if (!name)
return NULL;
asdl_seq_SET(args, k++, name);
}
i += 1; /* the name */
if (i < NCH(n) && TYPE(CHILD(n, i)) == COMMA)
i += 1; /* the comma, if present */
if (parenthesized && Py_Py3kWarningFlag &&
!ast_warn(c, ch, "parenthesized argument names "
"are invalid in 3.x"))
return NULL;
break;
}
case STAR:
if (!forbidden_check(c, CHILD(n, i+1), STR(CHILD(n, i+1))))
return NULL;
vararg = NEW_IDENTIFIER(CHILD(n, i+1));
if (!vararg)
return NULL;
i += 2; /* the star and the name */
if (i < NCH(n) && TYPE(CHILD(n, i)) == COMMA)
i += 1; /* the comma, if present */
break;
case DOUBLESTAR:
if (!forbidden_check(c, CHILD(n, i+1), STR(CHILD(n, i+1))))
return NULL;
kwarg = NEW_IDENTIFIER(CHILD(n, i+1));
if (!kwarg)
return NULL;
i += 2; /* the double star and the name */
if (i < NCH(n) && TYPE(CHILD(n, i)) == COMMA)
i += 1; /* the comma, if present */
break;
case TYPE_COMMENT:
assert(l < k + !!vararg + !!kwarg);
if (!type_comments) {
/* lazily allocate the type_comments seq for perf reasons */
type_comments = asdl_seq_new(n_all_args, c->c_arena);
if (!type_comments)
return NULL;
}
while (l < k + !!vararg + !!kwarg - 1) {
asdl_seq_SET(type_comments, l++, NULL);
}
asdl_seq_SET(type_comments, l++, NEW_TYPE_COMMENT(ch));
i += 1;
break;
default:
PyErr_Format(PyExc_SystemError,
"unexpected node in varargslist: %d @ %d",
TYPE(ch), i);
return NULL;
}
}
if (type_comments) {
while (l < n_all_args) {
asdl_seq_SET(type_comments, l++, NULL);
}
}
return arguments(args, vararg, kwarg, defaults, type_comments, c->c_arena);
}
static expr_ty
ast_for_dotted_name(struct compiling *c, const node *n)
{
expr_ty e;
identifier id;
int lineno, col_offset;
int i;
REQ(n, dotted_name);
lineno = LINENO(n);
col_offset = n->n_col_offset;
id = NEW_IDENTIFIER(CHILD(n, 0));
if (!id)
return NULL;
e = Name(id, Load, lineno, col_offset, c->c_arena);
if (!e)
return NULL;
for (i = 2; i < NCH(n); i+=2) {
id = NEW_IDENTIFIER(CHILD(n, i));
if (!id)
return NULL;
e = Attribute(e, id, Load, lineno, col_offset, c->c_arena);
if (!e)
return NULL;
}
return e;
}
static expr_ty
ast_for_decorator(struct compiling *c, const node *n)
{
/* decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE */
expr_ty d = NULL;
expr_ty name_expr;
REQ(n, decorator);
REQ(CHILD(n, 0), AT);
REQ(RCHILD(n, -1), NEWLINE);
name_expr = ast_for_dotted_name(c, CHILD(n, 1));
if (!name_expr)
return NULL;
if (NCH(n) == 3) { /* No arguments */
d = name_expr;
name_expr = NULL;
}
else if (NCH(n) == 5) { /* Call with no arguments */
d = Call(name_expr, NULL, NULL, NULL, NULL, LINENO(n),
n->n_col_offset, c->c_arena);
if (!d)
return NULL;
name_expr = NULL;
}
else {
d = ast_for_call(c, CHILD(n, 3), name_expr);
if (!d)
return NULL;
name_expr = NULL;
}
return d;
}
static asdl_seq*
ast_for_decorators(struct compiling *c, const node *n)
{
asdl_seq* decorator_seq;
expr_ty d;
int i;
REQ(n, decorators);
decorator_seq = asdl_seq_new(NCH(n), c->c_arena);
if (!decorator_seq)
return NULL;
for (i = 0; i < NCH(n); i++) {
d = ast_for_decorator(c, CHILD(n, i));
if (!d)
return NULL;
asdl_seq_SET(decorator_seq, i, d);
}
return decorator_seq;
}
static stmt_ty
ast_for_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
{
/* funcdef: 'def' NAME parameters ':' [TYPE_COMMENT] suite */
identifier name;
arguments_ty args;
asdl_seq *body;
int name_i = 1;
node *tc;
string type_comment = NULL;
REQ(n, funcdef);
name = NEW_IDENTIFIER(CHILD(n, name_i));
if (!name)
return NULL;
else if (!forbidden_check(c, CHILD(n, name_i), STR(CHILD(n, name_i))))
return NULL;
args = ast_for_arguments(c, CHILD(n, name_i + 1));
if (!args)
return NULL;
if (TYPE(CHILD(n, name_i + 3)) == TYPE_COMMENT) {
type_comment = NEW_TYPE_COMMENT(CHILD(n, name_i + 3));
name_i += 1;
}
body = ast_for_suite(c, CHILD(n, name_i + 3));
if (!body)
return NULL;
if (!type_comment && NCH(CHILD(n, name_i + 3)) > 1) {
/* If the function doesn't have a type comment on the same line, check
* if the suite has a type comment in it. */
tc = CHILD(CHILD(n, name_i + 3), 1);
if (TYPE(tc) == TYPE_COMMENT)
type_comment = NEW_TYPE_COMMENT(tc);
}
return FunctionDef(name, args, body, decorator_seq, type_comment, LINENO(n),
n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_decorated(struct compiling *c, const node *n)
{
/* decorated: decorators (classdef | funcdef) */
stmt_ty thing = NULL;
asdl_seq *decorator_seq = NULL;
REQ(n, decorated);
decorator_seq = ast_for_decorators(c, CHILD(n, 0));
if (!decorator_seq)
return NULL;
assert(TYPE(CHILD(n, 1)) == funcdef ||
TYPE(CHILD(n, 1)) == classdef);
if (TYPE(CHILD(n, 1)) == funcdef) {
thing = ast_for_funcdef(c, CHILD(n, 1), decorator_seq);
} else if (TYPE(CHILD(n, 1)) == classdef) {
thing = ast_for_classdef(c, CHILD(n, 1), decorator_seq);
}
/* we count the decorators in when talking about the class' or
function's line number */
if (thing) {
thing->lineno = LINENO(n);
thing->col_offset = n->n_col_offset;
}
return thing;
}
static expr_ty
ast_for_lambdef(struct compiling *c, const node *n)
{
/* lambdef: 'lambda' [varargslist] ':' test */
arguments_ty args;
expr_ty expression;
if (NCH(n) == 3) {
args = arguments(NULL, NULL, NULL, NULL, NULL, c->c_arena);
if (!args)
return NULL;
expression = ast_for_expr(c, CHILD(n, 2));
if (!expression)
return NULL;
}
else {
args = ast_for_arguments(c, CHILD(n, 1));
if (!args)
return NULL;
expression = ast_for_expr(c, CHILD(n, 3));
if (!expression)
return NULL;
}
return Lambda(args, expression, LINENO(n), n->n_col_offset, c->c_arena);
}
static expr_ty
ast_for_ifexpr(struct compiling *c, const node *n)
{
/* test: or_test 'if' or_test 'else' test */
expr_ty expression, body, orelse;
assert(NCH(n) == 5);
body = ast_for_expr(c, CHILD(n, 0));
if (!body)
return NULL;
expression = ast_for_expr(c, CHILD(n, 2));
if (!expression)
return NULL;
orelse = ast_for_expr(c, CHILD(n, 4));
if (!orelse)
return NULL;
return IfExp(expression, body, orelse, LINENO(n), n->n_col_offset,
c->c_arena);
}
/* XXX(nnorwitz): the listcomp and genexpr code should be refactored
so there is only a single version. Possibly for loops can also re-use
the code.
*/
/* Count the number of 'for' loop in a list comprehension.
Helper for ast_for_listcomp().
*/
static int
count_list_fors(struct compiling *c, const node *n)
{
int n_fors = 0;
node *ch = CHILD(n, 1);
count_list_for:
n_fors++;
REQ(ch, list_for);
if (NCH(ch) == 5)
ch = CHILD(ch, 4);
else
return n_fors;
count_list_iter:
REQ(ch, list_iter);
ch = CHILD(ch, 0);
if (TYPE(ch) == list_for)
goto count_list_for;
else if (TYPE(ch) == list_if) {
if (NCH(ch) == 3) {
ch = CHILD(ch, 2);
goto count_list_iter;
}
else
return n_fors;
}
/* Should never be reached */
PyErr_SetString(PyExc_SystemError, "logic error in count_list_fors");
return -1;
}
/* Count the number of 'if' statements in a list comprehension.
Helper for ast_for_listcomp().
*/
static int
count_list_ifs(struct compiling *c, const node *n)
{
int n_ifs = 0;
count_list_iter:
REQ(n, list_iter);
if (TYPE(CHILD(n, 0)) == list_for)
return n_ifs;
n = CHILD(n, 0);
REQ(n, list_if);
n_ifs++;
if (NCH(n) == 2)
return n_ifs;
n = CHILD(n, 2);
goto count_list_iter;
}
static expr_ty
ast_for_listcomp(struct compiling *c, const node *n)
{
/* listmaker: test ( list_for | (',' test)* [','] )
list_for: 'for' exprlist 'in' testlist_safe [list_iter]
list_iter: list_for | list_if
list_if: 'if' test [list_iter]
testlist_safe: test [(',' test)+ [',']]
*/
expr_ty elt, first;
asdl_seq *listcomps;
int i, n_fors;
node *ch;
REQ(n, listmaker);
assert(NCH(n) > 1);
elt = ast_for_expr(c, CHILD(n, 0));
if (!elt)
return NULL;
n_fors = count_list_fors(c, n);
if (n_fors == -1)
return NULL;
listcomps = asdl_seq_new(n_fors, c->c_arena);
if (!listcomps)
return NULL;
ch = CHILD(n, 1);
for (i = 0; i < n_fors; i++) {
comprehension_ty lc;
asdl_seq *t;
expr_ty expression;
node *for_ch;
REQ(ch, list_for);
for_ch = CHILD(ch, 1);
t = ast_for_exprlist(c, for_ch, Store);
if (!t)
return NULL;
expression = ast_for_testlist(c, CHILD(ch, 3));
if (!expression)
return NULL;
/* Check the # of children rather than the length of t, since
[x for x, in ... ] has 1 element in t, but still requires a Tuple.
*/
first = (expr_ty)asdl_seq_GET(t, 0);
if (NCH(for_ch) == 1)
lc = comprehension(first, expression, NULL, c->c_arena);
else
lc = comprehension(Tuple(t, Store, first->lineno, first->col_offset,
c->c_arena),
expression, NULL, c->c_arena);
if (!lc)
return NULL;
if (NCH(ch) == 5) {
int j, n_ifs;
asdl_seq *ifs;
expr_ty list_for_expr;
ch = CHILD(ch, 4);
n_ifs = count_list_ifs(c, ch);
if (n_ifs == -1)
return NULL;
ifs = asdl_seq_new(n_ifs, c->c_arena);
if (!ifs)
return NULL;
for (j = 0; j < n_ifs; j++) {
REQ(ch, list_iter);
ch = CHILD(ch, 0);
REQ(ch, list_if);
list_for_expr = ast_for_expr(c, CHILD(ch, 1));
if (!list_for_expr)
return NULL;
asdl_seq_SET(ifs, j, list_for_expr);
if (NCH(ch) == 3)
ch = CHILD(ch, 2);
}
/* on exit, must guarantee that ch is a list_for */
if (TYPE(ch) == list_iter)
ch = CHILD(ch, 0);
lc->ifs = ifs;
}
asdl_seq_SET(listcomps, i, lc);
}
return ListComp(elt, listcomps, LINENO(n), n->n_col_offset, c->c_arena);
}
/*
Count the number of 'for' loops in a comprehension.
Helper for ast_for_comprehension().
*/
static int
count_comp_fors(struct compiling *c, const node *n)
{
int n_fors = 0;
count_comp_for:
n_fors++;
REQ(n, comp_for);
if (NCH(n) == 5)
n = CHILD(n, 4);
else
return n_fors;
count_comp_iter:
REQ(n, comp_iter);
n = CHILD(n, 0);
if (TYPE(n) == comp_for)
goto count_comp_for;
else if (TYPE(n) == comp_if) {
if (NCH(n) == 3) {
n = CHILD(n, 2);
goto count_comp_iter;
}
else
return n_fors;
}
/* Should never be reached */
PyErr_SetString(PyExc_SystemError,
"logic error in count_comp_fors");
return -1;
}
/* Count the number of 'if' statements in a comprehension.
Helper for ast_for_comprehension().
*/
static int
count_comp_ifs(struct compiling *c, const node *n)
{
int n_ifs = 0;
while (1) {
REQ(n, comp_iter);
if (TYPE(CHILD(n, 0)) == comp_for)
return n_ifs;
n = CHILD(n, 0);
REQ(n, comp_if);
n_ifs++;
if (NCH(n) == 2)
return n_ifs;
n = CHILD(n, 2);
}
}
static asdl_seq *
ast_for_comprehension(struct compiling *c, const node *n)
{
int i, n_fors;
asdl_seq *comps;
n_fors = count_comp_fors(c, n);
if (n_fors == -1)
return NULL;
comps = asdl_seq_new(n_fors, c->c_arena);
if (!comps)
return NULL;
for (i = 0; i < n_fors; i++) {
comprehension_ty comp;
asdl_seq *t;
expr_ty expression, first;
node *for_ch;
REQ(n, comp_for);
for_ch = CHILD(n, 1);
t = ast_for_exprlist(c, for_ch, Store);
if (!t)
return NULL;
expression = ast_for_expr(c, CHILD(n, 3));
if (!expression)
return NULL;
/* Check the # of children rather than the length of t, since
(x for x, in ...) has 1 element in t, but still requires a Tuple. */
first = (expr_ty)asdl_seq_GET(t, 0);
if (NCH(for_ch) == 1)
comp = comprehension(first, expression, NULL, c->c_arena);
else
comp = comprehension(Tuple(t, Store, first->lineno, first->col_offset,
c->c_arena),
expression, NULL, c->c_arena);
if (!comp)
return NULL;
if (NCH(n) == 5) {
int j, n_ifs;
asdl_seq *ifs;
n = CHILD(n, 4);
n_ifs = count_comp_ifs(c, n);
if (n_ifs == -1)
return NULL;
ifs = asdl_seq_new(n_ifs, c->c_arena);
if (!ifs)
return NULL;
for (j = 0; j < n_ifs; j++) {
REQ(n, comp_iter);
n = CHILD(n, 0);
REQ(n, comp_if);
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
asdl_seq_SET(ifs, j, expression);
if (NCH(n) == 3)
n = CHILD(n, 2);
}
/* on exit, must guarantee that n is a comp_for */
if (TYPE(n) == comp_iter)
n = CHILD(n, 0);
comp->ifs = ifs;
}
asdl_seq_SET(comps, i, comp);
}
return comps;
}
static expr_ty
ast_for_itercomp(struct compiling *c, const node *n, int type)
{
expr_ty elt;
asdl_seq *comps;
assert(NCH(n) > 1);
elt = ast_for_expr(c, CHILD(n, 0));
if (!elt)
return NULL;
comps = ast_for_comprehension(c, CHILD(n, 1));
if (!comps)
return NULL;
if (type == COMP_GENEXP)
return GeneratorExp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
else if (type == COMP_SETCOMP)
return SetComp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
else
/* Should never happen */
return NULL;
}
static expr_ty
ast_for_dictcomp(struct compiling *c, const node *n)
{
expr_ty key, value;
asdl_seq *comps;
assert(NCH(n) > 3);
REQ(CHILD(n, 1), COLON);
key = ast_for_expr(c, CHILD(n, 0));
if (!key)
return NULL;
value = ast_for_expr(c, CHILD(n, 2));
if (!value)
return NULL;
comps = ast_for_comprehension(c, CHILD(n, 3));
if (!comps)
return NULL;
return DictComp(key, value, comps, LINENO(n), n->n_col_offset, c->c_arena);
}
static expr_ty
ast_for_genexp(struct compiling *c, const node *n)
{
assert(TYPE(n) == (testlist_comp) || TYPE(n) == (argument));
return ast_for_itercomp(c, n, COMP_GENEXP);
}
static expr_ty
ast_for_setcomp(struct compiling *c, const node *n)
{
assert(TYPE(n) == (dictorsetmaker));
return ast_for_itercomp(c, n, COMP_SETCOMP);
}
static expr_ty
ast_for_atom(struct compiling *c, const node *n)
{
/* atom: '(' [yield_expr|testlist_comp] ')' | '[' [listmaker] ']'
| '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+
*/
node *ch = CHILD(n, 0);
switch (TYPE(ch)) {
case NAME: {
/* All names start in Load context, but may later be
changed. */
PyObject *name = NEW_IDENTIFIER(ch);
if (!name)
return NULL;
return Name(name, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
case STRING: {
PyObject *kind, *str = parsestrplus(c, n);
const char *raw, *s = STR(CHILD(n, 0));
int quote = Py_CHARMASK(*s);
/* currently Python allows up to 2 string modifiers */
char *ch, s_kind[3] = {0, 0, 0};
ch = s_kind;
raw = s;
while (*raw && *raw != '\'' && *raw != '"') {
*ch++ = *raw++;
}
kind = PyUnicode_FromString(s_kind);
if (!kind) {
return NULL;
}
if (!str) {
#ifdef Py_USING_UNICODE
if (PyErr_ExceptionMatches(PyExc_UnicodeError)){
PyObject *type, *value, *tback, *errstr;
PyErr_Fetch(&type, &value, &tback);
errstr = PyObject_Str(value);
if (errstr) {
char *s = "";
char buf[128];
s = _PyUnicode_AsString(errstr);
PyOS_snprintf(buf, sizeof(buf), "(unicode error) %s", s);
ast_error(n, buf);
Py_DECREF(errstr);
} else {
ast_error(n, "(unicode error) unknown error");
}
Py_DECREF(type);
Py_DECREF(value);
Py_XDECREF(tback);
}
#endif
return NULL;
}
PyArena_AddPyObject(c->c_arena, str);
return Str(str, kind, LINENO(n), n->n_col_offset, c->c_arena);
}
case NUMBER: {
PyObject *pynum = parsenumber(c, STR(ch));
if (!pynum)
return NULL;
PyArena_AddPyObject(c->c_arena, pynum);
return Num(pynum, LINENO(n), n->n_col_offset, c->c_arena);
}
case LPAR: /* some parenthesized expressions */
ch = CHILD(n, 1);
if (TYPE(ch) == RPAR)
return Tuple(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena);
if (TYPE(ch) == yield_expr)
return ast_for_expr(c, ch);
return ast_for_testlist_comp(c, ch);
case LSQB: /* list (or list comprehension) */
ch = CHILD(n, 1);
if (TYPE(ch) == RSQB)
return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena);
REQ(ch, listmaker);
if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) {
asdl_seq *elts = seq_for_testlist(c, ch);
if (!elts)
return NULL;
return List(elts, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
else
return ast_for_listcomp(c, ch);
case LBRACE: {
/* dictorsetmaker:
* (test ':' test (comp_for | (',' test ':' test)* [','])) |
* (test (comp_for | (',' test)* [',']))
*/
int i, size;
asdl_seq *keys, *values;
ch = CHILD(n, 1);
if (TYPE(ch) == RBRACE) {
/* it's an empty dict */
return Dict(NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena);
} else if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) {
/* it's a simple set */
asdl_seq *elts;
size = (NCH(ch) + 1) / 2; /* +1 in case no trailing comma */
elts = asdl_seq_new(size, c->c_arena);
if (!elts)
return NULL;
for (i = 0; i < NCH(ch); i += 2) {
expr_ty expression;
expression = ast_for_expr(c, CHILD(ch, i));
if (!expression)
return NULL;
asdl_seq_SET(elts, i / 2, expression);
}
return Set(elts, LINENO(n), n->n_col_offset, c->c_arena);
} else if (TYPE(CHILD(ch, 1)) == comp_for) {
/* it's a set comprehension */
return ast_for_setcomp(c, ch);
} else if (NCH(ch) > 3 && TYPE(CHILD(ch, 3)) == comp_for) {
return ast_for_dictcomp(c, ch);
} else {
/* it's a dict */
size = (NCH(ch) + 1) / 4; /* +1 in case no trailing comma */
keys = asdl_seq_new(size, c->c_arena);
if (!keys)
return NULL;
values = asdl_seq_new(size, c->c_arena);
if (!values)
return NULL;
for (i = 0; i < NCH(ch); i += 4) {
expr_ty expression;
expression = ast_for_expr(c, CHILD(ch, i));
if (!expression)
return NULL;
asdl_seq_SET(keys, i / 4, expression);
expression = ast_for_expr(c, CHILD(ch, i + 2));
if (!expression)
return NULL;
asdl_seq_SET(values, i / 4, expression);
}
return Dict(keys, values, LINENO(n), n->n_col_offset, c->c_arena);
}
}
case BACKQUOTE: { /* repr */
expr_ty expression;
if (Py_Py3kWarningFlag &&
!ast_warn(c, n, "backquote not supported in 3.x; use repr()"))
return NULL;
expression = ast_for_testlist(c, CHILD(n, 1));
if (!expression)
return NULL;
return Repr(expression, LINENO(n), n->n_col_offset, c->c_arena);
}
default:
PyErr_Format(PyExc_SystemError, "unhandled atom %d", TYPE(ch));
return NULL;
}
}
static slice_ty
ast_for_slice(struct compiling *c, const node *n)
{
node *ch;
expr_ty lower = NULL, upper = NULL, step = NULL;
REQ(n, subscript);
/*
subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop]
sliceop: ':' [test]
*/
ch = CHILD(n, 0);
if (TYPE(ch) == DOT)
return Ellipsis(c->c_arena);
if (NCH(n) == 1 && TYPE(ch) == test) {
/* 'step' variable hold no significance in terms of being used over
other vars */
step = ast_for_expr(c, ch);
if (!step)
return NULL;
return Index(step, c->c_arena);
}
if (TYPE(ch) == test) {
lower = ast_for_expr(c, ch);
if (!lower)
return NULL;
}
/* If there's an upper bound it's in the second or third position. */
if (TYPE(ch) == COLON) {
if (NCH(n) > 1) {
node *n2 = CHILD(n, 1);
if (TYPE(n2) == test) {
upper = ast_for_expr(c, n2);
if (!upper)
return NULL;
}
}
} else if (NCH(n) > 2) {
node *n2 = CHILD(n, 2);
if (TYPE(n2) == test) {
upper = ast_for_expr(c, n2);
if (!upper)
return NULL;
}
}
ch = CHILD(n, NCH(n) - 1);
if (TYPE(ch) == sliceop) {
if (NCH(ch) == 1) {
/*
This is an extended slice (ie "x[::]") with no expression in the
step field. We set this literally to "None" in order to
disambiguate it from x[:]. (The interpreter might have to call
__getslice__ for x[:], but it must call __getitem__ for x[::].)
*/
identifier none = new_identifier("None", c->c_arena);
if (!none)
return NULL;
ch = CHILD(ch, 0);
step = Name(none, Load, LINENO(ch), ch->n_col_offset, c->c_arena);
if (!step)
return NULL;
} else {
ch = CHILD(ch, 1);
if (TYPE(ch) == test) {
step = ast_for_expr(c, ch);
if (!step)
return NULL;
}
}
}
return Slice(lower, upper, step, c->c_arena);
}
static expr_ty
ast_for_binop(struct compiling *c, const node *n)
{
/* Must account for a sequence of expressions.
How should A op B op C by represented?
BinOp(BinOp(A, op, B), op, C).
*/
int i, nops;
expr_ty expr1, expr2, result;
operator_ty newoperator;
expr1 = ast_for_expr(c, CHILD(n, 0));
if (!expr1)
return NULL;
expr2 = ast_for_expr(c, CHILD(n, 2));
if (!expr2)
return NULL;
newoperator = get_operator(CHILD(n, 1));
if (!newoperator)
return NULL;
result = BinOp(expr1, newoperator, expr2, LINENO(n), n->n_col_offset,
c->c_arena);
if (!result)
return NULL;
nops = (NCH(n) - 1) / 2;
for (i = 1; i < nops; i++) {
expr_ty tmp_result, tmp;
const node* next_oper = CHILD(n, i * 2 + 1);
newoperator = get_operator(next_oper);
if (!newoperator)
return NULL;
tmp = ast_for_expr(c, CHILD(n, i * 2 + 2));
if (!tmp)
return NULL;
tmp_result = BinOp(result, newoperator, tmp,
LINENO(next_oper), next_oper->n_col_offset,
c->c_arena);
if (!tmp_result)
return NULL;
result = tmp_result;
}
return result;
}
static expr_ty
ast_for_trailer(struct compiling *c, const node *n, expr_ty left_expr)
{
/* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
subscriptlist: subscript (',' subscript)* [',']
subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop]
*/
REQ(n, trailer);
if (TYPE(CHILD(n, 0)) == LPAR) {
if (NCH(n) == 2)
return Call(left_expr, NULL, NULL, NULL, NULL, LINENO(n),
n->n_col_offset, c->c_arena);
else
return ast_for_call(c, CHILD(n, 1), left_expr);
}
else if (TYPE(CHILD(n, 0)) == DOT ) {
PyObject *attr_id = NEW_IDENTIFIER(CHILD(n, 1));
if (!attr_id)
return NULL;
return Attribute(left_expr, attr_id, Load,
LINENO(n), n->n_col_offset, c->c_arena);
}
else {
REQ(CHILD(n, 0), LSQB);
REQ(CHILD(n, 2), RSQB);
n = CHILD(n, 1);
if (NCH(n) == 1) {
slice_ty slc = ast_for_slice(c, CHILD(n, 0));
if (!slc)
return NULL;
return Subscript(left_expr, slc, Load, LINENO(n), n->n_col_offset,
c->c_arena);
}
else {
/* The grammar is ambiguous here. The ambiguity is resolved
by treating the sequence as a tuple literal if there are
no slice features.
*/
int j;
slice_ty slc;
expr_ty e;
bool simple = true;
asdl_seq *slices, *elts;
slices = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!slices)
return NULL;
for (j = 0; j < NCH(n); j += 2) {
slc = ast_for_slice(c, CHILD(n, j));
if (!slc)
return NULL;
if (slc->kind != Index_kind)
simple = false;
asdl_seq_SET(slices, j / 2, slc);
}
if (!simple) {
return Subscript(left_expr, ExtSlice(slices, c->c_arena),
Load, LINENO(n), n->n_col_offset, c->c_arena);
}
/* extract Index values and put them in a Tuple */
elts = asdl_seq_new(asdl_seq_LEN(slices), c->c_arena);
if (!elts)
return NULL;
for (j = 0; j < asdl_seq_LEN(slices); ++j) {
slc = (slice_ty)asdl_seq_GET(slices, j);
assert(slc->kind == Index_kind && slc->v.Index.value);
asdl_seq_SET(elts, j, slc->v.Index.value);
}
e = Tuple(elts, Load, LINENO(n), n->n_col_offset, c->c_arena);
if (!e)
return NULL;
return Subscript(left_expr, Index(e, c->c_arena),
Load, LINENO(n), n->n_col_offset, c->c_arena);
}
}
}
static expr_ty
ast_for_factor(struct compiling *c, const node *n)
{
node *pfactor, *ppower, *patom, *pnum;
expr_ty expression;
/* If the unary - operator is applied to a constant, don't generate
a UNARY_NEGATIVE opcode. Just store the approriate value as a
constant. The peephole optimizer already does something like
this but it doesn't handle the case where the constant is
(sys.maxint - 1). In that case, we want a PyIntObject, not a
PyLongObject.
*/
if (TYPE(CHILD(n, 0)) == MINUS &&
NCH(n) == 2 &&
TYPE((pfactor = CHILD(n, 1))) == factor &&
NCH(pfactor) == 1 &&
TYPE((ppower = CHILD(pfactor, 0))) == power &&
NCH(ppower) == 1 &&
TYPE((patom = CHILD(ppower, 0))) == atom &&
TYPE((pnum = CHILD(patom, 0))) == NUMBER) {
PyObject *pynum;
char *s = PyObject_MALLOC(strlen(STR(pnum)) + 2);
if (s == NULL)
return NULL;
s[0] = '-';
strcpy(s + 1, STR(pnum));
pynum = parsenumber(c, s);
PyObject_FREE(s);
if (!pynum)
return NULL;
PyArena_AddPyObject(c->c_arena, pynum);
return Num(pynum, LINENO(n), n->n_col_offset, c->c_arena);
}
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
switch (TYPE(CHILD(n, 0))) {
case PLUS:
return UnaryOp(UAdd, expression, LINENO(n), n->n_col_offset,
c->c_arena);
case MINUS:
return UnaryOp(USub, expression, LINENO(n), n->n_col_offset,
c->c_arena);
case TILDE:
return UnaryOp(Invert, expression, LINENO(n),
n->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError, "unhandled factor: %d",
TYPE(CHILD(n, 0)));
return NULL;
}
static expr_ty
ast_for_power(struct compiling *c, const node *n)
{
/* power: atom trailer* ('**' factor)*
*/
int i;
expr_ty e, tmp;
REQ(n, power);
e = ast_for_atom(c, CHILD(n, 0));
if (!e)
return NULL;
if (NCH(n) == 1)
return e;
for (i = 1; i < NCH(n); i++) {
node *ch = CHILD(n, i);
if (TYPE(ch) != trailer)
break;
tmp = ast_for_trailer(c, ch, e);
if (!tmp)
return NULL;
tmp->lineno = e->lineno;
tmp->col_offset = e->col_offset;
e = tmp;
}
if (TYPE(CHILD(n, NCH(n) - 1)) == factor) {
expr_ty f = ast_for_expr(c, CHILD(n, NCH(n) - 1));
if (!f)
return NULL;
tmp = BinOp(e, Pow, f, LINENO(n), n->n_col_offset, c->c_arena);
if (!tmp)
return NULL;
e = tmp;
}
return e;
}
/* Do not name a variable 'expr'! Will cause a compile error.
*/
static expr_ty
ast_for_expr(struct compiling *c, const node *n)
{
/* handle the full range of simple expressions
test: or_test ['if' or_test 'else' test] | lambdef
or_test: and_test ('or' and_test)*
and_test: not_test ('and' not_test)*
not_test: 'not' not_test | comparison
comparison: expr (comp_op expr)*
expr: xor_expr ('|' xor_expr)*
xor_expr: and_expr ('^' and_expr)*
and_expr: shift_expr ('&' shift_expr)*
shift_expr: arith_expr (('<<'|'>>') arith_expr)*
arith_expr: term (('+'|'-') term)*
term: factor (('*'|'/'|'%'|'//') factor)*
factor: ('+'|'-'|'~') factor | power
power: atom trailer* ('**' factor)*
As well as modified versions that exist for backward compatibility,
to explicitly allow:
[ x for x in lambda: 0, lambda: 1 ]
(which would be ambiguous without these extra rules)
old_test: or_test | old_lambdef
old_lambdef: 'lambda' [vararglist] ':' old_test
*/
asdl_seq *seq;
int i;
loop:
switch (TYPE(n)) {
case test:
case old_test:
if (TYPE(CHILD(n, 0)) == lambdef ||
TYPE(CHILD(n, 0)) == old_lambdef)
return ast_for_lambdef(c, CHILD(n, 0));
else if (NCH(n) > 1)
return ast_for_ifexpr(c, n);
/* Fallthrough */
case or_test:
case and_test:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
seq = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!seq)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
expr_ty e = ast_for_expr(c, CHILD(n, i));
if (!e)
return NULL;
asdl_seq_SET(seq, i / 2, e);
}
if (!strcmp(STR(CHILD(n, 1)), "and"))
return BoolOp(And, seq, LINENO(n), n->n_col_offset,
c->c_arena);
assert(!strcmp(STR(CHILD(n, 1)), "or"));
return BoolOp(Or, seq, LINENO(n), n->n_col_offset, c->c_arena);
case not_test:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
else {
expr_ty expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
return UnaryOp(Not, expression, LINENO(n), n->n_col_offset,
c->c_arena);
}
case comparison:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
else {
expr_ty expression;
asdl_int_seq *ops;
asdl_seq *cmps;
ops = asdl_int_seq_new(NCH(n) / 2, c->c_arena);
if (!ops)
return NULL;
cmps = asdl_seq_new(NCH(n) / 2, c->c_arena);
if (!cmps) {
return NULL;
}
for (i = 1; i < NCH(n); i += 2) {
cmpop_ty newoperator;
newoperator = ast_for_comp_op(c, CHILD(n, i));
if (!newoperator) {
return NULL;
}
expression = ast_for_expr(c, CHILD(n, i + 1));
if (!expression) {
return NULL;
}
asdl_seq_SET(ops, i / 2, newoperator);
asdl_seq_SET(cmps, i / 2, expression);
}
expression = ast_for_expr(c, CHILD(n, 0));
if (!expression) {
return NULL;
}
return Compare(expression, ops, cmps, LINENO(n),
n->n_col_offset, c->c_arena);
}
break;
/* The next five cases all handle BinOps. The main body of code
is the same in each case, but the switch turned inside out to
reuse the code for each type of operator.
*/
case expr:
case xor_expr:
case and_expr:
case shift_expr:
case arith_expr:
case term:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
return ast_for_binop(c, n);
case yield_expr: {
expr_ty exp = NULL;
if (NCH(n) == 2) {
exp = ast_for_testlist(c, CHILD(n, 1));
if (!exp)
return NULL;
}
return Yield(exp, LINENO(n), n->n_col_offset, c->c_arena);
}
case factor:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
return ast_for_factor(c, n);
case power:
return ast_for_power(c, n);
default:
PyErr_Format(PyExc_SystemError, "unhandled expr: %d", TYPE(n));
return NULL;
}
/* should never get here unless if error is set */
return NULL;
}
static expr_ty
ast_for_call(struct compiling *c, const node *n, expr_ty func)
{
/*
arglist: (argument ',')* (argument [',']| '*' test [',' '**' test]
| '**' test)
argument: [test '='] test [comp_for] # Really [keyword '='] test
*/
int i, nargs, nkeywords, ngens;
asdl_seq *args;
asdl_seq *keywords;
expr_ty vararg = NULL, kwarg = NULL;
REQ(n, arglist);
nargs = 0;
nkeywords = 0;
ngens = 0;
for (i = 0; i < NCH(n); i++) {
node *ch = CHILD(n, i);
if (TYPE(ch) == argument) {
if (NCH(ch) == 1)
nargs++;
else if (TYPE(CHILD(ch, 1)) == comp_for)
ngens++;
else
nkeywords++;
}
}
if (ngens > 1 || (ngens && (nargs || nkeywords))) {
ast_error(n, "Generator expression must be parenthesized "
"if not sole argument");
return NULL;
}
if (nargs + nkeywords + ngens > 255) {
ast_error(n, "more than 255 arguments");
return NULL;
}
args = asdl_seq_new(nargs + ngens, c->c_arena);
if (!args)
return NULL;
keywords = asdl_seq_new(nkeywords, c->c_arena);
if (!keywords)
return NULL;
nargs = 0;
nkeywords = 0;
for (i = 0; i < NCH(n); i++) {
node *ch = CHILD(n, i);
if (TYPE(ch) == argument) {
expr_ty e;
if (NCH(ch) == 1) {
if (nkeywords) {
ast_error(CHILD(ch, 0),
"non-keyword arg after keyword arg");
return NULL;
}
if (vararg) {
ast_error(CHILD(ch, 0),
"only named arguments may follow *expression");
return NULL;
}
e = ast_for_expr(c, CHILD(ch, 0));
if (!e)
return NULL;
asdl_seq_SET(args, nargs++, e);
}
else if (TYPE(CHILD(ch, 1)) == comp_for) {
e = ast_for_genexp(c, ch);
if (!e)
return NULL;
asdl_seq_SET(args, nargs++, e);
}
else {
keyword_ty kw;
identifier key;
int k;
char *tmp;
/* CHILD(ch, 0) is test, but must be an identifier? */
e = ast_for_expr(c, CHILD(ch, 0));
if (!e)
return NULL;
/* f(lambda x: x[0] = 3) ends up getting parsed with
* LHS test = lambda x: x[0], and RHS test = 3.
* SF bug 132313 points out that complaining about a keyword
* then is very confusing.
*/
if (e->kind == Lambda_kind) {
ast_error(CHILD(ch, 0),
"lambda cannot contain assignment");
return NULL;
} else if (e->kind != Name_kind) {
ast_error(CHILD(ch, 0), "keyword can't be an expression");
return NULL;
}
key = e->v.Name.id;
if (!forbidden_check(c, CHILD(ch, 0), PyUnicode_AsUTF8(key)))
return NULL;
for (k = 0; k < nkeywords; k++) {
tmp = _PyUnicode_AsString(
((keyword_ty)asdl_seq_GET(keywords, k))->arg);
if (!strcmp(tmp, _PyUnicode_AsString(key))) {
ast_error(CHILD(ch, 0), "keyword argument repeated");
return NULL;
}
}
e = ast_for_expr(c, CHILD(ch, 2));
if (!e)
return NULL;
kw = keyword(key, e, c->c_arena);
if (!kw)
return NULL;
asdl_seq_SET(keywords, nkeywords++, kw);
}
}
else if (TYPE(ch) == STAR) {
vararg = ast_for_expr(c, CHILD(n, i+1));
if (!vararg)
return NULL;
i++;
}
else if (TYPE(ch) == DOUBLESTAR) {
kwarg = ast_for_expr(c, CHILD(n, i+1));
if (!kwarg)
return NULL;
i++;
}
}
return Call(func, args, keywords, vararg, kwarg, func->lineno,
func->col_offset, c->c_arena);
}
static expr_ty
ast_for_testlist(struct compiling *c, const node* n)
{
/* testlist_comp: test (',' test)* [','] */
/* testlist: test (',' test)* [','] */
/* testlist_safe: test (',' test)+ [','] */
/* testlist1: test (',' test)* */
assert(NCH(n) > 0);
if (TYPE(n) == testlist_comp) {
if (NCH(n) > 1)
assert(TYPE(CHILD(n, 1)) != comp_for);
}
else {
assert(TYPE(n) == testlist ||
TYPE(n) == testlist_safe ||
TYPE(n) == testlist1);
}
if (NCH(n) == 1)
return ast_for_expr(c, CHILD(n, 0));
else {
asdl_seq *tmp = seq_for_testlist(c, n);
if (!tmp)
return NULL;
return Tuple(tmp, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
}
static expr_ty
ast_for_testlist_comp(struct compiling *c, const node* n)
{
/* testlist_comp: test ( comp_for | (',' test)* [','] ) */
/* argument: test [ comp_for ] */
assert(TYPE(n) == testlist_comp || TYPE(n) == argument);
if (NCH(n) > 1 && TYPE(CHILD(n, 1)) == comp_for)
return ast_for_genexp(c, n);
return ast_for_testlist(c, n);
}
/* like ast_for_testlist() but returns a sequence */
static asdl_seq*
ast_for_class_bases(struct compiling *c, const node* n)
{
/* testlist: test (',' test)* [','] */
assert(NCH(n) > 0);
REQ(n, testlist);
if (NCH(n) == 1) {
expr_ty base;
asdl_seq *bases = asdl_seq_new(1, c->c_arena);
if (!bases)
return NULL;
base = ast_for_expr(c, CHILD(n, 0));
if (!base)
return NULL;
asdl_seq_SET(bases, 0, base);
return bases;
}
return seq_for_testlist(c, n);
}
static stmt_ty
ast_for_expr_stmt(struct compiling *c, const node *n)
{
int num;
REQ(n, expr_stmt);
/* expr_stmt: testlist (augassign (yield_expr|testlist)
| ('=' (yield_expr|testlist))* [TYPE_COMMENT])
testlist: test (',' test)* [',']
augassign: '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^='
| '<<=' | '>>=' | '**=' | '//='
test: ... here starts the operator precendence dance
*/
num = NCH(n);
if (num == 1 || (num == 2 && TYPE(CHILD(n, 1)) == TYPE_COMMENT)) {
expr_ty e = ast_for_testlist(c, CHILD(n, 0));
if (!e)
return NULL;
return Expr(e, LINENO(n), n->n_col_offset, c->c_arena);
}
else if (TYPE(CHILD(n, 1)) == augassign) {
expr_ty expr1, expr2;
operator_ty newoperator;
node *ch = CHILD(n, 0);
expr1 = ast_for_testlist(c, ch);
if (!expr1)
return NULL;
if(!set_context(c, expr1, Store, ch))
return NULL;
/* set_context checks that most expressions are not the left side.
Augmented assignments can only have a name, a subscript, or an
attribute on the left, though, so we have to explicitly check for
those. */
switch (expr1->kind) {
case Name_kind:
case Attribute_kind:
case Subscript_kind:
break;
default:
ast_error(ch, "illegal expression for augmented assignment");
return NULL;
}
ch = CHILD(n, 2);
if (TYPE(ch) == testlist)
expr2 = ast_for_testlist(c, ch);
else
expr2 = ast_for_expr(c, ch);
if (!expr2)
return NULL;
newoperator = ast_for_augassign(c, CHILD(n, 1));
if (!newoperator)
return NULL;
return AugAssign(expr1, newoperator, expr2, LINENO(n), n->n_col_offset,
c->c_arena);
}
else {
int i, nch_minus_type, has_type_comment;
asdl_seq *targets;
node *value;
expr_ty expression;
string type_comment;
/* a normal assignment */
REQ(CHILD(n, 1), EQUAL);
has_type_comment = TYPE(CHILD(n, num - 1)) == TYPE_COMMENT;
nch_minus_type = num - has_type_comment;
targets = asdl_seq_new(nch_minus_type / 2, c->c_arena);
if (!targets)
return NULL;
for (i = 0; i < nch_minus_type - 2; i += 2) {
expr_ty e;
node *ch = CHILD(n, i);
if (TYPE(ch) == yield_expr) {
ast_error(ch, "assignment to yield expression not possible");
return NULL;
}
e = ast_for_testlist(c, ch);
if (!e)
return NULL;
/* set context to assign */
if (!set_context(c, e, Store, CHILD(n, i)))
return NULL;
asdl_seq_SET(targets, i / 2, e);
}
value = CHILD(n, nch_minus_type - 1);
if (TYPE(value) == testlist)
expression = ast_for_testlist(c, value);
else
expression = ast_for_expr(c, value);
if (!expression)
return NULL;
if (has_type_comment)
type_comment = NEW_TYPE_COMMENT(CHILD(n, nch_minus_type));
else
type_comment = NULL;
return Assign(targets, expression, type_comment, LINENO(n), n->n_col_offset,
c->c_arena);
}
}
static stmt_ty
ast_for_print_stmt(struct compiling *c, const node *n)
{
/* print_stmt: 'print' ( [ test (',' test)* [','] ]
| '>>' test [ (',' test)+ [','] ] )
*/
expr_ty dest = NULL, expression;
asdl_seq *seq = NULL;
bool nl;
int i, j, values_count, start = 1;
REQ(n, print_stmt);
if (NCH(n) >= 2 && TYPE(CHILD(n, 1)) == RIGHTSHIFT) {
dest = ast_for_expr(c, CHILD(n, 2));
if (!dest)
return NULL;
start = 4;
}
values_count = (NCH(n) + 1 - start) / 2;
if (values_count) {
seq = asdl_seq_new(values_count, c->c_arena);
if (!seq)
return NULL;
for (i = start, j = 0; i < NCH(n); i += 2, ++j) {
expression = ast_for_expr(c, CHILD(n, i));
if (!expression)
return NULL;
asdl_seq_SET(seq, j, expression);
}
}
nl = (TYPE(CHILD(n, NCH(n) - 1)) == COMMA) ? false : true;
return Print(dest, seq, nl, LINENO(n), n->n_col_offset, c->c_arena);
}
static asdl_seq *
ast_for_exprlist(struct compiling *c, const node *n, expr_context_ty context)
{
asdl_seq *seq;
int i;
expr_ty e;
REQ(n, exprlist);
seq = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!seq)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
e = ast_for_expr(c, CHILD(n, i));
if (!e)
return NULL;
asdl_seq_SET(seq, i / 2, e);
if (context && !set_context(c, e, context, CHILD(n, i)))
return NULL;
}
return seq;
}
static stmt_ty
ast_for_del_stmt(struct compiling *c, const node *n)
{
asdl_seq *expr_list;
/* del_stmt: 'del' exprlist */
REQ(n, del_stmt);
expr_list = ast_for_exprlist(c, CHILD(n, 1), Del);
if (!expr_list)
return NULL;
return Delete(expr_list, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_flow_stmt(struct compiling *c, const node *n)
{
/*
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
| yield_stmt
break_stmt: 'break'
continue_stmt: 'continue'
return_stmt: 'return' [testlist]
yield_stmt: yield_expr
yield_expr: 'yield' testlist
raise_stmt: 'raise' [test [',' test [',' test]]]
*/
node *ch;
REQ(n, flow_stmt);
ch = CHILD(n, 0);
switch (TYPE(ch)) {
case break_stmt:
return Break(LINENO(n), n->n_col_offset, c->c_arena);
case continue_stmt:
return Continue(LINENO(n), n->n_col_offset, c->c_arena);
case yield_stmt: { /* will reduce to yield_expr */
expr_ty exp = ast_for_expr(c, CHILD(ch, 0));
if (!exp)
return NULL;
return Expr(exp, LINENO(n), n->n_col_offset, c->c_arena);
}
case return_stmt:
if (NCH(ch) == 1)
return Return(NULL, LINENO(n), n->n_col_offset, c->c_arena);
else {
expr_ty expression = ast_for_testlist(c, CHILD(ch, 1));
if (!expression)
return NULL;
return Return(expression, LINENO(n), n->n_col_offset,
c->c_arena);
}
case raise_stmt:
if (NCH(ch) == 1)
return Raise(NULL, NULL, NULL, LINENO(n), n->n_col_offset,
c->c_arena);
else if (NCH(ch) == 2) {
expr_ty expression = ast_for_expr(c, CHILD(ch, 1));
if (!expression)
return NULL;
return Raise(expression, NULL, NULL, LINENO(n),
n->n_col_offset, c->c_arena);
}
else if (NCH(ch) == 4) {
expr_ty expr1, expr2;
expr1 = ast_for_expr(c, CHILD(ch, 1));
if (!expr1)
return NULL;
expr2 = ast_for_expr(c, CHILD(ch, 3));
if (!expr2)
return NULL;
return Raise(expr1, expr2, NULL, LINENO(n), n->n_col_offset,
c->c_arena);
}
else if (NCH(ch) == 6) {
expr_ty expr1, expr2, expr3;
expr1 = ast_for_expr(c, CHILD(ch, 1));
if (!expr1)
return NULL;
expr2 = ast_for_expr(c, CHILD(ch, 3));
if (!expr2)
return NULL;
expr3 = ast_for_expr(c, CHILD(ch, 5));
if (!expr3)
return NULL;
return Raise(expr1, expr2, expr3, LINENO(n), n->n_col_offset,
c->c_arena);
}
default:
PyErr_Format(PyExc_SystemError,
"unexpected flow_stmt: %d", TYPE(ch));
return NULL;
}
}
static alias_ty
alias_for_import_name(struct compiling *c, const node *n, int store)
{
/*
import_as_name: NAME ['as' NAME]
dotted_as_name: dotted_name ['as' NAME]
dotted_name: NAME ('.' NAME)*
*/
PyObject *str, *name;
loop:
switch (TYPE(n)) {
case import_as_name: {
node *name_node = CHILD(n, 0);
str = NULL;
if (NCH(n) == 3) {
node *str_node = CHILD(n, 2);
if (store && !forbidden_check(c, str_node, STR(str_node)))
return NULL;
str = NEW_IDENTIFIER(str_node);
if (!str)
return NULL;
}
else {
if (!forbidden_check(c, name_node, STR(name_node)))
return NULL;
}
name = NEW_IDENTIFIER(name_node);
if (!name)
return NULL;
return alias(name, str, c->c_arena);
}
case dotted_as_name:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
else {
node *asname_node = CHILD(n, 2);
alias_ty a = alias_for_import_name(c, CHILD(n, 0), 0);
if (!a)
return NULL;
assert(!a->asname);
if (!forbidden_check(c, asname_node, STR(asname_node)))
return NULL;
a->asname = NEW_IDENTIFIER(asname_node);
if (!a->asname)
return NULL;
return a;
}
break;
case dotted_name:
if (NCH(n) == 1) {
node *name_node = CHILD(n, 0);
if (store && !forbidden_check(c, name_node, STR(name_node)))
return NULL;
name = NEW_IDENTIFIER(name_node);
if (!name)
return NULL;
return alias(name, NULL, c->c_arena);
}
else {
/* Create a string of the form "a.b.c" */
int i;
size_t len;
char *s;
PyObject *uni;
len = 0;
for (i = 0; i < NCH(n); i += 2)
/* length of string plus one for the dot */
len += strlen(STR(CHILD(n, i))) + 1;
len--; /* the last name doesn't have a dot */
str = PyBytes_FromStringAndSize(NULL, len);
if (!str)
return NULL;
s = PyBytes_AS_STRING(str);
if (!s)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
char *sch = STR(CHILD(n, i));
strcpy(s, STR(CHILD(n, i)));
s += strlen(sch);
*s++ = '.';
}
--s;
*s = '\0';
uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str),
PyBytes_GET_SIZE(str),
NULL);
Py_DECREF(str);
if (!uni)
return NULL;
str = uni;
PyUnicode_InternInPlace(&str);
if (PyArena_AddPyObject(c->c_arena, str) < 0) {
Py_DECREF(str);
return NULL;
}
return alias(str, NULL, c->c_arena);
}
break;
case STAR:
str = PyUnicode_InternFromString("*");
if (PyArena_AddPyObject(c->c_arena, str) < 0) {
Py_DECREF(str);
return NULL;
}
return alias(str, NULL, c->c_arena);
default:
PyErr_Format(PyExc_SystemError,
"unexpected import name: %d", TYPE(n));
return NULL;
}
PyErr_SetString(PyExc_SystemError, "unhandled import name condition");
return NULL;
}
static stmt_ty
ast_for_import_stmt(struct compiling *c, const node *n)
{
/*
import_stmt: import_name | import_from
import_name: 'import' dotted_as_names
import_from: 'from' ('.'* dotted_name | '.') 'import'
('*' | '(' import_as_names ')' | import_as_names)
*/
int lineno;
int col_offset;
int i;
asdl_seq *aliases;
REQ(n, import_stmt);
lineno = LINENO(n);
col_offset = n->n_col_offset;
n = CHILD(n, 0);
if (TYPE(n) == import_name) {
n = CHILD(n, 1);
REQ(n, dotted_as_names);
aliases = asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!aliases)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1);
if (!import_alias)
return NULL;
asdl_seq_SET(aliases, i / 2, import_alias);
}
return Import(aliases, lineno, col_offset, c->c_arena);
}
else if (TYPE(n) == import_from) {
int n_children;
int idx, ndots = 0;
alias_ty mod = NULL;
identifier modname = NULL;
/* Count the number of dots (for relative imports) and check for the
optional module name */
for (idx = 1; idx < NCH(n); idx++) {
if (TYPE(CHILD(n, idx)) == dotted_name) {
mod = alias_for_import_name(c, CHILD(n, idx), 0);
if (!mod)
return NULL;
idx++;
break;
} else if (TYPE(CHILD(n, idx)) != DOT) {
break;
}
ndots++;
}
idx++; /* skip over the 'import' keyword */
switch (TYPE(CHILD(n, idx))) {
case STAR:
/* from ... import * */
n = CHILD(n, idx);
n_children = 1;
break;
case LPAR:
/* from ... import (x, y, z) */
n = CHILD(n, idx + 1);
n_children = NCH(n);
break;
case import_as_names:
/* from ... import x, y, z */
n = CHILD(n, idx);
n_children = NCH(n);
if (n_children % 2 == 0) {
ast_error(n, "trailing comma not allowed without"
" surrounding parentheses");
return NULL;
}
break;
default:
ast_error(n, "Unexpected node-type in from-import");
return NULL;
}
aliases = asdl_seq_new((n_children + 1) / 2, c->c_arena);
if (!aliases)
return NULL;
/* handle "from ... import *" special b/c there's no children */
if (TYPE(n) == STAR) {
alias_ty import_alias = alias_for_import_name(c, n, 1);
if (!import_alias)
return NULL;
asdl_seq_SET(aliases, 0, import_alias);
}
else {
for (i = 0; i < NCH(n); i += 2) {
alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1);
if (!import_alias)
return NULL;
asdl_seq_SET(aliases, i / 2, import_alias);
}
}
if (mod != NULL)
modname = mod->name;
return ImportFrom(modname, aliases, ndots, lineno, col_offset,
c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"unknown import statement: starts with command '%s'",
STR(CHILD(n, 0)));
return NULL;
}
static stmt_ty
ast_for_global_stmt(struct compiling *c, const node *n)
{
/* global_stmt: 'global' NAME (',' NAME)* */
identifier name;
asdl_seq *s;
int i;
REQ(n, global_stmt);
s = asdl_seq_new(NCH(n) / 2, c->c_arena);
if (!s)
return NULL;
for (i = 1; i < NCH(n); i += 2) {
name = NEW_IDENTIFIER(CHILD(n, i));
if (!name)
return NULL;
asdl_seq_SET(s, i / 2, name);
}
return Global(s, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_exec_stmt(struct compiling *c, const node *n)
{
expr_ty expr1, globals = NULL, locals = NULL;
int n_children = NCH(n);
if (n_children != 2 && n_children != 4 && n_children != 6) {
PyErr_Format(PyExc_SystemError,
"poorly formed 'exec' statement: %d parts to statement",
n_children);
return NULL;
}
/* exec_stmt: 'exec' expr ['in' test [',' test]] */
REQ(n, exec_stmt);
expr1 = ast_for_expr(c, CHILD(n, 1));
if (!expr1)
return NULL;
if (expr1->kind == Tuple_kind && n_children < 4 &&
(asdl_seq_LEN(expr1->v.Tuple.elts) == 2 ||
asdl_seq_LEN(expr1->v.Tuple.elts) == 3)) {
/* Backwards compatibility: passing exec args as a tuple */
globals = asdl_seq_GET(expr1->v.Tuple.elts, 1);
if (asdl_seq_LEN(expr1->v.Tuple.elts) == 3) {
locals = asdl_seq_GET(expr1->v.Tuple.elts, 2);
}
expr1 = asdl_seq_GET(expr1->v.Tuple.elts, 0);
}
if (n_children >= 4) {
globals = ast_for_expr(c, CHILD(n, 3));
if (!globals)
return NULL;
}
if (n_children == 6) {
locals = ast_for_expr(c, CHILD(n, 5));
if (!locals)
return NULL;
}
return Exec(expr1, globals, locals, LINENO(n), n->n_col_offset,
c->c_arena);
}
static stmt_ty
ast_for_assert_stmt(struct compiling *c, const node *n)
{
/* assert_stmt: 'assert' test [',' test] */
REQ(n, assert_stmt);
if (NCH(n) == 2) {
expr_ty expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
return Assert(expression, NULL, LINENO(n), n->n_col_offset,
c->c_arena);
}
else if (NCH(n) == 4) {
expr_ty expr1, expr2;
expr1 = ast_for_expr(c, CHILD(n, 1));
if (!expr1)
return NULL;
expr2 = ast_for_expr(c, CHILD(n, 3));
if (!expr2)
return NULL;
return Assert(expr1, expr2, LINENO(n), n->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"improper number of parts to 'assert' statement: %d",
NCH(n));
return NULL;
}
static asdl_seq *
ast_for_suite(struct compiling *c, const node *n)
{
/* suite: simple_stmt | NEWLINE [TYPE_COMMENT NEWLINE] INDENT stmt+ DEDENT */
asdl_seq *seq;
stmt_ty s;
int i, total, num, end, pos = 0;
node *ch;
REQ(n, suite);
total = num_stmts(n);
seq = asdl_seq_new(total, c->c_arena);
if (!seq)
return NULL;
if (TYPE(CHILD(n, 0)) == simple_stmt) {
n = CHILD(n, 0);
/* simple_stmt always ends with a NEWLINE,
and may have a trailing SEMI
*/
end = NCH(n) - 1;
if (TYPE(CHILD(n, end - 1)) == SEMI)
end--;
/* loop by 2 to skip semi-colons */
for (i = 0; i < end; i += 2) {
ch = CHILD(n, i);
s = ast_for_stmt(c, ch);
if (!s)
return NULL;
asdl_seq_SET(seq, pos++, s);
}
}
else {
i = 2;
if (TYPE(CHILD(n, 1)) == TYPE_COMMENT)
i += 2;
for (; i < (NCH(n) - 1); i++) {
ch = CHILD(n, i);
REQ(ch, stmt);
num = num_stmts(ch);
if (num == 1) {
/* small_stmt or compound_stmt with only one child */
s = ast_for_stmt(c, ch);
if (!s)
return NULL;
asdl_seq_SET(seq, pos++, s);
}
else {
int j;
ch = CHILD(ch, 0);
REQ(ch, simple_stmt);
for (j = 0; j < NCH(ch); j += 2) {
/* statement terminates with a semi-colon ';' */
if (NCH(CHILD(ch, j)) == 0) {
assert((j + 1) == NCH(ch));
break;
}
s = ast_for_stmt(c, CHILD(ch, j));
if (!s)
return NULL;
asdl_seq_SET(seq, pos++, s);
}
}
}
}
assert(pos == seq->size);
return seq;
}
static stmt_ty
ast_for_if_stmt(struct compiling *c, const node *n)
{
/* if_stmt: 'if' test ':' suite ('elif' test ':' suite)*
['else' ':' suite]
*/
char *s;
REQ(n, if_stmt);
if (NCH(n) == 4) {
expr_ty expression;
asdl_seq *suite_seq;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 3));
if (!suite_seq)
return NULL;
return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset,
c->c_arena);
}
s = STR(CHILD(n, 4));
/* s[2], the third character in the string, will be
's' for el_s_e, or
'i' for el_i_f
*/
if (s[2] == 's') {
expr_ty expression;
asdl_seq *seq1, *seq2;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
seq1 = ast_for_suite(c, CHILD(n, 3));
if (!seq1)
return NULL;
seq2 = ast_for_suite(c, CHILD(n, 6));
if (!seq2)
return NULL;
return If(expression, seq1, seq2, LINENO(n), n->n_col_offset,
c->c_arena);
}
else if (s[2] == 'i') {
int i, n_elif, has_else = 0;
expr_ty expression;
asdl_seq *suite_seq;
asdl_seq *orelse = NULL;
n_elif = NCH(n) - 4;
/* must reference the child n_elif+1 since 'else' token is third,
not fourth, child from the end. */
if (TYPE(CHILD(n, (n_elif + 1))) == NAME
&& STR(CHILD(n, (n_elif + 1)))[2] == 's') {
has_else = 1;
n_elif -= 3;
}
n_elif /= 4;
if (has_else) {
asdl_seq *suite_seq2;
orelse = asdl_seq_new(1, c->c_arena);
if (!orelse)
return NULL;
expression = ast_for_expr(c, CHILD(n, NCH(n) - 6));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, NCH(n) - 4));
if (!suite_seq)
return NULL;
suite_seq2 = ast_for_suite(c, CHILD(n, NCH(n) - 1));
if (!suite_seq2)
return NULL;
asdl_seq_SET(orelse, 0,
If(expression, suite_seq, suite_seq2,
LINENO(CHILD(n, NCH(n) - 6)),
CHILD(n, NCH(n) - 6)->n_col_offset,
c->c_arena));
/* the just-created orelse handled the last elif */
n_elif--;
}
for (i = 0; i < n_elif; i++) {
int off = 5 + (n_elif - i - 1) * 4;
asdl_seq *newobj = asdl_seq_new(1, c->c_arena);
if (!newobj)
return NULL;
expression = ast_for_expr(c, CHILD(n, off));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, off + 2));
if (!suite_seq)
return NULL;
asdl_seq_SET(newobj, 0,
If(expression, suite_seq, orelse,
LINENO(CHILD(n, off)),
CHILD(n, off)->n_col_offset, c->c_arena));
orelse = newobj;
}
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 3));
if (!suite_seq)
return NULL;
return If(expression, suite_seq, orelse,
LINENO(n), n->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"unexpected token in 'if' statement: %s", s);
return NULL;
}
static stmt_ty
ast_for_while_stmt(struct compiling *c, const node *n)
{
/* while_stmt: 'while' test ':' suite ['else' ':' suite] */
REQ(n, while_stmt);
if (NCH(n) == 4) {
expr_ty expression;
asdl_seq *suite_seq;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 3));
if (!suite_seq)
return NULL;
return While(expression, suite_seq, NULL, LINENO(n), n->n_col_offset,
c->c_arena);
}
else if (NCH(n) == 7) {
expr_ty expression;
asdl_seq *seq1, *seq2;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
seq1 = ast_for_suite(c, CHILD(n, 3));
if (!seq1)
return NULL;
seq2 = ast_for_suite(c, CHILD(n, 6));
if (!seq2)
return NULL;
return While(expression, seq1, seq2, LINENO(n), n->n_col_offset,
c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"wrong number of tokens for 'while' statement: %d",
NCH(n));
return NULL;
}
static stmt_ty
ast_for_for_stmt(struct compiling *c, const node *n)
{
asdl_seq *_target, *seq = NULL, *suite_seq;
expr_ty expression;
expr_ty target, first;
const node *node_target;
int has_type_comment;
string type_comment;
/* for_stmt: 'for' exprlist 'in' testlist ':' [TYPE_COMMENT] suite ['else' ':' suite] */
REQ(n, for_stmt);
has_type_comment = TYPE(CHILD(n, 5)) == TYPE_COMMENT;
if (NCH(n) == 9 + has_type_comment) {
seq = ast_for_suite(c, CHILD(n, 8 + has_type_comment));
if (!seq)
return NULL;
}
node_target = CHILD(n, 1);
_target = ast_for_exprlist(c, node_target, Store);
if (!_target)
return NULL;
/* Check the # of children rather than the length of _target, since
for x, in ... has 1 element in _target, but still requires a Tuple. */
first = (expr_ty)asdl_seq_GET(_target, 0);
if (NCH(node_target) == 1)
target = first;
else
target = Tuple(_target, Store, first->lineno, first->col_offset, c->c_arena);
expression = ast_for_testlist(c, CHILD(n, 3));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 5 + has_type_comment));
if (!suite_seq)
return NULL;
if (has_type_comment)
type_comment = NEW_TYPE_COMMENT(CHILD(n, 5));
else
type_comment = NULL;
return For(target, expression, suite_seq, seq, type_comment, LINENO(n), n->n_col_offset,
c->c_arena);
}
static excepthandler_ty
ast_for_except_clause(struct compiling *c, const node *exc, node *body)
{
/* except_clause: 'except' [test [(',' | 'as') test]] */
REQ(exc, except_clause);
REQ(body, suite);
if (NCH(exc) == 1) {
asdl_seq *suite_seq = ast_for_suite(c, body);
if (!suite_seq)
return NULL;
return ExceptHandler(NULL, NULL, suite_seq, LINENO(exc),
exc->n_col_offset, c->c_arena);
}
else if (NCH(exc) == 2) {
expr_ty expression;
asdl_seq *suite_seq;
expression = ast_for_expr(c, CHILD(exc, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, body);
if (!suite_seq)
return NULL;
return ExceptHandler(expression, NULL, suite_seq, LINENO(exc),
exc->n_col_offset, c->c_arena);
}
else if (NCH(exc) == 4) {
asdl_seq *suite_seq;
expr_ty expression;
expr_ty e = ast_for_expr(c, CHILD(exc, 3));
if (!e)
return NULL;
if (!set_context(c, e, Store, CHILD(exc, 3)))
return NULL;
expression = ast_for_expr(c, CHILD(exc, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, body);
if (!suite_seq)
return NULL;
return ExceptHandler(expression, e, suite_seq, LINENO(exc),
exc->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"wrong number of children for 'except' clause: %d",
NCH(exc));
return NULL;
}
static stmt_ty
ast_for_try_stmt(struct compiling *c, const node *n)
{
const int nch = NCH(n);
int n_except = (nch - 3)/3;
asdl_seq *body, *orelse = NULL, *finally = NULL;
REQ(n, try_stmt);
body = ast_for_suite(c, CHILD(n, 2));
if (body == NULL)
return NULL;
if (TYPE(CHILD(n, nch - 3)) == NAME) {
if (strcmp(STR(CHILD(n, nch - 3)), "finally") == 0) {
if (nch >= 9 && TYPE(CHILD(n, nch - 6)) == NAME) {
/* we can assume it's an "else",
because nch >= 9 for try-else-finally and
it would otherwise have a type of except_clause */
orelse = ast_for_suite(c, CHILD(n, nch - 4));
if (orelse == NULL)
return NULL;
n_except--;
}
finally = ast_for_suite(c, CHILD(n, nch - 1));
if (finally == NULL)
return NULL;
n_except--;
}
else {
/* we can assume it's an "else",
otherwise it would have a type of except_clause */
orelse = ast_for_suite(c, CHILD(n, nch - 1));
if (orelse == NULL)
return NULL;
n_except--;
}
}
else if (TYPE(CHILD(n, nch - 3)) != except_clause) {
ast_error(n, "malformed 'try' statement");
return NULL;
}
if (n_except > 0) {
int i;
stmt_ty except_st;
/* process except statements to create a try ... except */
asdl_seq *handlers = asdl_seq_new(n_except, c->c_arena);
if (handlers == NULL)
return NULL;
for (i = 0; i < n_except; i++) {
excepthandler_ty e = ast_for_except_clause(c, CHILD(n, 3 + i * 3),
CHILD(n, 5 + i * 3));
if (!e)
return NULL;
asdl_seq_SET(handlers, i, e);
}
except_st = TryExcept(body, handlers, orelse, LINENO(n),
n->n_col_offset, c->c_arena);
if (!finally)
return except_st;
/* if a 'finally' is present too, we nest the TryExcept within a
TryFinally to emulate try ... except ... finally */
body = asdl_seq_new(1, c->c_arena);
if (body == NULL)
return NULL;
asdl_seq_SET(body, 0, except_st);
}
/* must be a try ... finally (except clauses are in body, if any exist) */
assert(finally != NULL);
return TryFinally(body, finally, LINENO(n), n->n_col_offset, c->c_arena);
}
/* with_item: test ['as' expr] */
static stmt_ty
ast_for_with_item(struct compiling *c, const node *n, asdl_seq *content, string type_comment)
{
expr_ty context_expr, optional_vars = NULL;
REQ(n, with_item);
context_expr = ast_for_expr(c, CHILD(n, 0));
if (!context_expr)
return NULL;
if (NCH(n) == 3) {
optional_vars = ast_for_expr(c, CHILD(n, 2));
if (!optional_vars) {
return NULL;
}
if (!set_context(c, optional_vars, Store, n)) {
return NULL;
}
}
return With(context_expr, optional_vars, content, type_comment, LINENO(n),
n->n_col_offset, c->c_arena);
}
/* with_stmt: 'with' with_item (',' with_item)* ':' [TYPE_COMMENT] suite */
static stmt_ty
ast_for_with_stmt(struct compiling *c, const node *n)
{
int i, has_type_comment;
stmt_ty ret;
asdl_seq *inner;
string type_comment;
REQ(n, with_stmt);
has_type_comment = TYPE(CHILD(n, NCH(n) - 2)) == TYPE_COMMENT;
/* process the with items inside-out */
i = NCH(n) - 1;
/* the suite of the innermost with item is the suite of the with stmt */
inner = ast_for_suite(c, CHILD(n, i));
if (!inner)
return NULL;
if (has_type_comment) {
type_comment = NEW_TYPE_COMMENT(CHILD(n, NCH(n) - 2));
i--;
} else
type_comment = NULL;
for (;;) {
i -= 2;
ret = ast_for_with_item(c, CHILD(n, i), inner, type_comment);
if (!ret)
return NULL;
/* was this the last item? */
if (i == 1)
break;
/* if not, wrap the result so far in a new sequence */
inner = asdl_seq_new(1, c->c_arena);
if (!inner)
return NULL;
asdl_seq_SET(inner, 0, ret);
}
return ret;
}
static stmt_ty
ast_for_classdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
{
/* classdef: 'class' NAME ['(' testlist ')'] ':' suite */
PyObject *classname;
asdl_seq *bases, *s;
REQ(n, classdef);
if (!forbidden_check(c, n, STR(CHILD(n, 1))))
return NULL;
if (NCH(n) == 4) {
s = ast_for_suite(c, CHILD(n, 3));
if (!s)
return NULL;
classname = NEW_IDENTIFIER(CHILD(n, 1));
if (!classname)
return NULL;
return ClassDef(classname, NULL, s, decorator_seq, LINENO(n),
n->n_col_offset, c->c_arena);
}
/* check for empty base list */
if (TYPE(CHILD(n,3)) == RPAR) {
s = ast_for_suite(c, CHILD(n,5));
if (!s)
return NULL;
classname = NEW_IDENTIFIER(CHILD(n, 1));
if (!classname)
return NULL;
return ClassDef(classname, NULL, s, decorator_seq, LINENO(n),
n->n_col_offset, c->c_arena);
}
/* else handle the base class list */
bases = ast_for_class_bases(c, CHILD(n, 3));
if (!bases)
return NULL;
s = ast_for_suite(c, CHILD(n, 6));
if (!s)
return NULL;
classname = NEW_IDENTIFIER(CHILD(n, 1));
if (!classname)
return NULL;
return ClassDef(classname, bases, s, decorator_seq,
LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_stmt(struct compiling *c, const node *n)
{
if (TYPE(n) == stmt) {
assert(NCH(n) == 1);
n = CHILD(n, 0);
}
if (TYPE(n) == simple_stmt) {
assert(num_stmts(n) == 1);
n = CHILD(n, 0);
}
if (TYPE(n) == small_stmt) {
n = CHILD(n, 0);
/* small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt
| flow_stmt | import_stmt | global_stmt | exec_stmt
| assert_stmt
*/
switch (TYPE(n)) {
case expr_stmt:
return ast_for_expr_stmt(c, n);
case print_stmt:
return ast_for_print_stmt(c, n);
case del_stmt:
return ast_for_del_stmt(c, n);
case pass_stmt:
return Pass(LINENO(n), n->n_col_offset, c->c_arena);
case flow_stmt:
return ast_for_flow_stmt(c, n);
case import_stmt:
return ast_for_import_stmt(c, n);
case global_stmt:
return ast_for_global_stmt(c, n);
case exec_stmt:
return ast_for_exec_stmt(c, n);
case assert_stmt:
return ast_for_assert_stmt(c, n);
default:
PyErr_Format(PyExc_SystemError,
"unhandled small_stmt: TYPE=%d NCH=%d\n",
TYPE(n), NCH(n));
return NULL;
}
}
else {
/* compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt
| funcdef | classdef | decorated
*/
node *ch = CHILD(n, 0);
REQ(n, compound_stmt);
switch (TYPE(ch)) {
case if_stmt:
return ast_for_if_stmt(c, ch);
case while_stmt:
return ast_for_while_stmt(c, ch);
case for_stmt:
return ast_for_for_stmt(c, ch);
case try_stmt:
return ast_for_try_stmt(c, ch);
case with_stmt:
return ast_for_with_stmt(c, ch);
case funcdef:
return ast_for_funcdef(c, ch, NULL);
case classdef:
return ast_for_classdef(c, ch, NULL);
case decorated:
return ast_for_decorated(c, ch);
default:
PyErr_Format(PyExc_SystemError,
"unhandled small_stmt: TYPE=%d NCH=%d\n",
TYPE(n), NCH(n));
return NULL;
}
}
}
static PyObject *
parsenumber(struct compiling *c, const char *s)
{
const char *end;
long x;
double dx;
int old_style_octal;
#ifndef WITHOUT_COMPLEX
Py_complex complex;
int imflag;
#endif
assert(s != NULL);
errno = 0;
end = s + strlen(s) - 1;
#ifndef WITHOUT_COMPLEX
imflag = *end == 'j' || *end == 'J';
#endif
if (*end == 'l' || *end == 'L') {
/* Make a copy without the trailing 'L' */
size_t len = end - s + 1;
char *copy = malloc(len);
PyObject *result;
if (copy == NULL)
return PyErr_NoMemory();
memcpy(copy, s, len);
copy[len - 1] = '\0';
old_style_octal = len > 2 && copy[0] == '0' && copy[1] >= '0' && copy[1] <= '9';
result = PyLong_FromString(copy, (char **)0, old_style_octal ? 8 : 0);
free(copy);
return result;
}
x = Ta27OS_strtol((char *)s, (char **)&end, 0);
if (*end == '\0') {
if (errno != 0) {
old_style_octal = end - s > 1 && s[0] == '0' && s[1] >= '0' && s[1] <= '9';
return PyLong_FromString((char *)s, (char **)0, old_style_octal ? 8 : 0);
}
return PyLong_FromLong(x);
}
/* XXX Huge floats may silently fail */
#ifndef WITHOUT_COMPLEX
if (imflag) {
complex.real = 0.;
complex.imag = PyOS_string_to_double(s, (char **)&end, NULL);
if (complex.imag == -1.0 && PyErr_Occurred())
return NULL;
return PyComplex_FromCComplex(complex);
}
else
#endif
{
dx = PyOS_string_to_double(s, NULL, NULL);
if (dx == -1.0 && PyErr_Occurred())
return NULL;
return PyFloat_FromDouble(dx);
}
}
/* adapted from Python 3.5.1 */
static PyObject *
decode_utf8(struct compiling *c, const char **sPtr, const char *end)
{
#ifndef Py_USING_UNICODE
Py_FatalError("decode_utf8 should not be called in this build.");
return NULL;
#else
const char *s, *t;
t = s = *sPtr;
/* while (s < end && *s != '\\') s++; */ /* inefficient for u".." */
while (s < end && (*s & 0x80)) s++;
*sPtr = s;
return PyUnicode_DecodeUTF8(t, s - t, NULL);
#endif
}
#ifdef Py_USING_UNICODE
/* taken from Python 3.5.1 */
static PyObject *
decode_unicode(struct compiling *c, const char *s, size_t len, int rawmode, const char *encoding)
{
PyObject *v, *u;
char *buf;
char *p;
const char *end;
if (encoding == NULL) {
u = NULL;
} else {
/* check for integer overflow */
if (len > PY_SIZE_MAX / 6)
return NULL;
/* "ä" (2 bytes) may become "\U000000E4" (10 bytes), or 1:5
"\ä" (3 bytes) may become "\u005c\U000000E4" (16 bytes), or ~1:6 */
u = PyBytes_FromStringAndSize((char *)NULL, len * 6);
if (u == NULL)
return NULL;
p = buf = PyBytes_AsString(u);
end = s + len;
while (s < end) {
if (*s == '\\') {
*p++ = *s++;
if (*s & 0x80) {
strcpy(p, "u005c");
p += 5;
}
}
if (*s & 0x80) { /* XXX inefficient */
PyObject *w;
int kind;
void *data;
Py_ssize_t len, i;
w = decode_utf8(c, &s, end);
if (w == NULL) {
Py_DECREF(u);
return NULL;
}
kind = PyUnicode_KIND(w);
data = PyUnicode_DATA(w);
len = PyUnicode_GET_LENGTH(w);
for (i = 0; i < len; i++) {
Py_UCS4 chr = PyUnicode_READ(kind, data, i);
sprintf(p, "\\U%08x", chr);
p += 10;
}
/* Should be impossible to overflow */
assert(p - buf <= Py_SIZE(u));
Py_DECREF(w);
} else {
*p++ = *s++;
}
}
len = p - buf;
s = buf;
}
if (rawmode)
v = PyUnicode_DecodeRawUnicodeEscape(s, len, NULL);
else
v = PyUnicode_DecodeUnicodeEscape(s, len, NULL);
Py_XDECREF(u);
return v;
}
#endif
/* s is a Python string literal, including the bracketing quote characters,
* and r &/or u prefixes (if any), and embedded escape sequences (if any).
* parsestr parses it, and returns the decoded Python string object.
*/
static PyObject *
parsestr(struct compiling *c, const node *n, const char *s)
{
size_t len, i;
int quote = Py_CHARMASK(*s);
int rawmode = 0;
int need_encoding;
int unicode = c->c_future_unicode;
int bytes = 0;
if (isalpha(quote) || quote == '_') {
if (quote == 'u' || quote == 'U') {
quote = *++s;
unicode = 1;
}
if (quote == 'b' || quote == 'B') {
quote = *++s;
unicode = 0;
bytes = 1;
}
if (quote == 'r' || quote == 'R') {
quote = *++s;
rawmode = 1;
}
}
if (quote != '\'' && quote != '\"') {
PyErr_BadInternalCall();
return NULL;
}
s++;
len = strlen(s);
if (len > INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"string to parse is too long");
return NULL;
}
if (s[--len] != quote) {
PyErr_BadInternalCall();
return NULL;
}
if (len >= 4 && s[0] == quote && s[1] == quote) {
s += 2;
len -= 2;
if (s[--len] != quote || s[--len] != quote) {
PyErr_BadInternalCall();
return NULL;
}
}
if (Py_Py3kWarningFlag && bytes) {
for (i = 0; i < len; i++) {
if ((unsigned char)s[i] > 127) {
if (!ast_warn(c, n,
"non-ascii bytes literals not supported in 3.x"))
return NULL;
break;
}
}
}
#ifdef Py_USING_UNICODE
if (unicode || Py_UnicodeFlag) {
return decode_unicode(c, s, len, rawmode, c->c_encoding);
}
#endif
need_encoding = (c->c_encoding != NULL &&
strcmp(c->c_encoding, "utf-8") != 0 &&
strcmp(c->c_encoding, "iso-8859-1") != 0);
if (rawmode || strchr(s, '\\') == NULL) {
if (need_encoding) {
#ifndef Py_USING_UNICODE
/* This should not happen - we never see any other
encoding. */
Py_FatalError(
"cannot deal with encodings in this build.");
#else
PyObject *v, *u = PyUnicode_DecodeUTF8(s, len, NULL);
if (u == NULL)
return NULL;
v = PyUnicode_AsEncodedString(u, c->c_encoding, NULL);
Py_DECREF(u);
return v;
#endif
} else {
return PyBytes_FromStringAndSize(s, len);
}
}
return PyBytes_DecodeEscape(s, len, NULL, 1,
need_encoding ? c->c_encoding : NULL);
}
/* Build a Python string object out of a STRING atom. This takes care of
* compile-time literal catenation, calling parsestr() on each piece, and
* pasting the intermediate results together.
*/
static PyObject *
parsestrplus(struct compiling *c, const node *n)
{
PyObject *v;
int i;
REQ(CHILD(n, 0), STRING);
if ((v = parsestr(c, n, STR(CHILD(n, 0)))) != NULL) {
/* String literal concatenation */
for (i = 1; i < NCH(n); i++) {
PyObject *s;
s = parsestr(c, n, STR(CHILD(n, i)));
if (s == NULL)
goto onError;
if (PyBytes_Check(v) && PyBytes_Check(s)) {
PyBytes_ConcatAndDel(&v, s);
if (v == NULL)
goto onError;
}
#ifdef Py_USING_UNICODE
else {
PyObject *temp;
/* Python 2's PyUnicode_FromObject (which is
* called on the arguments to PyUnicode_Concat)
* automatically converts Bytes objects into
* Str objects, but in Python 3 it throws a
* syntax error. To allow mixed literal
* concatenation e.g. "foo" u"bar" (which is
* valid in Python 2), we have to explicitly
* check for Bytes and convert manually. */
if (PyBytes_Check(s)) {
temp = PyUnicode_FromEncodedObject(s, NULL, "strict");
Py_DECREF(s);
s = temp;
}
if (PyBytes_Check(v)) {
temp = PyUnicode_FromEncodedObject(v, NULL, "strict");
Py_DECREF(v);
v = temp;
}
temp = PyUnicode_Concat(v, s);
Py_DECREF(s);
Py_DECREF(v);
v = temp;
if (v == NULL)
goto onError;
}
#endif
}
}
return v;
onError:
Py_XDECREF(v);
return NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_1282_1 |
crossvul-cpp_data_good_4843_0 | /*
* linux/fs/ext4/super.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/inode.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller (davem@caip.rutgers.edu), 1995
*/
#include <linux/module.h>
#include <linux/string.h>
#include <linux/fs.h>
#include <linux/time.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/backing-dev.h>
#include <linux/parser.h>
#include <linux/buffer_head.h>
#include <linux/exportfs.h>
#include <linux/vfs.h>
#include <linux/random.h>
#include <linux/mount.h>
#include <linux/namei.h>
#include <linux/quotaops.h>
#include <linux/seq_file.h>
#include <linux/ctype.h>
#include <linux/log2.h>
#include <linux/crc16.h>
#include <linux/cleancache.h>
#include <asm/uaccess.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include "ext4.h"
#include "ext4_extents.h" /* Needed for trace points definition */
#include "ext4_jbd2.h"
#include "xattr.h"
#include "acl.h"
#include "mballoc.h"
#define CREATE_TRACE_POINTS
#include <trace/events/ext4.h>
static struct ext4_lazy_init *ext4_li_info;
static struct mutex ext4_li_mtx;
static struct ratelimit_state ext4_mount_msg_ratelimit;
static int ext4_load_journal(struct super_block *, struct ext4_super_block *,
unsigned long journal_devnum);
static int ext4_show_options(struct seq_file *seq, struct dentry *root);
static int ext4_commit_super(struct super_block *sb, int sync);
static void ext4_mark_recovery_complete(struct super_block *sb,
struct ext4_super_block *es);
static void ext4_clear_journal_err(struct super_block *sb,
struct ext4_super_block *es);
static int ext4_sync_fs(struct super_block *sb, int wait);
static int ext4_remount(struct super_block *sb, int *flags, char *data);
static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf);
static int ext4_unfreeze(struct super_block *sb);
static int ext4_freeze(struct super_block *sb);
static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data);
static inline int ext2_feature_set_ok(struct super_block *sb);
static inline int ext3_feature_set_ok(struct super_block *sb);
static int ext4_feature_set_ok(struct super_block *sb, int readonly);
static void ext4_destroy_lazyinit_thread(void);
static void ext4_unregister_li_request(struct super_block *sb);
static void ext4_clear_request_list(void);
static struct inode *ext4_get_journal_inode(struct super_block *sb,
unsigned int journal_inum);
/*
* Lock ordering
*
* Note the difference between i_mmap_sem (EXT4_I(inode)->i_mmap_sem) and
* i_mmap_rwsem (inode->i_mmap_rwsem)!
*
* page fault path:
* mmap_sem -> sb_start_pagefault -> i_mmap_sem (r) -> transaction start ->
* page lock -> i_data_sem (rw)
*
* buffered write path:
* sb_start_write -> i_mutex -> mmap_sem
* sb_start_write -> i_mutex -> transaction start -> page lock ->
* i_data_sem (rw)
*
* truncate:
* sb_start_write -> i_mutex -> EXT4_STATE_DIOREAD_LOCK (w) -> i_mmap_sem (w) ->
* i_mmap_rwsem (w) -> page lock
* sb_start_write -> i_mutex -> EXT4_STATE_DIOREAD_LOCK (w) -> i_mmap_sem (w) ->
* transaction start -> i_data_sem (rw)
*
* direct IO:
* sb_start_write -> i_mutex -> EXT4_STATE_DIOREAD_LOCK (r) -> mmap_sem
* sb_start_write -> i_mutex -> EXT4_STATE_DIOREAD_LOCK (r) ->
* transaction start -> i_data_sem (rw)
*
* writepages:
* transaction start -> page lock(s) -> i_data_sem (rw)
*/
#if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT2)
static struct file_system_type ext2_fs_type = {
.owner = THIS_MODULE,
.name = "ext2",
.mount = ext4_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext2");
MODULE_ALIAS("ext2");
#define IS_EXT2_SB(sb) ((sb)->s_bdev->bd_holder == &ext2_fs_type)
#else
#define IS_EXT2_SB(sb) (0)
#endif
static struct file_system_type ext3_fs_type = {
.owner = THIS_MODULE,
.name = "ext3",
.mount = ext4_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext3");
MODULE_ALIAS("ext3");
#define IS_EXT3_SB(sb) ((sb)->s_bdev->bd_holder == &ext3_fs_type)
static int ext4_verify_csum_type(struct super_block *sb,
struct ext4_super_block *es)
{
if (!ext4_has_feature_metadata_csum(sb))
return 1;
return es->s_checksum_type == EXT4_CRC32C_CHKSUM;
}
static __le32 ext4_superblock_csum(struct super_block *sb,
struct ext4_super_block *es)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int offset = offsetof(struct ext4_super_block, s_checksum);
__u32 csum;
csum = ext4_chksum(sbi, ~0, (char *)es, offset);
return cpu_to_le32(csum);
}
static int ext4_superblock_csum_verify(struct super_block *sb,
struct ext4_super_block *es)
{
if (!ext4_has_metadata_csum(sb))
return 1;
return es->s_checksum == ext4_superblock_csum(sb, es);
}
void ext4_superblock_csum_set(struct super_block *sb)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
if (!ext4_has_metadata_csum(sb))
return;
es->s_checksum = ext4_superblock_csum(sb, es);
}
void *ext4_kvmalloc(size_t size, gfp_t flags)
{
void *ret;
ret = kmalloc(size, flags | __GFP_NOWARN);
if (!ret)
ret = __vmalloc(size, flags, PAGE_KERNEL);
return ret;
}
void *ext4_kvzalloc(size_t size, gfp_t flags)
{
void *ret;
ret = kzalloc(size, flags | __GFP_NOWARN);
if (!ret)
ret = __vmalloc(size, flags | __GFP_ZERO, PAGE_KERNEL);
return ret;
}
ext4_fsblk_t ext4_block_bitmap(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_block_bitmap_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_block_bitmap_hi) << 32 : 0);
}
ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_inode_bitmap_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_inode_bitmap_hi) << 32 : 0);
}
ext4_fsblk_t ext4_inode_table(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le32_to_cpu(bg->bg_inode_table_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(ext4_fsblk_t)le32_to_cpu(bg->bg_inode_table_hi) << 32 : 0);
}
__u32 ext4_free_group_clusters(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_free_blocks_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_free_blocks_count_hi) << 16 : 0);
}
__u32 ext4_free_inodes_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_free_inodes_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_free_inodes_count_hi) << 16 : 0);
}
__u32 ext4_used_dirs_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_used_dirs_count_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_used_dirs_count_hi) << 16 : 0);
}
__u32 ext4_itable_unused_count(struct super_block *sb,
struct ext4_group_desc *bg)
{
return le16_to_cpu(bg->bg_itable_unused_lo) |
(EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT ?
(__u32)le16_to_cpu(bg->bg_itable_unused_hi) << 16 : 0);
}
void ext4_block_bitmap_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_block_bitmap_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_block_bitmap_hi = cpu_to_le32(blk >> 32);
}
void ext4_inode_bitmap_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_inode_bitmap_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_inode_bitmap_hi = cpu_to_le32(blk >> 32);
}
void ext4_inode_table_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk)
{
bg->bg_inode_table_lo = cpu_to_le32((u32)blk);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_inode_table_hi = cpu_to_le32(blk >> 32);
}
void ext4_free_group_clusters_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_free_blocks_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_free_blocks_count_hi = cpu_to_le16(count >> 16);
}
void ext4_free_inodes_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_free_inodes_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_free_inodes_count_hi = cpu_to_le16(count >> 16);
}
void ext4_used_dirs_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_used_dirs_count_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_used_dirs_count_hi = cpu_to_le16(count >> 16);
}
void ext4_itable_unused_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count)
{
bg->bg_itable_unused_lo = cpu_to_le16((__u16)count);
if (EXT4_DESC_SIZE(sb) >= EXT4_MIN_DESC_SIZE_64BIT)
bg->bg_itable_unused_hi = cpu_to_le16(count >> 16);
}
static void __save_error_info(struct super_block *sb, const char *func,
unsigned int line)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
if (bdev_read_only(sb->s_bdev))
return;
es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
es->s_last_error_time = cpu_to_le32(get_seconds());
strncpy(es->s_last_error_func, func, sizeof(es->s_last_error_func));
es->s_last_error_line = cpu_to_le32(line);
if (!es->s_first_error_time) {
es->s_first_error_time = es->s_last_error_time;
strncpy(es->s_first_error_func, func,
sizeof(es->s_first_error_func));
es->s_first_error_line = cpu_to_le32(line);
es->s_first_error_ino = es->s_last_error_ino;
es->s_first_error_block = es->s_last_error_block;
}
/*
* Start the daily error reporting function if it hasn't been
* started already
*/
if (!es->s_error_count)
mod_timer(&EXT4_SB(sb)->s_err_report, jiffies + 24*60*60*HZ);
le32_add_cpu(&es->s_error_count, 1);
}
static void save_error_info(struct super_block *sb, const char *func,
unsigned int line)
{
__save_error_info(sb, func, line);
ext4_commit_super(sb, 1);
}
/*
* The del_gendisk() function uninitializes the disk-specific data
* structures, including the bdi structure, without telling anyone
* else. Once this happens, any attempt to call mark_buffer_dirty()
* (for example, by ext4_commit_super), will cause a kernel OOPS.
* This is a kludge to prevent these oops until we can put in a proper
* hook in del_gendisk() to inform the VFS and file system layers.
*/
static int block_device_ejected(struct super_block *sb)
{
struct inode *bd_inode = sb->s_bdev->bd_inode;
struct backing_dev_info *bdi = inode_to_bdi(bd_inode);
return bdi->dev == NULL;
}
static void ext4_journal_commit_callback(journal_t *journal, transaction_t *txn)
{
struct super_block *sb = journal->j_private;
struct ext4_sb_info *sbi = EXT4_SB(sb);
int error = is_journal_aborted(journal);
struct ext4_journal_cb_entry *jce;
BUG_ON(txn->t_state == T_FINISHED);
spin_lock(&sbi->s_md_lock);
while (!list_empty(&txn->t_private_list)) {
jce = list_entry(txn->t_private_list.next,
struct ext4_journal_cb_entry, jce_list);
list_del_init(&jce->jce_list);
spin_unlock(&sbi->s_md_lock);
jce->jce_func(sb, jce, error);
spin_lock(&sbi->s_md_lock);
}
spin_unlock(&sbi->s_md_lock);
}
/* Deal with the reporting of failure conditions on a filesystem such as
* inconsistencies detected or read IO failures.
*
* On ext2, we can store the error state of the filesystem in the
* superblock. That is not possible on ext4, because we may have other
* write ordering constraints on the superblock which prevent us from
* writing it out straight away; and given that the journal is about to
* be aborted, we can't rely on the current, or future, transactions to
* write out the superblock safely.
*
* We'll just use the jbd2_journal_abort() error code to record an error in
* the journal instead. On recovery, the journal will complain about
* that error until we've noted it down and cleared it.
*/
static void ext4_handle_error(struct super_block *sb)
{
if (sb->s_flags & MS_RDONLY)
return;
if (!test_opt(sb, ERRORS_CONT)) {
journal_t *journal = EXT4_SB(sb)->s_journal;
EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
if (journal)
jbd2_journal_abort(journal, -EIO);
}
if (test_opt(sb, ERRORS_RO)) {
ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
/*
* Make sure updated value of ->s_mount_flags will be visible
* before ->s_flags update
*/
smp_wmb();
sb->s_flags |= MS_RDONLY;
}
if (test_opt(sb, ERRORS_PANIC)) {
if (EXT4_SB(sb)->s_journal &&
!(EXT4_SB(sb)->s_journal->j_flags & JBD2_REC_ERR))
return;
panic("EXT4-fs (device %s): panic forced after error\n",
sb->s_id);
}
}
#define ext4_error_ratelimit(sb) \
___ratelimit(&(EXT4_SB(sb)->s_err_ratelimit_state), \
"EXT4-fs error")
void __ext4_error(struct super_block *sb, const char *function,
unsigned int line, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (ext4_error_ratelimit(sb)) {
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: comm %s: %pV\n",
sb->s_id, function, line, current->comm, &vaf);
va_end(args);
}
save_error_info(sb, function, line);
ext4_handle_error(sb);
}
void __ext4_error_inode(struct inode *inode, const char *function,
unsigned int line, ext4_fsblk_t block,
const char *fmt, ...)
{
va_list args;
struct va_format vaf;
struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
es->s_last_error_ino = cpu_to_le32(inode->i_ino);
es->s_last_error_block = cpu_to_le64(block);
if (ext4_error_ratelimit(inode->i_sb)) {
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (block)
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
"inode #%lu: block %llu: comm %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
block, current->comm, &vaf);
else
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: "
"inode #%lu: comm %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
current->comm, &vaf);
va_end(args);
}
save_error_info(inode->i_sb, function, line);
ext4_handle_error(inode->i_sb);
}
void __ext4_error_file(struct file *file, const char *function,
unsigned int line, ext4_fsblk_t block,
const char *fmt, ...)
{
va_list args;
struct va_format vaf;
struct ext4_super_block *es;
struct inode *inode = file_inode(file);
char pathname[80], *path;
es = EXT4_SB(inode->i_sb)->s_es;
es->s_last_error_ino = cpu_to_le32(inode->i_ino);
if (ext4_error_ratelimit(inode->i_sb)) {
path = file_path(file, pathname, sizeof(pathname));
if (IS_ERR(path))
path = "(unknown)";
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (block)
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: inode #%lu: "
"block %llu: comm %s: path %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
block, current->comm, path, &vaf);
else
printk(KERN_CRIT
"EXT4-fs error (device %s): %s:%d: inode #%lu: "
"comm %s: path %s: %pV\n",
inode->i_sb->s_id, function, line, inode->i_ino,
current->comm, path, &vaf);
va_end(args);
}
save_error_info(inode->i_sb, function, line);
ext4_handle_error(inode->i_sb);
}
const char *ext4_decode_error(struct super_block *sb, int errno,
char nbuf[16])
{
char *errstr = NULL;
switch (errno) {
case -EFSCORRUPTED:
errstr = "Corrupt filesystem";
break;
case -EFSBADCRC:
errstr = "Filesystem failed CRC";
break;
case -EIO:
errstr = "IO failure";
break;
case -ENOMEM:
errstr = "Out of memory";
break;
case -EROFS:
if (!sb || (EXT4_SB(sb)->s_journal &&
EXT4_SB(sb)->s_journal->j_flags & JBD2_ABORT))
errstr = "Journal has aborted";
else
errstr = "Readonly filesystem";
break;
default:
/* If the caller passed in an extra buffer for unknown
* errors, textualise them now. Else we just return
* NULL. */
if (nbuf) {
/* Check for truncated error codes... */
if (snprintf(nbuf, 16, "error %d", -errno) >= 0)
errstr = nbuf;
}
break;
}
return errstr;
}
/* __ext4_std_error decodes expected errors from journaling functions
* automatically and invokes the appropriate error response. */
void __ext4_std_error(struct super_block *sb, const char *function,
unsigned int line, int errno)
{
char nbuf[16];
const char *errstr;
/* Special case: if the error is EROFS, and we're not already
* inside a transaction, then there's really no point in logging
* an error. */
if (errno == -EROFS && journal_current_handle() == NULL &&
(sb->s_flags & MS_RDONLY))
return;
if (ext4_error_ratelimit(sb)) {
errstr = ext4_decode_error(sb, errno, nbuf);
printk(KERN_CRIT "EXT4-fs error (device %s) in %s:%d: %s\n",
sb->s_id, function, line, errstr);
}
save_error_info(sb, function, line);
ext4_handle_error(sb);
}
/*
* ext4_abort is a much stronger failure handler than ext4_error. The
* abort function may be used to deal with unrecoverable failures such
* as journal IO errors or ENOMEM at a critical moment in log management.
*
* We unconditionally force the filesystem into an ABORT|READONLY state,
* unless the error response on the fs has been set to panic in which
* case we take the easy way out and panic immediately.
*/
void __ext4_abort(struct super_block *sb, const char *function,
unsigned int line, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
save_error_info(sb, function, line);
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: %pV\n",
sb->s_id, function, line, &vaf);
va_end(args);
if ((sb->s_flags & MS_RDONLY) == 0) {
ext4_msg(sb, KERN_CRIT, "Remounting filesystem read-only");
EXT4_SB(sb)->s_mount_flags |= EXT4_MF_FS_ABORTED;
/*
* Make sure updated value of ->s_mount_flags will be visible
* before ->s_flags update
*/
smp_wmb();
sb->s_flags |= MS_RDONLY;
if (EXT4_SB(sb)->s_journal)
jbd2_journal_abort(EXT4_SB(sb)->s_journal, -EIO);
save_error_info(sb, function, line);
}
if (test_opt(sb, ERRORS_PANIC)) {
if (EXT4_SB(sb)->s_journal &&
!(EXT4_SB(sb)->s_journal->j_flags & JBD2_REC_ERR))
return;
panic("EXT4-fs panic from previous error\n");
}
}
void __ext4_msg(struct super_block *sb,
const char *prefix, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (!___ratelimit(&(EXT4_SB(sb)->s_msg_ratelimit_state), "EXT4-fs"))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk("%sEXT4-fs (%s): %pV\n", prefix, sb->s_id, &vaf);
va_end(args);
}
#define ext4_warning_ratelimit(sb) \
___ratelimit(&(EXT4_SB(sb)->s_warning_ratelimit_state), \
"EXT4-fs warning")
void __ext4_warning(struct super_block *sb, const char *function,
unsigned int line, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (!ext4_warning_ratelimit(sb))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: %pV\n",
sb->s_id, function, line, &vaf);
va_end(args);
}
void __ext4_warning_inode(const struct inode *inode, const char *function,
unsigned int line, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
if (!ext4_warning_ratelimit(inode->i_sb))
return;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_WARNING "EXT4-fs warning (device %s): %s:%d: "
"inode #%lu: comm %s: %pV\n", inode->i_sb->s_id,
function, line, inode->i_ino, current->comm, &vaf);
va_end(args);
}
void __ext4_grp_locked_error(const char *function, unsigned int line,
struct super_block *sb, ext4_group_t grp,
unsigned long ino, ext4_fsblk_t block,
const char *fmt, ...)
__releases(bitlock)
__acquires(bitlock)
{
struct va_format vaf;
va_list args;
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
es->s_last_error_ino = cpu_to_le32(ino);
es->s_last_error_block = cpu_to_le64(block);
__save_error_info(sb, function, line);
if (ext4_error_ratelimit(sb)) {
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk(KERN_CRIT "EXT4-fs error (device %s): %s:%d: group %u, ",
sb->s_id, function, line, grp);
if (ino)
printk(KERN_CONT "inode %lu: ", ino);
if (block)
printk(KERN_CONT "block %llu:",
(unsigned long long) block);
printk(KERN_CONT "%pV\n", &vaf);
va_end(args);
}
if (test_opt(sb, ERRORS_CONT)) {
ext4_commit_super(sb, 0);
return;
}
ext4_unlock_group(sb, grp);
ext4_handle_error(sb);
/*
* We only get here in the ERRORS_RO case; relocking the group
* may be dangerous, but nothing bad will happen since the
* filesystem will have already been marked read/only and the
* journal has been aborted. We return 1 as a hint to callers
* who might what to use the return value from
* ext4_grp_locked_error() to distinguish between the
* ERRORS_CONT and ERRORS_RO case, and perhaps return more
* aggressively from the ext4 function in question, with a
* more appropriate error code.
*/
ext4_lock_group(sb, grp);
return;
}
void ext4_update_dynamic_rev(struct super_block *sb)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
if (le32_to_cpu(es->s_rev_level) > EXT4_GOOD_OLD_REV)
return;
ext4_warning(sb,
"updating to rev %d because of new feature flag, "
"running e2fsck is recommended",
EXT4_DYNAMIC_REV);
es->s_first_ino = cpu_to_le32(EXT4_GOOD_OLD_FIRST_INO);
es->s_inode_size = cpu_to_le16(EXT4_GOOD_OLD_INODE_SIZE);
es->s_rev_level = cpu_to_le32(EXT4_DYNAMIC_REV);
/* leave es->s_feature_*compat flags alone */
/* es->s_uuid will be set by e2fsck if empty */
/*
* The rest of the superblock fields should be zero, and if not it
* means they are likely already in use, so leave them alone. We
* can leave it up to e2fsck to clean up any inconsistencies there.
*/
}
/*
* Open the external journal device
*/
static struct block_device *ext4_blkdev_get(dev_t dev, struct super_block *sb)
{
struct block_device *bdev;
char b[BDEVNAME_SIZE];
bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL, sb);
if (IS_ERR(bdev))
goto fail;
return bdev;
fail:
ext4_msg(sb, KERN_ERR, "failed to open journal device %s: %ld",
__bdevname(dev, b), PTR_ERR(bdev));
return NULL;
}
/*
* Release the journal device
*/
static void ext4_blkdev_put(struct block_device *bdev)
{
blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
}
static void ext4_blkdev_remove(struct ext4_sb_info *sbi)
{
struct block_device *bdev;
bdev = sbi->journal_bdev;
if (bdev) {
ext4_blkdev_put(bdev);
sbi->journal_bdev = NULL;
}
}
static inline struct inode *orphan_list_entry(struct list_head *l)
{
return &list_entry(l, struct ext4_inode_info, i_orphan)->vfs_inode;
}
static void dump_orphan_list(struct super_block *sb, struct ext4_sb_info *sbi)
{
struct list_head *l;
ext4_msg(sb, KERN_ERR, "sb orphan head is %d",
le32_to_cpu(sbi->s_es->s_last_orphan));
printk(KERN_ERR "sb_info orphan list:\n");
list_for_each(l, &sbi->s_orphan) {
struct inode *inode = orphan_list_entry(l);
printk(KERN_ERR " "
"inode %s:%lu at %p: mode %o, nlink %d, next %d\n",
inode->i_sb->s_id, inode->i_ino, inode,
inode->i_mode, inode->i_nlink,
NEXT_ORPHAN(inode));
}
}
static void ext4_put_super(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int i, err;
ext4_unregister_li_request(sb);
dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
flush_workqueue(sbi->rsv_conversion_wq);
destroy_workqueue(sbi->rsv_conversion_wq);
if (sbi->s_journal) {
err = jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
if (err < 0)
ext4_abort(sb, "Couldn't clean up the journal");
}
ext4_unregister_sysfs(sb);
ext4_es_unregister_shrinker(sbi);
del_timer_sync(&sbi->s_err_report);
ext4_release_system_zone(sb);
ext4_mb_release(sb);
ext4_ext_release(sb);
if (!(sb->s_flags & MS_RDONLY)) {
ext4_clear_feature_journal_needs_recovery(sb);
es->s_state = cpu_to_le16(sbi->s_mount_state);
}
if (!(sb->s_flags & MS_RDONLY))
ext4_commit_super(sb, 1);
for (i = 0; i < sbi->s_gdb_count; i++)
brelse(sbi->s_group_desc[i]);
kvfree(sbi->s_group_desc);
kvfree(sbi->s_flex_groups);
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
percpu_free_rwsem(&sbi->s_journal_flag_rwsem);
#ifdef CONFIG_QUOTA
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
/* Debugging code just in case the in-memory inode orphan list
* isn't empty. The on-disk one can be non-empty if we've
* detected an error and taken the fs readonly, but the
* in-memory list had better be clean by this point. */
if (!list_empty(&sbi->s_orphan))
dump_orphan_list(sb, sbi);
J_ASSERT(list_empty(&sbi->s_orphan));
sync_blockdev(sb->s_bdev);
invalidate_bdev(sb->s_bdev);
if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) {
/*
* Invalidate the journal device's buffers. We don't want them
* floating about in memory - the physical journal device may
* hotswapped, and it breaks the `ro-after' testing code.
*/
sync_blockdev(sbi->journal_bdev);
invalidate_bdev(sbi->journal_bdev);
ext4_blkdev_remove(sbi);
}
if (sbi->s_mb_cache) {
ext4_xattr_destroy_cache(sbi->s_mb_cache);
sbi->s_mb_cache = NULL;
}
if (sbi->s_mmp_tsk)
kthread_stop(sbi->s_mmp_tsk);
brelse(sbi->s_sbh);
sb->s_fs_info = NULL;
/*
* Now that we are completely done shutting down the
* superblock, we need to actually destroy the kobject.
*/
kobject_put(&sbi->s_kobj);
wait_for_completion(&sbi->s_kobj_unregister);
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
}
static struct kmem_cache *ext4_inode_cachep;
/*
* Called inside transaction, so use GFP_NOFS
*/
static struct inode *ext4_alloc_inode(struct super_block *sb)
{
struct ext4_inode_info *ei;
ei = kmem_cache_alloc(ext4_inode_cachep, GFP_NOFS);
if (!ei)
return NULL;
ei->vfs_inode.i_version = 1;
spin_lock_init(&ei->i_raw_lock);
INIT_LIST_HEAD(&ei->i_prealloc_list);
spin_lock_init(&ei->i_prealloc_lock);
ext4_es_init_tree(&ei->i_es_tree);
rwlock_init(&ei->i_es_lock);
INIT_LIST_HEAD(&ei->i_es_list);
ei->i_es_all_nr = 0;
ei->i_es_shk_nr = 0;
ei->i_es_shrink_lblk = 0;
ei->i_reserved_data_blocks = 0;
ei->i_reserved_meta_blocks = 0;
ei->i_allocated_meta_blocks = 0;
ei->i_da_metadata_calc_len = 0;
ei->i_da_metadata_calc_last_lblock = 0;
spin_lock_init(&(ei->i_block_reservation_lock));
#ifdef CONFIG_QUOTA
ei->i_reserved_quota = 0;
memset(&ei->i_dquot, 0, sizeof(ei->i_dquot));
#endif
ei->jinode = NULL;
INIT_LIST_HEAD(&ei->i_rsv_conversion_list);
spin_lock_init(&ei->i_completed_io_lock);
ei->i_sync_tid = 0;
ei->i_datasync_tid = 0;
atomic_set(&ei->i_unwritten, 0);
INIT_WORK(&ei->i_rsv_conversion_work, ext4_end_io_rsv_work);
return &ei->vfs_inode;
}
static int ext4_drop_inode(struct inode *inode)
{
int drop = generic_drop_inode(inode);
trace_ext4_drop_inode(inode, drop);
return drop;
}
static void ext4_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(ext4_inode_cachep, EXT4_I(inode));
}
static void ext4_destroy_inode(struct inode *inode)
{
if (!list_empty(&(EXT4_I(inode)->i_orphan))) {
ext4_msg(inode->i_sb, KERN_ERR,
"Inode %lu (%p): orphan list check failed!",
inode->i_ino, EXT4_I(inode));
print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 16, 4,
EXT4_I(inode), sizeof(struct ext4_inode_info),
true);
dump_stack();
}
call_rcu(&inode->i_rcu, ext4_i_callback);
}
static void init_once(void *foo)
{
struct ext4_inode_info *ei = (struct ext4_inode_info *) foo;
INIT_LIST_HEAD(&ei->i_orphan);
init_rwsem(&ei->xattr_sem);
init_rwsem(&ei->i_data_sem);
init_rwsem(&ei->i_mmap_sem);
inode_init_once(&ei->vfs_inode);
}
static int __init init_inodecache(void)
{
ext4_inode_cachep = kmem_cache_create("ext4_inode_cache",
sizeof(struct ext4_inode_info),
0, (SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD|SLAB_ACCOUNT),
init_once);
if (ext4_inode_cachep == NULL)
return -ENOMEM;
return 0;
}
static void destroy_inodecache(void)
{
/*
* Make sure all delayed rcu free inodes are flushed before we
* destroy cache.
*/
rcu_barrier();
kmem_cache_destroy(ext4_inode_cachep);
}
void ext4_clear_inode(struct inode *inode)
{
invalidate_inode_buffers(inode);
clear_inode(inode);
dquot_drop(inode);
ext4_discard_preallocations(inode);
ext4_es_remove_extent(inode, 0, EXT_MAX_BLOCKS);
if (EXT4_I(inode)->jinode) {
jbd2_journal_release_jbd_inode(EXT4_JOURNAL(inode),
EXT4_I(inode)->jinode);
jbd2_free_inode(EXT4_I(inode)->jinode);
EXT4_I(inode)->jinode = NULL;
}
#ifdef CONFIG_EXT4_FS_ENCRYPTION
fscrypt_put_encryption_info(inode, NULL);
#endif
}
static struct inode *ext4_nfs_get_inode(struct super_block *sb,
u64 ino, u32 generation)
{
struct inode *inode;
if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
return ERR_PTR(-ESTALE);
if (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
return ERR_PTR(-ESTALE);
/* iget isn't really right if the inode is currently unallocated!!
*
* ext4_read_inode will return a bad_inode if the inode had been
* deleted, so we should be safe.
*
* Currently we don't know the generation for parent directory, so
* a generation of 0 means "accept any"
*/
inode = ext4_iget_normal(sb, ino);
if (IS_ERR(inode))
return ERR_CAST(inode);
if (generation && inode->i_generation != generation) {
iput(inode);
return ERR_PTR(-ESTALE);
}
return inode;
}
static struct dentry *ext4_fh_to_dentry(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
ext4_nfs_get_inode);
}
static struct dentry *ext4_fh_to_parent(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_parent(sb, fid, fh_len, fh_type,
ext4_nfs_get_inode);
}
/*
* Try to release metadata pages (indirect blocks, directories) which are
* mapped via the block device. Since these pages could have journal heads
* which would prevent try_to_free_buffers() from freeing them, we must use
* jbd2 layer's try_to_free_buffers() function to release them.
*/
static int bdev_try_to_free_page(struct super_block *sb, struct page *page,
gfp_t wait)
{
journal_t *journal = EXT4_SB(sb)->s_journal;
WARN_ON(PageChecked(page));
if (!page_has_buffers(page))
return 0;
if (journal)
return jbd2_journal_try_to_free_buffers(journal, page,
wait & ~__GFP_DIRECT_RECLAIM);
return try_to_free_buffers(page);
}
#ifdef CONFIG_EXT4_FS_ENCRYPTION
static int ext4_get_context(struct inode *inode, void *ctx, size_t len)
{
return ext4_xattr_get(inode, EXT4_XATTR_INDEX_ENCRYPTION,
EXT4_XATTR_NAME_ENCRYPTION_CONTEXT, ctx, len);
}
static int ext4_key_prefix(struct inode *inode, u8 **key)
{
*key = EXT4_SB(inode->i_sb)->key_prefix;
return EXT4_SB(inode->i_sb)->key_prefix_size;
}
static int ext4_prepare_context(struct inode *inode)
{
return ext4_convert_inline_data(inode);
}
static int ext4_set_context(struct inode *inode, const void *ctx, size_t len,
void *fs_data)
{
handle_t *handle = fs_data;
int res, res2, retries = 0;
/*
* If a journal handle was specified, then the encryption context is
* being set on a new inode via inheritance and is part of a larger
* transaction to create the inode. Otherwise the encryption context is
* being set on an existing inode in its own transaction. Only in the
* latter case should the "retry on ENOSPC" logic be used.
*/
if (handle) {
res = ext4_xattr_set_handle(handle, inode,
EXT4_XATTR_INDEX_ENCRYPTION,
EXT4_XATTR_NAME_ENCRYPTION_CONTEXT,
ctx, len, 0);
if (!res) {
ext4_set_inode_flag(inode, EXT4_INODE_ENCRYPT);
ext4_clear_inode_state(inode,
EXT4_STATE_MAY_INLINE_DATA);
/*
* Update inode->i_flags - e.g. S_DAX may get disabled
*/
ext4_set_inode_flags(inode);
}
return res;
}
retry:
handle = ext4_journal_start(inode, EXT4_HT_MISC,
ext4_jbd2_credits_xattr(inode));
if (IS_ERR(handle))
return PTR_ERR(handle);
res = ext4_xattr_set_handle(handle, inode, EXT4_XATTR_INDEX_ENCRYPTION,
EXT4_XATTR_NAME_ENCRYPTION_CONTEXT,
ctx, len, 0);
if (!res) {
ext4_set_inode_flag(inode, EXT4_INODE_ENCRYPT);
/* Update inode->i_flags - e.g. S_DAX may get disabled */
ext4_set_inode_flags(inode);
res = ext4_mark_inode_dirty(handle, inode);
if (res)
EXT4_ERROR_INODE(inode, "Failed to mark inode dirty");
}
res2 = ext4_journal_stop(handle);
if (res == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
goto retry;
if (!res)
res = res2;
return res;
}
static int ext4_dummy_context(struct inode *inode)
{
return DUMMY_ENCRYPTION_ENABLED(EXT4_SB(inode->i_sb));
}
static unsigned ext4_max_namelen(struct inode *inode)
{
return S_ISLNK(inode->i_mode) ? inode->i_sb->s_blocksize :
EXT4_NAME_LEN;
}
static struct fscrypt_operations ext4_cryptops = {
.get_context = ext4_get_context,
.key_prefix = ext4_key_prefix,
.prepare_context = ext4_prepare_context,
.set_context = ext4_set_context,
.dummy_context = ext4_dummy_context,
.is_encrypted = ext4_encrypted_inode,
.empty_dir = ext4_empty_dir,
.max_namelen = ext4_max_namelen,
};
#else
static struct fscrypt_operations ext4_cryptops = {
.is_encrypted = ext4_encrypted_inode,
};
#endif
#ifdef CONFIG_QUOTA
static char *quotatypes[] = INITQFNAMES;
#define QTYPE2NAME(t) (quotatypes[t])
static int ext4_write_dquot(struct dquot *dquot);
static int ext4_acquire_dquot(struct dquot *dquot);
static int ext4_release_dquot(struct dquot *dquot);
static int ext4_mark_dquot_dirty(struct dquot *dquot);
static int ext4_write_info(struct super_block *sb, int type);
static int ext4_quota_on(struct super_block *sb, int type, int format_id,
struct path *path);
static int ext4_quota_off(struct super_block *sb, int type);
static int ext4_quota_on_mount(struct super_block *sb, int type);
static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
size_t len, loff_t off);
static ssize_t ext4_quota_write(struct super_block *sb, int type,
const char *data, size_t len, loff_t off);
static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
unsigned int flags);
static int ext4_enable_quotas(struct super_block *sb);
static int ext4_get_next_id(struct super_block *sb, struct kqid *qid);
static struct dquot **ext4_get_dquots(struct inode *inode)
{
return EXT4_I(inode)->i_dquot;
}
static const struct dquot_operations ext4_quota_operations = {
.get_reserved_space = ext4_get_reserved_space,
.write_dquot = ext4_write_dquot,
.acquire_dquot = ext4_acquire_dquot,
.release_dquot = ext4_release_dquot,
.mark_dirty = ext4_mark_dquot_dirty,
.write_info = ext4_write_info,
.alloc_dquot = dquot_alloc,
.destroy_dquot = dquot_destroy,
.get_projid = ext4_get_projid,
.get_next_id = ext4_get_next_id,
};
static const struct quotactl_ops ext4_qctl_operations = {
.quota_on = ext4_quota_on,
.quota_off = ext4_quota_off,
.quota_sync = dquot_quota_sync,
.get_state = dquot_get_state,
.set_info = dquot_set_dqinfo,
.get_dqblk = dquot_get_dqblk,
.set_dqblk = dquot_set_dqblk,
.get_nextdqblk = dquot_get_next_dqblk,
};
#endif
static const struct super_operations ext4_sops = {
.alloc_inode = ext4_alloc_inode,
.destroy_inode = ext4_destroy_inode,
.write_inode = ext4_write_inode,
.dirty_inode = ext4_dirty_inode,
.drop_inode = ext4_drop_inode,
.evict_inode = ext4_evict_inode,
.put_super = ext4_put_super,
.sync_fs = ext4_sync_fs,
.freeze_fs = ext4_freeze,
.unfreeze_fs = ext4_unfreeze,
.statfs = ext4_statfs,
.remount_fs = ext4_remount,
.show_options = ext4_show_options,
#ifdef CONFIG_QUOTA
.quota_read = ext4_quota_read,
.quota_write = ext4_quota_write,
.get_dquots = ext4_get_dquots,
#endif
.bdev_try_to_free_page = bdev_try_to_free_page,
};
static const struct export_operations ext4_export_ops = {
.fh_to_dentry = ext4_fh_to_dentry,
.fh_to_parent = ext4_fh_to_parent,
.get_parent = ext4_get_parent,
};
enum {
Opt_bsd_df, Opt_minix_df, Opt_grpid, Opt_nogrpid,
Opt_resgid, Opt_resuid, Opt_sb, Opt_err_cont, Opt_err_panic, Opt_err_ro,
Opt_nouid32, Opt_debug, Opt_removed,
Opt_user_xattr, Opt_nouser_xattr, Opt_acl, Opt_noacl,
Opt_auto_da_alloc, Opt_noauto_da_alloc, Opt_noload,
Opt_commit, Opt_min_batch_time, Opt_max_batch_time, Opt_journal_dev,
Opt_journal_path, Opt_journal_checksum, Opt_journal_async_commit,
Opt_abort, Opt_data_journal, Opt_data_ordered, Opt_data_writeback,
Opt_data_err_abort, Opt_data_err_ignore, Opt_test_dummy_encryption,
Opt_usrjquota, Opt_grpjquota, Opt_offusrjquota, Opt_offgrpjquota,
Opt_jqfmt_vfsold, Opt_jqfmt_vfsv0, Opt_jqfmt_vfsv1, Opt_quota,
Opt_noquota, Opt_barrier, Opt_nobarrier, Opt_err,
Opt_usrquota, Opt_grpquota, Opt_prjquota, Opt_i_version, Opt_dax,
Opt_stripe, Opt_delalloc, Opt_nodelalloc, Opt_mblk_io_submit,
Opt_lazytime, Opt_nolazytime,
Opt_nomblk_io_submit, Opt_block_validity, Opt_noblock_validity,
Opt_inode_readahead_blks, Opt_journal_ioprio,
Opt_dioread_nolock, Opt_dioread_lock,
Opt_discard, Opt_nodiscard, Opt_init_itable, Opt_noinit_itable,
Opt_max_dir_size_kb, Opt_nojournal_checksum,
};
static const match_table_t tokens = {
{Opt_bsd_df, "bsddf"},
{Opt_minix_df, "minixdf"},
{Opt_grpid, "grpid"},
{Opt_grpid, "bsdgroups"},
{Opt_nogrpid, "nogrpid"},
{Opt_nogrpid, "sysvgroups"},
{Opt_resgid, "resgid=%u"},
{Opt_resuid, "resuid=%u"},
{Opt_sb, "sb=%u"},
{Opt_err_cont, "errors=continue"},
{Opt_err_panic, "errors=panic"},
{Opt_err_ro, "errors=remount-ro"},
{Opt_nouid32, "nouid32"},
{Opt_debug, "debug"},
{Opt_removed, "oldalloc"},
{Opt_removed, "orlov"},
{Opt_user_xattr, "user_xattr"},
{Opt_nouser_xattr, "nouser_xattr"},
{Opt_acl, "acl"},
{Opt_noacl, "noacl"},
{Opt_noload, "norecovery"},
{Opt_noload, "noload"},
{Opt_removed, "nobh"},
{Opt_removed, "bh"},
{Opt_commit, "commit=%u"},
{Opt_min_batch_time, "min_batch_time=%u"},
{Opt_max_batch_time, "max_batch_time=%u"},
{Opt_journal_dev, "journal_dev=%u"},
{Opt_journal_path, "journal_path=%s"},
{Opt_journal_checksum, "journal_checksum"},
{Opt_nojournal_checksum, "nojournal_checksum"},
{Opt_journal_async_commit, "journal_async_commit"},
{Opt_abort, "abort"},
{Opt_data_journal, "data=journal"},
{Opt_data_ordered, "data=ordered"},
{Opt_data_writeback, "data=writeback"},
{Opt_data_err_abort, "data_err=abort"},
{Opt_data_err_ignore, "data_err=ignore"},
{Opt_offusrjquota, "usrjquota="},
{Opt_usrjquota, "usrjquota=%s"},
{Opt_offgrpjquota, "grpjquota="},
{Opt_grpjquota, "grpjquota=%s"},
{Opt_jqfmt_vfsold, "jqfmt=vfsold"},
{Opt_jqfmt_vfsv0, "jqfmt=vfsv0"},
{Opt_jqfmt_vfsv1, "jqfmt=vfsv1"},
{Opt_grpquota, "grpquota"},
{Opt_noquota, "noquota"},
{Opt_quota, "quota"},
{Opt_usrquota, "usrquota"},
{Opt_prjquota, "prjquota"},
{Opt_barrier, "barrier=%u"},
{Opt_barrier, "barrier"},
{Opt_nobarrier, "nobarrier"},
{Opt_i_version, "i_version"},
{Opt_dax, "dax"},
{Opt_stripe, "stripe=%u"},
{Opt_delalloc, "delalloc"},
{Opt_lazytime, "lazytime"},
{Opt_nolazytime, "nolazytime"},
{Opt_nodelalloc, "nodelalloc"},
{Opt_removed, "mblk_io_submit"},
{Opt_removed, "nomblk_io_submit"},
{Opt_block_validity, "block_validity"},
{Opt_noblock_validity, "noblock_validity"},
{Opt_inode_readahead_blks, "inode_readahead_blks=%u"},
{Opt_journal_ioprio, "journal_ioprio=%u"},
{Opt_auto_da_alloc, "auto_da_alloc=%u"},
{Opt_auto_da_alloc, "auto_da_alloc"},
{Opt_noauto_da_alloc, "noauto_da_alloc"},
{Opt_dioread_nolock, "dioread_nolock"},
{Opt_dioread_lock, "dioread_lock"},
{Opt_discard, "discard"},
{Opt_nodiscard, "nodiscard"},
{Opt_init_itable, "init_itable=%u"},
{Opt_init_itable, "init_itable"},
{Opt_noinit_itable, "noinit_itable"},
{Opt_max_dir_size_kb, "max_dir_size_kb=%u"},
{Opt_test_dummy_encryption, "test_dummy_encryption"},
{Opt_removed, "check=none"}, /* mount option from ext2/3 */
{Opt_removed, "nocheck"}, /* mount option from ext2/3 */
{Opt_removed, "reservation"}, /* mount option from ext2/3 */
{Opt_removed, "noreservation"}, /* mount option from ext2/3 */
{Opt_removed, "journal=%u"}, /* mount option from ext2/3 */
{Opt_err, NULL},
};
static ext4_fsblk_t get_sb_block(void **data)
{
ext4_fsblk_t sb_block;
char *options = (char *) *data;
if (!options || strncmp(options, "sb=", 3) != 0)
return 1; /* Default location */
options += 3;
/* TODO: use simple_strtoll with >32bit ext4 */
sb_block = simple_strtoul(options, &options, 0);
if (*options && *options != ',') {
printk(KERN_ERR "EXT4-fs: Invalid sb specification: %s\n",
(char *) *data);
return 1;
}
if (*options == ',')
options++;
*data = (void *) options;
return sb_block;
}
#define DEFAULT_JOURNAL_IOPRIO (IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 3))
static char deprecated_msg[] = "Mount option \"%s\" will be removed by %s\n"
"Contact linux-ext4@vger.kernel.org if you think we should keep it.\n";
#ifdef CONFIG_QUOTA
static int set_qf_name(struct super_block *sb, int qtype, substring_t *args)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
char *qname;
int ret = -1;
if (sb_any_quota_loaded(sb) &&
!sbi->s_qf_names[qtype]) {
ext4_msg(sb, KERN_ERR,
"Cannot change journaled "
"quota options when quota turned on");
return -1;
}
if (ext4_has_feature_quota(sb)) {
ext4_msg(sb, KERN_INFO, "Journaled quota options "
"ignored when QUOTA feature is enabled");
return 1;
}
qname = match_strdup(args);
if (!qname) {
ext4_msg(sb, KERN_ERR,
"Not enough memory for storing quotafile name");
return -1;
}
if (sbi->s_qf_names[qtype]) {
if (strcmp(sbi->s_qf_names[qtype], qname) == 0)
ret = 1;
else
ext4_msg(sb, KERN_ERR,
"%s quota file already specified",
QTYPE2NAME(qtype));
goto errout;
}
if (strchr(qname, '/')) {
ext4_msg(sb, KERN_ERR,
"quotafile must be on filesystem root");
goto errout;
}
sbi->s_qf_names[qtype] = qname;
set_opt(sb, QUOTA);
return 1;
errout:
kfree(qname);
return ret;
}
static int clear_qf_name(struct super_block *sb, int qtype)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (sb_any_quota_loaded(sb) &&
sbi->s_qf_names[qtype]) {
ext4_msg(sb, KERN_ERR, "Cannot change journaled quota options"
" when quota turned on");
return -1;
}
kfree(sbi->s_qf_names[qtype]);
sbi->s_qf_names[qtype] = NULL;
return 1;
}
#endif
#define MOPT_SET 0x0001
#define MOPT_CLEAR 0x0002
#define MOPT_NOSUPPORT 0x0004
#define MOPT_EXPLICIT 0x0008
#define MOPT_CLEAR_ERR 0x0010
#define MOPT_GTE0 0x0020
#ifdef CONFIG_QUOTA
#define MOPT_Q 0
#define MOPT_QFMT 0x0040
#else
#define MOPT_Q MOPT_NOSUPPORT
#define MOPT_QFMT MOPT_NOSUPPORT
#endif
#define MOPT_DATAJ 0x0080
#define MOPT_NO_EXT2 0x0100
#define MOPT_NO_EXT3 0x0200
#define MOPT_EXT4_ONLY (MOPT_NO_EXT2 | MOPT_NO_EXT3)
#define MOPT_STRING 0x0400
static const struct mount_opts {
int token;
int mount_opt;
int flags;
} ext4_mount_opts[] = {
{Opt_minix_df, EXT4_MOUNT_MINIX_DF, MOPT_SET},
{Opt_bsd_df, EXT4_MOUNT_MINIX_DF, MOPT_CLEAR},
{Opt_grpid, EXT4_MOUNT_GRPID, MOPT_SET},
{Opt_nogrpid, EXT4_MOUNT_GRPID, MOPT_CLEAR},
{Opt_block_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_SET},
{Opt_noblock_validity, EXT4_MOUNT_BLOCK_VALIDITY, MOPT_CLEAR},
{Opt_dioread_nolock, EXT4_MOUNT_DIOREAD_NOLOCK,
MOPT_EXT4_ONLY | MOPT_SET},
{Opt_dioread_lock, EXT4_MOUNT_DIOREAD_NOLOCK,
MOPT_EXT4_ONLY | MOPT_CLEAR},
{Opt_discard, EXT4_MOUNT_DISCARD, MOPT_SET},
{Opt_nodiscard, EXT4_MOUNT_DISCARD, MOPT_CLEAR},
{Opt_delalloc, EXT4_MOUNT_DELALLOC,
MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
{Opt_nodelalloc, EXT4_MOUNT_DELALLOC,
MOPT_EXT4_ONLY | MOPT_CLEAR},
{Opt_nojournal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
MOPT_EXT4_ONLY | MOPT_CLEAR},
{Opt_journal_checksum, EXT4_MOUNT_JOURNAL_CHECKSUM,
MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
{Opt_journal_async_commit, (EXT4_MOUNT_JOURNAL_ASYNC_COMMIT |
EXT4_MOUNT_JOURNAL_CHECKSUM),
MOPT_EXT4_ONLY | MOPT_SET | MOPT_EXPLICIT},
{Opt_noload, EXT4_MOUNT_NOLOAD, MOPT_NO_EXT2 | MOPT_SET},
{Opt_err_panic, EXT4_MOUNT_ERRORS_PANIC, MOPT_SET | MOPT_CLEAR_ERR},
{Opt_err_ro, EXT4_MOUNT_ERRORS_RO, MOPT_SET | MOPT_CLEAR_ERR},
{Opt_err_cont, EXT4_MOUNT_ERRORS_CONT, MOPT_SET | MOPT_CLEAR_ERR},
{Opt_data_err_abort, EXT4_MOUNT_DATA_ERR_ABORT,
MOPT_NO_EXT2},
{Opt_data_err_ignore, EXT4_MOUNT_DATA_ERR_ABORT,
MOPT_NO_EXT2},
{Opt_barrier, EXT4_MOUNT_BARRIER, MOPT_SET},
{Opt_nobarrier, EXT4_MOUNT_BARRIER, MOPT_CLEAR},
{Opt_noauto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_SET},
{Opt_auto_da_alloc, EXT4_MOUNT_NO_AUTO_DA_ALLOC, MOPT_CLEAR},
{Opt_noinit_itable, EXT4_MOUNT_INIT_INODE_TABLE, MOPT_CLEAR},
{Opt_commit, 0, MOPT_GTE0},
{Opt_max_batch_time, 0, MOPT_GTE0},
{Opt_min_batch_time, 0, MOPT_GTE0},
{Opt_inode_readahead_blks, 0, MOPT_GTE0},
{Opt_init_itable, 0, MOPT_GTE0},
{Opt_dax, EXT4_MOUNT_DAX, MOPT_SET},
{Opt_stripe, 0, MOPT_GTE0},
{Opt_resuid, 0, MOPT_GTE0},
{Opt_resgid, 0, MOPT_GTE0},
{Opt_journal_dev, 0, MOPT_NO_EXT2 | MOPT_GTE0},
{Opt_journal_path, 0, MOPT_NO_EXT2 | MOPT_STRING},
{Opt_journal_ioprio, 0, MOPT_NO_EXT2 | MOPT_GTE0},
{Opt_data_journal, EXT4_MOUNT_JOURNAL_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
{Opt_data_ordered, EXT4_MOUNT_ORDERED_DATA, MOPT_NO_EXT2 | MOPT_DATAJ},
{Opt_data_writeback, EXT4_MOUNT_WRITEBACK_DATA,
MOPT_NO_EXT2 | MOPT_DATAJ},
{Opt_user_xattr, EXT4_MOUNT_XATTR_USER, MOPT_SET},
{Opt_nouser_xattr, EXT4_MOUNT_XATTR_USER, MOPT_CLEAR},
#ifdef CONFIG_EXT4_FS_POSIX_ACL
{Opt_acl, EXT4_MOUNT_POSIX_ACL, MOPT_SET},
{Opt_noacl, EXT4_MOUNT_POSIX_ACL, MOPT_CLEAR},
#else
{Opt_acl, 0, MOPT_NOSUPPORT},
{Opt_noacl, 0, MOPT_NOSUPPORT},
#endif
{Opt_nouid32, EXT4_MOUNT_NO_UID32, MOPT_SET},
{Opt_debug, EXT4_MOUNT_DEBUG, MOPT_SET},
{Opt_quota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA, MOPT_SET | MOPT_Q},
{Opt_usrquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA,
MOPT_SET | MOPT_Q},
{Opt_grpquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_GRPQUOTA,
MOPT_SET | MOPT_Q},
{Opt_prjquota, EXT4_MOUNT_QUOTA | EXT4_MOUNT_PRJQUOTA,
MOPT_SET | MOPT_Q},
{Opt_noquota, (EXT4_MOUNT_QUOTA | EXT4_MOUNT_USRQUOTA |
EXT4_MOUNT_GRPQUOTA | EXT4_MOUNT_PRJQUOTA),
MOPT_CLEAR | MOPT_Q},
{Opt_usrjquota, 0, MOPT_Q},
{Opt_grpjquota, 0, MOPT_Q},
{Opt_offusrjquota, 0, MOPT_Q},
{Opt_offgrpjquota, 0, MOPT_Q},
{Opt_jqfmt_vfsold, QFMT_VFS_OLD, MOPT_QFMT},
{Opt_jqfmt_vfsv0, QFMT_VFS_V0, MOPT_QFMT},
{Opt_jqfmt_vfsv1, QFMT_VFS_V1, MOPT_QFMT},
{Opt_max_dir_size_kb, 0, MOPT_GTE0},
{Opt_test_dummy_encryption, 0, MOPT_GTE0},
{Opt_err, 0, 0}
};
static int handle_mount_opt(struct super_block *sb, char *opt, int token,
substring_t *args, unsigned long *journal_devnum,
unsigned int *journal_ioprio, int is_remount)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
const struct mount_opts *m;
kuid_t uid;
kgid_t gid;
int arg = 0;
#ifdef CONFIG_QUOTA
if (token == Opt_usrjquota)
return set_qf_name(sb, USRQUOTA, &args[0]);
else if (token == Opt_grpjquota)
return set_qf_name(sb, GRPQUOTA, &args[0]);
else if (token == Opt_offusrjquota)
return clear_qf_name(sb, USRQUOTA);
else if (token == Opt_offgrpjquota)
return clear_qf_name(sb, GRPQUOTA);
#endif
switch (token) {
case Opt_noacl:
case Opt_nouser_xattr:
ext4_msg(sb, KERN_WARNING, deprecated_msg, opt, "3.5");
break;
case Opt_sb:
return 1; /* handled by get_sb_block() */
case Opt_removed:
ext4_msg(sb, KERN_WARNING, "Ignoring removed %s option", opt);
return 1;
case Opt_abort:
sbi->s_mount_flags |= EXT4_MF_FS_ABORTED;
return 1;
case Opt_i_version:
sb->s_flags |= MS_I_VERSION;
return 1;
case Opt_lazytime:
sb->s_flags |= MS_LAZYTIME;
return 1;
case Opt_nolazytime:
sb->s_flags &= ~MS_LAZYTIME;
return 1;
}
for (m = ext4_mount_opts; m->token != Opt_err; m++)
if (token == m->token)
break;
if (m->token == Opt_err) {
ext4_msg(sb, KERN_ERR, "Unrecognized mount option \"%s\" "
"or missing value", opt);
return -1;
}
if ((m->flags & MOPT_NO_EXT2) && IS_EXT2_SB(sb)) {
ext4_msg(sb, KERN_ERR,
"Mount option \"%s\" incompatible with ext2", opt);
return -1;
}
if ((m->flags & MOPT_NO_EXT3) && IS_EXT3_SB(sb)) {
ext4_msg(sb, KERN_ERR,
"Mount option \"%s\" incompatible with ext3", opt);
return -1;
}
if (args->from && !(m->flags & MOPT_STRING) && match_int(args, &arg))
return -1;
if (args->from && (m->flags & MOPT_GTE0) && (arg < 0))
return -1;
if (m->flags & MOPT_EXPLICIT) {
if (m->mount_opt & EXT4_MOUNT_DELALLOC) {
set_opt2(sb, EXPLICIT_DELALLOC);
} else if (m->mount_opt & EXT4_MOUNT_JOURNAL_CHECKSUM) {
set_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM);
} else
return -1;
}
if (m->flags & MOPT_CLEAR_ERR)
clear_opt(sb, ERRORS_MASK);
if (token == Opt_noquota && sb_any_quota_loaded(sb)) {
ext4_msg(sb, KERN_ERR, "Cannot change quota "
"options when quota turned on");
return -1;
}
if (m->flags & MOPT_NOSUPPORT) {
ext4_msg(sb, KERN_ERR, "%s option not supported", opt);
} else if (token == Opt_commit) {
if (arg == 0)
arg = JBD2_DEFAULT_MAX_COMMIT_AGE;
sbi->s_commit_interval = HZ * arg;
} else if (token == Opt_max_batch_time) {
sbi->s_max_batch_time = arg;
} else if (token == Opt_min_batch_time) {
sbi->s_min_batch_time = arg;
} else if (token == Opt_inode_readahead_blks) {
if (arg && (arg > (1 << 30) || !is_power_of_2(arg))) {
ext4_msg(sb, KERN_ERR,
"EXT4-fs: inode_readahead_blks must be "
"0 or a power of 2 smaller than 2^31");
return -1;
}
sbi->s_inode_readahead_blks = arg;
} else if (token == Opt_init_itable) {
set_opt(sb, INIT_INODE_TABLE);
if (!args->from)
arg = EXT4_DEF_LI_WAIT_MULT;
sbi->s_li_wait_mult = arg;
} else if (token == Opt_max_dir_size_kb) {
sbi->s_max_dir_size_kb = arg;
} else if (token == Opt_stripe) {
sbi->s_stripe = arg;
} else if (token == Opt_resuid) {
uid = make_kuid(current_user_ns(), arg);
if (!uid_valid(uid)) {
ext4_msg(sb, KERN_ERR, "Invalid uid value %d", arg);
return -1;
}
sbi->s_resuid = uid;
} else if (token == Opt_resgid) {
gid = make_kgid(current_user_ns(), arg);
if (!gid_valid(gid)) {
ext4_msg(sb, KERN_ERR, "Invalid gid value %d", arg);
return -1;
}
sbi->s_resgid = gid;
} else if (token == Opt_journal_dev) {
if (is_remount) {
ext4_msg(sb, KERN_ERR,
"Cannot specify journal on remount");
return -1;
}
*journal_devnum = arg;
} else if (token == Opt_journal_path) {
char *journal_path;
struct inode *journal_inode;
struct path path;
int error;
if (is_remount) {
ext4_msg(sb, KERN_ERR,
"Cannot specify journal on remount");
return -1;
}
journal_path = match_strdup(&args[0]);
if (!journal_path) {
ext4_msg(sb, KERN_ERR, "error: could not dup "
"journal device string");
return -1;
}
error = kern_path(journal_path, LOOKUP_FOLLOW, &path);
if (error) {
ext4_msg(sb, KERN_ERR, "error: could not find "
"journal device path: error %d", error);
kfree(journal_path);
return -1;
}
journal_inode = d_inode(path.dentry);
if (!S_ISBLK(journal_inode->i_mode)) {
ext4_msg(sb, KERN_ERR, "error: journal path %s "
"is not a block device", journal_path);
path_put(&path);
kfree(journal_path);
return -1;
}
*journal_devnum = new_encode_dev(journal_inode->i_rdev);
path_put(&path);
kfree(journal_path);
} else if (token == Opt_journal_ioprio) {
if (arg > 7) {
ext4_msg(sb, KERN_ERR, "Invalid journal IO priority"
" (must be 0-7)");
return -1;
}
*journal_ioprio =
IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, arg);
} else if (token == Opt_test_dummy_encryption) {
#ifdef CONFIG_EXT4_FS_ENCRYPTION
sbi->s_mount_flags |= EXT4_MF_TEST_DUMMY_ENCRYPTION;
ext4_msg(sb, KERN_WARNING,
"Test dummy encryption mode enabled");
#else
ext4_msg(sb, KERN_WARNING,
"Test dummy encryption mount option ignored");
#endif
} else if (m->flags & MOPT_DATAJ) {
if (is_remount) {
if (!sbi->s_journal)
ext4_msg(sb, KERN_WARNING, "Remounting file system with no journal so ignoring journalled data option");
else if (test_opt(sb, DATA_FLAGS) != m->mount_opt) {
ext4_msg(sb, KERN_ERR,
"Cannot change data mode on remount");
return -1;
}
} else {
clear_opt(sb, DATA_FLAGS);
sbi->s_mount_opt |= m->mount_opt;
}
#ifdef CONFIG_QUOTA
} else if (m->flags & MOPT_QFMT) {
if (sb_any_quota_loaded(sb) &&
sbi->s_jquota_fmt != m->mount_opt) {
ext4_msg(sb, KERN_ERR, "Cannot change journaled "
"quota options when quota turned on");
return -1;
}
if (ext4_has_feature_quota(sb)) {
ext4_msg(sb, KERN_INFO,
"Quota format mount options ignored "
"when QUOTA feature is enabled");
return 1;
}
sbi->s_jquota_fmt = m->mount_opt;
#endif
} else if (token == Opt_dax) {
#ifdef CONFIG_FS_DAX
ext4_msg(sb, KERN_WARNING,
"DAX enabled. Warning: EXPERIMENTAL, use at your own risk");
sbi->s_mount_opt |= m->mount_opt;
#else
ext4_msg(sb, KERN_INFO, "dax option not supported");
return -1;
#endif
} else if (token == Opt_data_err_abort) {
sbi->s_mount_opt |= m->mount_opt;
} else if (token == Opt_data_err_ignore) {
sbi->s_mount_opt &= ~m->mount_opt;
} else {
if (!args->from)
arg = 1;
if (m->flags & MOPT_CLEAR)
arg = !arg;
else if (unlikely(!(m->flags & MOPT_SET))) {
ext4_msg(sb, KERN_WARNING,
"buggy handling of option %s", opt);
WARN_ON(1);
return -1;
}
if (arg != 0)
sbi->s_mount_opt |= m->mount_opt;
else
sbi->s_mount_opt &= ~m->mount_opt;
}
return 1;
}
static int parse_options(char *options, struct super_block *sb,
unsigned long *journal_devnum,
unsigned int *journal_ioprio,
int is_remount)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
char *p;
substring_t args[MAX_OPT_ARGS];
int token;
if (!options)
return 1;
while ((p = strsep(&options, ",")) != NULL) {
if (!*p)
continue;
/*
* Initialize args struct so we know whether arg was
* found; some options take optional arguments.
*/
args[0].to = args[0].from = NULL;
token = match_token(p, tokens, args);
if (handle_mount_opt(sb, p, token, args, journal_devnum,
journal_ioprio, is_remount) < 0)
return 0;
}
#ifdef CONFIG_QUOTA
/*
* We do the test below only for project quotas. 'usrquota' and
* 'grpquota' mount options are allowed even without quota feature
* to support legacy quotas in quota files.
*/
if (test_opt(sb, PRJQUOTA) && !ext4_has_feature_project(sb)) {
ext4_msg(sb, KERN_ERR, "Project quota feature not enabled. "
"Cannot enable project quota enforcement.");
return 0;
}
if (sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) {
if (test_opt(sb, USRQUOTA) && sbi->s_qf_names[USRQUOTA])
clear_opt(sb, USRQUOTA);
if (test_opt(sb, GRPQUOTA) && sbi->s_qf_names[GRPQUOTA])
clear_opt(sb, GRPQUOTA);
if (test_opt(sb, GRPQUOTA) || test_opt(sb, USRQUOTA)) {
ext4_msg(sb, KERN_ERR, "old and new quota "
"format mixing");
return 0;
}
if (!sbi->s_jquota_fmt) {
ext4_msg(sb, KERN_ERR, "journaled quota format "
"not specified");
return 0;
}
}
#endif
if (test_opt(sb, DIOREAD_NOLOCK)) {
int blocksize =
BLOCK_SIZE << le32_to_cpu(sbi->s_es->s_log_block_size);
if (blocksize < PAGE_SIZE) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"dioread_nolock if block size != PAGE_SIZE");
return 0;
}
}
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA &&
test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ext4_msg(sb, KERN_ERR, "can't mount with journal_async_commit "
"in data=ordered mode");
return 0;
}
return 1;
}
static inline void ext4_show_quota_options(struct seq_file *seq,
struct super_block *sb)
{
#if defined(CONFIG_QUOTA)
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (sbi->s_jquota_fmt) {
char *fmtname = "";
switch (sbi->s_jquota_fmt) {
case QFMT_VFS_OLD:
fmtname = "vfsold";
break;
case QFMT_VFS_V0:
fmtname = "vfsv0";
break;
case QFMT_VFS_V1:
fmtname = "vfsv1";
break;
}
seq_printf(seq, ",jqfmt=%s", fmtname);
}
if (sbi->s_qf_names[USRQUOTA])
seq_show_option(seq, "usrjquota", sbi->s_qf_names[USRQUOTA]);
if (sbi->s_qf_names[GRPQUOTA])
seq_show_option(seq, "grpjquota", sbi->s_qf_names[GRPQUOTA]);
#endif
}
static const char *token2str(int token)
{
const struct match_token *t;
for (t = tokens; t->token != Opt_err; t++)
if (t->token == token && !strchr(t->pattern, '='))
break;
return t->pattern;
}
/*
* Show an option if
* - it's set to a non-default value OR
* - if the per-sb default is different from the global default
*/
static int _ext4_show_options(struct seq_file *seq, struct super_block *sb,
int nodefs)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int def_errors, def_mount_opt = nodefs ? 0 : sbi->s_def_mount_opt;
const struct mount_opts *m;
char sep = nodefs ? '\n' : ',';
#define SEQ_OPTS_PUTS(str) seq_printf(seq, "%c" str, sep)
#define SEQ_OPTS_PRINT(str, arg) seq_printf(seq, "%c" str, sep, arg)
if (sbi->s_sb_block != 1)
SEQ_OPTS_PRINT("sb=%llu", sbi->s_sb_block);
for (m = ext4_mount_opts; m->token != Opt_err; m++) {
int want_set = m->flags & MOPT_SET;
if (((m->flags & (MOPT_SET|MOPT_CLEAR)) == 0) ||
(m->flags & MOPT_CLEAR_ERR))
continue;
if (!(m->mount_opt & (sbi->s_mount_opt ^ def_mount_opt)))
continue; /* skip if same as the default */
if ((want_set &&
(sbi->s_mount_opt & m->mount_opt) != m->mount_opt) ||
(!want_set && (sbi->s_mount_opt & m->mount_opt)))
continue; /* select Opt_noFoo vs Opt_Foo */
SEQ_OPTS_PRINT("%s", token2str(m->token));
}
if (nodefs || !uid_eq(sbi->s_resuid, make_kuid(&init_user_ns, EXT4_DEF_RESUID)) ||
le16_to_cpu(es->s_def_resuid) != EXT4_DEF_RESUID)
SEQ_OPTS_PRINT("resuid=%u",
from_kuid_munged(&init_user_ns, sbi->s_resuid));
if (nodefs || !gid_eq(sbi->s_resgid, make_kgid(&init_user_ns, EXT4_DEF_RESGID)) ||
le16_to_cpu(es->s_def_resgid) != EXT4_DEF_RESGID)
SEQ_OPTS_PRINT("resgid=%u",
from_kgid_munged(&init_user_ns, sbi->s_resgid));
def_errors = nodefs ? -1 : le16_to_cpu(es->s_errors);
if (test_opt(sb, ERRORS_RO) && def_errors != EXT4_ERRORS_RO)
SEQ_OPTS_PUTS("errors=remount-ro");
if (test_opt(sb, ERRORS_CONT) && def_errors != EXT4_ERRORS_CONTINUE)
SEQ_OPTS_PUTS("errors=continue");
if (test_opt(sb, ERRORS_PANIC) && def_errors != EXT4_ERRORS_PANIC)
SEQ_OPTS_PUTS("errors=panic");
if (nodefs || sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ)
SEQ_OPTS_PRINT("commit=%lu", sbi->s_commit_interval / HZ);
if (nodefs || sbi->s_min_batch_time != EXT4_DEF_MIN_BATCH_TIME)
SEQ_OPTS_PRINT("min_batch_time=%u", sbi->s_min_batch_time);
if (nodefs || sbi->s_max_batch_time != EXT4_DEF_MAX_BATCH_TIME)
SEQ_OPTS_PRINT("max_batch_time=%u", sbi->s_max_batch_time);
if (sb->s_flags & MS_I_VERSION)
SEQ_OPTS_PUTS("i_version");
if (nodefs || sbi->s_stripe)
SEQ_OPTS_PRINT("stripe=%lu", sbi->s_stripe);
if (EXT4_MOUNT_DATA_FLAGS & (sbi->s_mount_opt ^ def_mount_opt)) {
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
SEQ_OPTS_PUTS("data=journal");
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
SEQ_OPTS_PUTS("data=ordered");
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)
SEQ_OPTS_PUTS("data=writeback");
}
if (nodefs ||
sbi->s_inode_readahead_blks != EXT4_DEF_INODE_READAHEAD_BLKS)
SEQ_OPTS_PRINT("inode_readahead_blks=%u",
sbi->s_inode_readahead_blks);
if (nodefs || (test_opt(sb, INIT_INODE_TABLE) &&
(sbi->s_li_wait_mult != EXT4_DEF_LI_WAIT_MULT)))
SEQ_OPTS_PRINT("init_itable=%u", sbi->s_li_wait_mult);
if (nodefs || sbi->s_max_dir_size_kb)
SEQ_OPTS_PRINT("max_dir_size_kb=%u", sbi->s_max_dir_size_kb);
if (test_opt(sb, DATA_ERR_ABORT))
SEQ_OPTS_PUTS("data_err=abort");
ext4_show_quota_options(seq, sb);
return 0;
}
static int ext4_show_options(struct seq_file *seq, struct dentry *root)
{
return _ext4_show_options(seq, root->d_sb, 0);
}
int ext4_seq_options_show(struct seq_file *seq, void *offset)
{
struct super_block *sb = seq->private;
int rc;
seq_puts(seq, (sb->s_flags & MS_RDONLY) ? "ro" : "rw");
rc = _ext4_show_options(seq, sb, 1);
seq_puts(seq, "\n");
return rc;
}
static int ext4_setup_super(struct super_block *sb, struct ext4_super_block *es,
int read_only)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
int res = 0;
if (le32_to_cpu(es->s_rev_level) > EXT4_MAX_SUPP_REV) {
ext4_msg(sb, KERN_ERR, "revision level too high, "
"forcing read-only mode");
res = MS_RDONLY;
}
if (read_only)
goto done;
if (!(sbi->s_mount_state & EXT4_VALID_FS))
ext4_msg(sb, KERN_WARNING, "warning: mounting unchecked fs, "
"running e2fsck is recommended");
else if (sbi->s_mount_state & EXT4_ERROR_FS)
ext4_msg(sb, KERN_WARNING,
"warning: mounting fs with errors, "
"running e2fsck is recommended");
else if ((__s16) le16_to_cpu(es->s_max_mnt_count) > 0 &&
le16_to_cpu(es->s_mnt_count) >=
(unsigned short) (__s16) le16_to_cpu(es->s_max_mnt_count))
ext4_msg(sb, KERN_WARNING,
"warning: maximal mount count reached, "
"running e2fsck is recommended");
else if (le32_to_cpu(es->s_checkinterval) &&
(le32_to_cpu(es->s_lastcheck) +
le32_to_cpu(es->s_checkinterval) <= get_seconds()))
ext4_msg(sb, KERN_WARNING,
"warning: checktime reached, "
"running e2fsck is recommended");
if (!sbi->s_journal)
es->s_state &= cpu_to_le16(~EXT4_VALID_FS);
if (!(__s16) le16_to_cpu(es->s_max_mnt_count))
es->s_max_mnt_count = cpu_to_le16(EXT4_DFL_MAX_MNT_COUNT);
le16_add_cpu(&es->s_mnt_count, 1);
es->s_mtime = cpu_to_le32(get_seconds());
ext4_update_dynamic_rev(sb);
if (sbi->s_journal)
ext4_set_feature_journal_needs_recovery(sb);
ext4_commit_super(sb, 1);
done:
if (test_opt(sb, DEBUG))
printk(KERN_INFO "[EXT4 FS bs=%lu, gc=%u, "
"bpg=%lu, ipg=%lu, mo=%04x, mo2=%04x]\n",
sb->s_blocksize,
sbi->s_groups_count,
EXT4_BLOCKS_PER_GROUP(sb),
EXT4_INODES_PER_GROUP(sb),
sbi->s_mount_opt, sbi->s_mount_opt2);
cleancache_init_fs(sb);
return res;
}
int ext4_alloc_flex_bg_array(struct super_block *sb, ext4_group_t ngroup)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct flex_groups *new_groups;
int size;
if (!sbi->s_log_groups_per_flex)
return 0;
size = ext4_flex_group(sbi, ngroup - 1) + 1;
if (size <= sbi->s_flex_groups_allocated)
return 0;
size = roundup_pow_of_two(size * sizeof(struct flex_groups));
new_groups = ext4_kvzalloc(size, GFP_KERNEL);
if (!new_groups) {
ext4_msg(sb, KERN_ERR, "not enough memory for %d flex groups",
size / (int) sizeof(struct flex_groups));
return -ENOMEM;
}
if (sbi->s_flex_groups) {
memcpy(new_groups, sbi->s_flex_groups,
(sbi->s_flex_groups_allocated *
sizeof(struct flex_groups)));
kvfree(sbi->s_flex_groups);
}
sbi->s_flex_groups = new_groups;
sbi->s_flex_groups_allocated = size / sizeof(struct flex_groups);
return 0;
}
static int ext4_fill_flex_info(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp = NULL;
ext4_group_t flex_group;
int i, err;
sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
if (sbi->s_log_groups_per_flex < 1 || sbi->s_log_groups_per_flex > 31) {
sbi->s_log_groups_per_flex = 0;
return 1;
}
err = ext4_alloc_flex_bg_array(sb, sbi->s_groups_count);
if (err)
goto failed;
for (i = 0; i < sbi->s_groups_count; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
flex_group = ext4_flex_group(sbi, i);
atomic_add(ext4_free_inodes_count(sb, gdp),
&sbi->s_flex_groups[flex_group].free_inodes);
atomic64_add(ext4_free_group_clusters(sb, gdp),
&sbi->s_flex_groups[flex_group].free_clusters);
atomic_add(ext4_used_dirs_count(sb, gdp),
&sbi->s_flex_groups[flex_group].used_dirs);
}
return 1;
failed:
return 0;
}
static __le16 ext4_group_desc_csum(struct super_block *sb, __u32 block_group,
struct ext4_group_desc *gdp)
{
int offset = offsetof(struct ext4_group_desc, bg_checksum);
__u16 crc = 0;
__le32 le_group = cpu_to_le32(block_group);
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (ext4_has_metadata_csum(sbi->s_sb)) {
/* Use new metadata_csum algorithm */
__u32 csum32;
__u16 dummy_csum = 0;
csum32 = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&le_group,
sizeof(le_group));
csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp, offset);
csum32 = ext4_chksum(sbi, csum32, (__u8 *)&dummy_csum,
sizeof(dummy_csum));
offset += sizeof(dummy_csum);
if (offset < sbi->s_desc_size)
csum32 = ext4_chksum(sbi, csum32, (__u8 *)gdp + offset,
sbi->s_desc_size - offset);
crc = csum32 & 0xFFFF;
goto out;
}
/* old crc16 code */
if (!ext4_has_feature_gdt_csum(sb))
return 0;
crc = crc16(~0, sbi->s_es->s_uuid, sizeof(sbi->s_es->s_uuid));
crc = crc16(crc, (__u8 *)&le_group, sizeof(le_group));
crc = crc16(crc, (__u8 *)gdp, offset);
offset += sizeof(gdp->bg_checksum); /* skip checksum */
/* for checksum of struct ext4_group_desc do the rest...*/
if (ext4_has_feature_64bit(sb) &&
offset < le16_to_cpu(sbi->s_es->s_desc_size))
crc = crc16(crc, (__u8 *)gdp + offset,
le16_to_cpu(sbi->s_es->s_desc_size) -
offset);
out:
return cpu_to_le16(crc);
}
int ext4_group_desc_csum_verify(struct super_block *sb, __u32 block_group,
struct ext4_group_desc *gdp)
{
if (ext4_has_group_desc_csum(sb) &&
(gdp->bg_checksum != ext4_group_desc_csum(sb, block_group, gdp)))
return 0;
return 1;
}
void ext4_group_desc_csum_set(struct super_block *sb, __u32 block_group,
struct ext4_group_desc *gdp)
{
if (!ext4_has_group_desc_csum(sb))
return;
gdp->bg_checksum = ext4_group_desc_csum(sb, block_group, gdp);
}
/* Called at mount-time, super-block is locked */
static int ext4_check_descriptors(struct super_block *sb,
ext4_fsblk_t sb_block,
ext4_group_t *first_not_zeroed)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_fsblk_t first_block = le32_to_cpu(sbi->s_es->s_first_data_block);
ext4_fsblk_t last_block;
ext4_fsblk_t block_bitmap;
ext4_fsblk_t inode_bitmap;
ext4_fsblk_t inode_table;
int flexbg_flag = 0;
ext4_group_t i, grp = sbi->s_groups_count;
if (ext4_has_feature_flex_bg(sb))
flexbg_flag = 1;
ext4_debug("Checking group descriptors");
for (i = 0; i < sbi->s_groups_count; i++) {
struct ext4_group_desc *gdp = ext4_get_group_desc(sb, i, NULL);
if (i == sbi->s_groups_count - 1 || flexbg_flag)
last_block = ext4_blocks_count(sbi->s_es) - 1;
else
last_block = first_block +
(EXT4_BLOCKS_PER_GROUP(sb) - 1);
if ((grp == sbi->s_groups_count) &&
!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
grp = i;
block_bitmap = ext4_block_bitmap(sb, gdp);
if (block_bitmap == sb_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Block bitmap for group %u overlaps "
"superblock", i);
}
if (block_bitmap < first_block || block_bitmap > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Block bitmap for group %u not in group "
"(block %llu)!", i, block_bitmap);
return 0;
}
inode_bitmap = ext4_inode_bitmap(sb, gdp);
if (inode_bitmap == sb_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode bitmap for group %u overlaps "
"superblock", i);
}
if (inode_bitmap < first_block || inode_bitmap > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode bitmap for group %u not in group "
"(block %llu)!", i, inode_bitmap);
return 0;
}
inode_table = ext4_inode_table(sb, gdp);
if (inode_table == sb_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode table for group %u overlaps "
"superblock", i);
}
if (inode_table < first_block ||
inode_table + sbi->s_itb_per_group - 1 > last_block) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Inode table for group %u not in group "
"(block %llu)!", i, inode_table);
return 0;
}
ext4_lock_group(sb, i);
if (!ext4_group_desc_csum_verify(sb, i, gdp)) {
ext4_msg(sb, KERN_ERR, "ext4_check_descriptors: "
"Checksum for group %u failed (%u!=%u)",
i, le16_to_cpu(ext4_group_desc_csum(sb, i,
gdp)), le16_to_cpu(gdp->bg_checksum));
if (!(sb->s_flags & MS_RDONLY)) {
ext4_unlock_group(sb, i);
return 0;
}
}
ext4_unlock_group(sb, i);
if (!flexbg_flag)
first_block += EXT4_BLOCKS_PER_GROUP(sb);
}
if (NULL != first_not_zeroed)
*first_not_zeroed = grp;
return 1;
}
/* ext4_orphan_cleanup() walks a singly-linked list of inodes (starting at
* the superblock) which were deleted from all directories, but held open by
* a process at the time of a crash. We walk the list and try to delete these
* inodes at recovery time (only with a read-write filesystem).
*
* In order to keep the orphan inode chain consistent during traversal (in
* case of crash during recovery), we link each inode into the superblock
* orphan list_head and handle it the same way as an inode deletion during
* normal operation (which journals the operations for us).
*
* We only do an iget() and an iput() on each inode, which is very safe if we
* accidentally point at an in-use or already deleted inode. The worst that
* can happen in this case is that we get a "bit already cleared" message from
* ext4_free_inode(). The only reason we would point at a wrong inode is if
* e2fsck was run on this filesystem, and it must have already done the orphan
* inode cleanup for us, so we can safely abort without any further action.
*/
static void ext4_orphan_cleanup(struct super_block *sb,
struct ext4_super_block *es)
{
unsigned int s_flags = sb->s_flags;
int ret, nr_orphans = 0, nr_truncates = 0;
#ifdef CONFIG_QUOTA
int i;
#endif
if (!es->s_last_orphan) {
jbd_debug(4, "no orphan inodes to clean up\n");
return;
}
if (bdev_read_only(sb->s_bdev)) {
ext4_msg(sb, KERN_ERR, "write access "
"unavailable, skipping orphan cleanup");
return;
}
/* Check if feature set would not allow a r/w mount */
if (!ext4_feature_set_ok(sb, 0)) {
ext4_msg(sb, KERN_INFO, "Skipping orphan cleanup due to "
"unknown ROCOMPAT features");
return;
}
if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
/* don't clear list on RO mount w/ errors */
if (es->s_last_orphan && !(s_flags & MS_RDONLY)) {
ext4_msg(sb, KERN_INFO, "Errors on filesystem, "
"clearing orphan list.\n");
es->s_last_orphan = 0;
}
jbd_debug(1, "Skipping orphan recovery on fs with errors.\n");
return;
}
if (s_flags & MS_RDONLY) {
ext4_msg(sb, KERN_INFO, "orphan cleanup on readonly fs");
sb->s_flags &= ~MS_RDONLY;
}
#ifdef CONFIG_QUOTA
/* Needed for iput() to work correctly and not trash data */
sb->s_flags |= MS_ACTIVE;
/* Turn on quotas so that they are updated correctly */
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
if (EXT4_SB(sb)->s_qf_names[i]) {
int ret = ext4_quota_on_mount(sb, i);
if (ret < 0)
ext4_msg(sb, KERN_ERR,
"Cannot turn on journaled "
"quota: error %d", ret);
}
}
#endif
while (es->s_last_orphan) {
struct inode *inode;
/*
* We may have encountered an error during cleanup; if
* so, skip the rest.
*/
if (EXT4_SB(sb)->s_mount_state & EXT4_ERROR_FS) {
jbd_debug(1, "Skipping orphan recovery on fs with errors.\n");
es->s_last_orphan = 0;
break;
}
inode = ext4_orphan_get(sb, le32_to_cpu(es->s_last_orphan));
if (IS_ERR(inode)) {
es->s_last_orphan = 0;
break;
}
list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan);
dquot_initialize(inode);
if (inode->i_nlink) {
if (test_opt(sb, DEBUG))
ext4_msg(sb, KERN_DEBUG,
"%s: truncating inode %lu to %lld bytes",
__func__, inode->i_ino, inode->i_size);
jbd_debug(2, "truncating inode %lu to %lld bytes\n",
inode->i_ino, inode->i_size);
inode_lock(inode);
truncate_inode_pages(inode->i_mapping, inode->i_size);
ret = ext4_truncate(inode);
if (ret)
ext4_std_error(inode->i_sb, ret);
inode_unlock(inode);
nr_truncates++;
} else {
if (test_opt(sb, DEBUG))
ext4_msg(sb, KERN_DEBUG,
"%s: deleting unreferenced inode %lu",
__func__, inode->i_ino);
jbd_debug(2, "deleting unreferenced inode %lu\n",
inode->i_ino);
nr_orphans++;
}
iput(inode); /* The delete magic happens here! */
}
#define PLURAL(x) (x), ((x) == 1) ? "" : "s"
if (nr_orphans)
ext4_msg(sb, KERN_INFO, "%d orphan inode%s deleted",
PLURAL(nr_orphans));
if (nr_truncates)
ext4_msg(sb, KERN_INFO, "%d truncate%s cleaned up",
PLURAL(nr_truncates));
#ifdef CONFIG_QUOTA
/* Turn quotas off */
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
if (sb_dqopt(sb)->files[i])
dquot_quota_off(sb, i);
}
#endif
sb->s_flags = s_flags; /* Restore MS_RDONLY status */
}
/*
* Maximal extent format file size.
* Resulting logical blkno at s_maxbytes must fit in our on-disk
* extent format containers, within a sector_t, and within i_blocks
* in the vfs. ext4 inode has 48 bits of i_block in fsblock units,
* so that won't be a limiting factor.
*
* However there is other limiting factor. We do store extents in the form
* of starting block and length, hence the resulting length of the extent
* covering maximum file size must fit into on-disk format containers as
* well. Given that length is always by 1 unit bigger than max unit (because
* we count 0 as well) we have to lower the s_maxbytes by one fs block.
*
* Note, this does *not* consider any metadata overhead for vfs i_blocks.
*/
static loff_t ext4_max_size(int blkbits, int has_huge_files)
{
loff_t res;
loff_t upper_limit = MAX_LFS_FILESIZE;
/* small i_blocks in vfs inode? */
if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) {
/*
* CONFIG_LBDAF is not enabled implies the inode
* i_block represent total blocks in 512 bytes
* 32 == size of vfs inode i_blocks * 8
*/
upper_limit = (1LL << 32) - 1;
/* total blocks in file system block size */
upper_limit >>= (blkbits - 9);
upper_limit <<= blkbits;
}
/*
* 32-bit extent-start container, ee_block. We lower the maxbytes
* by one fs block, so ee_len can cover the extent of maximum file
* size
*/
res = (1LL << 32) - 1;
res <<= blkbits;
/* Sanity check against vm- & vfs- imposed limits */
if (res > upper_limit)
res = upper_limit;
return res;
}
/*
* Maximal bitmap file size. There is a direct, and {,double-,triple-}indirect
* block limit, and also a limit of (2^48 - 1) 512-byte sectors in i_blocks.
* We need to be 1 filesystem block less than the 2^48 sector limit.
*/
static loff_t ext4_max_bitmap_size(int bits, int has_huge_files)
{
loff_t res = EXT4_NDIR_BLOCKS;
int meta_blocks;
loff_t upper_limit;
/* This is calculated to be the largest file size for a dense, block
* mapped file such that the file's total number of 512-byte sectors,
* including data and all indirect blocks, does not exceed (2^48 - 1).
*
* __u32 i_blocks_lo and _u16 i_blocks_high represent the total
* number of 512-byte sectors of the file.
*/
if (!has_huge_files || sizeof(blkcnt_t) < sizeof(u64)) {
/*
* !has_huge_files or CONFIG_LBDAF not enabled implies that
* the inode i_block field represents total file blocks in
* 2^32 512-byte sectors == size of vfs inode i_blocks * 8
*/
upper_limit = (1LL << 32) - 1;
/* total blocks in file system block size */
upper_limit >>= (bits - 9);
} else {
/*
* We use 48 bit ext4_inode i_blocks
* With EXT4_HUGE_FILE_FL set the i_blocks
* represent total number of blocks in
* file system block size
*/
upper_limit = (1LL << 48) - 1;
}
/* indirect blocks */
meta_blocks = 1;
/* double indirect blocks */
meta_blocks += 1 + (1LL << (bits-2));
/* tripple indirect blocks */
meta_blocks += 1 + (1LL << (bits-2)) + (1LL << (2*(bits-2)));
upper_limit -= meta_blocks;
upper_limit <<= bits;
res += 1LL << (bits-2);
res += 1LL << (2*(bits-2));
res += 1LL << (3*(bits-2));
res <<= bits;
if (res > upper_limit)
res = upper_limit;
if (res > MAX_LFS_FILESIZE)
res = MAX_LFS_FILESIZE;
return res;
}
static ext4_fsblk_t descriptor_loc(struct super_block *sb,
ext4_fsblk_t logical_sb_block, int nr)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
ext4_group_t bg, first_meta_bg;
int has_super = 0;
first_meta_bg = le32_to_cpu(sbi->s_es->s_first_meta_bg);
if (!ext4_has_feature_meta_bg(sb) || nr < first_meta_bg)
return logical_sb_block + nr + 1;
bg = sbi->s_desc_per_block * nr;
if (ext4_bg_has_super(sb, bg))
has_super = 1;
/*
* If we have a meta_bg fs with 1k blocks, group 0's GDT is at
* block 2, not 1. If s_first_data_block == 0 (bigalloc is enabled
* on modern mke2fs or blksize > 1k on older mke2fs) then we must
* compensate.
*/
if (sb->s_blocksize == 1024 && nr == 0 &&
le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block) == 0)
has_super++;
return (has_super + ext4_group_first_block_no(sb, bg));
}
/**
* ext4_get_stripe_size: Get the stripe size.
* @sbi: In memory super block info
*
* If we have specified it via mount option, then
* use the mount option value. If the value specified at mount time is
* greater than the blocks per group use the super block value.
* If the super block value is greater than blocks per group return 0.
* Allocator needs it be less than blocks per group.
*
*/
static unsigned long ext4_get_stripe_size(struct ext4_sb_info *sbi)
{
unsigned long stride = le16_to_cpu(sbi->s_es->s_raid_stride);
unsigned long stripe_width =
le32_to_cpu(sbi->s_es->s_raid_stripe_width);
int ret;
if (sbi->s_stripe && sbi->s_stripe <= sbi->s_blocks_per_group)
ret = sbi->s_stripe;
else if (stripe_width <= sbi->s_blocks_per_group)
ret = stripe_width;
else if (stride <= sbi->s_blocks_per_group)
ret = stride;
else
ret = 0;
/*
* If the stripe width is 1, this makes no sense and
* we set it to 0 to turn off stripe handling code.
*/
if (ret <= 1)
ret = 0;
return ret;
}
/*
* Check whether this filesystem can be mounted based on
* the features present and the RDONLY/RDWR mount requested.
* Returns 1 if this filesystem can be mounted as requested,
* 0 if it cannot be.
*/
static int ext4_feature_set_ok(struct super_block *sb, int readonly)
{
if (ext4_has_unknown_ext4_incompat_features(sb)) {
ext4_msg(sb, KERN_ERR,
"Couldn't mount because of "
"unsupported optional features (%x)",
(le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_incompat) &
~EXT4_FEATURE_INCOMPAT_SUPP));
return 0;
}
if (readonly)
return 1;
if (ext4_has_feature_readonly(sb)) {
ext4_msg(sb, KERN_INFO, "filesystem is read-only");
sb->s_flags |= MS_RDONLY;
return 1;
}
/* Check that feature set is OK for a read-write mount */
if (ext4_has_unknown_ext4_ro_compat_features(sb)) {
ext4_msg(sb, KERN_ERR, "couldn't mount RDWR because of "
"unsupported optional features (%x)",
(le32_to_cpu(EXT4_SB(sb)->s_es->s_feature_ro_compat) &
~EXT4_FEATURE_RO_COMPAT_SUPP));
return 0;
}
/*
* Large file size enabled file system can only be mounted
* read-write on 32-bit systems if kernel is built with CONFIG_LBDAF
*/
if (ext4_has_feature_huge_file(sb)) {
if (sizeof(blkcnt_t) < sizeof(u64)) {
ext4_msg(sb, KERN_ERR, "Filesystem with huge files "
"cannot be mounted RDWR without "
"CONFIG_LBDAF");
return 0;
}
}
if (ext4_has_feature_bigalloc(sb) && !ext4_has_feature_extents(sb)) {
ext4_msg(sb, KERN_ERR,
"Can't support bigalloc feature without "
"extents feature\n");
return 0;
}
#ifndef CONFIG_QUOTA
if (ext4_has_feature_quota(sb) && !readonly) {
ext4_msg(sb, KERN_ERR,
"Filesystem with quota feature cannot be mounted RDWR "
"without CONFIG_QUOTA");
return 0;
}
if (ext4_has_feature_project(sb) && !readonly) {
ext4_msg(sb, KERN_ERR,
"Filesystem with project quota feature cannot be mounted RDWR "
"without CONFIG_QUOTA");
return 0;
}
#endif /* CONFIG_QUOTA */
return 1;
}
/*
* This function is called once a day if we have errors logged
* on the file system
*/
static void print_daily_error_info(unsigned long arg)
{
struct super_block *sb = (struct super_block *) arg;
struct ext4_sb_info *sbi;
struct ext4_super_block *es;
sbi = EXT4_SB(sb);
es = sbi->s_es;
if (es->s_error_count)
/* fsck newer than v1.41.13 is needed to clean this condition. */
ext4_msg(sb, KERN_NOTICE, "error count since last fsck: %u",
le32_to_cpu(es->s_error_count));
if (es->s_first_error_time) {
printk(KERN_NOTICE "EXT4-fs (%s): initial error at time %u: %.*s:%d",
sb->s_id, le32_to_cpu(es->s_first_error_time),
(int) sizeof(es->s_first_error_func),
es->s_first_error_func,
le32_to_cpu(es->s_first_error_line));
if (es->s_first_error_ino)
printk(KERN_CONT ": inode %u",
le32_to_cpu(es->s_first_error_ino));
if (es->s_first_error_block)
printk(KERN_CONT ": block %llu", (unsigned long long)
le64_to_cpu(es->s_first_error_block));
printk(KERN_CONT "\n");
}
if (es->s_last_error_time) {
printk(KERN_NOTICE "EXT4-fs (%s): last error at time %u: %.*s:%d",
sb->s_id, le32_to_cpu(es->s_last_error_time),
(int) sizeof(es->s_last_error_func),
es->s_last_error_func,
le32_to_cpu(es->s_last_error_line));
if (es->s_last_error_ino)
printk(KERN_CONT ": inode %u",
le32_to_cpu(es->s_last_error_ino));
if (es->s_last_error_block)
printk(KERN_CONT ": block %llu", (unsigned long long)
le64_to_cpu(es->s_last_error_block));
printk(KERN_CONT "\n");
}
mod_timer(&sbi->s_err_report, jiffies + 24*60*60*HZ); /* Once a day */
}
/* Find next suitable group and run ext4_init_inode_table */
static int ext4_run_li_request(struct ext4_li_request *elr)
{
struct ext4_group_desc *gdp = NULL;
ext4_group_t group, ngroups;
struct super_block *sb;
unsigned long timeout = 0;
int ret = 0;
sb = elr->lr_super;
ngroups = EXT4_SB(sb)->s_groups_count;
for (group = elr->lr_next_group; group < ngroups; group++) {
gdp = ext4_get_group_desc(sb, group, NULL);
if (!gdp) {
ret = 1;
break;
}
if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
break;
}
if (group >= ngroups)
ret = 1;
if (!ret) {
timeout = jiffies;
ret = ext4_init_inode_table(sb, group,
elr->lr_timeout ? 0 : 1);
if (elr->lr_timeout == 0) {
timeout = (jiffies - timeout) *
elr->lr_sbi->s_li_wait_mult;
elr->lr_timeout = timeout;
}
elr->lr_next_sched = jiffies + elr->lr_timeout;
elr->lr_next_group = group + 1;
}
return ret;
}
/*
* Remove lr_request from the list_request and free the
* request structure. Should be called with li_list_mtx held
*/
static void ext4_remove_li_request(struct ext4_li_request *elr)
{
struct ext4_sb_info *sbi;
if (!elr)
return;
sbi = elr->lr_sbi;
list_del(&elr->lr_request);
sbi->s_li_request = NULL;
kfree(elr);
}
static void ext4_unregister_li_request(struct super_block *sb)
{
mutex_lock(&ext4_li_mtx);
if (!ext4_li_info) {
mutex_unlock(&ext4_li_mtx);
return;
}
mutex_lock(&ext4_li_info->li_list_mtx);
ext4_remove_li_request(EXT4_SB(sb)->s_li_request);
mutex_unlock(&ext4_li_info->li_list_mtx);
mutex_unlock(&ext4_li_mtx);
}
static struct task_struct *ext4_lazyinit_task;
/*
* This is the function where ext4lazyinit thread lives. It walks
* through the request list searching for next scheduled filesystem.
* When such a fs is found, run the lazy initialization request
* (ext4_rn_li_request) and keep track of the time spend in this
* function. Based on that time we compute next schedule time of
* the request. When walking through the list is complete, compute
* next waking time and put itself into sleep.
*/
static int ext4_lazyinit_thread(void *arg)
{
struct ext4_lazy_init *eli = (struct ext4_lazy_init *)arg;
struct list_head *pos, *n;
struct ext4_li_request *elr;
unsigned long next_wakeup, cur;
BUG_ON(NULL == eli);
cont_thread:
while (true) {
next_wakeup = MAX_JIFFY_OFFSET;
mutex_lock(&eli->li_list_mtx);
if (list_empty(&eli->li_request_list)) {
mutex_unlock(&eli->li_list_mtx);
goto exit_thread;
}
list_for_each_safe(pos, n, &eli->li_request_list) {
int err = 0;
int progress = 0;
elr = list_entry(pos, struct ext4_li_request,
lr_request);
if (time_before(jiffies, elr->lr_next_sched)) {
if (time_before(elr->lr_next_sched, next_wakeup))
next_wakeup = elr->lr_next_sched;
continue;
}
if (down_read_trylock(&elr->lr_super->s_umount)) {
if (sb_start_write_trylock(elr->lr_super)) {
progress = 1;
/*
* We hold sb->s_umount, sb can not
* be removed from the list, it is
* now safe to drop li_list_mtx
*/
mutex_unlock(&eli->li_list_mtx);
err = ext4_run_li_request(elr);
sb_end_write(elr->lr_super);
mutex_lock(&eli->li_list_mtx);
n = pos->next;
}
up_read((&elr->lr_super->s_umount));
}
/* error, remove the lazy_init job */
if (err) {
ext4_remove_li_request(elr);
continue;
}
if (!progress) {
elr->lr_next_sched = jiffies +
(prandom_u32()
% (EXT4_DEF_LI_MAX_START_DELAY * HZ));
}
if (time_before(elr->lr_next_sched, next_wakeup))
next_wakeup = elr->lr_next_sched;
}
mutex_unlock(&eli->li_list_mtx);
try_to_freeze();
cur = jiffies;
if ((time_after_eq(cur, next_wakeup)) ||
(MAX_JIFFY_OFFSET == next_wakeup)) {
cond_resched();
continue;
}
schedule_timeout_interruptible(next_wakeup - cur);
if (kthread_should_stop()) {
ext4_clear_request_list();
goto exit_thread;
}
}
exit_thread:
/*
* It looks like the request list is empty, but we need
* to check it under the li_list_mtx lock, to prevent any
* additions into it, and of course we should lock ext4_li_mtx
* to atomically free the list and ext4_li_info, because at
* this point another ext4 filesystem could be registering
* new one.
*/
mutex_lock(&ext4_li_mtx);
mutex_lock(&eli->li_list_mtx);
if (!list_empty(&eli->li_request_list)) {
mutex_unlock(&eli->li_list_mtx);
mutex_unlock(&ext4_li_mtx);
goto cont_thread;
}
mutex_unlock(&eli->li_list_mtx);
kfree(ext4_li_info);
ext4_li_info = NULL;
mutex_unlock(&ext4_li_mtx);
return 0;
}
static void ext4_clear_request_list(void)
{
struct list_head *pos, *n;
struct ext4_li_request *elr;
mutex_lock(&ext4_li_info->li_list_mtx);
list_for_each_safe(pos, n, &ext4_li_info->li_request_list) {
elr = list_entry(pos, struct ext4_li_request,
lr_request);
ext4_remove_li_request(elr);
}
mutex_unlock(&ext4_li_info->li_list_mtx);
}
static int ext4_run_lazyinit_thread(void)
{
ext4_lazyinit_task = kthread_run(ext4_lazyinit_thread,
ext4_li_info, "ext4lazyinit");
if (IS_ERR(ext4_lazyinit_task)) {
int err = PTR_ERR(ext4_lazyinit_task);
ext4_clear_request_list();
kfree(ext4_li_info);
ext4_li_info = NULL;
printk(KERN_CRIT "EXT4-fs: error %d creating inode table "
"initialization thread\n",
err);
return err;
}
ext4_li_info->li_state |= EXT4_LAZYINIT_RUNNING;
return 0;
}
/*
* Check whether it make sense to run itable init. thread or not.
* If there is at least one uninitialized inode table, return
* corresponding group number, else the loop goes through all
* groups and return total number of groups.
*/
static ext4_group_t ext4_has_uninit_itable(struct super_block *sb)
{
ext4_group_t group, ngroups = EXT4_SB(sb)->s_groups_count;
struct ext4_group_desc *gdp = NULL;
for (group = 0; group < ngroups; group++) {
gdp = ext4_get_group_desc(sb, group, NULL);
if (!gdp)
continue;
if (!(gdp->bg_flags & cpu_to_le16(EXT4_BG_INODE_ZEROED)))
break;
}
return group;
}
static int ext4_li_info_new(void)
{
struct ext4_lazy_init *eli = NULL;
eli = kzalloc(sizeof(*eli), GFP_KERNEL);
if (!eli)
return -ENOMEM;
INIT_LIST_HEAD(&eli->li_request_list);
mutex_init(&eli->li_list_mtx);
eli->li_state |= EXT4_LAZYINIT_QUIT;
ext4_li_info = eli;
return 0;
}
static struct ext4_li_request *ext4_li_request_new(struct super_block *sb,
ext4_group_t start)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_li_request *elr;
elr = kzalloc(sizeof(*elr), GFP_KERNEL);
if (!elr)
return NULL;
elr->lr_super = sb;
elr->lr_sbi = sbi;
elr->lr_next_group = start;
/*
* Randomize first schedule time of the request to
* spread the inode table initialization requests
* better.
*/
elr->lr_next_sched = jiffies + (prandom_u32() %
(EXT4_DEF_LI_MAX_START_DELAY * HZ));
return elr;
}
int ext4_register_li_request(struct super_block *sb,
ext4_group_t first_not_zeroed)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_li_request *elr = NULL;
ext4_group_t ngroups = EXT4_SB(sb)->s_groups_count;
int ret = 0;
mutex_lock(&ext4_li_mtx);
if (sbi->s_li_request != NULL) {
/*
* Reset timeout so it can be computed again, because
* s_li_wait_mult might have changed.
*/
sbi->s_li_request->lr_timeout = 0;
goto out;
}
if (first_not_zeroed == ngroups ||
(sb->s_flags & MS_RDONLY) ||
!test_opt(sb, INIT_INODE_TABLE))
goto out;
elr = ext4_li_request_new(sb, first_not_zeroed);
if (!elr) {
ret = -ENOMEM;
goto out;
}
if (NULL == ext4_li_info) {
ret = ext4_li_info_new();
if (ret)
goto out;
}
mutex_lock(&ext4_li_info->li_list_mtx);
list_add(&elr->lr_request, &ext4_li_info->li_request_list);
mutex_unlock(&ext4_li_info->li_list_mtx);
sbi->s_li_request = elr;
/*
* set elr to NULL here since it has been inserted to
* the request_list and the removal and free of it is
* handled by ext4_clear_request_list from now on.
*/
elr = NULL;
if (!(ext4_li_info->li_state & EXT4_LAZYINIT_RUNNING)) {
ret = ext4_run_lazyinit_thread();
if (ret)
goto out;
}
out:
mutex_unlock(&ext4_li_mtx);
if (ret)
kfree(elr);
return ret;
}
/*
* We do not need to lock anything since this is called on
* module unload.
*/
static void ext4_destroy_lazyinit_thread(void)
{
/*
* If thread exited earlier
* there's nothing to be done.
*/
if (!ext4_li_info || !ext4_lazyinit_task)
return;
kthread_stop(ext4_lazyinit_task);
}
static int set_journal_csum_feature_set(struct super_block *sb)
{
int ret = 1;
int compat, incompat;
struct ext4_sb_info *sbi = EXT4_SB(sb);
if (ext4_has_metadata_csum(sb)) {
/* journal checksum v3 */
compat = 0;
incompat = JBD2_FEATURE_INCOMPAT_CSUM_V3;
} else {
/* journal checksum v1 */
compat = JBD2_FEATURE_COMPAT_CHECKSUM;
incompat = 0;
}
jbd2_journal_clear_features(sbi->s_journal,
JBD2_FEATURE_COMPAT_CHECKSUM, 0,
JBD2_FEATURE_INCOMPAT_CSUM_V3 |
JBD2_FEATURE_INCOMPAT_CSUM_V2);
if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ret = jbd2_journal_set_features(sbi->s_journal,
compat, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT |
incompat);
} else if (test_opt(sb, JOURNAL_CHECKSUM)) {
ret = jbd2_journal_set_features(sbi->s_journal,
compat, 0,
incompat);
jbd2_journal_clear_features(sbi->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
} else {
jbd2_journal_clear_features(sbi->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT);
}
return ret;
}
/*
* Note: calculating the overhead so we can be compatible with
* historical BSD practice is quite difficult in the face of
* clusters/bigalloc. This is because multiple metadata blocks from
* different block group can end up in the same allocation cluster.
* Calculating the exact overhead in the face of clustered allocation
* requires either O(all block bitmaps) in memory or O(number of block
* groups**2) in time. We will still calculate the superblock for
* older file systems --- and if we come across with a bigalloc file
* system with zero in s_overhead_clusters the estimate will be close to
* correct especially for very large cluster sizes --- but for newer
* file systems, it's better to calculate this figure once at mkfs
* time, and store it in the superblock. If the superblock value is
* present (even for non-bigalloc file systems), we will use it.
*/
static int count_overhead(struct super_block *sb, ext4_group_t grp,
char *buf)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_group_desc *gdp;
ext4_fsblk_t first_block, last_block, b;
ext4_group_t i, ngroups = ext4_get_groups_count(sb);
int s, j, count = 0;
if (!ext4_has_feature_bigalloc(sb))
return (ext4_bg_has_super(sb, grp) + ext4_bg_num_gdb(sb, grp) +
sbi->s_itb_per_group + 2);
first_block = le32_to_cpu(sbi->s_es->s_first_data_block) +
(grp * EXT4_BLOCKS_PER_GROUP(sb));
last_block = first_block + EXT4_BLOCKS_PER_GROUP(sb) - 1;
for (i = 0; i < ngroups; i++) {
gdp = ext4_get_group_desc(sb, i, NULL);
b = ext4_block_bitmap(sb, gdp);
if (b >= first_block && b <= last_block) {
ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
count++;
}
b = ext4_inode_bitmap(sb, gdp);
if (b >= first_block && b <= last_block) {
ext4_set_bit(EXT4_B2C(sbi, b - first_block), buf);
count++;
}
b = ext4_inode_table(sb, gdp);
if (b >= first_block && b + sbi->s_itb_per_group <= last_block)
for (j = 0; j < sbi->s_itb_per_group; j++, b++) {
int c = EXT4_B2C(sbi, b - first_block);
ext4_set_bit(c, buf);
count++;
}
if (i != grp)
continue;
s = 0;
if (ext4_bg_has_super(sb, grp)) {
ext4_set_bit(s++, buf);
count++;
}
j = ext4_bg_num_gdb(sb, grp);
if (s + j > EXT4_BLOCKS_PER_GROUP(sb)) {
ext4_error(sb, "Invalid number of block group "
"descriptor blocks: %d", j);
j = EXT4_BLOCKS_PER_GROUP(sb) - s;
}
count += j;
for (; j > 0; j--)
ext4_set_bit(EXT4_B2C(sbi, s++), buf);
}
if (!count)
return 0;
return EXT4_CLUSTERS_PER_GROUP(sb) -
ext4_count_free(buf, EXT4_CLUSTERS_PER_GROUP(sb) / 8);
}
/*
* Compute the overhead and stash it in sbi->s_overhead
*/
int ext4_calculate_overhead(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
struct inode *j_inode;
unsigned int j_blocks, j_inum = le32_to_cpu(es->s_journal_inum);
ext4_group_t i, ngroups = ext4_get_groups_count(sb);
ext4_fsblk_t overhead = 0;
char *buf = (char *) get_zeroed_page(GFP_NOFS);
if (!buf)
return -ENOMEM;
/*
* Compute the overhead (FS structures). This is constant
* for a given filesystem unless the number of block groups
* changes so we cache the previous value until it does.
*/
/*
* All of the blocks before first_data_block are overhead
*/
overhead = EXT4_B2C(sbi, le32_to_cpu(es->s_first_data_block));
/*
* Add the overhead found in each block group
*/
for (i = 0; i < ngroups; i++) {
int blks;
blks = count_overhead(sb, i, buf);
overhead += blks;
if (blks)
memset(buf, 0, PAGE_SIZE);
cond_resched();
}
/*
* Add the internal journal blocks whether the journal has been
* loaded or not
*/
if (sbi->s_journal && !sbi->journal_bdev)
overhead += EXT4_NUM_B2C(sbi, sbi->s_journal->j_maxlen);
else if (ext4_has_feature_journal(sb) && !sbi->s_journal) {
j_inode = ext4_get_journal_inode(sb, j_inum);
if (j_inode) {
j_blocks = j_inode->i_size >> sb->s_blocksize_bits;
overhead += EXT4_NUM_B2C(sbi, j_blocks);
iput(j_inode);
} else {
ext4_msg(sb, KERN_ERR, "can't get journal size");
}
}
sbi->s_overhead = overhead;
smp_wmb();
free_page((unsigned long) buf);
return 0;
}
static void ext4_set_resv_clusters(struct super_block *sb)
{
ext4_fsblk_t resv_clusters;
struct ext4_sb_info *sbi = EXT4_SB(sb);
/*
* There's no need to reserve anything when we aren't using extents.
* The space estimates are exact, there are no unwritten extents,
* hole punching doesn't need new metadata... This is needed especially
* to keep ext2/3 backward compatibility.
*/
if (!ext4_has_feature_extents(sb))
return;
/*
* By default we reserve 2% or 4096 clusters, whichever is smaller.
* This should cover the situations where we can not afford to run
* out of space like for example punch hole, or converting
* unwritten extents in delalloc path. In most cases such
* allocation would require 1, or 2 blocks, higher numbers are
* very rare.
*/
resv_clusters = (ext4_blocks_count(sbi->s_es) >>
sbi->s_cluster_bits);
do_div(resv_clusters, 50);
resv_clusters = min_t(ext4_fsblk_t, resv_clusters, 4096);
atomic64_set(&sbi->s_resv_clusters, resv_clusters);
}
static int ext4_fill_super(struct super_block *sb, void *data, int silent)
{
char *orig_data = kstrdup(data, GFP_KERNEL);
struct buffer_head *bh;
struct ext4_super_block *es = NULL;
struct ext4_sb_info *sbi = kzalloc(sizeof(*sbi), GFP_KERNEL);
ext4_fsblk_t block;
ext4_fsblk_t sb_block = get_sb_block(&data);
ext4_fsblk_t logical_sb_block;
unsigned long offset = 0;
unsigned long journal_devnum = 0;
unsigned long def_mount_opts;
struct inode *root;
const char *descr;
int ret = -ENOMEM;
int blocksize, clustersize;
unsigned int db_count;
unsigned int i;
int needs_recovery, has_huge_files, has_bigalloc;
__u64 blocks_count;
int err = 0;
unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
ext4_group_t first_not_zeroed;
if ((data && !orig_data) || !sbi)
goto out_free_base;
sbi->s_blockgroup_lock =
kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL);
if (!sbi->s_blockgroup_lock)
goto out_free_base;
sb->s_fs_info = sbi;
sbi->s_sb = sb;
sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS;
sbi->s_sb_block = sb_block;
if (sb->s_bdev->bd_part)
sbi->s_sectors_written_start =
part_stat_read(sb->s_bdev->bd_part, sectors[1]);
/* Cleanup superblock name */
strreplace(sb->s_id, '/', '!');
/* -EINVAL is default */
ret = -EINVAL;
blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE);
if (!blocksize) {
ext4_msg(sb, KERN_ERR, "unable to set blocksize");
goto out_fail;
}
/*
* The ext4 superblock will not be buffer aligned for other than 1kB
* block sizes. We need to calculate the offset from buffer start.
*/
if (blocksize != EXT4_MIN_BLOCK_SIZE) {
logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
offset = do_div(logical_sb_block, blocksize);
} else {
logical_sb_block = sb_block;
}
if (!(bh = sb_bread_unmovable(sb, logical_sb_block))) {
ext4_msg(sb, KERN_ERR, "unable to read superblock");
goto out_fail;
}
/*
* Note: s_es must be initialized as soon as possible because
* some ext4 macro-instructions depend on its value
*/
es = (struct ext4_super_block *) (bh->b_data + offset);
sbi->s_es = es;
sb->s_magic = le16_to_cpu(es->s_magic);
if (sb->s_magic != EXT4_SUPER_MAGIC)
goto cantfind_ext4;
sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written);
/* Warn if metadata_csum and gdt_csum are both set. */
if (ext4_has_feature_metadata_csum(sb) &&
ext4_has_feature_gdt_csum(sb))
ext4_warning(sb, "metadata_csum and uninit_bg are "
"redundant flags; please run fsck.");
/* Check for a known checksum algorithm */
if (!ext4_verify_csum_type(sb, es)) {
ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
"unknown checksum algorithm.");
silent = 1;
goto cantfind_ext4;
}
/* Load the checksum driver */
if (ext4_has_feature_metadata_csum(sb)) {
sbi->s_chksum_driver = crypto_alloc_shash("crc32c", 0, 0);
if (IS_ERR(sbi->s_chksum_driver)) {
ext4_msg(sb, KERN_ERR, "Cannot load crc32c driver.");
ret = PTR_ERR(sbi->s_chksum_driver);
sbi->s_chksum_driver = NULL;
goto failed_mount;
}
}
/* Check superblock checksum */
if (!ext4_superblock_csum_verify(sb, es)) {
ext4_msg(sb, KERN_ERR, "VFS: Found ext4 filesystem with "
"invalid superblock checksum. Run e2fsck?");
silent = 1;
ret = -EFSBADCRC;
goto cantfind_ext4;
}
/* Precompute checksum seed for all metadata */
if (ext4_has_feature_csum_seed(sb))
sbi->s_csum_seed = le32_to_cpu(es->s_checksum_seed);
else if (ext4_has_metadata_csum(sb))
sbi->s_csum_seed = ext4_chksum(sbi, ~0, es->s_uuid,
sizeof(es->s_uuid));
/* Set defaults before we parse the mount options */
def_mount_opts = le32_to_cpu(es->s_default_mount_opts);
set_opt(sb, INIT_INODE_TABLE);
if (def_mount_opts & EXT4_DEFM_DEBUG)
set_opt(sb, DEBUG);
if (def_mount_opts & EXT4_DEFM_BSDGROUPS)
set_opt(sb, GRPID);
if (def_mount_opts & EXT4_DEFM_UID16)
set_opt(sb, NO_UID32);
/* xattr user namespace & acls are now defaulted on */
set_opt(sb, XATTR_USER);
#ifdef CONFIG_EXT4_FS_POSIX_ACL
set_opt(sb, POSIX_ACL);
#endif
/* don't forget to enable journal_csum when metadata_csum is enabled. */
if (ext4_has_metadata_csum(sb))
set_opt(sb, JOURNAL_CHECKSUM);
if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA)
set_opt(sb, JOURNAL_DATA);
else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED)
set_opt(sb, ORDERED_DATA);
else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK)
set_opt(sb, WRITEBACK_DATA);
if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC)
set_opt(sb, ERRORS_PANIC);
else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE)
set_opt(sb, ERRORS_CONT);
else
set_opt(sb, ERRORS_RO);
/* block_validity enabled by default; disable with noblock_validity */
set_opt(sb, BLOCK_VALIDITY);
if (def_mount_opts & EXT4_DEFM_DISCARD)
set_opt(sb, DISCARD);
sbi->s_resuid = make_kuid(&init_user_ns, le16_to_cpu(es->s_def_resuid));
sbi->s_resgid = make_kgid(&init_user_ns, le16_to_cpu(es->s_def_resgid));
sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ;
sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME;
sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME;
if ((def_mount_opts & EXT4_DEFM_NOBARRIER) == 0)
set_opt(sb, BARRIER);
/*
* enable delayed allocation by default
* Use -o nodelalloc to turn it off
*/
if (!IS_EXT3_SB(sb) && !IS_EXT2_SB(sb) &&
((def_mount_opts & EXT4_DEFM_NODELALLOC) == 0))
set_opt(sb, DELALLOC);
/*
* set default s_li_wait_mult for lazyinit, for the case there is
* no mount option specified.
*/
sbi->s_li_wait_mult = EXT4_DEF_LI_WAIT_MULT;
if (sbi->s_es->s_mount_opts[0]) {
char *s_mount_opts = kstrndup(sbi->s_es->s_mount_opts,
sizeof(sbi->s_es->s_mount_opts),
GFP_KERNEL);
if (!s_mount_opts)
goto failed_mount;
if (!parse_options(s_mount_opts, sb, &journal_devnum,
&journal_ioprio, 0)) {
ext4_msg(sb, KERN_WARNING,
"failed to parse options in superblock: %s",
s_mount_opts);
}
kfree(s_mount_opts);
}
sbi->s_def_mount_opt = sbi->s_mount_opt;
if (!parse_options((char *) data, sb, &journal_devnum,
&journal_ioprio, 0))
goto failed_mount;
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
printk_once(KERN_WARNING "EXT4-fs: Warning: mounting "
"with data=journal disables delayed "
"allocation and O_DIRECT support!\n");
if (test_opt2(sb, EXPLICIT_DELALLOC)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and delalloc");
goto failed_mount;
}
if (test_opt(sb, DIOREAD_NOLOCK)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dioread_nolock");
goto failed_mount;
}
if (test_opt(sb, DAX)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dax");
goto failed_mount;
}
if (test_opt(sb, DELALLOC))
clear_opt(sb, DELALLOC);
} else {
sb->s_iflags |= SB_I_CGROUPWB;
}
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
(test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0);
if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV &&
(ext4_has_compat_features(sb) ||
ext4_has_ro_compat_features(sb) ||
ext4_has_incompat_features(sb)))
ext4_msg(sb, KERN_WARNING,
"feature flags set on rev 0 fs, "
"running e2fsck is recommended");
if (es->s_creator_os == cpu_to_le32(EXT4_OS_HURD)) {
set_opt2(sb, HURD_COMPAT);
if (ext4_has_feature_64bit(sb)) {
ext4_msg(sb, KERN_ERR,
"The Hurd can't support 64-bit file systems");
goto failed_mount;
}
}
if (IS_EXT2_SB(sb)) {
if (ext2_feature_set_ok(sb))
ext4_msg(sb, KERN_INFO, "mounting ext2 file system "
"using the ext4 subsystem");
else {
ext4_msg(sb, KERN_ERR, "couldn't mount as ext2 due "
"to feature incompatibilities");
goto failed_mount;
}
}
if (IS_EXT3_SB(sb)) {
if (ext3_feature_set_ok(sb))
ext4_msg(sb, KERN_INFO, "mounting ext3 file system "
"using the ext4 subsystem");
else {
ext4_msg(sb, KERN_ERR, "couldn't mount as ext3 due "
"to feature incompatibilities");
goto failed_mount;
}
}
/*
* Check feature flags regardless of the revision level, since we
* previously didn't change the revision level when setting the flags,
* so there is a chance incompat flags are set on a rev 0 filesystem.
*/
if (!ext4_feature_set_ok(sb, (sb->s_flags & MS_RDONLY)))
goto failed_mount;
blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size);
if (blocksize < EXT4_MIN_BLOCK_SIZE ||
blocksize > EXT4_MAX_BLOCK_SIZE) {
ext4_msg(sb, KERN_ERR,
"Unsupported filesystem blocksize %d (%d log_block_size)",
blocksize, le32_to_cpu(es->s_log_block_size));
goto failed_mount;
}
if (le32_to_cpu(es->s_log_block_size) >
(EXT4_MAX_BLOCK_LOG_SIZE - EXT4_MIN_BLOCK_LOG_SIZE)) {
ext4_msg(sb, KERN_ERR,
"Invalid log block size: %u",
le32_to_cpu(es->s_log_block_size));
goto failed_mount;
}
if (le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks) > (blocksize / 4)) {
ext4_msg(sb, KERN_ERR,
"Number of reserved GDT blocks insanely large: %d",
le16_to_cpu(sbi->s_es->s_reserved_gdt_blocks));
goto failed_mount;
}
if (sbi->s_mount_opt & EXT4_MOUNT_DAX) {
err = bdev_dax_supported(sb, blocksize);
if (err)
goto failed_mount;
}
if (ext4_has_feature_encrypt(sb) && es->s_encryption_level) {
ext4_msg(sb, KERN_ERR, "Unsupported encryption level %d",
es->s_encryption_level);
goto failed_mount;
}
if (sb->s_blocksize != blocksize) {
/* Validate the filesystem blocksize */
if (!sb_set_blocksize(sb, blocksize)) {
ext4_msg(sb, KERN_ERR, "bad block size %d",
blocksize);
goto failed_mount;
}
brelse(bh);
logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE;
offset = do_div(logical_sb_block, blocksize);
bh = sb_bread_unmovable(sb, logical_sb_block);
if (!bh) {
ext4_msg(sb, KERN_ERR,
"Can't read superblock on 2nd try");
goto failed_mount;
}
es = (struct ext4_super_block *)(bh->b_data + offset);
sbi->s_es = es;
if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) {
ext4_msg(sb, KERN_ERR,
"Magic mismatch, very weird!");
goto failed_mount;
}
}
has_huge_files = ext4_has_feature_huge_file(sb);
sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits,
has_huge_files);
sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files);
if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) {
sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE;
sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO;
} else {
sbi->s_inode_size = le16_to_cpu(es->s_inode_size);
sbi->s_first_ino = le32_to_cpu(es->s_first_ino);
if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) ||
(!is_power_of_2(sbi->s_inode_size)) ||
(sbi->s_inode_size > blocksize)) {
ext4_msg(sb, KERN_ERR,
"unsupported inode size: %d",
sbi->s_inode_size);
goto failed_mount;
}
if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE)
sb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2);
}
sbi->s_desc_size = le16_to_cpu(es->s_desc_size);
if (ext4_has_feature_64bit(sb)) {
if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT ||
sbi->s_desc_size > EXT4_MAX_DESC_SIZE ||
!is_power_of_2(sbi->s_desc_size)) {
ext4_msg(sb, KERN_ERR,
"unsupported descriptor size %lu",
sbi->s_desc_size);
goto failed_mount;
}
} else
sbi->s_desc_size = EXT4_MIN_DESC_SIZE;
sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group);
sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group);
sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb);
if (sbi->s_inodes_per_block == 0)
goto cantfind_ext4;
if (sbi->s_inodes_per_group < sbi->s_inodes_per_block ||
sbi->s_inodes_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR, "invalid inodes per group: %lu\n",
sbi->s_blocks_per_group);
goto failed_mount;
}
sbi->s_itb_per_group = sbi->s_inodes_per_group /
sbi->s_inodes_per_block;
sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb);
sbi->s_sbh = bh;
sbi->s_mount_state = le16_to_cpu(es->s_state);
sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb));
sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb));
for (i = 0; i < 4; i++)
sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]);
sbi->s_def_hash_version = es->s_def_hash_version;
if (ext4_has_feature_dir_index(sb)) {
i = le32_to_cpu(es->s_flags);
if (i & EXT2_FLAGS_UNSIGNED_HASH)
sbi->s_hash_unsigned = 3;
else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) {
#ifdef __CHAR_UNSIGNED__
if (!(sb->s_flags & MS_RDONLY))
es->s_flags |=
cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH);
sbi->s_hash_unsigned = 3;
#else
if (!(sb->s_flags & MS_RDONLY))
es->s_flags |=
cpu_to_le32(EXT2_FLAGS_SIGNED_HASH);
#endif
}
}
/* Handle clustersize */
clustersize = BLOCK_SIZE << le32_to_cpu(es->s_log_cluster_size);
has_bigalloc = ext4_has_feature_bigalloc(sb);
if (has_bigalloc) {
if (clustersize < blocksize) {
ext4_msg(sb, KERN_ERR,
"cluster size (%d) smaller than "
"block size (%d)", clustersize, blocksize);
goto failed_mount;
}
if (le32_to_cpu(es->s_log_cluster_size) >
(EXT4_MAX_CLUSTER_LOG_SIZE - EXT4_MIN_BLOCK_LOG_SIZE)) {
ext4_msg(sb, KERN_ERR,
"Invalid log cluster size: %u",
le32_to_cpu(es->s_log_cluster_size));
goto failed_mount;
}
sbi->s_cluster_bits = le32_to_cpu(es->s_log_cluster_size) -
le32_to_cpu(es->s_log_block_size);
sbi->s_clusters_per_group =
le32_to_cpu(es->s_clusters_per_group);
if (sbi->s_clusters_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#clusters per group too big: %lu",
sbi->s_clusters_per_group);
goto failed_mount;
}
if (sbi->s_blocks_per_group !=
(sbi->s_clusters_per_group * (clustersize / blocksize))) {
ext4_msg(sb, KERN_ERR, "blocks per group (%lu) and "
"clusters per group (%lu) inconsistent",
sbi->s_blocks_per_group,
sbi->s_clusters_per_group);
goto failed_mount;
}
} else {
if (clustersize != blocksize) {
ext4_warning(sb, "fragment/cluster size (%d) != "
"block size (%d)", clustersize,
blocksize);
clustersize = blocksize;
}
if (sbi->s_blocks_per_group > blocksize * 8) {
ext4_msg(sb, KERN_ERR,
"#blocks per group too big: %lu",
sbi->s_blocks_per_group);
goto failed_mount;
}
sbi->s_clusters_per_group = sbi->s_blocks_per_group;
sbi->s_cluster_bits = 0;
}
sbi->s_cluster_ratio = clustersize / blocksize;
/* Do we have standard group size of clustersize * 8 blocks ? */
if (sbi->s_blocks_per_group == clustersize << 3)
set_opt2(sb, STD_GROUP_SIZE);
/*
* Test whether we have more sectors than will fit in sector_t,
* and whether the max offset is addressable by the page cache.
*/
err = generic_check_addressable(sb->s_blocksize_bits,
ext4_blocks_count(es));
if (err) {
ext4_msg(sb, KERN_ERR, "filesystem"
" too large to mount safely on this system");
if (sizeof(sector_t) < 8)
ext4_msg(sb, KERN_WARNING, "CONFIG_LBDAF not enabled");
goto failed_mount;
}
if (EXT4_BLOCKS_PER_GROUP(sb) == 0)
goto cantfind_ext4;
/* check blocks count against device size */
blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits;
if (blocks_count && ext4_blocks_count(es) > blocks_count) {
ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu "
"exceeds size of device (%llu blocks)",
ext4_blocks_count(es), blocks_count);
goto failed_mount;
}
/*
* It makes no sense for the first data block to be beyond the end
* of the filesystem.
*/
if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) {
ext4_msg(sb, KERN_WARNING, "bad geometry: first data "
"block %u is beyond end of filesystem (%llu)",
le32_to_cpu(es->s_first_data_block),
ext4_blocks_count(es));
goto failed_mount;
}
blocks_count = (ext4_blocks_count(es) -
le32_to_cpu(es->s_first_data_block) +
EXT4_BLOCKS_PER_GROUP(sb) - 1);
do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb));
if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) {
ext4_msg(sb, KERN_WARNING, "groups count too large: %u "
"(block count %llu, first data block %u, "
"blocks per group %lu)", sbi->s_groups_count,
ext4_blocks_count(es),
le32_to_cpu(es->s_first_data_block),
EXT4_BLOCKS_PER_GROUP(sb));
goto failed_mount;
}
sbi->s_groups_count = blocks_count;
sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count,
(EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb)));
db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) /
EXT4_DESC_PER_BLOCK(sb);
if (ext4_has_feature_meta_bg(sb)) {
if (le32_to_cpu(es->s_first_meta_bg) >= db_count) {
ext4_msg(sb, KERN_WARNING,
"first meta block group too large: %u "
"(group descriptor block count %u)",
le32_to_cpu(es->s_first_meta_bg), db_count);
goto failed_mount;
}
}
sbi->s_group_desc = ext4_kvmalloc(db_count *
sizeof(struct buffer_head *),
GFP_KERNEL);
if (sbi->s_group_desc == NULL) {
ext4_msg(sb, KERN_ERR, "not enough memory");
ret = -ENOMEM;
goto failed_mount;
}
bgl_lock_init(sbi->s_blockgroup_lock);
for (i = 0; i < db_count; i++) {
block = descriptor_loc(sb, logical_sb_block, i);
sbi->s_group_desc[i] = sb_bread_unmovable(sb, block);
if (!sbi->s_group_desc[i]) {
ext4_msg(sb, KERN_ERR,
"can't read group descriptor %d", i);
db_count = i;
goto failed_mount2;
}
}
if (!ext4_check_descriptors(sb, logical_sb_block, &first_not_zeroed)) {
ext4_msg(sb, KERN_ERR, "group descriptors corrupted!");
ret = -EFSCORRUPTED;
goto failed_mount2;
}
sbi->s_gdb_count = db_count;
get_random_bytes(&sbi->s_next_generation, sizeof(u32));
spin_lock_init(&sbi->s_next_gen_lock);
setup_timer(&sbi->s_err_report, print_daily_error_info,
(unsigned long) sb);
/* Register extent status tree shrinker */
if (ext4_es_register_shrinker(sbi))
goto failed_mount3;
sbi->s_stripe = ext4_get_stripe_size(sbi);
sbi->s_extent_max_zeroout_kb = 32;
/*
* set up enough so that it can read an inode
*/
sb->s_op = &ext4_sops;
sb->s_export_op = &ext4_export_ops;
sb->s_xattr = ext4_xattr_handlers;
sb->s_cop = &ext4_cryptops;
#ifdef CONFIG_QUOTA
sb->dq_op = &ext4_quota_operations;
if (ext4_has_feature_quota(sb))
sb->s_qcop = &dquot_quotactl_sysfile_ops;
else
sb->s_qcop = &ext4_qctl_operations;
sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP | QTYPE_MASK_PRJ;
#endif
memcpy(sb->s_uuid, es->s_uuid, sizeof(es->s_uuid));
INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */
mutex_init(&sbi->s_orphan_lock);
sb->s_root = NULL;
needs_recovery = (es->s_last_orphan != 0 ||
ext4_has_feature_journal_needs_recovery(sb));
if (ext4_has_feature_mmp(sb) && !(sb->s_flags & MS_RDONLY))
if (ext4_multi_mount_protect(sb, le64_to_cpu(es->s_mmp_block)))
goto failed_mount3a;
/*
* The first inode we look at is the journal inode. Don't try
* root first: it may be modified in the journal!
*/
if (!test_opt(sb, NOLOAD) && ext4_has_feature_journal(sb)) {
if (ext4_load_journal(sb, es, journal_devnum))
goto failed_mount3a;
} else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) &&
ext4_has_feature_journal_needs_recovery(sb)) {
ext4_msg(sb, KERN_ERR, "required journal recovery "
"suppressed and not mounted read-only");
goto failed_mount_wq;
} else {
/* Nojournal mode, all journal mount options are illegal */
if (test_opt2(sb, EXPLICIT_JOURNAL_CHECKSUM)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"journal_checksum, fs mounted w/o journal");
goto failed_mount_wq;
}
if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"journal_async_commit, fs mounted w/o journal");
goto failed_mount_wq;
}
if (sbi->s_commit_interval != JBD2_DEFAULT_MAX_COMMIT_AGE*HZ) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"commit=%lu, fs mounted w/o journal",
sbi->s_commit_interval / HZ);
goto failed_mount_wq;
}
if (EXT4_MOUNT_DATA_FLAGS &
(sbi->s_mount_opt ^ sbi->s_def_mount_opt)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"data=, fs mounted w/o journal");
goto failed_mount_wq;
}
sbi->s_def_mount_opt &= EXT4_MOUNT_JOURNAL_CHECKSUM;
clear_opt(sb, JOURNAL_CHECKSUM);
clear_opt(sb, DATA_FLAGS);
sbi->s_journal = NULL;
needs_recovery = 0;
goto no_journal;
}
if (ext4_has_feature_64bit(sb) &&
!jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0,
JBD2_FEATURE_INCOMPAT_64BIT)) {
ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature");
goto failed_mount_wq;
}
if (!set_journal_csum_feature_set(sb)) {
ext4_msg(sb, KERN_ERR, "Failed to set journal checksum "
"feature set");
goto failed_mount_wq;
}
/* We have now updated the journal if required, so we can
* validate the data journaling mode. */
switch (test_opt(sb, DATA_FLAGS)) {
case 0:
/* No mode set, assume a default based on the journal
* capabilities: ORDERED_DATA if the journal can
* cope, else JOURNAL_DATA
*/
if (jbd2_journal_check_available_features
(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE))
set_opt(sb, ORDERED_DATA);
else
set_opt(sb, JOURNAL_DATA);
break;
case EXT4_MOUNT_ORDERED_DATA:
case EXT4_MOUNT_WRITEBACK_DATA:
if (!jbd2_journal_check_available_features
(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) {
ext4_msg(sb, KERN_ERR, "Journal does not support "
"requested data journaling mode");
goto failed_mount_wq;
}
default:
break;
}
set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
sbi->s_journal->j_commit_callback = ext4_journal_commit_callback;
no_journal:
sbi->s_mb_cache = ext4_xattr_create_cache();
if (!sbi->s_mb_cache) {
ext4_msg(sb, KERN_ERR, "Failed to create an mb_cache");
goto failed_mount_wq;
}
if ((DUMMY_ENCRYPTION_ENABLED(sbi) || ext4_has_feature_encrypt(sb)) &&
(blocksize != PAGE_SIZE)) {
ext4_msg(sb, KERN_ERR,
"Unsupported blocksize for fs encryption");
goto failed_mount_wq;
}
if (DUMMY_ENCRYPTION_ENABLED(sbi) && !(sb->s_flags & MS_RDONLY) &&
!ext4_has_feature_encrypt(sb)) {
ext4_set_feature_encrypt(sb);
ext4_commit_super(sb, 1);
}
/*
* Get the # of file system overhead blocks from the
* superblock if present.
*/
if (es->s_overhead_clusters)
sbi->s_overhead = le32_to_cpu(es->s_overhead_clusters);
else {
err = ext4_calculate_overhead(sb);
if (err)
goto failed_mount_wq;
}
/*
* The maximum number of concurrent works can be high and
* concurrency isn't really necessary. Limit it to 1.
*/
EXT4_SB(sb)->rsv_conversion_wq =
alloc_workqueue("ext4-rsv-conversion", WQ_MEM_RECLAIM | WQ_UNBOUND, 1);
if (!EXT4_SB(sb)->rsv_conversion_wq) {
printk(KERN_ERR "EXT4-fs: failed to create workqueue\n");
ret = -ENOMEM;
goto failed_mount4;
}
/*
* The jbd2_journal_load will have done any necessary log recovery,
* so we can safely mount the rest of the filesystem now.
*/
root = ext4_iget(sb, EXT4_ROOT_INO);
if (IS_ERR(root)) {
ext4_msg(sb, KERN_ERR, "get root inode failed");
ret = PTR_ERR(root);
root = NULL;
goto failed_mount4;
}
if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck");
iput(root);
goto failed_mount4;
}
sb->s_root = d_make_root(root);
if (!sb->s_root) {
ext4_msg(sb, KERN_ERR, "get root dentry failed");
ret = -ENOMEM;
goto failed_mount4;
}
if (ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY))
sb->s_flags |= MS_RDONLY;
/* determine the minimum size of new large inodes, if present */
if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) {
sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
if (ext4_has_feature_extra_isize(sb)) {
if (sbi->s_want_extra_isize <
le16_to_cpu(es->s_want_extra_isize))
sbi->s_want_extra_isize =
le16_to_cpu(es->s_want_extra_isize);
if (sbi->s_want_extra_isize <
le16_to_cpu(es->s_min_extra_isize))
sbi->s_want_extra_isize =
le16_to_cpu(es->s_min_extra_isize);
}
}
/* Check if enough inode space is available */
if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize >
sbi->s_inode_size) {
sbi->s_want_extra_isize = sizeof(struct ext4_inode) -
EXT4_GOOD_OLD_INODE_SIZE;
ext4_msg(sb, KERN_INFO, "required extra inode space not"
"available");
}
ext4_set_resv_clusters(sb);
err = ext4_setup_system_zone(sb);
if (err) {
ext4_msg(sb, KERN_ERR, "failed to initialize system "
"zone (%d)", err);
goto failed_mount4a;
}
ext4_ext_init(sb);
err = ext4_mb_init(sb);
if (err) {
ext4_msg(sb, KERN_ERR, "failed to initialize mballoc (%d)",
err);
goto failed_mount5;
}
block = ext4_count_free_clusters(sb);
ext4_free_blocks_count_set(sbi->s_es,
EXT4_C2B(sbi, block));
err = percpu_counter_init(&sbi->s_freeclusters_counter, block,
GFP_KERNEL);
if (!err) {
unsigned long freei = ext4_count_free_inodes(sb);
sbi->s_es->s_free_inodes_count = cpu_to_le32(freei);
err = percpu_counter_init(&sbi->s_freeinodes_counter, freei,
GFP_KERNEL);
}
if (!err)
err = percpu_counter_init(&sbi->s_dirs_counter,
ext4_count_dirs(sb), GFP_KERNEL);
if (!err)
err = percpu_counter_init(&sbi->s_dirtyclusters_counter, 0,
GFP_KERNEL);
if (!err)
err = percpu_init_rwsem(&sbi->s_journal_flag_rwsem);
if (err) {
ext4_msg(sb, KERN_ERR, "insufficient memory");
goto failed_mount6;
}
if (ext4_has_feature_flex_bg(sb))
if (!ext4_fill_flex_info(sb)) {
ext4_msg(sb, KERN_ERR,
"unable to initialize "
"flex_bg meta info!");
goto failed_mount6;
}
err = ext4_register_li_request(sb, first_not_zeroed);
if (err)
goto failed_mount6;
err = ext4_register_sysfs(sb);
if (err)
goto failed_mount7;
#ifdef CONFIG_QUOTA
/* Enable quota usage during mount. */
if (ext4_has_feature_quota(sb) && !(sb->s_flags & MS_RDONLY)) {
err = ext4_enable_quotas(sb);
if (err)
goto failed_mount8;
}
#endif /* CONFIG_QUOTA */
EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS;
ext4_orphan_cleanup(sb, es);
EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS;
if (needs_recovery) {
ext4_msg(sb, KERN_INFO, "recovery complete");
ext4_mark_recovery_complete(sb, es);
}
if (EXT4_SB(sb)->s_journal) {
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)
descr = " journalled data mode";
else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA)
descr = " ordered data mode";
else
descr = " writeback data mode";
} else
descr = "out journal";
if (test_opt(sb, DISCARD)) {
struct request_queue *q = bdev_get_queue(sb->s_bdev);
if (!blk_queue_discard(q))
ext4_msg(sb, KERN_WARNING,
"mounting with \"discard\" option, but "
"the device does not support discard");
}
if (___ratelimit(&ext4_mount_msg_ratelimit, "EXT4-fs mount"))
ext4_msg(sb, KERN_INFO, "mounted filesystem with%s. "
"Opts: %.*s%s%s", descr,
(int) sizeof(sbi->s_es->s_mount_opts),
sbi->s_es->s_mount_opts,
*sbi->s_es->s_mount_opts ? "; " : "", orig_data);
if (es->s_error_count)
mod_timer(&sbi->s_err_report, jiffies + 300*HZ); /* 5 minutes */
/* Enable message ratelimiting. Default is 10 messages per 5 secs. */
ratelimit_state_init(&sbi->s_err_ratelimit_state, 5 * HZ, 10);
ratelimit_state_init(&sbi->s_warning_ratelimit_state, 5 * HZ, 10);
ratelimit_state_init(&sbi->s_msg_ratelimit_state, 5 * HZ, 10);
kfree(orig_data);
#ifdef CONFIG_EXT4_FS_ENCRYPTION
memcpy(sbi->key_prefix, EXT4_KEY_DESC_PREFIX,
EXT4_KEY_DESC_PREFIX_SIZE);
sbi->key_prefix_size = EXT4_KEY_DESC_PREFIX_SIZE;
#endif
return 0;
cantfind_ext4:
if (!silent)
ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem");
goto failed_mount;
#ifdef CONFIG_QUOTA
failed_mount8:
ext4_unregister_sysfs(sb);
#endif
failed_mount7:
ext4_unregister_li_request(sb);
failed_mount6:
ext4_mb_release(sb);
if (sbi->s_flex_groups)
kvfree(sbi->s_flex_groups);
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
failed_mount5:
ext4_ext_release(sb);
ext4_release_system_zone(sb);
failed_mount4a:
dput(sb->s_root);
sb->s_root = NULL;
failed_mount4:
ext4_msg(sb, KERN_ERR, "mount failed");
if (EXT4_SB(sb)->rsv_conversion_wq)
destroy_workqueue(EXT4_SB(sb)->rsv_conversion_wq);
failed_mount_wq:
if (sbi->s_mb_cache) {
ext4_xattr_destroy_cache(sbi->s_mb_cache);
sbi->s_mb_cache = NULL;
}
if (sbi->s_journal) {
jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
}
failed_mount3a:
ext4_es_unregister_shrinker(sbi);
failed_mount3:
del_timer_sync(&sbi->s_err_report);
if (sbi->s_mmp_tsk)
kthread_stop(sbi->s_mmp_tsk);
failed_mount2:
for (i = 0; i < db_count; i++)
brelse(sbi->s_group_desc[i]);
kvfree(sbi->s_group_desc);
failed_mount:
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
#ifdef CONFIG_QUOTA
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
ext4_blkdev_remove(sbi);
brelse(bh);
out_fail:
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
out_free_base:
kfree(sbi);
kfree(orig_data);
return err ? err : ret;
}
/*
* Setup any per-fs journal parameters now. We'll do this both on
* initial mount, once the journal has been initialised but before we've
* done any recovery; and again on any subsequent remount.
*/
static void ext4_init_journal_params(struct super_block *sb, journal_t *journal)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
journal->j_commit_interval = sbi->s_commit_interval;
journal->j_min_batch_time = sbi->s_min_batch_time;
journal->j_max_batch_time = sbi->s_max_batch_time;
write_lock(&journal->j_state_lock);
if (test_opt(sb, BARRIER))
journal->j_flags |= JBD2_BARRIER;
else
journal->j_flags &= ~JBD2_BARRIER;
if (test_opt(sb, DATA_ERR_ABORT))
journal->j_flags |= JBD2_ABORT_ON_SYNCDATA_ERR;
else
journal->j_flags &= ~JBD2_ABORT_ON_SYNCDATA_ERR;
write_unlock(&journal->j_state_lock);
}
static struct inode *ext4_get_journal_inode(struct super_block *sb,
unsigned int journal_inum)
{
struct inode *journal_inode;
/*
* Test for the existence of a valid inode on disk. Bad things
* happen if we iget() an unused inode, as the subsequent iput()
* will try to delete it.
*/
journal_inode = ext4_iget(sb, journal_inum);
if (IS_ERR(journal_inode)) {
ext4_msg(sb, KERN_ERR, "no journal found");
return NULL;
}
if (!journal_inode->i_nlink) {
make_bad_inode(journal_inode);
iput(journal_inode);
ext4_msg(sb, KERN_ERR, "journal inode is deleted");
return NULL;
}
jbd_debug(2, "Journal inode found at %p: %lld bytes\n",
journal_inode, journal_inode->i_size);
if (!S_ISREG(journal_inode->i_mode)) {
ext4_msg(sb, KERN_ERR, "invalid journal inode");
iput(journal_inode);
return NULL;
}
return journal_inode;
}
static journal_t *ext4_get_journal(struct super_block *sb,
unsigned int journal_inum)
{
struct inode *journal_inode;
journal_t *journal;
BUG_ON(!ext4_has_feature_journal(sb));
journal_inode = ext4_get_journal_inode(sb, journal_inum);
if (!journal_inode)
return NULL;
journal = jbd2_journal_init_inode(journal_inode);
if (!journal) {
ext4_msg(sb, KERN_ERR, "Could not load journal inode");
iput(journal_inode);
return NULL;
}
journal->j_private = sb;
ext4_init_journal_params(sb, journal);
return journal;
}
static journal_t *ext4_get_dev_journal(struct super_block *sb,
dev_t j_dev)
{
struct buffer_head *bh;
journal_t *journal;
ext4_fsblk_t start;
ext4_fsblk_t len;
int hblock, blocksize;
ext4_fsblk_t sb_block;
unsigned long offset;
struct ext4_super_block *es;
struct block_device *bdev;
BUG_ON(!ext4_has_feature_journal(sb));
bdev = ext4_blkdev_get(j_dev, sb);
if (bdev == NULL)
return NULL;
blocksize = sb->s_blocksize;
hblock = bdev_logical_block_size(bdev);
if (blocksize < hblock) {
ext4_msg(sb, KERN_ERR,
"blocksize too small for journal device");
goto out_bdev;
}
sb_block = EXT4_MIN_BLOCK_SIZE / blocksize;
offset = EXT4_MIN_BLOCK_SIZE % blocksize;
set_blocksize(bdev, blocksize);
if (!(bh = __bread(bdev, sb_block, blocksize))) {
ext4_msg(sb, KERN_ERR, "couldn't read superblock of "
"external journal");
goto out_bdev;
}
es = (struct ext4_super_block *) (bh->b_data + offset);
if ((le16_to_cpu(es->s_magic) != EXT4_SUPER_MAGIC) ||
!(le32_to_cpu(es->s_feature_incompat) &
EXT4_FEATURE_INCOMPAT_JOURNAL_DEV)) {
ext4_msg(sb, KERN_ERR, "external journal has "
"bad superblock");
brelse(bh);
goto out_bdev;
}
if ((le32_to_cpu(es->s_feature_ro_compat) &
EXT4_FEATURE_RO_COMPAT_METADATA_CSUM) &&
es->s_checksum != ext4_superblock_csum(sb, es)) {
ext4_msg(sb, KERN_ERR, "external journal has "
"corrupt superblock");
brelse(bh);
goto out_bdev;
}
if (memcmp(EXT4_SB(sb)->s_es->s_journal_uuid, es->s_uuid, 16)) {
ext4_msg(sb, KERN_ERR, "journal UUID does not match");
brelse(bh);
goto out_bdev;
}
len = ext4_blocks_count(es);
start = sb_block + 1;
brelse(bh); /* we're done with the superblock */
journal = jbd2_journal_init_dev(bdev, sb->s_bdev,
start, len, blocksize);
if (!journal) {
ext4_msg(sb, KERN_ERR, "failed to create device journal");
goto out_bdev;
}
journal->j_private = sb;
ll_rw_block(REQ_OP_READ, REQ_META | REQ_PRIO, 1, &journal->j_sb_buffer);
wait_on_buffer(journal->j_sb_buffer);
if (!buffer_uptodate(journal->j_sb_buffer)) {
ext4_msg(sb, KERN_ERR, "I/O error on journal device");
goto out_journal;
}
if (be32_to_cpu(journal->j_superblock->s_nr_users) != 1) {
ext4_msg(sb, KERN_ERR, "External journal has more than one "
"user (unsupported) - %d",
be32_to_cpu(journal->j_superblock->s_nr_users));
goto out_journal;
}
EXT4_SB(sb)->journal_bdev = bdev;
ext4_init_journal_params(sb, journal);
return journal;
out_journal:
jbd2_journal_destroy(journal);
out_bdev:
ext4_blkdev_put(bdev);
return NULL;
}
static int ext4_load_journal(struct super_block *sb,
struct ext4_super_block *es,
unsigned long journal_devnum)
{
journal_t *journal;
unsigned int journal_inum = le32_to_cpu(es->s_journal_inum);
dev_t journal_dev;
int err = 0;
int really_read_only;
BUG_ON(!ext4_has_feature_journal(sb));
if (journal_devnum &&
journal_devnum != le32_to_cpu(es->s_journal_dev)) {
ext4_msg(sb, KERN_INFO, "external journal device major/minor "
"numbers have changed");
journal_dev = new_decode_dev(journal_devnum);
} else
journal_dev = new_decode_dev(le32_to_cpu(es->s_journal_dev));
really_read_only = bdev_read_only(sb->s_bdev);
/*
* Are we loading a blank journal or performing recovery after a
* crash? For recovery, we need to check in advance whether we
* can get read-write access to the device.
*/
if (ext4_has_feature_journal_needs_recovery(sb)) {
if (sb->s_flags & MS_RDONLY) {
ext4_msg(sb, KERN_INFO, "INFO: recovery "
"required on readonly filesystem");
if (really_read_only) {
ext4_msg(sb, KERN_ERR, "write access "
"unavailable, cannot proceed");
return -EROFS;
}
ext4_msg(sb, KERN_INFO, "write access will "
"be enabled during recovery");
}
}
if (journal_inum && journal_dev) {
ext4_msg(sb, KERN_ERR, "filesystem has both journal "
"and inode journals!");
return -EINVAL;
}
if (journal_inum) {
if (!(journal = ext4_get_journal(sb, journal_inum)))
return -EINVAL;
} else {
if (!(journal = ext4_get_dev_journal(sb, journal_dev)))
return -EINVAL;
}
if (!(journal->j_flags & JBD2_BARRIER))
ext4_msg(sb, KERN_INFO, "barriers disabled");
if (!ext4_has_feature_journal_needs_recovery(sb))
err = jbd2_journal_wipe(journal, !really_read_only);
if (!err) {
char *save = kmalloc(EXT4_S_ERR_LEN, GFP_KERNEL);
if (save)
memcpy(save, ((char *) es) +
EXT4_S_ERR_START, EXT4_S_ERR_LEN);
err = jbd2_journal_load(journal);
if (save)
memcpy(((char *) es) + EXT4_S_ERR_START,
save, EXT4_S_ERR_LEN);
kfree(save);
}
if (err) {
ext4_msg(sb, KERN_ERR, "error loading journal");
jbd2_journal_destroy(journal);
return err;
}
EXT4_SB(sb)->s_journal = journal;
ext4_clear_journal_err(sb, es);
if (!really_read_only && journal_devnum &&
journal_devnum != le32_to_cpu(es->s_journal_dev)) {
es->s_journal_dev = cpu_to_le32(journal_devnum);
/* Make sure we flush the recovery flag to disk. */
ext4_commit_super(sb, 1);
}
return 0;
}
static int ext4_commit_super(struct super_block *sb, int sync)
{
struct ext4_super_block *es = EXT4_SB(sb)->s_es;
struct buffer_head *sbh = EXT4_SB(sb)->s_sbh;
int error = 0;
if (!sbh || block_device_ejected(sb))
return error;
/*
* If the file system is mounted read-only, don't update the
* superblock write time. This avoids updating the superblock
* write time when we are mounting the root file system
* read/only but we need to replay the journal; at that point,
* for people who are east of GMT and who make their clock
* tick in localtime for Windows bug-for-bug compatibility,
* the clock is set in the future, and this will cause e2fsck
* to complain and force a full file system check.
*/
if (!(sb->s_flags & MS_RDONLY))
es->s_wtime = cpu_to_le32(get_seconds());
if (sb->s_bdev->bd_part)
es->s_kbytes_written =
cpu_to_le64(EXT4_SB(sb)->s_kbytes_written +
((part_stat_read(sb->s_bdev->bd_part, sectors[1]) -
EXT4_SB(sb)->s_sectors_written_start) >> 1));
else
es->s_kbytes_written =
cpu_to_le64(EXT4_SB(sb)->s_kbytes_written);
if (percpu_counter_initialized(&EXT4_SB(sb)->s_freeclusters_counter))
ext4_free_blocks_count_set(es,
EXT4_C2B(EXT4_SB(sb), percpu_counter_sum_positive(
&EXT4_SB(sb)->s_freeclusters_counter)));
if (percpu_counter_initialized(&EXT4_SB(sb)->s_freeinodes_counter))
es->s_free_inodes_count =
cpu_to_le32(percpu_counter_sum_positive(
&EXT4_SB(sb)->s_freeinodes_counter));
BUFFER_TRACE(sbh, "marking dirty");
ext4_superblock_csum_set(sb);
if (sync)
lock_buffer(sbh);
if (buffer_write_io_error(sbh)) {
/*
* Oh, dear. A previous attempt to write the
* superblock failed. This could happen because the
* USB device was yanked out. Or it could happen to
* be a transient write error and maybe the block will
* be remapped. Nothing we can do but to retry the
* write and hope for the best.
*/
ext4_msg(sb, KERN_ERR, "previous I/O error to "
"superblock detected");
clear_buffer_write_io_error(sbh);
set_buffer_uptodate(sbh);
}
mark_buffer_dirty(sbh);
if (sync) {
unlock_buffer(sbh);
error = __sync_dirty_buffer(sbh,
test_opt(sb, BARRIER) ? WRITE_FUA : WRITE_SYNC);
if (error)
return error;
error = buffer_write_io_error(sbh);
if (error) {
ext4_msg(sb, KERN_ERR, "I/O error while writing "
"superblock");
clear_buffer_write_io_error(sbh);
set_buffer_uptodate(sbh);
}
}
return error;
}
/*
* Have we just finished recovery? If so, and if we are mounting (or
* remounting) the filesystem readonly, then we will end up with a
* consistent fs on disk. Record that fact.
*/
static void ext4_mark_recovery_complete(struct super_block *sb,
struct ext4_super_block *es)
{
journal_t *journal = EXT4_SB(sb)->s_journal;
if (!ext4_has_feature_journal(sb)) {
BUG_ON(journal != NULL);
return;
}
jbd2_journal_lock_updates(journal);
if (jbd2_journal_flush(journal) < 0)
goto out;
if (ext4_has_feature_journal_needs_recovery(sb) &&
sb->s_flags & MS_RDONLY) {
ext4_clear_feature_journal_needs_recovery(sb);
ext4_commit_super(sb, 1);
}
out:
jbd2_journal_unlock_updates(journal);
}
/*
* If we are mounting (or read-write remounting) a filesystem whose journal
* has recorded an error from a previous lifetime, move that error to the
* main filesystem now.
*/
static void ext4_clear_journal_err(struct super_block *sb,
struct ext4_super_block *es)
{
journal_t *journal;
int j_errno;
const char *errstr;
BUG_ON(!ext4_has_feature_journal(sb));
journal = EXT4_SB(sb)->s_journal;
/*
* Now check for any error status which may have been recorded in the
* journal by a prior ext4_error() or ext4_abort()
*/
j_errno = jbd2_journal_errno(journal);
if (j_errno) {
char nbuf[16];
errstr = ext4_decode_error(sb, j_errno, nbuf);
ext4_warning(sb, "Filesystem error recorded "
"from previous mount: %s", errstr);
ext4_warning(sb, "Marking fs in need of filesystem check.");
EXT4_SB(sb)->s_mount_state |= EXT4_ERROR_FS;
es->s_state |= cpu_to_le16(EXT4_ERROR_FS);
ext4_commit_super(sb, 1);
jbd2_journal_clear_err(journal);
jbd2_journal_update_sb_errno(journal);
}
}
/*
* Force the running and committing transactions to commit,
* and wait on the commit.
*/
int ext4_force_commit(struct super_block *sb)
{
journal_t *journal;
if (sb->s_flags & MS_RDONLY)
return 0;
journal = EXT4_SB(sb)->s_journal;
return ext4_journal_force_commit(journal);
}
static int ext4_sync_fs(struct super_block *sb, int wait)
{
int ret = 0;
tid_t target;
bool needs_barrier = false;
struct ext4_sb_info *sbi = EXT4_SB(sb);
trace_ext4_sync_fs(sb, wait);
flush_workqueue(sbi->rsv_conversion_wq);
/*
* Writeback quota in non-journalled quota case - journalled quota has
* no dirty dquots
*/
dquot_writeback_dquots(sb, -1);
/*
* Data writeback is possible w/o journal transaction, so barrier must
* being sent at the end of the function. But we can skip it if
* transaction_commit will do it for us.
*/
if (sbi->s_journal) {
target = jbd2_get_latest_transaction(sbi->s_journal);
if (wait && sbi->s_journal->j_flags & JBD2_BARRIER &&
!jbd2_trans_will_send_data_barrier(sbi->s_journal, target))
needs_barrier = true;
if (jbd2_journal_start_commit(sbi->s_journal, &target)) {
if (wait)
ret = jbd2_log_wait_commit(sbi->s_journal,
target);
}
} else if (wait && test_opt(sb, BARRIER))
needs_barrier = true;
if (needs_barrier) {
int err;
err = blkdev_issue_flush(sb->s_bdev, GFP_KERNEL, NULL);
if (!ret)
ret = err;
}
return ret;
}
/*
* LVM calls this function before a (read-only) snapshot is created. This
* gives us a chance to flush the journal completely and mark the fs clean.
*
* Note that only this function cannot bring a filesystem to be in a clean
* state independently. It relies on upper layer to stop all data & metadata
* modifications.
*/
static int ext4_freeze(struct super_block *sb)
{
int error = 0;
journal_t *journal;
if (sb->s_flags & MS_RDONLY)
return 0;
journal = EXT4_SB(sb)->s_journal;
if (journal) {
/* Now we set up the journal barrier. */
jbd2_journal_lock_updates(journal);
/*
* Don't clear the needs_recovery flag if we failed to
* flush the journal.
*/
error = jbd2_journal_flush(journal);
if (error < 0)
goto out;
/* Journal blocked and flushed, clear needs_recovery flag. */
ext4_clear_feature_journal_needs_recovery(sb);
}
error = ext4_commit_super(sb, 1);
out:
if (journal)
/* we rely on upper layer to stop further updates */
jbd2_journal_unlock_updates(journal);
return error;
}
/*
* Called by LVM after the snapshot is done. We need to reset the RECOVER
* flag here, even though the filesystem is not technically dirty yet.
*/
static int ext4_unfreeze(struct super_block *sb)
{
if (sb->s_flags & MS_RDONLY)
return 0;
if (EXT4_SB(sb)->s_journal) {
/* Reset the needs_recovery flag before the fs is unlocked. */
ext4_set_feature_journal_needs_recovery(sb);
}
ext4_commit_super(sb, 1);
return 0;
}
/*
* Structure to save mount options for ext4_remount's benefit
*/
struct ext4_mount_options {
unsigned long s_mount_opt;
unsigned long s_mount_opt2;
kuid_t s_resuid;
kgid_t s_resgid;
unsigned long s_commit_interval;
u32 s_min_batch_time, s_max_batch_time;
#ifdef CONFIG_QUOTA
int s_jquota_fmt;
char *s_qf_names[EXT4_MAXQUOTAS];
#endif
};
static int ext4_remount(struct super_block *sb, int *flags, char *data)
{
struct ext4_super_block *es;
struct ext4_sb_info *sbi = EXT4_SB(sb);
unsigned long old_sb_flags;
struct ext4_mount_options old_opts;
int enable_quota = 0;
ext4_group_t g;
unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO;
int err = 0;
#ifdef CONFIG_QUOTA
int i, j;
#endif
char *orig_data = kstrdup(data, GFP_KERNEL);
/* Store the original options */
old_sb_flags = sb->s_flags;
old_opts.s_mount_opt = sbi->s_mount_opt;
old_opts.s_mount_opt2 = sbi->s_mount_opt2;
old_opts.s_resuid = sbi->s_resuid;
old_opts.s_resgid = sbi->s_resgid;
old_opts.s_commit_interval = sbi->s_commit_interval;
old_opts.s_min_batch_time = sbi->s_min_batch_time;
old_opts.s_max_batch_time = sbi->s_max_batch_time;
#ifdef CONFIG_QUOTA
old_opts.s_jquota_fmt = sbi->s_jquota_fmt;
for (i = 0; i < EXT4_MAXQUOTAS; i++)
if (sbi->s_qf_names[i]) {
old_opts.s_qf_names[i] = kstrdup(sbi->s_qf_names[i],
GFP_KERNEL);
if (!old_opts.s_qf_names[i]) {
for (j = 0; j < i; j++)
kfree(old_opts.s_qf_names[j]);
kfree(orig_data);
return -ENOMEM;
}
} else
old_opts.s_qf_names[i] = NULL;
#endif
if (sbi->s_journal && sbi->s_journal->j_task->io_context)
journal_ioprio = sbi->s_journal->j_task->io_context->ioprio;
if (!parse_options(data, sb, NULL, &journal_ioprio, 1)) {
err = -EINVAL;
goto restore_opts;
}
if ((old_opts.s_mount_opt & EXT4_MOUNT_JOURNAL_CHECKSUM) ^
test_opt(sb, JOURNAL_CHECKSUM)) {
ext4_msg(sb, KERN_ERR, "changing journal_checksum "
"during remount not supported; ignoring");
sbi->s_mount_opt ^= EXT4_MOUNT_JOURNAL_CHECKSUM;
}
if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) {
if (test_opt2(sb, EXPLICIT_DELALLOC)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and delalloc");
err = -EINVAL;
goto restore_opts;
}
if (test_opt(sb, DIOREAD_NOLOCK)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dioread_nolock");
err = -EINVAL;
goto restore_opts;
}
if (test_opt(sb, DAX)) {
ext4_msg(sb, KERN_ERR, "can't mount with "
"both data=journal and dax");
err = -EINVAL;
goto restore_opts;
}
}
if ((sbi->s_mount_opt ^ old_opts.s_mount_opt) & EXT4_MOUNT_DAX) {
ext4_msg(sb, KERN_WARNING, "warning: refusing change of "
"dax flag with busy inodes while remounting");
sbi->s_mount_opt ^= EXT4_MOUNT_DAX;
}
if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED)
ext4_abort(sb, "Abort forced by user");
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
(test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0);
es = sbi->s_es;
if (sbi->s_journal) {
ext4_init_journal_params(sb, sbi->s_journal);
set_task_ioprio(sbi->s_journal->j_task, journal_ioprio);
}
if (*flags & MS_LAZYTIME)
sb->s_flags |= MS_LAZYTIME;
if ((*flags & MS_RDONLY) != (sb->s_flags & MS_RDONLY)) {
if (sbi->s_mount_flags & EXT4_MF_FS_ABORTED) {
err = -EROFS;
goto restore_opts;
}
if (*flags & MS_RDONLY) {
err = sync_filesystem(sb);
if (err < 0)
goto restore_opts;
err = dquot_suspend(sb, -1);
if (err < 0)
goto restore_opts;
/*
* First of all, the unconditional stuff we have to do
* to disable replay of the journal when we next remount
*/
sb->s_flags |= MS_RDONLY;
/*
* OK, test if we are remounting a valid rw partition
* readonly, and if so set the rdonly flag and then
* mark the partition as valid again.
*/
if (!(es->s_state & cpu_to_le16(EXT4_VALID_FS)) &&
(sbi->s_mount_state & EXT4_VALID_FS))
es->s_state = cpu_to_le16(sbi->s_mount_state);
if (sbi->s_journal)
ext4_mark_recovery_complete(sb, es);
} else {
/* Make sure we can mount this feature set readwrite */
if (ext4_has_feature_readonly(sb) ||
!ext4_feature_set_ok(sb, 0)) {
err = -EROFS;
goto restore_opts;
}
/*
* Make sure the group descriptor checksums
* are sane. If they aren't, refuse to remount r/w.
*/
for (g = 0; g < sbi->s_groups_count; g++) {
struct ext4_group_desc *gdp =
ext4_get_group_desc(sb, g, NULL);
if (!ext4_group_desc_csum_verify(sb, g, gdp)) {
ext4_msg(sb, KERN_ERR,
"ext4_remount: Checksum for group %u failed (%u!=%u)",
g, le16_to_cpu(ext4_group_desc_csum(sb, g, gdp)),
le16_to_cpu(gdp->bg_checksum));
err = -EFSBADCRC;
goto restore_opts;
}
}
/*
* If we have an unprocessed orphan list hanging
* around from a previously readonly bdev mount,
* require a full umount/remount for now.
*/
if (es->s_last_orphan) {
ext4_msg(sb, KERN_WARNING, "Couldn't "
"remount RDWR because of unprocessed "
"orphan inode list. Please "
"umount/remount instead");
err = -EINVAL;
goto restore_opts;
}
/*
* Mounting a RDONLY partition read-write, so reread
* and store the current valid flag. (It may have
* been changed by e2fsck since we originally mounted
* the partition.)
*/
if (sbi->s_journal)
ext4_clear_journal_err(sb, es);
sbi->s_mount_state = le16_to_cpu(es->s_state);
if (!ext4_setup_super(sb, es, 0))
sb->s_flags &= ~MS_RDONLY;
if (ext4_has_feature_mmp(sb))
if (ext4_multi_mount_protect(sb,
le64_to_cpu(es->s_mmp_block))) {
err = -EROFS;
goto restore_opts;
}
enable_quota = 1;
}
}
/*
* Reinitialize lazy itable initialization thread based on
* current settings
*/
if ((sb->s_flags & MS_RDONLY) || !test_opt(sb, INIT_INODE_TABLE))
ext4_unregister_li_request(sb);
else {
ext4_group_t first_not_zeroed;
first_not_zeroed = ext4_has_uninit_itable(sb);
ext4_register_li_request(sb, first_not_zeroed);
}
ext4_setup_system_zone(sb);
if (sbi->s_journal == NULL && !(old_sb_flags & MS_RDONLY))
ext4_commit_super(sb, 1);
#ifdef CONFIG_QUOTA
/* Release old quota file names */
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(old_opts.s_qf_names[i]);
if (enable_quota) {
if (sb_any_quota_suspended(sb))
dquot_resume(sb, -1);
else if (ext4_has_feature_quota(sb)) {
err = ext4_enable_quotas(sb);
if (err)
goto restore_opts;
}
}
#endif
*flags = (*flags & ~MS_LAZYTIME) | (sb->s_flags & MS_LAZYTIME);
ext4_msg(sb, KERN_INFO, "re-mounted. Opts: %s", orig_data);
kfree(orig_data);
return 0;
restore_opts:
sb->s_flags = old_sb_flags;
sbi->s_mount_opt = old_opts.s_mount_opt;
sbi->s_mount_opt2 = old_opts.s_mount_opt2;
sbi->s_resuid = old_opts.s_resuid;
sbi->s_resgid = old_opts.s_resgid;
sbi->s_commit_interval = old_opts.s_commit_interval;
sbi->s_min_batch_time = old_opts.s_min_batch_time;
sbi->s_max_batch_time = old_opts.s_max_batch_time;
#ifdef CONFIG_QUOTA
sbi->s_jquota_fmt = old_opts.s_jquota_fmt;
for (i = 0; i < EXT4_MAXQUOTAS; i++) {
kfree(sbi->s_qf_names[i]);
sbi->s_qf_names[i] = old_opts.s_qf_names[i];
}
#endif
kfree(orig_data);
return err;
}
#ifdef CONFIG_QUOTA
static int ext4_statfs_project(struct super_block *sb,
kprojid_t projid, struct kstatfs *buf)
{
struct kqid qid;
struct dquot *dquot;
u64 limit;
u64 curblock;
qid = make_kqid_projid(projid);
dquot = dqget(sb, qid);
if (IS_ERR(dquot))
return PTR_ERR(dquot);
spin_lock(&dq_data_lock);
limit = (dquot->dq_dqb.dqb_bsoftlimit ?
dquot->dq_dqb.dqb_bsoftlimit :
dquot->dq_dqb.dqb_bhardlimit) >> sb->s_blocksize_bits;
if (limit && buf->f_blocks > limit) {
curblock = dquot->dq_dqb.dqb_curspace >> sb->s_blocksize_bits;
buf->f_blocks = limit;
buf->f_bfree = buf->f_bavail =
(buf->f_blocks > curblock) ?
(buf->f_blocks - curblock) : 0;
}
limit = dquot->dq_dqb.dqb_isoftlimit ?
dquot->dq_dqb.dqb_isoftlimit :
dquot->dq_dqb.dqb_ihardlimit;
if (limit && buf->f_files > limit) {
buf->f_files = limit;
buf->f_ffree =
(buf->f_files > dquot->dq_dqb.dqb_curinodes) ?
(buf->f_files - dquot->dq_dqb.dqb_curinodes) : 0;
}
spin_unlock(&dq_data_lock);
dqput(dquot);
return 0;
}
#endif
static int ext4_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct super_block *sb = dentry->d_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
ext4_fsblk_t overhead = 0, resv_blocks;
u64 fsid;
s64 bfree;
resv_blocks = EXT4_C2B(sbi, atomic64_read(&sbi->s_resv_clusters));
if (!test_opt(sb, MINIX_DF))
overhead = sbi->s_overhead;
buf->f_type = EXT4_SUPER_MAGIC;
buf->f_bsize = sb->s_blocksize;
buf->f_blocks = ext4_blocks_count(es) - EXT4_C2B(sbi, overhead);
bfree = percpu_counter_sum_positive(&sbi->s_freeclusters_counter) -
percpu_counter_sum_positive(&sbi->s_dirtyclusters_counter);
/* prevent underflow in case that few free space is available */
buf->f_bfree = EXT4_C2B(sbi, max_t(s64, bfree, 0));
buf->f_bavail = buf->f_bfree -
(ext4_r_blocks_count(es) + resv_blocks);
if (buf->f_bfree < (ext4_r_blocks_count(es) + resv_blocks))
buf->f_bavail = 0;
buf->f_files = le32_to_cpu(es->s_inodes_count);
buf->f_ffree = percpu_counter_sum_positive(&sbi->s_freeinodes_counter);
buf->f_namelen = EXT4_NAME_LEN;
fsid = le64_to_cpup((void *)es->s_uuid) ^
le64_to_cpup((void *)es->s_uuid + sizeof(u64));
buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL;
buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL;
#ifdef CONFIG_QUOTA
if (ext4_test_inode_flag(dentry->d_inode, EXT4_INODE_PROJINHERIT) &&
sb_has_quota_limits_enabled(sb, PRJQUOTA))
ext4_statfs_project(sb, EXT4_I(dentry->d_inode)->i_projid, buf);
#endif
return 0;
}
/* Helper function for writing quotas on sync - we need to start transaction
* before quota file is locked for write. Otherwise the are possible deadlocks:
* Process 1 Process 2
* ext4_create() quota_sync()
* jbd2_journal_start() write_dquot()
* dquot_initialize() down(dqio_mutex)
* down(dqio_mutex) jbd2_journal_start()
*
*/
#ifdef CONFIG_QUOTA
static inline struct inode *dquot_to_inode(struct dquot *dquot)
{
return sb_dqopt(dquot->dq_sb)->files[dquot->dq_id.type];
}
static int ext4_write_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
struct inode *inode;
inode = dquot_to_inode(dquot);
handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
EXT4_QUOTA_TRANS_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_commit(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_acquire_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
EXT4_QUOTA_INIT_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_acquire(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_release_dquot(struct dquot *dquot)
{
int ret, err;
handle_t *handle;
handle = ext4_journal_start(dquot_to_inode(dquot), EXT4_HT_QUOTA,
EXT4_QUOTA_DEL_BLOCKS(dquot->dq_sb));
if (IS_ERR(handle)) {
/* Release dquot anyway to avoid endless cycle in dqput() */
dquot_release(dquot);
return PTR_ERR(handle);
}
ret = dquot_release(dquot);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
static int ext4_mark_dquot_dirty(struct dquot *dquot)
{
struct super_block *sb = dquot->dq_sb;
struct ext4_sb_info *sbi = EXT4_SB(sb);
/* Are we journaling quotas? */
if (ext4_has_feature_quota(sb) ||
sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) {
dquot_mark_dquot_dirty(dquot);
return ext4_write_dquot(dquot);
} else {
return dquot_mark_dquot_dirty(dquot);
}
}
static int ext4_write_info(struct super_block *sb, int type)
{
int ret, err;
handle_t *handle;
/* Data block + inode block */
handle = ext4_journal_start(d_inode(sb->s_root), EXT4_HT_QUOTA, 2);
if (IS_ERR(handle))
return PTR_ERR(handle);
ret = dquot_commit_info(sb, type);
err = ext4_journal_stop(handle);
if (!ret)
ret = err;
return ret;
}
/*
* Turn on quotas during mount time - we need to find
* the quota file and such...
*/
static int ext4_quota_on_mount(struct super_block *sb, int type)
{
return dquot_quota_on_mount(sb, EXT4_SB(sb)->s_qf_names[type],
EXT4_SB(sb)->s_jquota_fmt, type);
}
static void lockdep_set_quota_inode(struct inode *inode, int subclass)
{
struct ext4_inode_info *ei = EXT4_I(inode);
/* The first argument of lockdep_set_subclass has to be
* *exactly* the same as the argument to init_rwsem() --- in
* this case, in init_once() --- or lockdep gets unhappy
* because the name of the lock is set using the
* stringification of the argument to init_rwsem().
*/
(void) ei; /* shut up clang warning if !CONFIG_LOCKDEP */
lockdep_set_subclass(&ei->i_data_sem, subclass);
}
/*
* Standard function to be called on quota_on
*/
static int ext4_quota_on(struct super_block *sb, int type, int format_id,
struct path *path)
{
int err;
if (!test_opt(sb, QUOTA))
return -EINVAL;
/* Quotafile not on the same filesystem? */
if (path->dentry->d_sb != sb)
return -EXDEV;
/* Journaling quota? */
if (EXT4_SB(sb)->s_qf_names[type]) {
/* Quotafile not in fs root? */
if (path->dentry->d_parent != sb->s_root)
ext4_msg(sb, KERN_WARNING,
"Quota file not on filesystem root. "
"Journaled quota will not work");
}
/*
* When we journal data on quota file, we have to flush journal to see
* all updates to the file when we bypass pagecache...
*/
if (EXT4_SB(sb)->s_journal &&
ext4_should_journal_data(d_inode(path->dentry))) {
/*
* We don't need to lock updates but journal_flush() could
* otherwise be livelocked...
*/
jbd2_journal_lock_updates(EXT4_SB(sb)->s_journal);
err = jbd2_journal_flush(EXT4_SB(sb)->s_journal);
jbd2_journal_unlock_updates(EXT4_SB(sb)->s_journal);
if (err)
return err;
}
lockdep_set_quota_inode(path->dentry->d_inode, I_DATA_SEM_QUOTA);
err = dquot_quota_on(sb, type, format_id, path);
if (err)
lockdep_set_quota_inode(path->dentry->d_inode,
I_DATA_SEM_NORMAL);
return err;
}
static int ext4_quota_enable(struct super_block *sb, int type, int format_id,
unsigned int flags)
{
int err;
struct inode *qf_inode;
unsigned long qf_inums[EXT4_MAXQUOTAS] = {
le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_prj_quota_inum)
};
BUG_ON(!ext4_has_feature_quota(sb));
if (!qf_inums[type])
return -EPERM;
qf_inode = ext4_iget(sb, qf_inums[type]);
if (IS_ERR(qf_inode)) {
ext4_error(sb, "Bad quota inode # %lu", qf_inums[type]);
return PTR_ERR(qf_inode);
}
/* Don't account quota for quota files to avoid recursion */
qf_inode->i_flags |= S_NOQUOTA;
lockdep_set_quota_inode(qf_inode, I_DATA_SEM_QUOTA);
err = dquot_enable(qf_inode, type, format_id, flags);
iput(qf_inode);
if (err)
lockdep_set_quota_inode(qf_inode, I_DATA_SEM_NORMAL);
return err;
}
/* Enable usage tracking for all quota types. */
static int ext4_enable_quotas(struct super_block *sb)
{
int type, err = 0;
unsigned long qf_inums[EXT4_MAXQUOTAS] = {
le32_to_cpu(EXT4_SB(sb)->s_es->s_usr_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_grp_quota_inum),
le32_to_cpu(EXT4_SB(sb)->s_es->s_prj_quota_inum)
};
bool quota_mopt[EXT4_MAXQUOTAS] = {
test_opt(sb, USRQUOTA),
test_opt(sb, GRPQUOTA),
test_opt(sb, PRJQUOTA),
};
sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE;
for (type = 0; type < EXT4_MAXQUOTAS; type++) {
if (qf_inums[type]) {
err = ext4_quota_enable(sb, type, QFMT_VFS_V1,
DQUOT_USAGE_ENABLED |
(quota_mopt[type] ? DQUOT_LIMITS_ENABLED : 0));
if (err) {
ext4_warning(sb,
"Failed to enable quota tracking "
"(type=%d, err=%d). Please run "
"e2fsck to fix.", type, err);
return err;
}
}
}
return 0;
}
static int ext4_quota_off(struct super_block *sb, int type)
{
struct inode *inode = sb_dqopt(sb)->files[type];
handle_t *handle;
/* Force all delayed allocation blocks to be allocated.
* Caller already holds s_umount sem */
if (test_opt(sb, DELALLOC))
sync_filesystem(sb);
if (!inode)
goto out;
/* Update modification times of quota files when userspace can
* start looking at them */
handle = ext4_journal_start(inode, EXT4_HT_QUOTA, 1);
if (IS_ERR(handle))
goto out;
inode->i_mtime = inode->i_ctime = current_time(inode);
ext4_mark_inode_dirty(handle, inode);
ext4_journal_stop(handle);
out:
return dquot_quota_off(sb, type);
}
/* Read data from quotafile - avoid pagecache and such because we cannot afford
* acquiring the locks... As quota files are never truncated and quota code
* itself serializes the operations (and no one else should touch the files)
* we don't have to be afraid of races */
static ssize_t ext4_quota_read(struct super_block *sb, int type, char *data,
size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
int offset = off & (sb->s_blocksize - 1);
int tocopy;
size_t toread;
struct buffer_head *bh;
loff_t i_size = i_size_read(inode);
if (off > i_size)
return 0;
if (off+len > i_size)
len = i_size-off;
toread = len;
while (toread > 0) {
tocopy = sb->s_blocksize - offset < toread ?
sb->s_blocksize - offset : toread;
bh = ext4_bread(NULL, inode, blk, 0);
if (IS_ERR(bh))
return PTR_ERR(bh);
if (!bh) /* A hole? */
memset(data, 0, tocopy);
else
memcpy(data, bh->b_data+offset, tocopy);
brelse(bh);
offset = 0;
toread -= tocopy;
data += tocopy;
blk++;
}
return len;
}
/* Write to quotafile (we know the transaction is already started and has
* enough credits) */
static ssize_t ext4_quota_write(struct super_block *sb, int type,
const char *data, size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
ext4_lblk_t blk = off >> EXT4_BLOCK_SIZE_BITS(sb);
int err, offset = off & (sb->s_blocksize - 1);
int retries = 0;
struct buffer_head *bh;
handle_t *handle = journal_current_handle();
if (EXT4_SB(sb)->s_journal && !handle) {
ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
" cancelled because transaction is not started",
(unsigned long long)off, (unsigned long long)len);
return -EIO;
}
/*
* Since we account only one data block in transaction credits,
* then it is impossible to cross a block boundary.
*/
if (sb->s_blocksize - offset < len) {
ext4_msg(sb, KERN_WARNING, "Quota write (off=%llu, len=%llu)"
" cancelled because not block aligned",
(unsigned long long)off, (unsigned long long)len);
return -EIO;
}
do {
bh = ext4_bread(handle, inode, blk,
EXT4_GET_BLOCKS_CREATE |
EXT4_GET_BLOCKS_METADATA_NOFAIL);
} while (IS_ERR(bh) && (PTR_ERR(bh) == -ENOSPC) &&
ext4_should_retry_alloc(inode->i_sb, &retries));
if (IS_ERR(bh))
return PTR_ERR(bh);
if (!bh)
goto out;
BUFFER_TRACE(bh, "get write access");
err = ext4_journal_get_write_access(handle, bh);
if (err) {
brelse(bh);
return err;
}
lock_buffer(bh);
memcpy(bh->b_data+offset, data, len);
flush_dcache_page(bh->b_page);
unlock_buffer(bh);
err = ext4_handle_dirty_metadata(handle, NULL, bh);
brelse(bh);
out:
if (inode->i_size < off + len) {
i_size_write(inode, off + len);
EXT4_I(inode)->i_disksize = inode->i_size;
ext4_mark_inode_dirty(handle, inode);
}
return len;
}
static int ext4_get_next_id(struct super_block *sb, struct kqid *qid)
{
const struct quota_format_ops *ops;
if (!sb_has_quota_loaded(sb, qid->type))
return -ESRCH;
ops = sb_dqopt(sb)->ops[qid->type];
if (!ops || !ops->get_next_id)
return -ENOSYS;
return dquot_get_next_id(sb, qid);
}
#endif
static struct dentry *ext4_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data)
{
return mount_bdev(fs_type, flags, dev_name, data, ext4_fill_super);
}
#if !defined(CONFIG_EXT2_FS) && !defined(CONFIG_EXT2_FS_MODULE) && defined(CONFIG_EXT4_USE_FOR_EXT2)
static inline void register_as_ext2(void)
{
int err = register_filesystem(&ext2_fs_type);
if (err)
printk(KERN_WARNING
"EXT4-fs: Unable to register as ext2 (%d)\n", err);
}
static inline void unregister_as_ext2(void)
{
unregister_filesystem(&ext2_fs_type);
}
static inline int ext2_feature_set_ok(struct super_block *sb)
{
if (ext4_has_unknown_ext2_incompat_features(sb))
return 0;
if (sb->s_flags & MS_RDONLY)
return 1;
if (ext4_has_unknown_ext2_ro_compat_features(sb))
return 0;
return 1;
}
#else
static inline void register_as_ext2(void) { }
static inline void unregister_as_ext2(void) { }
static inline int ext2_feature_set_ok(struct super_block *sb) { return 0; }
#endif
static inline void register_as_ext3(void)
{
int err = register_filesystem(&ext3_fs_type);
if (err)
printk(KERN_WARNING
"EXT4-fs: Unable to register as ext3 (%d)\n", err);
}
static inline void unregister_as_ext3(void)
{
unregister_filesystem(&ext3_fs_type);
}
static inline int ext3_feature_set_ok(struct super_block *sb)
{
if (ext4_has_unknown_ext3_incompat_features(sb))
return 0;
if (!ext4_has_feature_journal(sb))
return 0;
if (sb->s_flags & MS_RDONLY)
return 1;
if (ext4_has_unknown_ext3_ro_compat_features(sb))
return 0;
return 1;
}
static struct file_system_type ext4_fs_type = {
.owner = THIS_MODULE,
.name = "ext4",
.mount = ext4_mount,
.kill_sb = kill_block_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("ext4");
/* Shared across all ext4 file systems */
wait_queue_head_t ext4__ioend_wq[EXT4_WQ_HASH_SZ];
static int __init ext4_init_fs(void)
{
int i, err;
ratelimit_state_init(&ext4_mount_msg_ratelimit, 30 * HZ, 64);
ext4_li_info = NULL;
mutex_init(&ext4_li_mtx);
/* Build-time check for flags consistency */
ext4_check_flag_values();
for (i = 0; i < EXT4_WQ_HASH_SZ; i++)
init_waitqueue_head(&ext4__ioend_wq[i]);
err = ext4_init_es();
if (err)
return err;
err = ext4_init_pageio();
if (err)
goto out5;
err = ext4_init_system_zone();
if (err)
goto out4;
err = ext4_init_sysfs();
if (err)
goto out3;
err = ext4_init_mballoc();
if (err)
goto out2;
err = init_inodecache();
if (err)
goto out1;
register_as_ext3();
register_as_ext2();
err = register_filesystem(&ext4_fs_type);
if (err)
goto out;
return 0;
out:
unregister_as_ext2();
unregister_as_ext3();
destroy_inodecache();
out1:
ext4_exit_mballoc();
out2:
ext4_exit_sysfs();
out3:
ext4_exit_system_zone();
out4:
ext4_exit_pageio();
out5:
ext4_exit_es();
return err;
}
static void __exit ext4_exit_fs(void)
{
ext4_destroy_lazyinit_thread();
unregister_as_ext2();
unregister_as_ext3();
unregister_filesystem(&ext4_fs_type);
destroy_inodecache();
ext4_exit_mballoc();
ext4_exit_sysfs();
ext4_exit_system_zone();
ext4_exit_pageio();
ext4_exit_es();
}
MODULE_AUTHOR("Remy Card, Stephen Tweedie, Andrew Morton, Andreas Dilger, Theodore Ts'o and others");
MODULE_DESCRIPTION("Fourth Extended Filesystem");
MODULE_LICENSE("GPL");
module_init(ext4_init_fs)
module_exit(ext4_exit_fs)
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4843_0 |
crossvul-cpp_data_good_5241_5 | /*
We're testing that reading corrupt TIFF files doesn't cause any memory issues,
and that the operation gracefully fails (i.e. gdImageCreateFromTiffPtr() returns
NULL).
*/
#include "gd.h"
#include "gdtest.h"
static void check_file(char *basename);
static size_t read_test_file(char **buffer, char *basename);
int main()
{
check_file("tiff_invalid_read_1.tiff");
check_file("tiff_invalid_read_2.tiff");
check_file("tiff_invalid_read_3.tiff");
return gdNumFailures();
}
static void check_file(char *basename)
{
gdImagePtr im;
char *buffer;
size_t size;
size = read_test_file(&buffer, basename);
im = gdImageCreateFromTiffPtr(size, (void *) buffer);
gdTestAssert(im == NULL);
free(buffer);
}
static size_t read_test_file(char **buffer, char *basename)
{
char *filename;
FILE *fp;
size_t exp_size, act_size;
filename = gdTestFilePath2("tiff", basename);
fp = fopen(filename, "rb");
gdTestAssert(fp != NULL);
fseek(fp, 0, SEEK_END);
exp_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
*buffer = malloc(exp_size);
gdTestAssert(*buffer != NULL);
act_size = fread(*buffer, sizeof(**buffer), exp_size, fp);
gdTestAssert(act_size == exp_size);
fclose(fp);
free(filename);
return act_size;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5241_5 |
crossvul-cpp_data_bad_210_2 | /*
* GPAC - Multimedia Framework C SDK
*
* Authors: Jean Le Feuvre
* Copyright (c) Telecom ParisTech 2000-2012
* All rights reserved
*
* This file is part of GPAC / ISO Media File Format sub-project
*
* GPAC is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* GPAC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <gpac/internal/isomedia_dev.h>
#include <gpac/utf.h>
#include <gpac/network.h>
#include <gpac/color.h>
#include <gpac/avparse.h>
#include <time.h>
#ifndef GPAC_DISABLE_ISOM_DUMP
static void dump_data(FILE *trace, char *data, u32 dataLength)
{
u32 i;
fprintf(trace, "data:application/octet-string,");
for (i=0; i<dataLength; i++) {
fprintf(trace, "%02X", (unsigned char) data[i]);
}
}
static void dump_data_hex(FILE *trace, char *data, u32 dataLength)
{
u32 i;
fprintf(trace, "0x");
for (i=0; i<dataLength; i++) {
fprintf(trace, "%02X", (unsigned char) data[i]);
}
}
static void dump_data_attribute(FILE *trace, char *name, char *data, u32 data_size)
{
u32 i;
if (!data || !data_size) {
fprintf(trace, "%s=\"\"", name);
return;
}
fprintf(trace, "%s=\"0x", name);
for (i=0; i<data_size; i++) fprintf(trace, "%02X", (unsigned char) data[i]);
fprintf(trace, "\" ");
}
static void dump_data_string(FILE *trace, char *data, u32 dataLength)
{
u32 i;
for (i=0; i<dataLength; i++) {
switch ((unsigned char) data[i]) {
case '\'':
fprintf(trace, "'");
break;
case '\"':
fprintf(trace, """);
break;
case '&':
fprintf(trace, "&");
break;
case '>':
fprintf(trace, ">");
break;
case '<':
fprintf(trace, "<");
break;
default:
fprintf(trace, "%c", (u8) data[i]);
break;
}
}
}
GF_Err gf_isom_box_dump(void *ptr, FILE * trace)
{
return gf_isom_box_dump_ex(ptr, trace, 0);
}
GF_Err gf_isom_box_array_dump(GF_List *list, FILE * trace)
{
u32 i;
GF_Box *a;
if (!list) return GF_OK;
i=0;
while ((a = (GF_Box *)gf_list_enum(list, &i))) {
gf_isom_box_dump(a, trace);
}
return GF_OK;
}
extern Bool use_dump_mode;
GF_EXPORT
GF_Err gf_isom_dump(GF_ISOFile *mov, FILE * trace)
{
u32 i;
GF_Box *box;
if (!mov || !trace) return GF_BAD_PARAM;
use_dump_mode = mov->dump_mode_alloc;
fprintf(trace, "<!--MP4Box dump trace-->\n");
fprintf(trace, "<IsoMediaFile xmlns=\"urn:mpeg:isobmff:schema:file:2016\" Name=\"%s\">\n", mov->fileName);
i=0;
while ((box = (GF_Box *)gf_list_enum(mov->TopBoxes, &i))) {
if (box->type==GF_ISOM_BOX_TYPE_UNKNOWN) {
fprintf(trace, "<!--WARNING: Unknown Top-level Box Found -->\n");
} else if (box->type==GF_ISOM_BOX_TYPE_UUID) {
} else if (!gf_isom_box_is_file_level(box)) {
fprintf(trace, "<!--ERROR: Invalid Top-level Box Found (\"%s\")-->\n", gf_4cc_to_str(box->type));
}
gf_isom_box_dump(box, trace);
}
fprintf(trace, "</IsoMediaFile>\n");
return GF_OK;
}
GF_Err reftype_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_TrackReferenceTypeBox *p = (GF_TrackReferenceTypeBox *)a;
if (!p->reference_type) return GF_OK;
p->type = p->reference_type;
gf_isom_box_dump_start(a, "TrackReferenceTypeBox", trace);
fprintf(trace, ">\n");
for (i=0; i<p->trackIDCount; i++) {
fprintf(trace, "<TrackReferenceEntry TrackID=\"%d\"/>\n", p->trackIDs[i]);
}
if (!p->size)
fprintf(trace, "<TrackReferenceEntry TrackID=\"\"/>\n");
gf_isom_box_dump_done("TrackReferenceTypeBox", a, trace);
p->type = GF_ISOM_BOX_TYPE_REFT;
return GF_OK;
}
GF_Err ireftype_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_ItemReferenceTypeBox *p = (GF_ItemReferenceTypeBox *)a;
if (!p->reference_type) return GF_OK;
p->type = p->reference_type;
gf_isom_box_dump_start(a, "ItemReferenceBox", trace);
fprintf(trace, "from_item_id=\"%d\">\n", p->from_item_id);
for (i = 0; i < p->reference_count; i++) {
fprintf(trace, "<ItemReferenceBoxEntry ItemID=\"%d\"/>\n", p->to_item_IDs[i]);
}
if (!p->size)
fprintf(trace, "<ItemReferenceBoxEntry ItemID=\"\"/>\n");
gf_isom_box_dump_done("ItemReferenceBox", a, trace);
p->type = GF_ISOM_BOX_TYPE_REFI;
return GF_OK;
}
GF_Err free_dump(GF_Box *a, FILE * trace)
{
GF_FreeSpaceBox *p = (GF_FreeSpaceBox *)a;
gf_isom_box_dump_start(a, (a->type==GF_ISOM_BOX_TYPE_FREE) ? "FreeSpaceBox" : "SkipBox", trace);
fprintf(trace, "dataSize=\"%d\">\n", p->dataSize);
gf_isom_box_dump_done( (a->type==GF_ISOM_BOX_TYPE_FREE) ? "FreeSpaceBox" : "SkipBox", a, trace);
return GF_OK;
}
GF_Err mdat_dump(GF_Box *a, FILE * trace)
{
GF_MediaDataBox *p;
const char *name = (a->type==GF_ISOM_BOX_TYPE_IDAT ? "ItemDataBox" : "MediaDataBox");
p = (GF_MediaDataBox *)a;
gf_isom_box_dump_start(a, name, trace);
fprintf(trace, "dataSize=\""LLD"\">\n", LLD_CAST p->dataSize);
gf_isom_box_dump_done(name, a, trace);
return GF_OK;
}
GF_Err moov_dump(GF_Box *a, FILE * trace)
{
GF_MovieBox *p;
p = (GF_MovieBox *)a;
gf_isom_box_dump_start(a, "MovieBox", trace);
fprintf(trace, ">\n");
if (p->iods) gf_isom_box_dump(p->iods, trace);
if (p->meta) gf_isom_box_dump(p->meta, trace);
//dump only if size
if (p->size)
gf_isom_box_dump_ex(p->mvhd, trace,GF_ISOM_BOX_TYPE_MVHD);
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
if (p->mvex) gf_isom_box_dump(p->mvex, trace);
#endif
gf_isom_box_array_dump(p->trackList, trace);
if (p->udta) gf_isom_box_dump(p->udta, trace);
gf_isom_box_dump_done("MovieBox", a, trace);
return GF_OK;
}
GF_Err mvhd_dump(GF_Box *a, FILE * trace)
{
GF_MovieHeaderBox *p;
p = (GF_MovieHeaderBox *) a;
gf_isom_box_dump_start(a, "MovieHeaderBox", trace);
fprintf(trace, "CreationTime=\""LLD"\" ", LLD_CAST p->creationTime);
fprintf(trace, "ModificationTime=\""LLD"\" ", LLD_CAST p->modificationTime);
fprintf(trace, "TimeScale=\"%d\" ", p->timeScale);
fprintf(trace, "Duration=\""LLD"\" ", LLD_CAST p->duration);
fprintf(trace, "NextTrackID=\"%d\">\n", p->nextTrackID);
gf_isom_box_dump_done("MovieHeaderBox", a, trace);
return GF_OK;
}
GF_Err mdhd_dump(GF_Box *a, FILE * trace)
{
GF_MediaHeaderBox *p;
p = (GF_MediaHeaderBox *)a;
gf_isom_box_dump_start(a, "MediaHeaderBox", trace);
fprintf(trace, "CreationTime=\""LLD"\" ", LLD_CAST p->creationTime);
fprintf(trace, "ModificationTime=\""LLD"\" ", LLD_CAST p->modificationTime);
fprintf(trace, "TimeScale=\"%d\" ", p->timeScale);
fprintf(trace, "Duration=\""LLD"\" ", LLD_CAST p->duration);
fprintf(trace, "LanguageCode=\"%c%c%c\">\n", p->packedLanguage[0], p->packedLanguage[1], p->packedLanguage[2]);
gf_isom_box_dump_done("MediaHeaderBox", a, trace);
return GF_OK;
}
GF_Err vmhd_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "VideoMediaHeaderBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("VideoMediaHeaderBox", a, trace);
return GF_OK;
}
GF_Err smhd_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "SoundMediaHeaderBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("SoundMediaHeaderBox", a, trace);
return GF_OK;
}
GF_Err hmhd_dump(GF_Box *a, FILE * trace)
{
GF_HintMediaHeaderBox *p;
p = (GF_HintMediaHeaderBox *)a;
gf_isom_box_dump_start(a, "HintMediaHeaderBox", trace);
fprintf(trace, "MaximumPDUSize=\"%d\" ", p->maxPDUSize);
fprintf(trace, "AveragePDUSize=\"%d\" ", p->avgPDUSize);
fprintf(trace, "MaxBitRate=\"%d\" ", p->maxBitrate);
fprintf(trace, "AverageBitRate=\"%d\">\n", p->avgBitrate);
gf_isom_box_dump_done("HintMediaHeaderBox", a, trace);
return GF_OK;
}
GF_Err nmhd_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "MPEGMediaHeaderBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("MPEGMediaHeaderBox", a, trace);
return GF_OK;
}
GF_Err stbl_dump(GF_Box *a, FILE * trace)
{
GF_SampleTableBox *p;
p = (GF_SampleTableBox *)a;
gf_isom_box_dump_start(a, "SampleTableBox", trace);
fprintf(trace, ">\n");
if (p->size)
gf_isom_box_dump_ex(p->SampleDescription, trace, GF_ISOM_BOX_TYPE_STSD);
if (p->size)
gf_isom_box_dump_ex(p->TimeToSample, trace, GF_ISOM_BOX_TYPE_STTS);
if (p->CompositionOffset) gf_isom_box_dump(p->CompositionOffset, trace);
if (p->CompositionToDecode) gf_isom_box_dump(p->CompositionToDecode, trace);
if (p->SyncSample) gf_isom_box_dump(p->SyncSample, trace);
if (p->ShadowSync) gf_isom_box_dump(p->ShadowSync, trace);
if (p->size)
gf_isom_box_dump_ex(p->SampleToChunk, trace, GF_ISOM_BOX_TYPE_STSC);
if (p->size)
gf_isom_box_dump_ex(p->SampleSize, trace, GF_ISOM_BOX_TYPE_STSZ);
if (p->size)
gf_isom_box_dump_ex(p->ChunkOffset, trace, GF_ISOM_BOX_TYPE_STCO);
if (p->DegradationPriority) gf_isom_box_dump(p->DegradationPriority, trace);
if (p->SampleDep) gf_isom_box_dump(p->SampleDep, trace);
if (p->PaddingBits) gf_isom_box_dump(p->PaddingBits, trace);
if (p->Fragments) gf_isom_box_dump(p->Fragments, trace);
if (p->sub_samples) gf_isom_box_array_dump(p->sub_samples, trace);
if (p->sampleGroupsDescription) gf_isom_box_array_dump(p->sampleGroupsDescription, trace);
if (p->sampleGroups) gf_isom_box_array_dump(p->sampleGroups, trace);
if (p->sai_sizes) {
u32 i;
for (i = 0; i < gf_list_count(p->sai_sizes); i++) {
GF_SampleAuxiliaryInfoSizeBox *saiz = (GF_SampleAuxiliaryInfoSizeBox *)gf_list_get(p->sai_sizes, i);
gf_isom_box_dump(saiz, trace);
}
}
if (p->sai_offsets) {
u32 i;
for (i = 0; i < gf_list_count(p->sai_offsets); i++) {
GF_SampleAuxiliaryInfoOffsetBox *saio = (GF_SampleAuxiliaryInfoOffsetBox *)gf_list_get(p->sai_offsets, i);
gf_isom_box_dump(saio, trace);
}
}
gf_isom_box_dump_done("SampleTableBox", a, trace);
return GF_OK;
}
GF_Err dinf_dump(GF_Box *a, FILE * trace)
{
GF_DataInformationBox *p;
p = (GF_DataInformationBox *)a;
gf_isom_box_dump_start(a, "DataInformationBox", trace);
fprintf(trace, ">\n");
if (p->size)
gf_isom_box_dump_ex(p->dref, trace, GF_ISOM_BOX_TYPE_DREF);
gf_isom_box_dump_done("DataInformationBox", a, trace);
return GF_OK;
}
GF_Err url_dump(GF_Box *a, FILE * trace)
{
GF_DataEntryURLBox *p;
p = (GF_DataEntryURLBox *)a;
gf_isom_box_dump_start(a, "URLDataEntryBox", trace);
if (p->location) {
fprintf(trace, " URL=\"%s\">\n", p->location);
} else {
fprintf(trace, ">\n");
if (p->size) {
if (! (p->flags & 1) ) {
fprintf(trace, "<!--ERROR: No location indicated-->\n");
} else {
fprintf(trace, "<!--Data is contained in the movie file-->\n");
}
}
}
gf_isom_box_dump_done("URLDataEntryBox", a, trace);
return GF_OK;
}
GF_Err urn_dump(GF_Box *a, FILE * trace)
{
GF_DataEntryURNBox *p;
p = (GF_DataEntryURNBox *)a;
gf_isom_box_dump_start(a, "URNDataEntryBox", trace);
if (p->nameURN) fprintf(trace, " URN=\"%s\"", p->nameURN);
if (p->location) fprintf(trace, " URL=\"%s\"", p->location);
fprintf(trace, ">\n");
gf_isom_box_dump_done("URNDataEntryBox", a, trace);
return GF_OK;
}
GF_Err cprt_dump(GF_Box *a, FILE * trace)
{
GF_CopyrightBox *p;
p = (GF_CopyrightBox *)a;
gf_isom_box_dump_start(a, "CopyrightBox", trace);
fprintf(trace, "LanguageCode=\"%s\" CopyrightNotice=\"%s\">\n", p->packedLanguageCode, p->notice);
gf_isom_box_dump_done("CopyrightBox", a, trace);
return GF_OK;
}
GF_Err kind_dump(GF_Box *a, FILE * trace)
{
GF_KindBox *p;
p = (GF_KindBox *)a;
gf_isom_box_dump_start(a, "KindBox", trace);
fprintf(trace, "schemeURI=\"%s\" value=\"%s\">\n", p->schemeURI, (p->value ? p->value : ""));
gf_isom_box_dump_done("KindBox", a, trace);
return GF_OK;
}
static char *format_duration(u64 dur, u32 timescale, char *szDur)
{
u32 h, m, s, ms;
dur = (u32) (( ((Double) (s64) dur)/timescale)*1000);
h = (u32) (dur / 3600000);
dur -= h*3600000;
m = (u32) (dur / 60000);
dur -= m*60000;
s = (u32) (dur/1000);
dur -= s*1000;
ms = (u32) (dur);
sprintf(szDur, "%02d:%02d:%02d.%03d", h, m, s, ms);
return szDur;
}
static void dump_escape_string(FILE * trace, char *name)
{
u32 i, len = (u32) strlen(name);
for (i=0; i<len; i++) {
if (name[i]=='"') fprintf(trace, """);
else fputc(name[i], trace);
}
}
GF_Err chpl_dump(GF_Box *a, FILE * trace)
{
u32 i, count;
char szDur[20];
GF_ChapterListBox *p = (GF_ChapterListBox *)a;
gf_isom_box_dump_start(a, "ChapterListBox", trace);
fprintf(trace, ">\n");
if (p->size) {
count = gf_list_count(p->list);
for (i=0; i<count; i++) {
GF_ChapterEntry *ce = (GF_ChapterEntry *)gf_list_get(p->list, i);
fprintf(trace, "<Chapter name=\"");
dump_escape_string(trace, ce->name);
fprintf(trace, "\" startTime=\"%s\" />\n", format_duration(ce->start_time, 1000*10000, szDur));
}
} else {
fprintf(trace, "<Chapter name=\"\" startTime=\"\"/>\n");
}
gf_isom_box_dump_done("ChapterListBox", a, trace);
return GF_OK;
}
GF_Err pdin_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_ProgressiveDownloadBox *p = (GF_ProgressiveDownloadBox *)a;
gf_isom_box_dump_start(a, "ProgressiveDownloadBox", trace);
fprintf(trace, ">\n");
if (p->size) {
for (i=0; i<p->count; i++) {
fprintf(trace, "<DownloadInfo rate=\"%d\" estimatedTime=\"%d\" />\n", p->rates[i], p->times[i]);
}
} else {
fprintf(trace, "<DownloadInfo rate=\"\" estimatedTime=\"\" />\n");
}
gf_isom_box_dump_done("ProgressiveDownloadBox", a, trace);
return GF_OK;
}
GF_Err hdlr_dump(GF_Box *a, FILE * trace)
{
GF_HandlerBox *p = (GF_HandlerBox *)a;
gf_isom_box_dump_start(a, "HandlerBox", trace);
if (p->nameUTF8 && (u32) p->nameUTF8[0] == strlen(p->nameUTF8+1)) {
fprintf(trace, "hdlrType=\"%s\" Name=\"%s\" ", gf_4cc_to_str(p->handlerType), p->nameUTF8+1);
} else {
fprintf(trace, "hdlrType=\"%s\" Name=\"%s\" ", gf_4cc_to_str(p->handlerType), p->nameUTF8);
}
fprintf(trace, "reserved1=\"%d\" reserved2=\"", p->reserved1);
dump_data(trace, (char *) p->reserved2, 12);
fprintf(trace, "\"");
fprintf(trace, ">\n");
gf_isom_box_dump_done("HandlerBox", a, trace);
return GF_OK;
}
GF_Err iods_dump(GF_Box *a, FILE * trace)
{
GF_ObjectDescriptorBox *p;
p = (GF_ObjectDescriptorBox *)a;
gf_isom_box_dump_start(a, "ObjectDescriptorBox", trace);
fprintf(trace, ">\n");
if (p->descriptor) {
#ifndef GPAC_DISABLE_OD_DUMP
gf_odf_dump_desc(p->descriptor, trace, 1, GF_TRUE);
#else
fprintf(trace, "<!-- Object Descriptor Dumping disabled in this build of GPAC -->\n");
#endif
} else if (p->size) {
fprintf(trace, "<!--WARNING: Object Descriptor not present-->\n");
}
gf_isom_box_dump_done("ObjectDescriptorBox", a, trace);
return GF_OK;
}
GF_Err trak_dump(GF_Box *a, FILE * trace)
{
GF_TrackBox *p;
p = (GF_TrackBox *)a;
gf_isom_box_dump_start(a, "TrackBox", trace);
fprintf(trace, ">\n");
if (p->Header) {
gf_isom_box_dump(p->Header, trace);
} else if (p->size) {
fprintf(trace, "<!--INVALID FILE: Missing Track Header-->\n");
}
if (p->References) gf_isom_box_dump(p->References, trace);
if (p->meta) gf_isom_box_dump(p->meta, trace);
if (p->editBox) gf_isom_box_dump(p->editBox, trace);
if (p->Media) gf_isom_box_dump(p->Media, trace);
if (p->groups) gf_isom_box_dump(p->groups, trace);
if (p->udta) gf_isom_box_dump(p->udta, trace);
gf_isom_box_dump_done("TrackBox", a, trace);
return GF_OK;
}
GF_Err mp4s_dump(GF_Box *a, FILE * trace)
{
GF_MPEGSampleEntryBox *p;
p = (GF_MPEGSampleEntryBox *)a;
gf_isom_box_dump_start(a, "MPEGSystemsSampleDescriptionBox", trace);
fprintf(trace, "DataReferenceIndex=\"%d\">\n", p->dataReferenceIndex);
if (p->esd) {
gf_isom_box_dump(p->esd, trace);
} else if (p->size) {
fprintf(trace, "<!--INVALID MP4 FILE: ESDBox not present in MPEG Sample Description or corrupted-->\n");
}
if (a->type == GF_ISOM_BOX_TYPE_ENCS) {
gf_isom_box_array_dump(p->protections, trace);
}
gf_isom_box_dump_done("MPEGSystemsSampleDescriptionBox", a, trace);
return GF_OK;
}
GF_Err video_sample_entry_dump(GF_Box *a, FILE * trace)
{
GF_MPEGVisualSampleEntryBox *p = (GF_MPEGVisualSampleEntryBox *)a;
const char *name;
switch (p->type) {
case GF_ISOM_SUBTYPE_AVC_H264:
case GF_ISOM_SUBTYPE_AVC2_H264:
case GF_ISOM_SUBTYPE_AVC3_H264:
case GF_ISOM_SUBTYPE_AVC4_H264:
name = "AVCSampleEntryBox";
break;
case GF_ISOM_SUBTYPE_MVC_H264:
name = "MVCSampleEntryBox";
break;
case GF_ISOM_SUBTYPE_SVC_H264:
name = "SVCSampleEntryBox";
break;
case GF_ISOM_SUBTYPE_HVC1:
case GF_ISOM_SUBTYPE_HEV1:
case GF_ISOM_SUBTYPE_HVC2:
case GF_ISOM_SUBTYPE_HEV2:
name = "HEVCSampleEntryBox";
break;
case GF_ISOM_SUBTYPE_LHV1:
case GF_ISOM_SUBTYPE_LHE1:
name = "LHEVCSampleEntryBox";
break;
case GF_ISOM_SUBTYPE_3GP_H263:
name = "H263SampleDescriptionBox";
break;
default:
name = "MPEGVisualSampleDescriptionBox";
}
gf_isom_box_dump_start(a, name, trace);
fprintf(trace, " DataReferenceIndex=\"%d\" Width=\"%d\" Height=\"%d\"", p->dataReferenceIndex, p->Width, p->Height);
//dump reserved info
fprintf(trace, " XDPI=\"%d\" YDPI=\"%d\" BitDepth=\"%d\"", p->horiz_res, p->vert_res, p->bit_depth);
if (strlen((const char*)p->compressor_name) )
fprintf(trace, " CompressorName=\"%s\"\n", p->compressor_name+1);
fprintf(trace, ">\n");
if (p->esd) {
gf_isom_box_dump(p->esd, trace);
} else {
if (p->hevc_config) gf_isom_box_dump(p->hevc_config, trace);
if (p->avc_config) gf_isom_box_dump(p->avc_config, trace);
if (p->ipod_ext) gf_isom_box_dump(p->ipod_ext, trace);
if (p->descr) gf_isom_box_dump(p->descr, trace);
if (p->svc_config) gf_isom_box_dump(p->svc_config, trace);
if (p->mvc_config) gf_isom_box_dump(p->mvc_config, trace);
if (p->lhvc_config) gf_isom_box_dump(p->lhvc_config, trace);
if (p->cfg_3gpp) gf_isom_box_dump(p->cfg_3gpp, trace);
}
if (a->type == GF_ISOM_BOX_TYPE_ENCV) {
gf_isom_box_array_dump(p->protections, trace);
}
if (p->pasp) gf_isom_box_dump(p->pasp, trace);
if (p->rvcc) gf_isom_box_dump(p->rvcc, trace);
if (p->rinf) gf_isom_box_dump(p->rinf, trace);
gf_isom_box_dump_done(name, a, trace);
return GF_OK;
}
void base_audio_entry_dump(GF_AudioSampleEntryBox *p, FILE * trace)
{
fprintf(trace, " DataReferenceIndex=\"%d\" SampleRate=\"%d\"", p->dataReferenceIndex, p->samplerate_hi);
fprintf(trace, " Channels=\"%d\" BitsPerSample=\"%d\"", p->channel_count, p->bitspersample);
}
GF_Err audio_sample_entry_dump(GF_Box *a, FILE * trace)
{
char *szName;
Bool is_3gpp = GF_FALSE;
GF_MPEGAudioSampleEntryBox *p = (GF_MPEGAudioSampleEntryBox *)a;
switch (p->type) {
case GF_ISOM_SUBTYPE_3GP_AMR:
szName = "AMRSampleDescriptionBox";
is_3gpp = GF_TRUE;
break;
case GF_ISOM_SUBTYPE_3GP_AMR_WB:
szName = "AMR_WB_SampleDescriptionBox";
is_3gpp = GF_TRUE;
break;
case GF_ISOM_SUBTYPE_3GP_EVRC:
szName = "EVRCSampleDescriptionBox";
is_3gpp = GF_TRUE;
break;
case GF_ISOM_SUBTYPE_3GP_QCELP:
szName = "QCELPSampleDescriptionBox";
is_3gpp = GF_TRUE;
break;
case GF_ISOM_SUBTYPE_3GP_SMV:
szName = "SMVSampleDescriptionBox";
is_3gpp = GF_TRUE;
break;
case GF_ISOM_BOX_TYPE_MP4A:
szName = "MPEGAudioSampleDescriptionBox";
break;
case GF_ISOM_BOX_TYPE_AC3:
szName = "AC3SampleEntryBox";
break;
case GF_ISOM_BOX_TYPE_EC3:
szName = "EC3SampleEntryBox";
break;
default:
szName = "AudioSampleDescriptionBox";
break;
}
gf_isom_box_dump_start(a, szName, trace);
base_audio_entry_dump((GF_AudioSampleEntryBox *)p, trace);
fprintf(trace, ">\n");
if (p->esd) {
gf_isom_box_dump(p->esd, trace);
} else if (p->cfg_3gpp) {
gf_isom_box_dump(p->cfg_3gpp, trace);
} else if (p->cfg_ac3) {
if (p->size)
gf_isom_box_dump(p->cfg_ac3, trace);
} else if (p->size) {
if (is_3gpp) {
fprintf(trace, "<!-- INVALID 3GPP FILE: Config not present in Sample Description-->\n");
} else {
fprintf(trace, "<!--INVALID MP4 FILE: ESDBox not present in MPEG Sample Description or corrupted-->\n");
}
}
if (a->type == GF_ISOM_BOX_TYPE_ENCA) {
gf_isom_box_array_dump(p->protections, trace);
}
gf_isom_box_dump_done(szName, a, trace);
return GF_OK;
}
GF_Err gnrm_dump(GF_Box *a, FILE * trace)
{
GF_GenericSampleEntryBox *p = (GF_GenericSampleEntryBox *)a;
if (p->EntryType)
a->type = p->EntryType;
gf_isom_box_dump_start(a, "SampleDescriptionBox", trace);
fprintf(trace, "DataReferenceIndex=\"%d\" ExtensionDataSize=\"%d\">\n", p->dataReferenceIndex, p->data_size);
a->type = GF_ISOM_BOX_TYPE_GNRM;
gf_isom_box_dump_done("SampleDescriptionBox", a, trace);
return GF_OK;
}
GF_Err gnrv_dump(GF_Box *a, FILE * trace)
{
GF_GenericVisualSampleEntryBox *p = (GF_GenericVisualSampleEntryBox *)a;
if (p->EntryType)
a->type = p->EntryType;
gf_isom_box_dump_start(a, "VisualSampleDescriptionBox", trace);
fprintf(trace, "DataReferenceIndex=\"%d\" Version=\"%d\" Revision=\"%d\" Vendor=\"%d\" TemporalQuality=\"%d\" SpacialQuality=\"%d\" Width=\"%d\" Height=\"%d\" HorizontalResolution=\"%d\" VerticalResolution=\"%d\" CompressorName=\"%s\" BitDepth=\"%d\">\n",
p->dataReferenceIndex, p->version, p->revision, p->vendor, p->temporal_quality, p->spatial_quality, p->Width, p->Height, p->horiz_res, p->vert_res, p->compressor_name+1, p->bit_depth);
a->type = GF_ISOM_BOX_TYPE_GNRV;
gf_isom_box_dump_done("VisualSampleDescriptionBox", a, trace);
return GF_OK;
}
GF_Err gnra_dump(GF_Box *a, FILE * trace)
{
GF_GenericAudioSampleEntryBox *p = (GF_GenericAudioSampleEntryBox *)a;
if (p->EntryType)
a->type = p->EntryType;
gf_isom_box_dump_start(a, "AudioSampleDescriptionBox", trace);
fprintf(trace, "DataReferenceIndex=\"%d\" Version=\"%d\" Revision=\"%d\" Vendor=\"%d\" ChannelCount=\"%d\" BitsPerSample=\"%d\" Samplerate=\"%d\">\n",
p->dataReferenceIndex, p->version, p->revision, p->vendor, p->channel_count, p->bitspersample, p->samplerate_hi);
a->type = GF_ISOM_BOX_TYPE_GNRA;
gf_isom_box_dump_done("AudioSampleDescriptionBox", a, trace);
return GF_OK;
}
GF_Err edts_dump(GF_Box *a, FILE * trace)
{
GF_EditBox *p;
p = (GF_EditBox *)a;
gf_isom_box_dump_start(a, "EditBox", trace);
fprintf(trace, ">\n");
if (p->size)
gf_isom_box_dump_ex(p->editList, trace, GF_ISOM_BOX_TYPE_ELST);
gf_isom_box_dump_done("EditBox", a, trace);
return GF_OK;
}
GF_Err udta_dump(GF_Box *a, FILE * trace)
{
GF_UserDataBox *p;
GF_UserDataMap *map;
u32 i;
p = (GF_UserDataBox *)a;
gf_isom_box_dump_start(a, "UserDataBox", trace);
fprintf(trace, ">\n");
i=0;
while ((map = (GF_UserDataMap *)gf_list_enum(p->recordList, &i))) {
gf_isom_box_array_dump(map->other_boxes, trace);
}
gf_isom_box_dump_done("UserDataBox", a, trace);
return GF_OK;
}
GF_Err dref_dump(GF_Box *a, FILE * trace)
{
// GF_DataReferenceBox *p = (GF_DataReferenceBox *)a;
gf_isom_box_dump_start(a, "DataReferenceBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("DataReferenceBox", a, trace);
return GF_OK;
}
GF_Err stsd_dump(GF_Box *a, FILE * trace)
{
// GF_SampleDescriptionBox *p = (GF_SampleDescriptionBox *)a;
gf_isom_box_dump_start(a, "SampleDescriptionBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("SampleDescriptionBox", a, trace);
return GF_OK;
}
GF_Err stts_dump(GF_Box *a, FILE * trace)
{
GF_TimeToSampleBox *p;
u32 i, nb_samples;
p = (GF_TimeToSampleBox *)a;
gf_isom_box_dump_start(a, "TimeToSampleBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", p->nb_entries);
nb_samples = 0;
for (i=0; i<p->nb_entries; i++) {
fprintf(trace, "<TimeToSampleEntry SampleDelta=\"%d\" SampleCount=\"%d\"/>\n", p->entries[i].sampleDelta, p->entries[i].sampleCount);
nb_samples += p->entries[i].sampleCount;
}
if (p->size)
fprintf(trace, "<!-- counted %d samples in STTS entries -->\n", nb_samples);
else
fprintf(trace, "<TimeToSampleEntry SampleDelta=\"\" SampleCount=\"\"/>\n");
gf_isom_box_dump_done("TimeToSampleBox", a, trace);
return GF_OK;
}
GF_Err ctts_dump(GF_Box *a, FILE * trace)
{
GF_CompositionOffsetBox *p;
u32 i, nb_samples;
p = (GF_CompositionOffsetBox *)a;
gf_isom_box_dump_start(a, "CompositionOffsetBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", p->nb_entries);
nb_samples = 0;
for (i=0; i<p->nb_entries; i++) {
fprintf(trace, "<CompositionOffsetEntry CompositionOffset=\"%d\" SampleCount=\"%d\"/>\n", p->entries[i].decodingOffset, p->entries[i].sampleCount);
nb_samples += p->entries[i].sampleCount;
}
if (p->size)
fprintf(trace, "<!-- counted %d samples in CTTS entries -->\n", nb_samples);
else
fprintf(trace, "<CompositionOffsetEntry CompositionOffset=\"\" SampleCount=\"\"/>\n");
gf_isom_box_dump_done("CompositionOffsetBox", a, trace);
return GF_OK;
}
GF_Err cslg_dump(GF_Box *a, FILE * trace)
{
GF_CompositionToDecodeBox *p;
p = (GF_CompositionToDecodeBox *)a;
gf_isom_box_dump_start(a, "CompositionToDecodeBox", trace);
fprintf(trace, "compositionToDTSShift=\"%d\" leastDecodeToDisplayDelta=\"%d\" compositionStartTime=\"%d\" compositionEndTime=\"%d\">\n", p->leastDecodeToDisplayDelta, p->greatestDecodeToDisplayDelta, p->compositionStartTime, p->compositionEndTime);
gf_isom_box_dump_done("CompositionToDecodeBox", a, trace);
return GF_OK;
}
GF_Err ccst_dump(GF_Box *a, FILE * trace)
{
GF_CodingConstraintsBox *p = (GF_CodingConstraintsBox *)a;
gf_isom_box_dump_start(a, "CodingConstraintsBox", trace);
fprintf(trace, "all_ref_pics_intra=\"%d\" intra_pred_used=\"%d\" max_ref_per_pic=\"%d\" reserved=\"%d\">\n", p->all_ref_pics_intra, p->intra_pred_used, p->max_ref_per_pic, p->reserved);
gf_isom_box_dump_done("CodingConstraintsBox", a, trace);
return GF_OK;
}
GF_Err stsh_dump(GF_Box *a, FILE * trace)
{
GF_ShadowSyncBox *p;
u32 i;
GF_StshEntry *t;
p = (GF_ShadowSyncBox *)a;
gf_isom_box_dump_start(a, "SyncShadowBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", gf_list_count(p->entries));
i=0;
while ((t = (GF_StshEntry *)gf_list_enum(p->entries, &i))) {
fprintf(trace, "<SyncShadowEntry ShadowedSample=\"%d\" SyncSample=\"%d\"/>\n", t->shadowedSampleNumber, t->syncSampleNumber);
}
if (!p->size) {
fprintf(trace, "<SyncShadowEntry ShadowedSample=\"\" SyncSample=\"\"/>\n");
}
gf_isom_box_dump_done("SyncShadowBox", a, trace);
return GF_OK;
}
GF_Err elst_dump(GF_Box *a, FILE * trace)
{
GF_EditListBox *p;
u32 i;
GF_EdtsEntry *t;
p = (GF_EditListBox *)a;
gf_isom_box_dump_start(a, "EditListBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", gf_list_count(p->entryList));
i=0;
while ((t = (GF_EdtsEntry *)gf_list_enum(p->entryList, &i))) {
fprintf(trace, "<EditListEntry Duration=\""LLD"\" MediaTime=\""LLD"\" MediaRate=\"%u\"/>\n", LLD_CAST t->segmentDuration, LLD_CAST t->mediaTime, t->mediaRate);
}
if (!p->size) {
fprintf(trace, "<EditListEntry Duration=\"\" MediaTime=\"\" MediaRate=\"\"/>\n");
}
gf_isom_box_dump_done("EditListBox", a, trace);
return GF_OK;
}
GF_Err stsc_dump(GF_Box *a, FILE * trace)
{
GF_SampleToChunkBox *p;
u32 i, nb_samples;
p = (GF_SampleToChunkBox *)a;
gf_isom_box_dump_start(a, "SampleToChunkBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", p->nb_entries);
nb_samples = 0;
for (i=0; i<p->nb_entries; i++) {
fprintf(trace, "<SampleToChunkEntry FirstChunk=\"%d\" SamplesPerChunk=\"%d\" SampleDescriptionIndex=\"%d\"/>\n", p->entries[i].firstChunk, p->entries[i].samplesPerChunk, p->entries[i].sampleDescriptionIndex);
if (i+1<p->nb_entries) {
nb_samples += (p->entries[i+1].firstChunk - p->entries[i].firstChunk) * p->entries[i].samplesPerChunk;
} else {
nb_samples += p->entries[i].samplesPerChunk;
}
}
if (p->size)
fprintf(trace, "<!-- counted %d samples in STSC entries (could be less than sample count) -->\n", nb_samples);
else
fprintf(trace, "<SampleToChunkEntry FirstChunk=\"\" SamplesPerChunk=\"\" SampleDescriptionIndex=\"\"/>\n");
gf_isom_box_dump_done("SampleToChunkBox", a, trace);
return GF_OK;
}
GF_Err stsz_dump(GF_Box *a, FILE * trace)
{
GF_SampleSizeBox *p;
u32 i;
p = (GF_SampleSizeBox *)a;
if (a->type == GF_ISOM_BOX_TYPE_STSZ) {
gf_isom_box_dump_start(a, "SampleSizeBox", trace);
}
else {
gf_isom_box_dump_start(a, "CompactSampleSizeBox", trace);
}
fprintf(trace, "SampleCount=\"%d\"", p->sampleCount);
if (a->type == GF_ISOM_BOX_TYPE_STSZ) {
if (p->sampleSize) {
fprintf(trace, " ConstantSampleSize=\"%d\"", p->sampleSize);
}
} else {
fprintf(trace, " SampleSizeBits=\"%d\"", p->sampleSize);
}
fprintf(trace, ">\n");
if ((a->type != GF_ISOM_BOX_TYPE_STSZ) || !p->sampleSize) {
if (!p->sizes && p->size) {
fprintf(trace, "<!--WARNING: No Sample Size indications-->\n");
} else {
for (i=0; i<p->sampleCount; i++) {
fprintf(trace, "<SampleSizeEntry Size=\"%d\"/>\n", p->sizes[i]);
}
}
}
if (!p->size) {
fprintf(trace, "<SampleSizeEntry Size=\"\"/>\n");
}
gf_isom_box_dump_done((a->type == GF_ISOM_BOX_TYPE_STSZ) ? "SampleSizeBox" : "CompactSampleSizeBox", a, trace);
return GF_OK;
}
GF_Err stco_dump(GF_Box *a, FILE * trace)
{
GF_ChunkOffsetBox *p;
u32 i;
p = (GF_ChunkOffsetBox *)a;
gf_isom_box_dump_start(a, "ChunkOffsetBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", p->nb_entries);
if (!p->offsets && p->size) {
fprintf(trace, "<!--Warning: No Chunk Offsets indications-->\n");
} else {
for (i=0; i<p->nb_entries; i++) {
fprintf(trace, "<ChunkEntry offset=\"%u\"/>\n", p->offsets[i]);
}
}
if (!p->size) {
fprintf(trace, "<ChunkEntry offset=\"\"/>\n");
}
gf_isom_box_dump_done("ChunkOffsetBox", a, trace);
return GF_OK;
}
GF_Err stss_dump(GF_Box *a, FILE * trace)
{
GF_SyncSampleBox *p;
u32 i;
p = (GF_SyncSampleBox *)a;
gf_isom_box_dump_start(a, "SyncSampleBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", p->nb_entries);
if (!p->sampleNumbers && p->size) {
fprintf(trace, "<!--Warning: No Key Frames indications-->\n");
} else {
for (i=0; i<p->nb_entries; i++) {
fprintf(trace, "<SyncSampleEntry sampleNumber=\"%u\"/>\n", p->sampleNumbers[i]);
}
}
if (!p->size) {
fprintf(trace, "<SyncSampleEntry sampleNumber=\"\"/>\n");
}
gf_isom_box_dump_done("SyncSampleBox", a, trace);
return GF_OK;
}
GF_Err stdp_dump(GF_Box *a, FILE * trace)
{
GF_DegradationPriorityBox *p;
u32 i;
p = (GF_DegradationPriorityBox *)a;
gf_isom_box_dump_start(a, "DegradationPriorityBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", p->nb_entries);
if (!p->priorities && p->size) {
fprintf(trace, "<!--Warning: No Degradation Priority indications-->\n");
} else {
for (i=0; i<p->nb_entries; i++) {
fprintf(trace, "<DegradationPriorityEntry DegradationPriority=\"%d\"/>\n", p->priorities[i]);
}
}
if (!p->size) {
fprintf(trace, "<DegradationPriorityEntry DegradationPriority=\"\"/>\n");
}
gf_isom_box_dump_done("DegradationPriorityBox", a, trace);
return GF_OK;
}
GF_Err sdtp_dump(GF_Box *a, FILE * trace)
{
GF_SampleDependencyTypeBox *p;
u32 i;
p = (GF_SampleDependencyTypeBox*)a;
gf_isom_box_dump_start(a, "SampleDependencyTypeBox", trace);
fprintf(trace, "SampleCount=\"%d\">\n", p->sampleCount);
if (!p->sample_info && p->size) {
fprintf(trace, "<!--Warning: No sample dependencies indications-->\n");
} else {
for (i=0; i<p->sampleCount; i++) {
u8 flag = p->sample_info[i];
fprintf(trace, "<SampleDependencyEntry ");
switch ( (flag >> 4) & 3) {
case 0:
fprintf(trace, "dependsOnOther=\"unknown\" ");
break;
case 1:
fprintf(trace, "dependsOnOther=\"yes\" ");
break;
case 2:
fprintf(trace, "dependsOnOther=\"no\" ");
break;
case 3:
fprintf(trace, "dependsOnOther=\"RESERVED\" ");
break;
}
switch ( (flag >> 2) & 3) {
case 0:
fprintf(trace, "dependedOn=\"unknown\" ");
break;
case 1:
fprintf(trace, "dependedOn=\"yes\" ");
break;
case 2:
fprintf(trace, "dependedOn=\"no\" ");
break;
case 3:
fprintf(trace, "dependedOn=\"RESERVED\" ");
break;
}
switch ( flag & 3) {
case 0:
fprintf(trace, "hasRedundancy=\"unknown\" ");
break;
case 1:
fprintf(trace, "hasRedundancy=\"yes\" ");
break;
case 2:
fprintf(trace, "hasRedundancy=\"no\" ");
break;
case 3:
fprintf(trace, "hasRedundancy=\"RESERVED\" ");
break;
}
fprintf(trace, " />\n");
}
}
if (!p->size) {
fprintf(trace, "<SampleDependencyEntry dependsOnOther=\"unknown|yes|no|RESERVED\" dependedOn=\"unknown|yes|no|RESERVED\" hasRedundancy=\"unknown|yes|no|RESERVED\"/>\n");
}
gf_isom_box_dump_done("SampleDependencyTypeBox", a, trace);
return GF_OK;
}
GF_Err co64_dump(GF_Box *a, FILE * trace)
{
GF_ChunkLargeOffsetBox *p;
u32 i;
p = (GF_ChunkLargeOffsetBox *)a;
gf_isom_box_dump_start(a, "ChunkLargeOffsetBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", p->nb_entries);
if (!p->offsets && p->size) {
fprintf(trace, "<!-- Warning: No Chunk Offsets indications/>\n");
} else {
for (i=0; i<p->nb_entries; i++)
fprintf(trace, "<ChunkOffsetEntry offset=\""LLU"\"/>\n", LLU_CAST p->offsets[i]);
}
if (!p->size) {
fprintf(trace, "<ChunkOffsetEntry offset=\"\"/>\n");
}
gf_isom_box_dump_done("ChunkLargeOffsetBox", a, trace);
return GF_OK;
}
GF_Err esds_dump(GF_Box *a, FILE * trace)
{
GF_ESDBox *p;
p = (GF_ESDBox *)a;
gf_isom_box_dump_start(a, "MPEG4ESDescriptorBox", trace);
fprintf(trace, ">\n");
if (p->desc) {
#ifndef GPAC_DISABLE_OD_DUMP
gf_odf_dump_desc((GF_Descriptor *) p->desc, trace, 1, GF_TRUE);
#else
fprintf(trace, "<!-- Object Descriptor Dumping disabled in this build of GPAC -->\n");
#endif
} else if (p->size) {
fprintf(trace, "<!--INVALID MP4 FILE: ESD not present in MPEG Sample Description or corrupted-->\n");
}
gf_isom_box_dump_done("MPEG4ESDescriptorBox", a, trace);
return GF_OK;
}
GF_Err minf_dump(GF_Box *a, FILE * trace)
{
GF_MediaInformationBox *p;
p = (GF_MediaInformationBox *)a;
gf_isom_box_dump_start(a, "MediaInformationBox", trace);
fprintf(trace, ">\n");
if (p->size)
gf_isom_box_dump_ex(p->InfoHeader, trace, GF_ISOM_BOX_TYPE_NMHD);
if (p->size)
gf_isom_box_dump_ex(p->dataInformation, trace, GF_ISOM_BOX_TYPE_DINF);
if (p->size)
gf_isom_box_dump_ex(p->sampleTable, trace, GF_ISOM_BOX_TYPE_STBL);
gf_isom_box_dump_done("MediaInformationBox", a, trace);
return GF_OK;
}
GF_Err tkhd_dump(GF_Box *a, FILE * trace)
{
GF_TrackHeaderBox *p;
p = (GF_TrackHeaderBox *)a;
gf_isom_box_dump_start(a, "TrackHeaderBox", trace);
fprintf(trace, "CreationTime=\""LLD"\" ModificationTime=\""LLD"\" TrackID=\"%u\" Duration=\""LLD"\"",
LLD_CAST p->creationTime, LLD_CAST p->modificationTime, p->trackID, LLD_CAST p->duration);
if (p->alternate_group) fprintf(trace, " AlternateGroupID=\"%d\"", p->alternate_group);
if (p->volume) {
fprintf(trace, " Volume=\"%.2f\"", (Float)p->volume / 256);
} else if (p->width || p->height) {
fprintf(trace, " Width=\"%.2f\" Height=\"%.2f\"", (Float)p->width / 65536, (Float)p->height / 65536);
if (p->layer) fprintf(trace, " Layer=\"%d\"", p->layer);
}
fprintf(trace, ">\n");
if (p->width || p->height) {
fprintf(trace, "<Matrix m11=\"0x%.8x\" m12=\"0x%.8x\" m13=\"0x%.8x\" ", p->matrix[0], p->matrix[1], p->matrix[2]);
fprintf(trace, "m21=\"0x%.8x\" m22=\"0x%.8x\" m23=\"0x%.8x\" ", p->matrix[3], p->matrix[4], p->matrix[5]);
fprintf(trace, "m31=\"0x%.8x\" m32=\"0x%.8x\" m33=\"0x%.8x\"/>\n", p->matrix[6], p->matrix[7], p->matrix[8]);
}
gf_isom_box_dump_done("TrackHeaderBox", a, trace);
return GF_OK;
}
GF_Err tref_dump(GF_Box *a, FILE * trace)
{
// GF_TrackReferenceBox *p = (GF_TrackReferenceBox *)a;
gf_isom_box_dump_start(a, "TrackReferenceBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("TrackReferenceBox", a, trace);
return GF_OK;
}
GF_Err mdia_dump(GF_Box *a, FILE * trace)
{
GF_MediaBox *p = (GF_MediaBox *)a;
gf_isom_box_dump_start(a, "MediaBox", trace);
fprintf(trace, ">\n");
if (p->size)
gf_isom_box_dump_ex(p->mediaHeader, trace, GF_ISOM_BOX_TYPE_MDHD);
if (p->size)
gf_isom_box_dump_ex(p->handler, trace,GF_ISOM_BOX_TYPE_HDLR);
if (p->size)
gf_isom_box_dump_ex(p->information, trace, GF_ISOM_BOX_TYPE_MINF);
gf_isom_box_dump_done("MediaBox", a, trace);
return GF_OK;
}
GF_Err mfra_dump(GF_Box *a, FILE * trace)
{
GF_MovieFragmentRandomAccessBox *p = (GF_MovieFragmentRandomAccessBox *)a;
u32 i, count;
GF_TrackFragmentRandomAccessBox *tfra;
gf_isom_box_dump_start(a, "MovieFragmentRandomAccessBox", trace);
fprintf(trace, ">\n");
count = gf_list_count(p->tfra_list);
for (i=0; i<count; i++) {
tfra = (GF_TrackFragmentRandomAccessBox *)gf_list_get(p->tfra_list, i);
gf_isom_box_dump_ex(tfra, trace, GF_ISOM_BOX_TYPE_TFRA);
}
gf_isom_box_dump_done("MovieFragmentRandomAccessBox", a, trace);
return GF_OK;
}
GF_Err tfra_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_TrackFragmentRandomAccessBox *p = (GF_TrackFragmentRandomAccessBox *)a;
gf_isom_box_dump_start(a, "TrackFragmentRandomAccessBox", trace);
fprintf(trace, "TrackId=\"%u\" number_of_entries=\"%u\">\n", p->track_id, p->nb_entries);
for (i=0; i<p->nb_entries; i++) {
fprintf(trace, "<RandomAccessEntry time=\""LLU"\" moof_offset=\""LLU"\" traf=\"%u\" trun=\"%u\" sample=\"%u\"/>\n",
p->entries[i].time, p->entries[i].moof_offset,
p->entries[i].traf_number, p->entries[i].trun_number, p->entries[i].sample_number);
}
if (!p->size) {
fprintf(trace, "<RandomAccessEntry time=\"\" moof_offset=\"\" traf=\"\" trun=\"\" sample=\"\"/>\n");
}
gf_isom_box_dump_done("TrackFragmentRandomAccessBox", a, trace);
return GF_OK;
}
GF_Err mfro_dump(GF_Box *a, FILE * trace)
{
GF_MovieFragmentRandomAccessOffsetBox *p = (GF_MovieFragmentRandomAccessOffsetBox *)a;
gf_isom_box_dump_start(a, "MovieFragmentRandomAccessOffsetBox", trace);
fprintf(trace, "container_size=\"%d\" >\n", p->container_size);
gf_isom_box_dump_done("MovieFragmentRandomAccessOffsetBox", a, trace);
return GF_OK;
}
GF_Err elng_dump(GF_Box *a, FILE * trace)
{
GF_ExtendedLanguageBox *p = (GF_ExtendedLanguageBox *)a;
gf_isom_box_dump_start(a, "ExtendedLanguageBox", trace);
fprintf(trace, "LanguageCode=\"%s\">\n", p->extended_language);
gf_isom_box_dump_done("ExtendedLanguageBox", a, trace);
return GF_OK;
}
GF_Err unkn_dump(GF_Box *a, FILE * trace)
{
GF_UnknownBox *u = (GF_UnknownBox *)a;
u->type = u->original_4cc;
gf_isom_box_dump_start(a, "UnknownBox", trace);
u->type = GF_ISOM_BOX_TYPE_UNKNOWN;
if (u->dataSize<100)
dump_data_attribute(trace, "data", u->data, u->dataSize);
fprintf(trace, ">\n");
gf_isom_box_dump_done("UnknownBox", a, trace);
return GF_OK;
}
GF_Err uuid_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "UUIDBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("UUIDBox", a, trace);
return GF_OK;
}
GF_Err void_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "VoidBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("VoidBox", a, trace);
return GF_OK;
}
GF_Err ftyp_dump(GF_Box *a, FILE * trace)
{
GF_FileTypeBox *p;
u32 i;
p = (GF_FileTypeBox *)a;
gf_isom_box_dump_start(a, (a->type == GF_ISOM_BOX_TYPE_FTYP ? "FileTypeBox" : "SegmentTypeBox"), trace);
fprintf(trace, "MajorBrand=\"%s\" MinorVersion=\"%d\">\n", gf_4cc_to_str(p->majorBrand), p->minorVersion);
for (i=0; i<p->altCount; i++) {
fprintf(trace, "<BrandEntry AlternateBrand=\"%s\"/>\n", gf_4cc_to_str(p->altBrand[i]));
}
if (!p->type) {
fprintf(trace, "<BrandEntry AlternateBrand=\"4CC\"/>\n");
}
gf_isom_box_dump_done((a->type == GF_ISOM_BOX_TYPE_FTYP ? "FileTypeBox" : "SegmentTypeBox"), a, trace);
return GF_OK;
}
GF_Err padb_dump(GF_Box *a, FILE * trace)
{
GF_PaddingBitsBox *p;
u32 i;
p = (GF_PaddingBitsBox *)a;
gf_isom_box_dump_start(a, "PaddingBitsBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", p->SampleCount);
for (i=0; i<p->SampleCount; i+=1) {
fprintf(trace, "<PaddingBitsEntry PaddingBits=\"%d\"/>\n", p->padbits[i]);
}
if (!p->size) {
fprintf(trace, "<PaddingBitsEntry PaddingBits=\"\"/>\n");
}
gf_isom_box_dump_done("PaddingBitsBox", a, trace);
return GF_OK;
}
GF_Err stsf_dump(GF_Box *a, FILE * trace)
{
GF_SampleFragmentBox *p;
GF_StsfEntry *ent;
u32 i, j, count;
p = (GF_SampleFragmentBox *)a;
count = gf_list_count(p->entryList);
gf_isom_box_dump_start(a, "SampleFragmentBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", count);
for (i=0; i<count; i++) {
ent = (GF_StsfEntry *)gf_list_get(p->entryList, i);
fprintf(trace, "<SampleFragmentEntry SampleNumber=\"%d\" FragmentCount=\"%d\">\n", ent->SampleNumber, ent->fragmentCount);
for (j=0; j<ent->fragmentCount; j++) fprintf(trace, "<FragmentSizeEntry size=\"%d\"/>\n", ent->fragmentSizes[j]);
fprintf(trace, "</SampleFragmentEntry>\n");
}
if (!p->size) {
fprintf(trace, "<SampleFragmentEntry SampleNumber=\"\" FragmentCount=\"\">\n");
fprintf(trace, "<FragmentSizeEntry size=\"\"/>\n");
fprintf(trace, "</SampleFragmentEntry>\n");
}
gf_isom_box_dump_done("SampleFragmentBox", a, trace);
return GF_OK;
}
GF_Err gppc_dump(GF_Box *a, FILE * trace)
{
GF_3GPPConfigBox *p = (GF_3GPPConfigBox *)a;
const char *name = gf_4cc_to_str(p->cfg.vendor);
switch (p->cfg.type) {
case GF_ISOM_SUBTYPE_3GP_AMR:
case GF_ISOM_SUBTYPE_3GP_AMR_WB:
gf_isom_box_dump_start(a, "AMRConfigurationBox", trace);
fprintf(trace, "Vendor=\"%s\" Version=\"%d\"", name, p->cfg.decoder_version);
fprintf(trace, " FramesPerSample=\"%d\" SupportedModes=\"%x\" ModeRotating=\"%d\"", p->cfg.frames_per_sample, p->cfg.AMR_mode_set, p->cfg.AMR_mode_change_period);
fprintf(trace, ">\n");
gf_isom_box_dump_done("AMRConfigurationBox", a, trace);
break;
case GF_ISOM_SUBTYPE_3GP_EVRC:
gf_isom_box_dump_start(a, "EVRCConfigurationBox", trace);
fprintf(trace, "Vendor=\"%s\" Version=\"%d\" FramesPerSample=\"%d\" >\n", name, p->cfg.decoder_version, p->cfg.frames_per_sample);
gf_isom_box_dump_done("EVRCConfigurationBox", a, trace);
break;
case GF_ISOM_SUBTYPE_3GP_QCELP:
gf_isom_box_dump_start(a, "QCELPConfigurationBox", trace);
fprintf(trace, "Vendor=\"%s\" Version=\"%d\" FramesPerSample=\"%d\" >\n", name, p->cfg.decoder_version, p->cfg.frames_per_sample);
gf_isom_box_dump_done("QCELPConfigurationBox", a, trace);
break;
case GF_ISOM_SUBTYPE_3GP_SMV:
gf_isom_box_dump_start(a, "SMVConfigurationBox", trace);
fprintf(trace, "Vendor=\"%s\" Version=\"%d\" FramesPerSample=\"%d\" >\n", name, p->cfg.decoder_version, p->cfg.frames_per_sample);
gf_isom_box_dump_done("SMVConfigurationBox", a, trace);
break;
case GF_ISOM_SUBTYPE_3GP_H263:
gf_isom_box_dump_start(a, "H263ConfigurationBox", trace);
fprintf(trace, "Vendor=\"%s\" Version=\"%d\"", name, p->cfg.decoder_version);
fprintf(trace, " Profile=\"%d\" Level=\"%d\"", p->cfg.H263_profile, p->cfg.H263_level);
fprintf(trace, ">\n");
gf_isom_box_dump_done("H263ConfigurationBox", a, trace);
break;
default:
break;
}
return GF_OK;
}
GF_Err avcc_dump(GF_Box *a, FILE * trace)
{
u32 i, count;
GF_AVCConfigurationBox *p = (GF_AVCConfigurationBox *) a;
const char *name = (p->type==GF_ISOM_BOX_TYPE_MVCC) ? "MVC" : (p->type==GF_ISOM_BOX_TYPE_SVCC) ? "SVC" : "AVC";
char boxname[256];
sprintf(boxname, "%sConfigurationBox", name);
gf_isom_box_dump_start(a, boxname, trace);
fprintf(trace, ">\n");
fprintf(trace, "<%sDecoderConfigurationRecord", name);
if (! p->config) {
if (p->size) {
fprintf(trace, ">\n");
fprintf(trace, "<!-- INVALID AVC ENTRY : no AVC/SVC config record -->\n");
} else {
fprintf(trace, " configurationVersion=\"\" AVCProfileIndication=\"\" profile_compatibility=\"\" AVCLevelIndication=\"\" nal_unit_size=\"\" complete_representation=\"\"");
fprintf(trace, " chroma_format=\"\" luma_bit_depth=\"\" chroma_bit_depth=\"\"");
fprintf(trace, ">\n");
fprintf(trace, "<SequenceParameterSet size=\"\" content=\"\"/>\n");
fprintf(trace, "<PictureParameterSet size=\"\" content=\"\"/>\n");
fprintf(trace, "<SequenceParameterSetExtensions size=\"\" content=\"\"/>\n");
}
fprintf(trace, "</%sDecoderConfigurationRecord>\n", name);
gf_isom_box_dump_done(boxname, a, trace);
return GF_OK;
}
fprintf(trace, " configurationVersion=\"%d\" AVCProfileIndication=\"%d\" profile_compatibility=\"%d\" AVCLevelIndication=\"%d\" nal_unit_size=\"%d\"", p->config->configurationVersion, p->config->AVCProfileIndication, p->config->profile_compatibility, p->config->AVCLevelIndication, p->config->nal_unit_size);
if ((p->type==GF_ISOM_BOX_TYPE_SVCC) || (p->type==GF_ISOM_BOX_TYPE_MVCC) )
fprintf(trace, " complete_representation=\"%d\"", p->config->complete_representation);
if (p->type==GF_ISOM_BOX_TYPE_AVCC) {
if (gf_avc_is_rext_profile(p->config->AVCProfileIndication)) {
fprintf(trace, " chroma_format=\"%s\" luma_bit_depth=\"%d\" chroma_bit_depth=\"%d\"", gf_avc_hevc_get_chroma_format_name(p->config->chroma_format), p->config->luma_bit_depth, p->config->chroma_bit_depth);
}
}
fprintf(trace, ">\n");
count = gf_list_count(p->config->sequenceParameterSets);
for (i=0; i<count; i++) {
GF_AVCConfigSlot *c = (GF_AVCConfigSlot *)gf_list_get(p->config->sequenceParameterSets, i);
fprintf(trace, "<SequenceParameterSet size=\"%d\" content=\"", c->size);
dump_data(trace, c->data, c->size);
fprintf(trace, "\"/>\n");
}
count = gf_list_count(p->config->pictureParameterSets);
for (i=0; i<count; i++) {
GF_AVCConfigSlot *c = (GF_AVCConfigSlot *)gf_list_get(p->config->pictureParameterSets, i);
fprintf(trace, "<PictureParameterSet size=\"%d\" content=\"", c->size);
dump_data(trace, c->data, c->size);
fprintf(trace, "\"/>\n");
}
if (p->config->sequenceParameterSetExtensions) {
count = gf_list_count(p->config->sequenceParameterSetExtensions);
for (i=0; i<count; i++) {
GF_AVCConfigSlot *c = (GF_AVCConfigSlot *)gf_list_get(p->config->sequenceParameterSetExtensions, i);
fprintf(trace, "<SequenceParameterSetExtensions size=\"%d\" content=\"", c->size);
dump_data(trace, c->data, c->size);
fprintf(trace, "\"/>\n");
}
}
fprintf(trace, "</%sDecoderConfigurationRecord>\n", name);
gf_isom_box_dump_done(boxname, a, trace);
return GF_OK;
}
GF_Err hvcc_dump(GF_Box *a, FILE * trace)
{
u32 i, count;
const char *name = (a->type==GF_ISOM_BOX_TYPE_HVCC) ? "HEVC" : "L-HEVC";
char boxname[256];
GF_HEVCConfigurationBox *p = (GF_HEVCConfigurationBox *) a;
sprintf(boxname, "%sConfigurationBox", name);
gf_isom_box_dump_start(a, boxname, trace);
fprintf(trace, ">\n");
if (! p->config) {
if (p->size) {
fprintf(trace, "<!-- INVALID HEVC ENTRY: no HEVC/SHVC config record -->\n");
} else {
fprintf(trace, "<%sDecoderConfigurationRecord nal_unit_size=\"\" configurationVersion=\"\" ", name);
if (a->type==GF_ISOM_BOX_TYPE_HVCC) {
fprintf(trace, "profile_space=\"\" tier_flag=\"\" profile_idc=\"\" general_profile_compatibility_flags=\"\" progressive_source_flag=\"\" interlaced_source_flag=\"\" non_packed_constraint_flag=\"\" frame_only_constraint_flag=\"\" constraint_indicator_flags=\"\" level_idc=\"\" ");
}
fprintf(trace, "min_spatial_segmentation_idc=\"\" parallelismType=\"\" ");
if (a->type==GF_ISOM_BOX_TYPE_HVCC)
fprintf(trace, "chroma_format=\"\" luma_bit_depth=\"\" chroma_bit_depth=\"\" avgFrameRate=\"\" constantFrameRate=\"\" numTemporalLayers=\"\" temporalIdNested=\"\"");
fprintf(trace, ">\n");
fprintf(trace, "<ParameterSetArray nalu_type=\"\" complete_set=\"\">\n");
fprintf(trace, "<ParameterSet size=\"\" content=\"\"/>\n");
fprintf(trace, "</ParameterSetArray>\n");
fprintf(trace, "</%sDecoderConfigurationRecord>\n", name);
}
fprintf(trace, "</%sConfigurationBox>\n", name);
return GF_OK;
}
fprintf(trace, "<%sDecoderConfigurationRecord nal_unit_size=\"%d\" ", name, p->config->nal_unit_size);
fprintf(trace, "configurationVersion=\"%u\" ", p->config->configurationVersion);
if (a->type==GF_ISOM_BOX_TYPE_HVCC) {
fprintf(trace, "profile_space=\"%u\" ", p->config->profile_space);
fprintf(trace, "tier_flag=\"%u\" ", p->config->tier_flag);
fprintf(trace, "profile_idc=\"%u\" ", p->config->profile_idc);
fprintf(trace, "general_profile_compatibility_flags=\"%X\" ", p->config->general_profile_compatibility_flags);
fprintf(trace, "progressive_source_flag=\"%u\" ", p->config->progressive_source_flag);
fprintf(trace, "interlaced_source_flag=\"%u\" ", p->config->interlaced_source_flag);
fprintf(trace, "non_packed_constraint_flag=\"%u\" ", p->config->non_packed_constraint_flag);
fprintf(trace, "frame_only_constraint_flag=\"%u\" ", p->config->frame_only_constraint_flag);
fprintf(trace, "constraint_indicator_flags=\""LLX"\" ", p->config->constraint_indicator_flags);
fprintf(trace, "level_idc=\"%d\" ", p->config->level_idc);
}
fprintf(trace, "min_spatial_segmentation_idc=\"%u\" ", p->config->min_spatial_segmentation_idc);
fprintf(trace, "parallelismType=\"%u\" ", p->config->parallelismType);
if (a->type==GF_ISOM_BOX_TYPE_HVCC)
fprintf(trace, "chroma_format=\"%s\" luma_bit_depth=\"%u\" chroma_bit_depth=\"%u\" avgFrameRate=\"%u\" constantFrameRate=\"%u\" numTemporalLayers=\"%u\" temporalIdNested=\"%u\"",
gf_avc_hevc_get_chroma_format_name(p->config->chromaFormat), p->config->luma_bit_depth, p->config->chroma_bit_depth, p->config->avgFrameRate, p->config->constantFrameRate, p->config->numTemporalLayers, p->config->temporalIdNested);
fprintf(trace, ">\n");
count = gf_list_count(p->config->param_array);
for (i=0; i<count; i++) {
u32 nalucount, j;
GF_HEVCParamArray *ar = (GF_HEVCParamArray*)gf_list_get(p->config->param_array, i);
fprintf(trace, "<ParameterSetArray nalu_type=\"%d\" complete_set=\"%d\">\n", ar->type, ar->array_completeness);
nalucount = gf_list_count(ar->nalus);
for (j=0; j<nalucount; j++) {
GF_AVCConfigSlot *c = (GF_AVCConfigSlot *)gf_list_get(ar->nalus, j);
fprintf(trace, "<ParameterSet size=\"%d\" content=\"", c->size);
dump_data(trace, c->data, c->size);
fprintf(trace, "\"/>\n");
}
fprintf(trace, "</ParameterSetArray>\n");
}
fprintf(trace, "</%sDecoderConfigurationRecord>\n", name);
gf_isom_box_dump_done(boxname, a, trace);
return GF_OK;
}
GF_Err m4ds_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_Descriptor *desc;
GF_MPEG4ExtensionDescriptorsBox *p = (GF_MPEG4ExtensionDescriptorsBox *) a;
gf_isom_box_dump_start(a, "MPEG4ExtensionDescriptorsBox", trace);
fprintf(trace, ">\n");
i=0;
while ((desc = (GF_Descriptor *)gf_list_enum(p->descriptors, &i))) {
#ifndef GPAC_DISABLE_OD_DUMP
gf_odf_dump_desc(desc, trace, 1, GF_TRUE);
#else
fprintf(trace, "<!-- Object Descriptor Dumping disabled in this build of GPAC -->\n");
#endif
}
gf_isom_box_dump_done("MPEG4ExtensionDescriptorsBox", a, trace);
return GF_OK;
}
GF_Err btrt_dump(GF_Box *a, FILE * trace)
{
GF_BitRateBox *p = (GF_BitRateBox*)a;
gf_isom_box_dump_start(a, "BitRateBox", trace);
fprintf(trace, "BufferSizeDB=\"%d\" avgBitRate=\"%d\" maxBitRate=\"%d\">\n", p->bufferSizeDB, p->avgBitrate, p->maxBitrate);
gf_isom_box_dump_done("BitRateBox", a, trace);
return GF_OK;
}
GF_Err ftab_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_FontTableBox *p = (GF_FontTableBox *)a;
gf_isom_box_dump_start(a, "FontTableBox", trace);
fprintf(trace, ">\n");
for (i=0; i<p->entry_count; i++) {
fprintf(trace, "<FontRecord ID=\"%d\" name=\"%s\"/>\n", p->fonts[i].fontID, p->fonts[i].fontName ? p->fonts[i].fontName : "NULL");
}
if (!p->size) {
fprintf(trace, "<FontRecord ID=\"\" name=\"\"/>\n");
}
gf_isom_box_dump_done("FontTableBox", a, trace);
return GF_OK;
}
static void tx3g_dump_rgba8(FILE * trace, char *name, u32 col)
{
fprintf(trace, "%s=\"%x %x %x %x\"", name, (col>>16)&0xFF, (col>>8)&0xFF, (col)&0xFF, (col>>24)&0xFF);
}
static void tx3g_dump_rgb16(FILE * trace, char *name, char col[6])
{
fprintf(trace, "%s=\"%x %x %x\"", name, *((u16*)col), *((u16*)(col+1)), *((u16*)(col+2)));
}
static void tx3g_dump_box(FILE * trace, GF_BoxRecord *rec)
{
fprintf(trace, "<BoxRecord top=\"%d\" left=\"%d\" bottom=\"%d\" right=\"%d\"/>\n", rec->top, rec->left, rec->bottom, rec->right);
}
static void tx3g_dump_style(FILE * trace, GF_StyleRecord *rec)
{
fprintf(trace, "<StyleRecord startChar=\"%d\" endChar=\"%d\" fontID=\"%d\" styles=\"", rec->startCharOffset, rec->endCharOffset, rec->fontID);
if (!rec->style_flags) {
fprintf(trace, "Normal");
} else {
if (rec->style_flags & 1) fprintf(trace, "Bold ");
if (rec->style_flags & 2) fprintf(trace, "Italic ");
if (rec->style_flags & 4) fprintf(trace, "Underlined ");
}
fprintf(trace, "\" fontSize=\"%d\" ", rec->font_size);
tx3g_dump_rgba8(trace, "textColor", rec->text_color);
fprintf(trace, "/>\n");
}
GF_Err tx3g_dump(GF_Box *a, FILE * trace)
{
GF_Tx3gSampleEntryBox *p = (GF_Tx3gSampleEntryBox *)a;
gf_isom_box_dump_start(a, "Tx3gSampleEntryBox", trace);
fprintf(trace, "dataReferenceIndex=\"%d\" displayFlags=\"%x\" horizontal-justification=\"%d\" vertical-justification=\"%d\" ",
p->dataReferenceIndex, p->displayFlags, p->horizontal_justification, p->vertical_justification);
tx3g_dump_rgba8(trace, "backgroundColor", p->back_color);
fprintf(trace, ">\n");
fprintf(trace, "<DefaultBox>\n");
tx3g_dump_box(trace, &p->default_box);
gf_isom_box_dump_done("DefaultBox", a, trace);
fprintf(trace, "<DefaultStyle>\n");
tx3g_dump_style(trace, &p->default_style);
fprintf(trace, "</DefaultStyle>\n");
if (p->size) {
gf_isom_box_dump_ex(p->font_table, trace, GF_ISOM_BOX_TYPE_FTAB);
}
gf_isom_box_dump_done("Tx3gSampleEntryBox", a, trace);
return GF_OK;
}
GF_Err text_dump(GF_Box *a, FILE * trace)
{
GF_TextSampleEntryBox *p = (GF_TextSampleEntryBox *)a;
gf_isom_box_dump_start(a, "TextSampleEntryBox", trace);
fprintf(trace, "dataReferenceIndex=\"%d\" displayFlags=\"%x\" textJustification=\"%d\" ",
p->dataReferenceIndex, p->displayFlags, p->textJustification);
if (p->textName)
fprintf(trace, "textName=\"%s\" ", p->textName);
tx3g_dump_rgb16(trace, "background-color", p->background_color);
tx3g_dump_rgb16(trace, " foreground-color", p->foreground_color);
fprintf(trace, ">\n");
fprintf(trace, "<DefaultBox>\n");
tx3g_dump_box(trace, &p->default_box);
gf_isom_box_dump_done("DefaultBox", a, trace);
gf_isom_box_dump_done("TextSampleEntryBox", a, trace);
return GF_OK;
}
GF_Err styl_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_TextStyleBox*p = (GF_TextStyleBox*)a;
gf_isom_box_dump_start(a, "TextStyleBox", trace);
fprintf(trace, ">\n");
for (i=0; i<p->entry_count; i++) tx3g_dump_style(trace, &p->styles[i]);
if (!p->size) {
fprintf(trace, "<StyleRecord startChar=\"\" endChar=\"\" fontID=\"\" styles=\"Normal|Bold|Italic|Underlined\" fontSize=\"\" textColor=\"\" />\n");
}
gf_isom_box_dump_done("TextStyleBox", a, trace);
return GF_OK;
}
GF_Err hlit_dump(GF_Box *a, FILE * trace)
{
GF_TextHighlightBox*p = (GF_TextHighlightBox*)a;
gf_isom_box_dump_start(a, "TextHighlightBox", trace);
fprintf(trace, "startcharoffset=\"%d\" endcharoffset=\"%d\">\n", p->startcharoffset, p->endcharoffset);
gf_isom_box_dump_done("TextHighlightBox", a, trace);
return GF_OK;
}
GF_Err hclr_dump(GF_Box *a, FILE * trace)
{
GF_TextHighlightColorBox*p = (GF_TextHighlightColorBox*)a;
gf_isom_box_dump_start(a, "TextHighlightColorBox", trace);
tx3g_dump_rgba8(trace, "highlight_color", p->hil_color);
fprintf(trace, ">\n");
gf_isom_box_dump_done("TextHighlightColorBox", a, trace);
return GF_OK;
}
GF_Err krok_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_TextKaraokeBox*p = (GF_TextKaraokeBox*)a;
gf_isom_box_dump_start(a, "TextKaraokeBox", trace);
fprintf(trace, "highlight_starttime=\"%d\">\n", p->highlight_starttime);
for (i=0; i<p->nb_entries; i++) {
fprintf(trace, "<KaraokeRecord highlight_endtime=\"%d\" start_charoffset=\"%d\" end_charoffset=\"%d\"/>\n", p->records[i].highlight_endtime, p->records[i].start_charoffset, p->records[i].end_charoffset);
}
if (!p->size) {
fprintf(trace, "<KaraokeRecord highlight_endtime=\"\" start_charoffset=\"\" end_charoffset=\"\"/>\n");
}
gf_isom_box_dump_done("TextKaraokeBox", a, trace);
return GF_OK;
}
GF_Err dlay_dump(GF_Box *a, FILE * trace)
{
GF_TextScrollDelayBox*p = (GF_TextScrollDelayBox*)a;
gf_isom_box_dump_start(a, "TextScrollDelayBox", trace);
fprintf(trace, "scroll_delay=\"%d\">\n", p->scroll_delay);
gf_isom_box_dump_done("TextScrollDelayBox", a, trace);
return GF_OK;
}
GF_Err href_dump(GF_Box *a, FILE * trace)
{
GF_TextHyperTextBox*p = (GF_TextHyperTextBox*)a;
gf_isom_box_dump_start(a, "TextHyperTextBox", trace);
fprintf(trace, "startcharoffset=\"%d\" endcharoffset=\"%d\" URL=\"%s\" altString=\"%s\">\n", p->startcharoffset, p->endcharoffset, p->URL ? p->URL : "NULL", p->URL_hint ? p->URL_hint : "NULL");
gf_isom_box_dump_done("TextHyperTextBox", a, trace);
return GF_OK;
}
GF_Err tbox_dump(GF_Box *a, FILE * trace)
{
GF_TextBoxBox*p = (GF_TextBoxBox*)a;
gf_isom_box_dump_start(a, "TextBoxBox", trace);
fprintf(trace, ">\n");
tx3g_dump_box(trace, &p->box);
gf_isom_box_dump_done("TextBoxBox", a, trace);
return GF_OK;
}
GF_Err blnk_dump(GF_Box *a, FILE * trace)
{
GF_TextBlinkBox*p = (GF_TextBlinkBox*)a;
gf_isom_box_dump_start(a, "TextBlinkBox", trace);
fprintf(trace, "start_charoffset=\"%d\" end_charoffset=\"%d\">\n", p->startcharoffset, p->endcharoffset);
gf_isom_box_dump_done("TextBlinkBox", a, trace);
return GF_OK;
}
GF_Err twrp_dump(GF_Box *a, FILE * trace)
{
GF_TextWrapBox*p = (GF_TextWrapBox*)a;
gf_isom_box_dump_start(a, "TextWrapBox", trace);
fprintf(trace, "wrap_flag=\"%s\">\n", p->wrap_flag ? ( (p->wrap_flag>1) ? "Reserved" : "Automatic" ) : "No Wrap");
gf_isom_box_dump_done("TextWrapBox", a, trace);
return GF_OK;
}
GF_Err meta_dump(GF_Box *a, FILE * trace)
{
GF_MetaBox *p;
p = (GF_MetaBox *)a;
gf_isom_box_dump_start(a, "MetaBox", trace);
fprintf(trace, ">\n");
if (p->handler) gf_isom_box_dump(p->handler, trace);
if (p->primary_resource) gf_isom_box_dump(p->primary_resource, trace);
if (p->file_locations) gf_isom_box_dump(p->file_locations, trace);
if (p->item_locations) gf_isom_box_dump(p->item_locations, trace);
if (p->protections) gf_isom_box_dump(p->protections, trace);
if (p->item_infos) gf_isom_box_dump(p->item_infos, trace);
if (p->IPMP_control) gf_isom_box_dump(p->IPMP_control, trace);
if (p->item_refs) gf_isom_box_dump(p->item_refs, trace);
if (p->item_props) gf_isom_box_dump(p->item_props, trace);
gf_isom_box_dump_done("MetaBox", a, trace);
return GF_OK;
}
GF_Err xml_dump(GF_Box *a, FILE * trace)
{
GF_XMLBox *p = (GF_XMLBox *)a;
gf_isom_box_dump_start(a, "XMLBox", trace);
fprintf(trace, ">\n");
fprintf(trace, "<![CDATA[\n");
if (p->xml)
gf_fwrite(p->xml, strlen(p->xml), 1, trace);
fprintf(trace, "]]>\n");
gf_isom_box_dump_done("XMLBox", a, trace);
return GF_OK;
}
GF_Err bxml_dump(GF_Box *a, FILE * trace)
{
GF_BinaryXMLBox *p = (GF_BinaryXMLBox *)a;
gf_isom_box_dump_start(a, "BinaryXMLBox", trace);
fprintf(trace, "binarySize=\"%d\">\n", p->data_length);
gf_isom_box_dump_done("BinaryXMLBox", a, trace);
return GF_OK;
}
GF_Err pitm_dump(GF_Box *a, FILE * trace)
{
GF_PrimaryItemBox *p = (GF_PrimaryItemBox *)a;
gf_isom_box_dump_start(a, "PrimaryItemBox", trace);
fprintf(trace, "item_ID=\"%d\">\n", p->item_ID);
gf_isom_box_dump_done("PrimaryItemBox", a, trace);
return GF_OK;
}
GF_Err ipro_dump(GF_Box *a, FILE * trace)
{
GF_ItemProtectionBox *p = (GF_ItemProtectionBox *)a;
gf_isom_box_dump_start(a, "ItemProtectionBox", trace);
fprintf(trace, ">\n");
gf_isom_box_array_dump(p->protection_information, trace);
gf_isom_box_dump_done("ItemProtectionBox", a, trace);
return GF_OK;
}
GF_Err infe_dump(GF_Box *a, FILE * trace)
{
GF_ItemInfoEntryBox *p = (GF_ItemInfoEntryBox *)a;
gf_isom_box_dump_start(a, "ItemInfoEntryBox", trace);
fprintf(trace, "item_ID=\"%d\" item_protection_index=\"%d\" item_name=\"%s\" content_type=\"%s\" content_encoding=\"%s\" item_type=\"%s\">\n", p->item_ID, p->item_protection_index, p->item_name, p->content_type, p->content_encoding, gf_4cc_to_str(p->item_type));
gf_isom_box_dump_done("ItemInfoEntryBox", a, trace);
return GF_OK;
}
GF_Err iinf_dump(GF_Box *a, FILE * trace)
{
GF_ItemInfoBox *p = (GF_ItemInfoBox *)a;
gf_isom_box_dump_start(a, "ItemInfoBox", trace);
fprintf(trace, ">\n");
gf_isom_box_array_dump(p->item_infos, trace);
gf_isom_box_dump_done("ItemInfoBox", a, trace);
return GF_OK;
}
GF_Err iloc_dump(GF_Box *a, FILE * trace)
{
u32 i, j, count, count2;
GF_ItemLocationBox *p = (GF_ItemLocationBox*)a;
gf_isom_box_dump_start(a, "ItemLocationBox", trace);
fprintf(trace, "offset_size=\"%d\" length_size=\"%d\" base_offset_size=\"%d\" index_size=\"%d\">\n", p->offset_size, p->length_size, p->base_offset_size, p->index_size);
count = gf_list_count(p->location_entries);
for (i=0; i<count; i++) {
GF_ItemLocationEntry *ie = (GF_ItemLocationEntry *)gf_list_get(p->location_entries, i);
count2 = gf_list_count(ie->extent_entries);
fprintf(trace, "<ItemLocationEntry item_ID=\"%d\" data_reference_index=\"%d\" base_offset=\""LLD"\" construction_method=\"%d\">\n", ie->item_ID, ie->data_reference_index, LLD_CAST ie->base_offset, ie->construction_method);
for (j=0; j<count2; j++) {
GF_ItemExtentEntry *iee = (GF_ItemExtentEntry *)gf_list_get(ie->extent_entries, j);
fprintf(trace, "<ItemExtentEntry extent_offset=\""LLD"\" extent_length=\""LLD"\" extent_index=\""LLD"\" />\n", LLD_CAST iee->extent_offset, LLD_CAST iee->extent_length, LLD_CAST iee->extent_index);
}
fprintf(trace, "</ItemLocationEntry>\n");
}
if (!p->size) {
fprintf(trace, "<ItemLocationEntry item_ID=\"\" data_reference_index=\"\" base_offset=\"\" construction_method=\"\">\n");
fprintf(trace, "<ItemExtentEntry extent_offset=\"\" extent_length=\"\" extent_index=\"\" />\n");
fprintf(trace, "</ItemLocationEntry>\n");
}
gf_isom_box_dump_done("ItemLocationBox", a, trace);
return GF_OK;
}
GF_Err iref_dump(GF_Box *a, FILE * trace)
{
GF_ItemReferenceBox *p = (GF_ItemReferenceBox *)a;
gf_isom_box_dump_start(a, "ItemReferenceBox", trace);
fprintf(trace, ">\n");
gf_isom_box_array_dump(p->references, trace);
gf_isom_box_dump_done("ItemReferenceBox", a, trace);
return GF_OK;
}
GF_Err hinf_dump(GF_Box *a, FILE * trace)
{
// GF_HintInfoBox *p = (GF_HintInfoBox *)a;
gf_isom_box_dump_start(a, "HintInfoBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("HintInfoBox", a, trace);
return GF_OK;
}
GF_Err trpy_dump(GF_Box *a, FILE * trace)
{
GF_TRPYBox *p = (GF_TRPYBox *)a;
gf_isom_box_dump_start(a, "LargeTotalRTPBytesBox", trace);
fprintf(trace, "RTPBytesSent=\""LLD"\">\n", LLD_CAST p->nbBytes);
gf_isom_box_dump_done("LargeTotalRTPBytesBox", a, trace);
return GF_OK;
}
GF_Err totl_dump(GF_Box *a, FILE * trace)
{
GF_TOTLBox *p;
p = (GF_TOTLBox *)a;
gf_isom_box_dump_start(a, "TotalRTPBytesBox", trace);
fprintf(trace, "RTPBytesSent=\"%d\">\n", p->nbBytes);
gf_isom_box_dump_done("TotalRTPBytesBox", a, trace);
return GF_OK;
}
GF_Err nump_dump(GF_Box *a, FILE * trace)
{
GF_NUMPBox *p;
p = (GF_NUMPBox *)a;
gf_isom_box_dump_start(a, "LargeTotalPacketBox", trace);
fprintf(trace, "PacketsSent=\""LLD"\">\n", LLD_CAST p->nbPackets);
gf_isom_box_dump_done("LargeTotalPacketBox", a, trace);
return GF_OK;
}
GF_Err npck_dump(GF_Box *a, FILE * trace)
{
GF_NPCKBox *p;
p = (GF_NPCKBox *)a;
gf_isom_box_dump_start(a, "TotalPacketBox", trace);
fprintf(trace, "packetsSent=\"%d\">\n", p->nbPackets);
gf_isom_box_dump_done("TotalPacketBox", a, trace);
return GF_OK;
}
GF_Err tpyl_dump(GF_Box *a, FILE * trace)
{
GF_NTYLBox *p;
p = (GF_NTYLBox *)a;
gf_isom_box_dump_start(a, "LargeTotalMediaBytesBox", trace);
fprintf(trace, "BytesSent=\""LLD"\">\n", LLD_CAST p->nbBytes);
gf_isom_box_dump_done("LargeTotalMediaBytesBox", a, trace);
return GF_OK;
}
GF_Err tpay_dump(GF_Box *a, FILE * trace)
{
GF_TPAYBox *p;
p = (GF_TPAYBox *)a;
gf_isom_box_dump_start(a, "TotalMediaBytesBox", trace);
fprintf(trace, "BytesSent=\"%d\">\n", p->nbBytes);
gf_isom_box_dump_done("TotalMediaBytesBox", a, trace);
return GF_OK;
}
GF_Err maxr_dump(GF_Box *a, FILE * trace)
{
GF_MAXRBox *p;
p = (GF_MAXRBox *)a;
gf_isom_box_dump_start(a, "MaxDataRateBox", trace);
fprintf(trace, "MaxDataRate=\"%d\" Granularity=\"%d\">\n", p->maxDataRate, p->granularity);
gf_isom_box_dump_done("MaxDataRateBox", a, trace);
return GF_OK;
}
GF_Err dmed_dump(GF_Box *a, FILE * trace)
{
GF_DMEDBox *p;
p = (GF_DMEDBox *)a;
gf_isom_box_dump_start(a, "BytesFromMediaTrackBox", trace);
fprintf(trace, "BytesSent=\""LLD"\">\n", LLD_CAST p->nbBytes);
gf_isom_box_dump_done("BytesFromMediaTrackBox", a, trace);
return GF_OK;
}
GF_Err dimm_dump(GF_Box *a, FILE * trace)
{
GF_DIMMBox *p;
p = (GF_DIMMBox *)a;
gf_isom_box_dump_start(a, "ImmediateDataBytesBox", trace);
fprintf(trace, "BytesSent=\""LLD"\">\n", LLD_CAST p->nbBytes);
gf_isom_box_dump_done("ImmediateDataBytesBox", a, trace);
return GF_OK;
}
GF_Err drep_dump(GF_Box *a, FILE * trace)
{
GF_DREPBox *p;
p = (GF_DREPBox *)a;
gf_isom_box_dump_start(a, "RepeatedDataBytesBox", trace);
fprintf(trace, "RepeatedBytes=\""LLD"\">\n", LLD_CAST p->nbBytes);
gf_isom_box_dump_done("RepeatedDataBytesBox", a, trace);
return GF_OK;
}
GF_Err tssy_dump(GF_Box *a, FILE * trace)
{
GF_TimeStampSynchronyBox *p = (GF_TimeStampSynchronyBox *)a;
gf_isom_box_dump_start(a, "TimeStampSynchronyBox", trace);
fprintf(trace, "timestamp_sync=\"%d\">\n", p->timestamp_sync);
gf_isom_box_dump_done("TimeStampSynchronyBox", a, trace);
return GF_OK;
}
GF_Err rssr_dump(GF_Box *a, FILE * trace)
{
GF_ReceivedSsrcBox *p = (GF_ReceivedSsrcBox *)a;
gf_isom_box_dump_start(a, "ReceivedSsrcBox", trace);
fprintf(trace, "SSRC=\"%d\">\n", p->ssrc);
gf_isom_box_dump_done("ReceivedSsrcBox", a, trace);
return GF_OK;
}
GF_Err tmin_dump(GF_Box *a, FILE * trace)
{
GF_TMINBox *p;
p = (GF_TMINBox *)a;
gf_isom_box_dump_start(a, "MinTransmissionTimeBox", trace);
fprintf(trace, "MinimumTransmitTime=\"%d\">\n", p->minTime);
gf_isom_box_dump_done("MinTransmissionTimeBox", a, trace);
return GF_OK;
}
GF_Err tmax_dump(GF_Box *a, FILE * trace)
{
GF_TMAXBox *p;
p = (GF_TMAXBox *)a;
gf_isom_box_dump_start(a, "MaxTransmissionTimeBox", trace);
fprintf(trace, "MaximumTransmitTime=\"%d\">\n", p->maxTime);
gf_isom_box_dump_done("MaxTransmissionTimeBox", a, trace);
return GF_OK;
}
GF_Err pmax_dump(GF_Box *a, FILE * trace)
{
GF_PMAXBox *p;
p = (GF_PMAXBox *)a;
gf_isom_box_dump_start(a, "MaxPacketSizeBox", trace);
fprintf(trace, "MaximumSize=\"%d\">\n", p->maxSize);
gf_isom_box_dump_done("MaxPacketSizeBox", a, trace);
return GF_OK;
}
GF_Err dmax_dump(GF_Box *a, FILE * trace)
{
GF_DMAXBox *p;
p = (GF_DMAXBox *)a;
gf_isom_box_dump_start(a, "MaxPacketDurationBox", trace);
fprintf(trace, "MaximumDuration=\"%d\">\n", p->maxDur);
gf_isom_box_dump_done("MaxPacketDurationBox", a, trace);
return GF_OK;
}
GF_Err payt_dump(GF_Box *a, FILE * trace)
{
GF_PAYTBox *p;
p = (GF_PAYTBox *)a;
gf_isom_box_dump_start(a, "PayloadTypeBox", trace);
fprintf(trace, "PayloadID=\"%d\" PayloadString=\"%s\">\n", p->payloadCode, p->payloadString);
gf_isom_box_dump_done("PayloadTypeBox", a, trace);
return GF_OK;
}
GF_Err name_dump(GF_Box *a, FILE * trace)
{
GF_NameBox *p;
p = (GF_NameBox *)a;
gf_isom_box_dump_start(a, "NameBox", trace);
fprintf(trace, "Name=\"%s\">\n", p->string);
gf_isom_box_dump_done("NameBox", a, trace);
return GF_OK;
}
GF_Err rely_dump(GF_Box *a, FILE * trace)
{
GF_RelyHintBox *p;
p = (GF_RelyHintBox *)a;
gf_isom_box_dump_start(a, "RelyTransmissionBox", trace);
fprintf(trace, "Prefered=\"%d\" required=\"%d\">\n", p->prefered, p->required);
gf_isom_box_dump_done("RelyTransmissionBox", a, trace);
return GF_OK;
}
GF_Err snro_dump(GF_Box *a, FILE * trace)
{
GF_SeqOffHintEntryBox *p;
p = (GF_SeqOffHintEntryBox *)a;
gf_isom_box_dump_start(a, "PacketSequenceOffsetBox", trace);
fprintf(trace, "SeqNumOffset=\"%d\">\n", p->SeqOffset);
gf_isom_box_dump_done("PacketSequenceOffsetBox", a, trace);
return GF_OK;
}
GF_Err tims_dump(GF_Box *a, FILE * trace)
{
GF_TSHintEntryBox *p;
p = (GF_TSHintEntryBox *)a;
gf_isom_box_dump_start(a, "RTPTimeScaleBox", trace);
fprintf(trace, "TimeScale=\"%d\">\n", p->timeScale);
gf_isom_box_dump_done("RTPTimeScaleBox", a, trace);
return GF_OK;
}
GF_Err tsro_dump(GF_Box *a, FILE * trace)
{
GF_TimeOffHintEntryBox *p;
p = (GF_TimeOffHintEntryBox *)a;
gf_isom_box_dump_start(a, "TimeStampOffsetBox", trace);
fprintf(trace, "TimeStampOffset=\"%d\">\n", p->TimeOffset);
gf_isom_box_dump_done("TimeStampOffsetBox", a, trace);
return GF_OK;
}
GF_Err ghnt_dump(GF_Box *a, FILE * trace)
{
char *name;
GF_HintSampleEntryBox *p;
p = (GF_HintSampleEntryBox *)a;
if (a->type == GF_ISOM_BOX_TYPE_RTP_STSD) {
name = "RTPHintSampleEntryBox";
} else if (a->type == GF_ISOM_BOX_TYPE_SRTP_STSD) {
name = "SRTPHintSampleEntryBox";
} else if (a->type == GF_ISOM_BOX_TYPE_FDP_STSD) {
name = "FDPHintSampleEntryBox";
} else if (a->type == GF_ISOM_BOX_TYPE_RRTP_STSD) {
name = "RTPReceptionHintSampleEntryBox";
} else if (a->type == GF_ISOM_BOX_TYPE_RTCP_STSD) {
name = "RTCPReceptionHintSampleEntryBox";
} else {
name = "GenericHintSampleEntryBox";
}
gf_isom_box_dump_start(a, name, trace);
fprintf(trace, "DataReferenceIndex=\"%d\" HintTrackVersion=\"%d\" LastCompatibleVersion=\"%d\"", p->dataReferenceIndex, p->HintTrackVersion, p->LastCompatibleVersion);
if ((a->type == GF_ISOM_BOX_TYPE_RTP_STSD) || (a->type == GF_ISOM_BOX_TYPE_SRTP_STSD) || (a->type == GF_ISOM_BOX_TYPE_RRTP_STSD) || (a->type == GF_ISOM_BOX_TYPE_RTCP_STSD)) {
fprintf(trace, " MaxPacketSize=\"%d\"", p->MaxPacketSize);
} else if (a->type == GF_ISOM_BOX_TYPE_FDP_STSD) {
fprintf(trace, " partition_entry_ID=\"%d\" FEC_overhead=\"%d\"", p->partition_entry_ID, p->FEC_overhead);
}
fprintf(trace, ">\n");
gf_isom_box_dump_done(name, a, trace);
return GF_OK;
}
GF_Err hnti_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "HintTrackInfoBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("HintTrackInfoBox", NULL, trace);
return GF_OK;
}
GF_Err sdp_dump(GF_Box *a, FILE * trace)
{
GF_SDPBox *p = (GF_SDPBox *)a;
gf_isom_box_dump_start(a, "SDPBox", trace);
fprintf(trace, ">\n");
if (p->sdpText)
fprintf(trace, "<!-- sdp text: %s -->\n", p->sdpText);
gf_isom_box_dump_done("SDPBox", a, trace);
return GF_OK;
}
GF_Err rtp_hnti_dump(GF_Box *a, FILE * trace)
{
GF_RTPBox *p = (GF_RTPBox *)a;
gf_isom_box_dump_start(a, "RTPMovieHintInformationBox", trace);
fprintf(trace, "descriptionformat=\"%s\">\n", gf_4cc_to_str(p->subType));
if (p->sdpText)
fprintf(trace, "<!-- sdp text: %s -->\n", p->sdpText);
gf_isom_box_dump_done("RTPMovieHintInformationBox", a, trace);
return GF_OK;
}
GF_Err rtpo_dump(GF_Box *a, FILE * trace)
{
GF_RTPOBox *p;
p = (GF_RTPOBox *)a;
gf_isom_box_dump_start(a, "RTPTimeOffsetBox", trace);
fprintf(trace, "PacketTimeOffset=\"%d\">\n", p->timeOffset);
gf_isom_box_dump_done("RTPTimeOffsetBox", a, trace);
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
GF_Err mvex_dump(GF_Box *a, FILE * trace)
{
GF_MovieExtendsBox *p;
p = (GF_MovieExtendsBox *)a;
gf_isom_box_dump_start(a, "MovieExtendsBox", trace);
fprintf(trace, ">\n");
if (p->mehd) gf_isom_box_dump(p->mehd, trace);
gf_isom_box_array_dump(p->TrackExList, trace);
gf_isom_box_array_dump(p->TrackExPropList, trace);
gf_isom_box_dump_done("MovieExtendsBox", a, trace);
return GF_OK;
}
GF_Err mehd_dump(GF_Box *a, FILE * trace)
{
GF_MovieExtendsHeaderBox *p = (GF_MovieExtendsHeaderBox*)a;
gf_isom_box_dump_start(a, "MovieExtendsHeaderBox", trace);
fprintf(trace, "fragmentDuration=\""LLD"\" >\n", LLD_CAST p->fragment_duration);
gf_isom_box_dump_done("MovieExtendsHeaderBox", a, trace);
return GF_OK;
}
void sample_flags_dump(const char *name, u32 sample_flags, FILE * trace)
{
fprintf(trace, "<%s", name);
fprintf(trace, " IsLeading=\"%d\"", GF_ISOM_GET_FRAG_LEAD(sample_flags) );
fprintf(trace, " SampleDependsOn=\"%d\"", GF_ISOM_GET_FRAG_DEPENDS(sample_flags) );
fprintf(trace, " SampleIsDependedOn=\"%d\"", GF_ISOM_GET_FRAG_DEPENDED(sample_flags) );
fprintf(trace, " SampleHasRedundancy=\"%d\"", GF_ISOM_GET_FRAG_REDUNDANT(sample_flags) );
fprintf(trace, " SamplePadding=\"%d\"", GF_ISOM_GET_FRAG_PAD(sample_flags) );
fprintf(trace, " SampleSync=\"%d\"", GF_ISOM_GET_FRAG_SYNC(sample_flags));
fprintf(trace, " SampleDegradationPriority=\"%d\"", GF_ISOM_GET_FRAG_DEG(sample_flags));
fprintf(trace, "/>\n");
}
GF_Err trex_dump(GF_Box *a, FILE * trace)
{
GF_TrackExtendsBox *p;
p = (GF_TrackExtendsBox *)a;
gf_isom_box_dump_start(a, "TrackExtendsBox", trace);
fprintf(trace, "TrackID=\"%d\"", p->trackID);
fprintf(trace, " SampleDescriptionIndex=\"%d\" SampleDuration=\"%d\" SampleSize=\"%d\"", p->def_sample_desc_index, p->def_sample_duration, p->def_sample_size);
fprintf(trace, ">\n");
sample_flags_dump("DefaultSampleFlags", p->def_sample_flags, trace);
gf_isom_box_dump_done("TrackExtendsBox", a, trace);
return GF_OK;
}
GF_Err trep_dump(GF_Box *a, FILE * trace)
{
GF_TrackExtensionPropertiesBox *p = (GF_TrackExtensionPropertiesBox*)a;
gf_isom_box_dump_start(a, "TrackExtensionPropertiesBox", trace);
fprintf(trace, "TrackID=\"%d\">\n", p->trackID);
gf_isom_box_dump_done("TrackExtensionPropertiesBox", a, trace);
return GF_OK;
}
GF_Err moof_dump(GF_Box *a, FILE * trace)
{
GF_MovieFragmentBox *p;
p = (GF_MovieFragmentBox *)a;
gf_isom_box_dump_start(a, "MovieFragmentBox", trace);
fprintf(trace, "TrackFragments=\"%d\">\n", gf_list_count(p->TrackList));
if (p->mfhd) gf_isom_box_dump(p->mfhd, trace);
gf_isom_box_array_dump(p->TrackList, trace);
gf_isom_box_dump_done("MovieFragmentBox", a, trace);
return GF_OK;
}
GF_Err mfhd_dump(GF_Box *a, FILE * trace)
{
GF_MovieFragmentHeaderBox *p;
p = (GF_MovieFragmentHeaderBox *)a;
gf_isom_box_dump_start(a, "MovieFragmentHeaderBox", trace);
fprintf(trace, "FragmentSequenceNumber=\"%d\">\n", p->sequence_number);
gf_isom_box_dump_done("MovieFragmentHeaderBox", a, trace);
return GF_OK;
}
GF_Err traf_dump(GF_Box *a, FILE * trace)
{
GF_TrackFragmentBox *p;
p = (GF_TrackFragmentBox *)a;
gf_isom_box_dump_start(a, "TrackFragmentBox", trace);
fprintf(trace, ">\n");
if (p->tfhd) gf_isom_box_dump(p->tfhd, trace);
if (p->sdtp) gf_isom_box_dump(p->sdtp, trace);
if (p->tfdt) gf_isom_box_dump(p->tfdt, trace);
if (p->sub_samples) gf_isom_box_array_dump(p->sub_samples, trace);
if (p->sampleGroupsDescription) gf_isom_box_array_dump(p->sampleGroupsDescription, trace);
if (p->sampleGroups) gf_isom_box_array_dump(p->sampleGroups, trace);
gf_isom_box_array_dump(p->TrackRuns, trace);
if (p->sai_sizes) gf_isom_box_array_dump(p->sai_sizes, trace);
if (p->sai_offsets) gf_isom_box_array_dump(p->sai_offsets, trace);
if (p->sample_encryption) gf_isom_box_dump(p->sample_encryption, trace);
gf_isom_box_dump_done("TrackFragmentBox", a, trace);
return GF_OK;
}
static void frag_dump_sample_flags(FILE * trace, u32 flags)
{
fprintf(trace, " SamplePadding=\"%d\" Sync=\"%d\" DegradationPriority=\"%d\" IsLeading=\"%d\" DependsOn=\"%d\" IsDependedOn=\"%d\" HasRedundancy=\"%d\"",
GF_ISOM_GET_FRAG_PAD(flags), GF_ISOM_GET_FRAG_SYNC(flags), GF_ISOM_GET_FRAG_DEG(flags),
GF_ISOM_GET_FRAG_LEAD(flags), GF_ISOM_GET_FRAG_DEPENDS(flags), GF_ISOM_GET_FRAG_DEPENDED(flags), GF_ISOM_GET_FRAG_REDUNDANT(flags));
}
GF_Err tfhd_dump(GF_Box *a, FILE * trace)
{
GF_TrackFragmentHeaderBox *p;
p = (GF_TrackFragmentHeaderBox *)a;
gf_isom_box_dump_start(a, "TrackFragmentHeaderBox", trace);
fprintf(trace, "TrackID=\"%u\"", p->trackID);
if (p->flags & GF_ISOM_TRAF_BASE_OFFSET) {
fprintf(trace, " BaseDataOffset=\""LLU"\"", p->base_data_offset);
} else {
fprintf(trace, " BaseDataOffset=\"%s\"", (p->flags & GF_ISOM_MOOF_BASE_OFFSET) ? "moof" : "moof-or-previous-traf");
}
if (p->flags & GF_ISOM_TRAF_SAMPLE_DESC)
fprintf(trace, " SampleDescriptionIndex=\"%u\"", p->sample_desc_index);
if (p->flags & GF_ISOM_TRAF_SAMPLE_DUR)
fprintf(trace, " SampleDuration=\"%u\"", p->def_sample_duration);
if (p->flags & GF_ISOM_TRAF_SAMPLE_SIZE)
fprintf(trace, " SampleSize=\"%u\"", p->def_sample_size);
if (p->flags & GF_ISOM_TRAF_SAMPLE_FLAGS) {
frag_dump_sample_flags(trace, p->def_sample_flags);
}
fprintf(trace, ">\n");
gf_isom_box_dump_done("TrackFragmentHeaderBox", a, trace);
return GF_OK;
}
GF_Err tfxd_dump(GF_Box *a, FILE * trace)
{
GF_MSSTimeExtBox *ptr = (GF_MSSTimeExtBox*)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "MSSTimeExtensionBox", trace);
fprintf(trace, "AbsoluteTime=\""LLU"\" FragmentDuration=\""LLU"\">\n", ptr->absolute_time_in_track_timescale, ptr->fragment_duration_in_track_timescale);
fprintf(trace, "<FullBoxInfo Version=\"%d\" Flags=\"%d\"/>\n", ptr->version, ptr->flags);
gf_isom_box_dump_done("MSSTimeExtensionBox", a, trace);
return GF_OK;
}
GF_Err trun_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_TrunEntry *ent;
GF_TrackFragmentRunBox *p;
p = (GF_TrackFragmentRunBox *)a;
gf_isom_box_dump_start(a, "TrackRunBox", trace);
fprintf(trace, "SampleCount=\"%d\"", p->sample_count);
if (p->flags & GF_ISOM_TRUN_DATA_OFFSET)
fprintf(trace, " DataOffset=\"%d\"", p->data_offset);
fprintf(trace, ">\n");
if (p->flags & GF_ISOM_TRUN_FIRST_FLAG) {
sample_flags_dump("FirstSampleFlags", p->first_sample_flags, trace);
}
if (p->flags & (GF_ISOM_TRUN_DURATION|GF_ISOM_TRUN_SIZE|GF_ISOM_TRUN_CTS_OFFSET|GF_ISOM_TRUN_FLAGS)) {
i=0;
while ((ent = (GF_TrunEntry *)gf_list_enum(p->entries, &i))) {
fprintf(trace, "<TrackRunEntry");
if (p->flags & GF_ISOM_TRUN_DURATION)
fprintf(trace, " Duration=\"%u\"", ent->Duration);
if (p->flags & GF_ISOM_TRUN_SIZE)
fprintf(trace, " Size=\"%u\"", ent->size);
if (p->flags & GF_ISOM_TRUN_CTS_OFFSET)
{
if (p->version == 0)
fprintf(trace, " CTSOffset=\"%u\"", (u32) ent->CTS_Offset);
else
fprintf(trace, " CTSOffset=\"%d\"", ent->CTS_Offset);
}
if (p->flags & GF_ISOM_TRUN_FLAGS) {
frag_dump_sample_flags(trace, ent->flags);
}
fprintf(trace, "/>\n");
}
} else if (p->size) {
fprintf(trace, "<!-- all default values used -->\n");
} else {
fprintf(trace, "<TrackRunEntry Duration=\"\" Size=\"\" CTSOffset=\"\"");
frag_dump_sample_flags(trace, 0);
fprintf(trace, "/>\n");
}
gf_isom_box_dump_done("TrackRunBox", a, trace);
return GF_OK;
}
#endif
#ifndef GPAC_DISABLE_ISOM_HINTING
GF_Err DTE_Dump(GF_List *dte, FILE * trace)
{
GF_GenericDTE *p;
GF_ImmediateDTE *i_p;
GF_SampleDTE *s_p;
GF_StreamDescDTE *sd_p;
u32 i, count;
count = gf_list_count(dte);
for (i=0; i<count; i++) {
p = (GF_GenericDTE *)gf_list_get(dte, i);
switch (p->source) {
case 0:
fprintf(trace, "<EmptyDataEntry/>\n");
break;
case 1:
i_p = (GF_ImmediateDTE *) p;
fprintf(trace, "<ImmediateDataEntry DataSize=\"%d\"/>\n", i_p->dataLength);
break;
case 2:
s_p = (GF_SampleDTE *) p;
fprintf(trace, "<SampleDataEntry DataSize=\"%d\" SampleOffset=\"%d\" SampleNumber=\"%d\" TrackReference=\"%d\"/>\n",
s_p->dataLength, s_p->byteOffset, s_p->sampleNumber, s_p->trackRefIndex);
break;
case 3:
sd_p = (GF_StreamDescDTE *) p;
fprintf(trace, "<SampleDescriptionEntry DataSize=\"%d\" DescriptionOffset=\"%d\" StreamDescriptionindex=\"%d\" TrackReference=\"%d\"/>\n",
sd_p->dataLength, sd_p->byteOffset, sd_p->streamDescIndex, sd_p->trackRefIndex);
break;
default:
fprintf(trace, "<UnknownTableEntry/>\n");
break;
}
}
return GF_OK;
}
GF_EXPORT
GF_Err gf_isom_dump_hint_sample(GF_ISOFile *the_file, u32 trackNumber, u32 SampleNum, FILE * trace)
{
GF_ISOSample *tmp;
GF_HintSampleEntryBox *entry;
u32 descIndex, count, count2, i;
GF_Err e=GF_OK;
GF_BitStream *bs;
GF_HintSample *s;
GF_TrackBox *trak;
GF_RTPPacket *pck;
char *szName;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak || !IsHintTrack(trak)) return GF_BAD_PARAM;
tmp = gf_isom_get_sample(the_file, trackNumber, SampleNum, &descIndex);
if (!tmp) return GF_BAD_PARAM;
e = Media_GetSampleDesc(trak->Media, descIndex, (GF_SampleEntryBox **) &entry, &count);
if (e) {
gf_isom_sample_del(&tmp);
return e;
}
//check we can read the sample
switch (entry->type) {
case GF_ISOM_BOX_TYPE_RTP_STSD:
case GF_ISOM_BOX_TYPE_SRTP_STSD:
case GF_ISOM_BOX_TYPE_RRTP_STSD:
szName = "RTP";
break;
case GF_ISOM_BOX_TYPE_RTCP_STSD:
szName = "RCTP";
break;
case GF_ISOM_BOX_TYPE_FDP_STSD:
szName = "FDP";
break;
default:
gf_isom_sample_del(&tmp);
return GF_NOT_SUPPORTED;
}
bs = gf_bs_new(tmp->data, tmp->dataLength, GF_BITSTREAM_READ);
s = gf_isom_hint_sample_new(entry->type);
s->trackID = trak->Header->trackID;
s->sampleNumber = SampleNum;
gf_isom_hint_sample_read(s, bs, tmp->dataLength);
gf_bs_del(bs);
count = gf_list_count(s->packetTable);
fprintf(trace, "<%sHintSample SampleNumber=\"%d\" DecodingTime=\""LLD"\" RandomAccessPoint=\"%d\" PacketCount=\"%u\" reserved=\"%u\">\n", szName, SampleNum, LLD_CAST tmp->DTS, tmp->IsRAP, s->packetCount, s->reserved);
if (s->hint_subtype==GF_ISOM_BOX_TYPE_FDP_STSD) {
e = gf_isom_box_dump((GF_Box*) s, trace);
goto err_exit;
}
if (s->packetCount != count) {
fprintf(trace, "<!-- WARNING: Broken %s hint sample, %d entries indicated but only %d parsed -->\n", szName, s->packetCount, count);
}
for (i=0; i<count; i++) {
pck = (GF_RTPPacket *)gf_list_get(s->packetTable, i);
if (pck->hint_subtype==GF_ISOM_BOX_TYPE_RTCP_STSD) {
GF_RTCPPacket *rtcp_pck = (GF_RTCPPacket *) pck;
fprintf(trace, "<RTCPHintPacket PacketNumber=\"%d\" V=\"%d\" P=\"%d\" Count=\"%d\" PayloadType=\"%d\" ",
i+1, rtcp_pck->Version, rtcp_pck->Padding, rtcp_pck->Count, rtcp_pck->PayloadType);
if (rtcp_pck->data) dump_data_attribute(trace, "payload", (char*)rtcp_pck->data, rtcp_pck->length);
fprintf(trace, ">\n");
fprintf(trace, "</RTCPHintPacket>\n");
} else {
fprintf(trace, "<RTPHintPacket PacketNumber=\"%d\" P=\"%d\" X=\"%d\" M=\"%d\" PayloadType=\"%d\"",
i+1, pck->P_bit, pck->X_bit, pck->M_bit, pck->payloadType);
fprintf(trace, " SequenceNumber=\"%d\" RepeatedPacket=\"%d\" DropablePacket=\"%d\" RelativeTransmissionTime=\"%d\" FullPacketSize=\"%d\">\n",
pck->SequenceNumber, pck->R_bit, pck->B_bit, pck->relativeTransTime, gf_isom_hint_rtp_length(pck));
//TLV is made of Boxes
count2 = gf_list_count(pck->TLV);
if (count2) {
fprintf(trace, "<PrivateExtensionTable EntryCount=\"%d\">\n", count2);
gf_isom_box_array_dump(pck->TLV, trace);
fprintf(trace, "</PrivateExtensionTable>\n");
}
//DTE is made of NON boxes
count2 = gf_list_count(pck->DataTable);
if (count2) {
fprintf(trace, "<PacketDataTable EntryCount=\"%d\">\n", count2);
DTE_Dump(pck->DataTable, trace);
fprintf(trace, "</PacketDataTable>\n");
}
fprintf(trace, "</RTPHintPacket>\n");
}
}
err_exit:
fprintf(trace, "</%sHintSample>\n", szName);
gf_isom_sample_del(&tmp);
gf_isom_hint_sample_del(s);
return e;
}
#endif /*GPAC_DISABLE_ISOM_HINTING*/
static void tx3g_dump_box_nobox(FILE * trace, GF_BoxRecord *rec)
{
fprintf(trace, "<TextBox top=\"%d\" left=\"%d\" bottom=\"%d\" right=\"%d\"/>\n", rec->top, rec->left, rec->bottom, rec->right);
}
static void tx3g_print_char_offsets(FILE * trace, u32 start, u32 end, u32 *shift_offset, u32 so_count)
{
u32 i;
if (shift_offset) {
for (i=0; i<so_count; i++) {
if (start>shift_offset[i]) {
start --;
break;
}
}
for (i=0; i<so_count; i++) {
if (end>shift_offset[i]) {
end --;
break;
}
}
}
if (start || end) fprintf(trace, "fromChar=\"%d\" toChar=\"%d\" ", start, end);
}
static void tx3g_dump_style_nobox(FILE * trace, GF_StyleRecord *rec, u32 *shift_offset, u32 so_count)
{
fprintf(trace, "<Style ");
if (rec->startCharOffset || rec->endCharOffset)
tx3g_print_char_offsets(trace, rec->startCharOffset, rec->endCharOffset, shift_offset, so_count);
fprintf(trace, "styles=\"");
if (!rec->style_flags) {
fprintf(trace, "Normal");
} else {
if (rec->style_flags & 1) fprintf(trace, "Bold ");
if (rec->style_flags & 2) fprintf(trace, "Italic ");
if (rec->style_flags & 4) fprintf(trace, "Underlined ");
}
fprintf(trace, "\" fontID=\"%d\" fontSize=\"%d\" ", rec->fontID, rec->font_size);
tx3g_dump_rgba8(trace, "color", rec->text_color);
fprintf(trace, "/>\n");
}
static char *tx3g_format_time(u64 ts, u32 timescale, char *szDur, Bool is_srt)
{
u32 h, m, s, ms;
ts = (u32) (ts*1000 / timescale);
h = (u32) (ts / 3600000);
m = (u32) (ts/ 60000) - h*60;
s = (u32) (ts/1000) - h*3600 - m*60;
ms = (u32) (ts) - h*3600000 - m*60000 - s*1000;
if (is_srt) {
sprintf(szDur, "%02d:%02d:%02d,%03d", h, m, s, ms);
} else {
sprintf(szDur, "%02d:%02d:%02d.%03d", h, m, s, ms);
}
return szDur;
}
static GF_Err gf_isom_dump_ttxt_track(GF_ISOFile *the_file, u32 track, FILE *dump, Bool box_dump)
{
u32 i, j, count, di, nb_descs, shift_offset[20], so_count;
u64 last_DTS;
size_t len;
GF_Box *a;
Bool has_scroll;
char szDur[100];
GF_Tx3gSampleEntryBox *txt;
GF_TrackBox *trak = gf_isom_get_track_from_file(the_file, track);
if (!trak) return GF_BAD_PARAM;
switch (trak->Media->handler->handlerType) {
case GF_ISOM_MEDIA_TEXT:
case GF_ISOM_MEDIA_SUBT:
break;
default:
return GF_BAD_PARAM;
}
txt = (GF_Tx3gSampleEntryBox *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, 0);
switch (txt->type) {
case GF_ISOM_BOX_TYPE_TX3G:
case GF_ISOM_BOX_TYPE_TEXT:
break;
case GF_ISOM_BOX_TYPE_STPP:
case GF_ISOM_BOX_TYPE_SBTT:
default:
return GF_BAD_PARAM;
}
if (box_dump) {
fprintf(dump, "<TextTrack trackID=\"%d\" version=\"1.1\">\n", gf_isom_get_track_id(the_file, track) );
} else {
fprintf(dump, "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
fprintf(dump, "<!-- GPAC 3GPP Text Stream -->\n");
fprintf(dump, "<TextStream version=\"1.1\">\n");
}
fprintf(dump, "<TextStreamHeader width=\"%d\" height=\"%d\" layer=\"%d\" translation_x=\"%d\" translation_y=\"%d\">\n", trak->Header->width >> 16 , trak->Header->height >> 16, trak->Header->layer, trak->Header->matrix[6] >> 16, trak->Header->matrix[7] >> 16);
nb_descs = gf_list_count(trak->Media->information->sampleTable->SampleDescription->other_boxes);
for (i=0; i<nb_descs; i++) {
GF_Tx3gSampleEntryBox *txt = (GF_Tx3gSampleEntryBox *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, i);
if (box_dump) {
gf_isom_box_dump((GF_Box*) txt, dump);
} else if (txt->type==GF_ISOM_BOX_TYPE_TX3G) {
fprintf(dump, "<TextSampleDescription horizontalJustification=\"");
switch (txt->horizontal_justification) {
case 1:
fprintf(dump, "center");
break;
case -1:
fprintf(dump, "right");
break;
default:
fprintf(dump, "left");
break;
}
fprintf(dump, "\" verticalJustification=\"");
switch (txt->vertical_justification) {
case 1:
fprintf(dump, "center");
break;
case -1:
fprintf(dump, "bottom");
break;
default:
fprintf(dump, "top");
break;
}
fprintf(dump, "\" ");
tx3g_dump_rgba8(dump, "backColor", txt->back_color);
fprintf(dump, " verticalText=\"%s\"", (txt->displayFlags & GF_TXT_VERTICAL) ? "yes" : "no");
fprintf(dump, " fillTextRegion=\"%s\"", (txt->displayFlags & GF_TXT_FILL_REGION) ? "yes" : "no");
fprintf(dump, " continuousKaraoke=\"%s\"", (txt->displayFlags & GF_TXT_KARAOKE) ? "yes" : "no");
has_scroll = GF_FALSE;
if (txt->displayFlags & GF_TXT_SCROLL_IN) {
has_scroll = GF_TRUE;
if (txt->displayFlags & GF_TXT_SCROLL_OUT) fprintf(dump, " scroll=\"InOut\"");
else fprintf(dump, " scroll=\"In\"");
} else if (txt->displayFlags & GF_TXT_SCROLL_OUT) {
has_scroll = GF_TRUE;
fprintf(dump, " scroll=\"Out\"");
} else {
fprintf(dump, " scroll=\"None\"");
}
if (has_scroll) {
u32 mode = (txt->displayFlags & GF_TXT_SCROLL_DIRECTION)>>7;
switch (mode) {
case GF_TXT_SCROLL_CREDITS:
fprintf(dump, " scrollMode=\"Credits\"");
break;
case GF_TXT_SCROLL_MARQUEE:
fprintf(dump, " scrollMode=\"Marquee\"");
break;
case GF_TXT_SCROLL_DOWN:
fprintf(dump, " scrollMode=\"Down\"");
break;
case GF_TXT_SCROLL_RIGHT:
fprintf(dump, " scrollMode=\"Right\"");
break;
default:
fprintf(dump, " scrollMode=\"Unknown\"");
break;
}
}
fprintf(dump, ">\n");
fprintf(dump, "<FontTable>\n");
if (txt->font_table) {
for (j=0; j<txt->font_table->entry_count; j++) {
fprintf(dump, "<FontTableEntry fontName=\"%s\" fontID=\"%d\"/>\n", txt->font_table->fonts[j].fontName, txt->font_table->fonts[j].fontID);
}
}
fprintf(dump, "</FontTable>\n");
if ((txt->default_box.bottom == txt->default_box.top) || (txt->default_box.right == txt->default_box.left)) {
txt->default_box.top = txt->default_box.left = 0;
txt->default_box.right = trak->Header->width / 65536;
txt->default_box.bottom = trak->Header->height / 65536;
}
tx3g_dump_box_nobox(dump, &txt->default_box);
tx3g_dump_style_nobox(dump, &txt->default_style, NULL, 0);
fprintf(dump, "</TextSampleDescription>\n");
} else {
GF_TextSampleEntryBox *text = (GF_TextSampleEntryBox *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, i);
fprintf(dump, "<TextSampleDescription horizontalJustification=\"");
switch (text->textJustification) {
case 1:
fprintf(dump, "center");
break;
case -1:
fprintf(dump, "right");
break;
default:
fprintf(dump, "left");
break;
}
fprintf(dump, "\"");
tx3g_dump_rgb16(dump, " backColor", text->background_color);
if ((text->default_box.bottom == text->default_box.top) || (text->default_box.right == text->default_box.left)) {
text->default_box.top = text->default_box.left = 0;
text->default_box.right = trak->Header->width / 65536;
text->default_box.bottom = trak->Header->height / 65536;
}
if (text->displayFlags & GF_TXT_SCROLL_IN) {
if (text->displayFlags & GF_TXT_SCROLL_OUT) fprintf(dump, " scroll=\"InOut\"");
else fprintf(dump, " scroll=\"In\"");
} else if (text->displayFlags & GF_TXT_SCROLL_OUT) {
fprintf(dump, " scroll=\"Out\"");
} else {
fprintf(dump, " scroll=\"None\"");
}
fprintf(dump, ">\n");
tx3g_dump_box_nobox(dump, &text->default_box);
fprintf(dump, "</TextSampleDescription>\n");
}
}
fprintf(dump, "</TextStreamHeader>\n");
last_DTS = 0;
count = gf_isom_get_sample_count(the_file, track);
for (i=0; i<count; i++) {
GF_BitStream *bs;
GF_TextSample *txt;
GF_ISOSample *s = gf_isom_get_sample(the_file, track, i+1, &di);
if (!s) continue;
fprintf(dump, "<TextSample sampleTime=\"%s\" sampleDescriptionIndex=\"%d\"", tx3g_format_time(s->DTS, trak->Media->mediaHeader->timeScale, szDur, GF_FALSE), di);
bs = gf_bs_new(s->data, s->dataLength, GF_BITSTREAM_READ);
txt = gf_isom_parse_texte_sample(bs);
gf_bs_del(bs);
if (!box_dump) {
if (txt->highlight_color) {
fprintf(dump, " ");
tx3g_dump_rgba8(dump, "highlightColor", txt->highlight_color->hil_color);
}
if (txt->scroll_delay) {
Double delay = txt->scroll_delay->scroll_delay;
delay /= trak->Media->mediaHeader->timeScale;
fprintf(dump, " scrollDelay=\"%g\"", delay);
}
if (txt->wrap) fprintf(dump, " wrap=\"%s\"", (txt->wrap->wrap_flag==0x01) ? "Automatic" : "None");
}
so_count = 0;
fprintf(dump, " xml:space=\"preserve\">");
if (!txt->len) {
last_DTS = (u32) trak->Media->mediaHeader->duration;
} else {
unsigned short utf16Line[10000];
last_DTS = s->DTS;
/*UTF16*/
if ((txt->len>2) && ((unsigned char) txt->text[0] == (unsigned char) 0xFE) && ((unsigned char) txt->text[1] == (unsigned char) 0xFF)) {
/*copy 2 more chars because the lib always add 2 '0' at the end for UTF16 end of string*/
memcpy((char *) utf16Line, txt->text+2, sizeof(char) * (txt->len));
len = gf_utf8_wcslen((const u16*)utf16Line);
} else {
char *str;
str = txt->text;
len = gf_utf8_mbstowcs((u16*)utf16Line, 10000, (const char **) &str);
}
if (len != (size_t) -1) {
utf16Line[len] = 0;
for (j=0; j<len; j++) {
if ((utf16Line[j]=='\n') || (utf16Line[j]=='\r') || (utf16Line[j]==0x85) || (utf16Line[j]==0x2028) || (utf16Line[j]==0x2029) ) {
fprintf(dump, "\n");
if ((utf16Line[j]=='\r') && (utf16Line[j+1]=='\n')) {
shift_offset[so_count] = j;
so_count++;
j++;
}
}
else {
switch (utf16Line[j]) {
case '\'':
fprintf(dump, "'");
break;
case '\"':
fprintf(dump, """);
break;
case '&':
fprintf(dump, "&");
break;
case '>':
fprintf(dump, ">");
break;
case '<':
fprintf(dump, "<");
break;
default:
if (utf16Line[j] < 128) {
fprintf(dump, "%c", (u8) utf16Line[j]);
} else {
fprintf(dump, "&#%d;", utf16Line[j]);
}
break;
}
}
}
}
}
if (box_dump) {
if (txt->highlight_color)
gf_isom_box_dump((GF_Box*) txt->highlight_color, dump);
if (txt->scroll_delay)
gf_isom_box_dump((GF_Box*) txt->scroll_delay, dump);
if (txt->wrap)
gf_isom_box_dump((GF_Box*) txt->wrap, dump);
if (txt->box)
gf_isom_box_dump((GF_Box*) txt->box, dump);
if (txt->styles)
gf_isom_box_dump((GF_Box*) txt->styles, dump);
} else {
if (txt->box) tx3g_dump_box_nobox(dump, &txt->box->box);
if (txt->styles) {
for (j=0; j<txt->styles->entry_count; j++) {
tx3g_dump_style_nobox(dump, &txt->styles->styles[j], shift_offset, so_count);
}
}
}
j=0;
while ((a = (GF_Box *)gf_list_enum(txt->others, &j))) {
if (box_dump) {
gf_isom_box_dump((GF_Box*) a, dump);
continue;
}
switch (a->type) {
case GF_ISOM_BOX_TYPE_HLIT:
fprintf(dump, "<Highlight ");
tx3g_print_char_offsets(dump, ((GF_TextHighlightBox *)a)->startcharoffset, ((GF_TextHighlightBox *)a)->endcharoffset, shift_offset, so_count);
fprintf(dump, "/>\n");
break;
case GF_ISOM_BOX_TYPE_HREF:
{
GF_TextHyperTextBox *ht = (GF_TextHyperTextBox *)a;
fprintf(dump, "<HyperLink ");
tx3g_print_char_offsets(dump, ht->startcharoffset, ht->endcharoffset, shift_offset, so_count);
fprintf(dump, "URL=\"%s\" URLToolTip=\"%s\"/>\n", ht->URL ? ht->URL : "", ht->URL_hint ? ht->URL_hint : "");
}
break;
case GF_ISOM_BOX_TYPE_BLNK:
fprintf(dump, "<Blinking ");
tx3g_print_char_offsets(dump, ((GF_TextBlinkBox *)a)->startcharoffset, ((GF_TextBlinkBox *)a)->endcharoffset, shift_offset, so_count);
fprintf(dump, "/>\n");
break;
case GF_ISOM_BOX_TYPE_KROK:
{
u32 k;
Double t;
GF_TextKaraokeBox *krok = (GF_TextKaraokeBox *)a;
t = krok->highlight_starttime;
t /= trak->Media->mediaHeader->timeScale;
fprintf(dump, "<Karaoke startTime=\"%g\">\n", t);
for (k=0; k<krok->nb_entries; k++) {
t = krok->records[k].highlight_endtime;
t /= trak->Media->mediaHeader->timeScale;
fprintf(dump, "<KaraokeRange ");
tx3g_print_char_offsets(dump, krok->records[k].start_charoffset, krok->records[k].end_charoffset, shift_offset, so_count);
fprintf(dump, "endTime=\"%g\"/>\n", t);
}
fprintf(dump, "</Karaoke>\n");
}
break;
}
}
fprintf(dump, "</TextSample>\n");
gf_isom_sample_del(&s);
gf_isom_delete_text_sample(txt);
gf_set_progress("TTXT Extract", i, count);
}
if (last_DTS < trak->Media->mediaHeader->duration) {
fprintf(dump, "<TextSample sampleTime=\"%s\" text=\"\" />\n", tx3g_format_time(trak->Media->mediaHeader->duration, trak->Media->mediaHeader->timeScale, szDur, GF_FALSE));
}
if (box_dump) {
fprintf(dump, "</TextTrack>\n");
} else {
fprintf(dump, "</TextStream>\n");
}
if (count) gf_set_progress("TTXT Extract", count, count);
return GF_OK;
}
static GF_Err gf_isom_dump_srt_track(GF_ISOFile *the_file, u32 track, FILE *dump)
{
u32 i, j, k, count, di, len, ts, cur_frame;
u64 start, end;
GF_Tx3gSampleEntryBox *txtd;
GF_BitStream *bs;
char szDur[100];
GF_TrackBox *trak = gf_isom_get_track_from_file(the_file, track);
if (!trak) return GF_BAD_PARAM;
switch (trak->Media->handler->handlerType) {
case GF_ISOM_MEDIA_TEXT:
case GF_ISOM_MEDIA_SUBT:
break;
default:
return GF_BAD_PARAM;
}
ts = trak->Media->mediaHeader->timeScale;
cur_frame = 0;
end = 0;
count = gf_isom_get_sample_count(the_file, track);
for (i=0; i<count; i++) {
GF_TextSample *txt;
GF_ISOSample *s = gf_isom_get_sample(the_file, track, i+1, &di);
if (!s) continue;
start = s->DTS;
if (s->dataLength==2) {
gf_isom_sample_del(&s);
continue;
}
if (i+1<count) {
GF_ISOSample *next = gf_isom_get_sample_info(the_file, track, i+2, NULL, NULL);
if (next) {
end = next->DTS;
gf_isom_sample_del(&next);
}
} else {
end = gf_isom_get_media_duration(the_file, track) ;
}
cur_frame++;
fprintf(dump, "%d\n", cur_frame);
tx3g_format_time(start, ts, szDur, GF_TRUE);
fprintf(dump, "%s --> ", szDur);
tx3g_format_time(end, ts, szDur, GF_TRUE);
fprintf(dump, "%s\n", szDur);
bs = gf_bs_new(s->data, s->dataLength, GF_BITSTREAM_READ);
txt = gf_isom_parse_texte_sample(bs);
gf_bs_del(bs);
txtd = (GF_Tx3gSampleEntryBox *)gf_list_get(trak->Media->information->sampleTable->SampleDescription->other_boxes, di-1);
if (!txt->len) {
fprintf(dump, "\n");
} else {
u32 styles, char_num, new_styles, color, new_color;
u16 utf16Line[10000];
/*UTF16*/
if ((txt->len>2) && ((unsigned char) txt->text[0] == (unsigned char) 0xFE) && ((unsigned char) txt->text[1] == (unsigned char) 0xFF)) {
memcpy(utf16Line, txt->text+2, sizeof(char)*txt->len);
( ((char *)utf16Line)[txt->len] ) = 0;
len = txt->len;
} else {
u8 *str = (u8 *) (txt->text);
size_t res = gf_utf8_mbstowcs(utf16Line, 10000, (const char **) &str);
if (res==(size_t)-1) return GF_NON_COMPLIANT_BITSTREAM;
len = (u32) res;
utf16Line[len] = 0;
}
char_num = 0;
styles = 0;
new_styles = txtd->default_style.style_flags;
color = new_color = txtd->default_style.text_color;
for (j=0; j<len; j++) {
Bool is_new_line;
if (txt->styles) {
new_styles = txtd->default_style.style_flags;
new_color = txtd->default_style.text_color;
for (k=0; k<txt->styles->entry_count; k++) {
if (txt->styles->styles[k].startCharOffset>char_num) continue;
if (txt->styles->styles[k].endCharOffset<char_num+1) continue;
if (txt->styles->styles[k].style_flags & (GF_TXT_STYLE_ITALIC | GF_TXT_STYLE_BOLD | GF_TXT_STYLE_UNDERLINED)) {
new_styles = txt->styles->styles[k].style_flags;
new_color = txt->styles->styles[k].text_color;
break;
}
}
}
if (new_styles != styles) {
if ((new_styles & GF_TXT_STYLE_BOLD) && !(styles & GF_TXT_STYLE_BOLD)) fprintf(dump, "<b>");
if ((new_styles & GF_TXT_STYLE_ITALIC) && !(styles & GF_TXT_STYLE_ITALIC)) fprintf(dump, "<i>");
if ((new_styles & GF_TXT_STYLE_UNDERLINED) && !(styles & GF_TXT_STYLE_UNDERLINED)) fprintf(dump, "<u>");
if ((styles & GF_TXT_STYLE_UNDERLINED) && !(new_styles & GF_TXT_STYLE_UNDERLINED)) fprintf(dump, "</u>");
if ((styles & GF_TXT_STYLE_ITALIC) && !(new_styles & GF_TXT_STYLE_ITALIC)) fprintf(dump, "</i>");
if ((styles & GF_TXT_STYLE_BOLD) && !(new_styles & GF_TXT_STYLE_BOLD)) fprintf(dump, "</b>");
styles = new_styles;
}
if (new_color != color) {
if (new_color ==txtd->default_style.text_color) {
fprintf(dump, "</font>");
} else {
fprintf(dump, "<font color=\"%s\">", gf_color_get_name(new_color) );
}
color = new_color;
}
/*not sure if styles must be reseted at line breaks in srt...*/
is_new_line = GF_FALSE;
if ((utf16Line[j]=='\n') || (utf16Line[j]=='\r') ) {
if ((utf16Line[j]=='\r') && (utf16Line[j+1]=='\n')) j++;
fprintf(dump, "\n");
is_new_line = GF_TRUE;
}
if (!is_new_line) {
size_t sl;
char szChar[30];
s16 swT[2], *swz;
swT[0] = utf16Line[j];
swT[1] = 0;
swz= (s16 *)swT;
sl = gf_utf8_wcstombs(szChar, 30, (const unsigned short **) &swz);
if (sl == (size_t)-1) sl=0;
szChar[(u32) sl]=0;
fprintf(dump, "%s", szChar);
}
char_num++;
}
new_styles = 0;
if (new_styles != styles) {
if (styles & GF_TXT_STYLE_UNDERLINED) fprintf(dump, "</u>");
if (styles & GF_TXT_STYLE_ITALIC) fprintf(dump, "</i>");
if (styles & GF_TXT_STYLE_BOLD) fprintf(dump, "</b>");
// styles = 0;
}
if (color != txtd->default_style.text_color) {
fprintf(dump, "</font>");
// color = txtd->default_style.text_color;
}
fprintf(dump, "\n");
}
gf_isom_sample_del(&s);
gf_isom_delete_text_sample(txt);
fprintf(dump, "\n");
gf_set_progress("SRT Extract", i, count);
}
if (count) gf_set_progress("SRT Extract", i, count);
return GF_OK;
}
static GF_Err gf_isom_dump_svg_track(GF_ISOFile *the_file, u32 track, FILE *dump)
{
char nhmlFileName[1024];
FILE *nhmlFile;
u32 i, count, di, ts, cur_frame;
u64 start, end;
GF_BitStream *bs;
GF_TrackBox *trak = gf_isom_get_track_from_file(the_file, track);
if (!trak) return GF_BAD_PARAM;
switch (trak->Media->handler->handlerType) {
case GF_ISOM_MEDIA_TEXT:
case GF_ISOM_MEDIA_SUBT:
break;
default:
return GF_BAD_PARAM;
}
strcpy(nhmlFileName, the_file->fileName);
strcat(nhmlFileName, ".nhml");
nhmlFile = gf_fopen(nhmlFileName, "wt");
fprintf(nhmlFile, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
fprintf(nhmlFile, "<NHNTStream streamType=\"3\" objectTypeIndication=\"10\" timeScale=\"%d\" baseMediaFile=\"file.svg\" inRootOD=\"yes\">\n", trak->Media->mediaHeader->timeScale);
fprintf(nhmlFile, "<NHNTSample isRAP=\"yes\" DTS=\"0\" xmlFrom=\"doc.start\" xmlTo=\"text_1.start\"/>\n");
ts = trak->Media->mediaHeader->timeScale;
cur_frame = 0;
end = 0;
fprintf(dump, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
fprintf(dump, "<svg version=\"1.2\" baseProfile=\"tiny\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"%d\" height=\"%d\" fill=\"black\">\n", trak->Header->width >> 16 , trak->Header->height >> 16);
fprintf(dump, "<g transform=\"translate(%d, %d)\" text-anchor=\"middle\">\n", (trak->Header->width >> 16)/2 , (trak->Header->height >> 16)/2);
count = gf_isom_get_sample_count(the_file, track);
for (i=0; i<count; i++) {
GF_TextSample *txt;
GF_ISOSample *s = gf_isom_get_sample(the_file, track, i+1, &di);
if (!s) continue;
start = s->DTS;
if (s->dataLength==2) {
gf_isom_sample_del(&s);
continue;
}
if (i+1<count) {
GF_ISOSample *next = gf_isom_get_sample_info(the_file, track, i+2, NULL, NULL);
if (next) {
end = next->DTS;
gf_isom_sample_del(&next);
}
}
cur_frame++;
bs = gf_bs_new(s->data, s->dataLength, GF_BITSTREAM_READ);
txt = gf_isom_parse_texte_sample(bs);
gf_bs_del(bs);
if (!txt->len) continue;
fprintf(dump, " <text id=\"text_%d\" display=\"none\">%s\n", cur_frame, txt->text);
fprintf(dump, " <set attributeName=\"display\" to=\"inline\" begin=\"%g\" end=\"%g\"/>\n", ((s64)start*1.0)/ts, ((s64)end*1.0)/ts);
fprintf(dump, " <discard begin=\"%g\"/>\n", ((s64)end*1.0)/ts);
fprintf(dump, " </text>\n");
gf_isom_sample_del(&s);
gf_isom_delete_text_sample(txt);
fprintf(dump, "\n");
gf_set_progress("SRT Extract", i, count);
if (i == count - 2) {
fprintf(nhmlFile, "<NHNTSample isRAP=\"no\" DTS=\"%f\" xmlFrom=\"text_%d.start\" xmlTo=\"doc.end\"/>\n", ((s64)start*1.0), cur_frame);
} else {
fprintf(nhmlFile, "<NHNTSample isRAP=\"no\" DTS=\"%f\" xmlFrom=\"text_%d.start\" xmlTo=\"text_%d.start\"/>\n", ((s64)start*1.0), cur_frame, cur_frame+1);
}
}
fprintf(dump, "</g>\n");
fprintf(dump, "</svg>\n");
fprintf(nhmlFile, "</NHNTStream>\n");
gf_fclose(nhmlFile);
if (count) gf_set_progress("SRT Extract", i, count);
return GF_OK;
}
GF_EXPORT
GF_Err gf_isom_text_dump(GF_ISOFile *the_file, u32 track, FILE *dump, GF_TextDumpType dump_type)
{
switch (dump_type) {
case GF_TEXTDUMPTYPE_SVG:
return gf_isom_dump_svg_track(the_file, track, dump);
case GF_TEXTDUMPTYPE_SRT:
return gf_isom_dump_srt_track(the_file, track, dump);
case GF_TEXTDUMPTYPE_TTXT:
case GF_TEXTDUMPTYPE_TTXT_BOXES:
return gf_isom_dump_ttxt_track(the_file, track, dump, (dump_type==GF_TEXTDUMPTYPE_TTXT_BOXES) ? GF_TRUE : GF_FALSE);
default:
return GF_BAD_PARAM;
}
}
/* ISMA 1.0 Encryption and Authentication V 1.0 dump */
GF_Err sinf_dump(GF_Box *a, FILE * trace)
{
GF_ProtectionSchemeInfoBox *p;
p = (GF_ProtectionSchemeInfoBox *)a;
gf_isom_box_dump_start(a, "ProtectionSchemeInfoBox", trace);
fprintf(trace, ">\n");
if (p->size)
gf_isom_box_dump_ex(p->original_format, trace, GF_ISOM_BOX_TYPE_FRMA);
if (p->size)
gf_isom_box_dump_ex(p->scheme_type, trace, GF_ISOM_BOX_TYPE_SCHM);
if (p->size)
gf_isom_box_dump_ex(p->info, trace, GF_ISOM_BOX_TYPE_SCHI);
gf_isom_box_dump_done("ProtectionSchemeInfoBox", a, trace);
return GF_OK;
}
GF_Err frma_dump(GF_Box *a, FILE * trace)
{
GF_OriginalFormatBox *p;
p = (GF_OriginalFormatBox *)a;
gf_isom_box_dump_start(a, "OriginalFormatBox", trace);
fprintf(trace, "data_format=\"%s\">\n", gf_4cc_to_str(p->data_format));
gf_isom_box_dump_done("OriginalFormatBox", a, trace);
return GF_OK;
}
GF_Err schm_dump(GF_Box *a, FILE * trace)
{
GF_SchemeTypeBox *p;
p = (GF_SchemeTypeBox *)a;
gf_isom_box_dump_start(a, "SchemeTypeBox", trace);
fprintf(trace, "scheme_type=\"%s\" scheme_version=\"%d\" ", gf_4cc_to_str(p->scheme_type), p->scheme_version);
if (p->URI) fprintf(trace, "scheme_uri=\"%s\"", p->URI);
fprintf(trace, ">\n");
gf_isom_box_dump_done("SchemeTypeBox", a, trace);
return GF_OK;
}
GF_Err schi_dump(GF_Box *a, FILE * trace)
{
GF_SchemeInformationBox *p;
p = (GF_SchemeInformationBox *)a;
gf_isom_box_dump_start(a, "SchemeInformationBox", trace);
fprintf(trace, ">\n");
if (p->ikms) gf_isom_box_dump(p->ikms, trace);
if (p->isfm) gf_isom_box_dump(p->isfm, trace);
if (p->islt) gf_isom_box_dump(p->islt, trace);
if (p->odkm) gf_isom_box_dump(p->odkm, trace);
if (p->tenc) gf_isom_box_dump(p->tenc, trace);
if (p->adkm) gf_isom_box_dump(p->adkm, trace);
gf_isom_box_dump_done("SchemeInformationBox", a, trace);
return GF_OK;
}
GF_Err iKMS_dump(GF_Box *a, FILE * trace)
{
GF_ISMAKMSBox *p;
p = (GF_ISMAKMSBox *)a;
gf_isom_box_dump_start(a, "KMSBox", trace);
fprintf(trace, "kms_URI=\"%s\">\n", p->URI);
gf_isom_box_dump_done("KMSBox", a, trace);
return GF_OK;
}
GF_Err iSFM_dump(GF_Box *a, FILE * trace)
{
GF_ISMASampleFormatBox *p;
const char *name = (a->type==GF_ISOM_BOX_TYPE_ISFM) ? "ISMASampleFormat" : "OMADRMAUFormatBox";
p = (GF_ISMASampleFormatBox *)a;
gf_isom_box_dump_start(a, name, trace);
fprintf(trace, "selective_encryption=\"%d\" key_indicator_length=\"%d\" IV_length=\"%d\">\n", p->selective_encryption, p->key_indicator_length, p->IV_length);
gf_isom_box_dump_done(name, a, trace);
return GF_OK;
}
GF_Err iSLT_dump(GF_Box *a, FILE * trace)
{
GF_ISMACrypSaltBox *p = (GF_ISMACrypSaltBox *)a;
gf_isom_box_dump_start(a, "ISMACrypSaltBox", trace);
fprintf(trace, "salt=\""LLU"\">\n", p->salt);
gf_isom_box_dump_done("ISMACrypSaltBox", a, trace);
return GF_OK;
}
GF_EXPORT
GF_Err gf_isom_dump_ismacryp_protection(GF_ISOFile *the_file, u32 trackNumber, FILE * trace)
{
u32 i, count;
GF_SampleEntryBox *entry;
GF_Err e;
GF_TrackBox *trak;
trak = gf_isom_get_track_from_file(the_file, trackNumber);
if (!trak) return GF_BAD_PARAM;
fprintf(trace, "<ISMACrypSampleDescriptions>\n");
count = gf_isom_get_sample_description_count(the_file, trackNumber);
for (i=0; i<count; i++) {
e = Media_GetSampleDesc(trak->Media, i+1, (GF_SampleEntryBox **) &entry, NULL);
if (e) return e;
switch (entry->type) {
case GF_ISOM_BOX_TYPE_ENCA:
case GF_ISOM_BOX_TYPE_ENCV:
case GF_ISOM_BOX_TYPE_ENCT:
case GF_ISOM_BOX_TYPE_ENCS:
break;
default:
continue;
}
gf_isom_box_dump(entry, trace);
}
fprintf(trace, "</ISMACrypSampleDescriptions>\n");
return GF_OK;
}
GF_EXPORT
GF_Err gf_isom_dump_ismacryp_sample(GF_ISOFile *the_file, u32 trackNumber, u32 SampleNum, FILE * trace)
{
GF_ISOSample *samp;
GF_ISMASample *isma_samp;
u32 descIndex;
samp = gf_isom_get_sample(the_file, trackNumber, SampleNum, &descIndex);
if (!samp) return GF_BAD_PARAM;
isma_samp = gf_isom_get_ismacryp_sample(the_file, trackNumber, samp, descIndex);
if (!isma_samp) {
gf_isom_sample_del(&samp);
return GF_NOT_SUPPORTED;
}
fprintf(trace, "<ISMACrypSample SampleNumber=\"%d\" DataSize=\"%d\" CompositionTime=\""LLD"\" ", SampleNum, isma_samp->dataLength, LLD_CAST (samp->DTS+samp->CTS_Offset) );
if (samp->CTS_Offset) fprintf(trace, "DecodingTime=\""LLD"\" ", LLD_CAST samp->DTS);
if (gf_isom_has_sync_points(the_file, trackNumber)) fprintf(trace, "RandomAccessPoint=\"%s\" ", samp->IsRAP ? "Yes" : "No");
fprintf(trace, "IsEncrypted=\"%s\" ", (isma_samp->flags & GF_ISOM_ISMA_IS_ENCRYPTED) ? "Yes" : "No");
if (isma_samp->flags & GF_ISOM_ISMA_IS_ENCRYPTED) {
fprintf(trace, "IV=\""LLD"\" ", LLD_CAST isma_samp->IV);
if (isma_samp->key_indicator) dump_data_attribute(trace, "KeyIndicator", (char*)isma_samp->key_indicator, isma_samp->KI_length);
}
fprintf(trace, "/>\n");
gf_isom_sample_del(&samp);
gf_isom_ismacryp_delete_sample(isma_samp);
return GF_OK;
}
/* end of ISMA 1.0 Encryption and Authentication V 1.0 */
/* Apple extensions */
GF_Err ilst_item_dump(GF_Box *a, FILE * trace)
{
GF_BitStream *bs;
u32 val;
Bool no_dump = GF_FALSE;
char *name = "UnknownBox";
GF_ListItemBox *itune = (GF_ListItemBox *)a;
switch (itune->type) {
case GF_ISOM_BOX_TYPE_0xA9NAM:
name = "NameBox";
break;
case GF_ISOM_BOX_TYPE_0xA9CMT:
name = "CommentBox";
break;
case GF_ISOM_BOX_TYPE_0xA9DAY:
name = "CreatedBox";
break;
case GF_ISOM_BOX_TYPE_0xA9ART:
name = "ArtistBox";
break;
case GF_ISOM_BOX_TYPE_0xA9TRK:
name = "TrackBox";
break;
case GF_ISOM_BOX_TYPE_0xA9ALB:
name = "AlbumBox";
break;
case GF_ISOM_BOX_TYPE_0xA9COM:
name = "CompositorBox";
break;
case GF_ISOM_BOX_TYPE_0xA9WRT:
name = "WriterBox";
break;
case GF_ISOM_BOX_TYPE_0xA9TOO:
name = "ToolBox";
break;
case GF_ISOM_BOX_TYPE_0xA9CPY:
name = "CopyrightBox";
break;
case GF_ISOM_BOX_TYPE_0xA9DES:
name = "DescriptionBox";
break;
case GF_ISOM_BOX_TYPE_0xA9GEN:
case GF_ISOM_BOX_TYPE_GNRE:
name = "GenreBox";
break;
case GF_ISOM_BOX_TYPE_aART:
name = "AlbumArtistBox";
break;
case GF_ISOM_BOX_TYPE_PGAP:
name = "GapelessBox";
break;
case GF_ISOM_BOX_TYPE_DISK:
name = "DiskBox";
break;
case GF_ISOM_BOX_TYPE_TRKN:
name = "TrackNumberBox";
break;
case GF_ISOM_BOX_TYPE_TMPO:
name = "TempoBox";
break;
case GF_ISOM_BOX_TYPE_CPIL:
name = "CompilationBox";
break;
case GF_ISOM_BOX_TYPE_COVR:
name = "CoverArtBox";
no_dump = GF_TRUE;
break;
case GF_ISOM_BOX_TYPE_iTunesSpecificInfo:
name = "iTunesSpecificBox";
no_dump = GF_TRUE;
break;
case GF_ISOM_BOX_TYPE_0xA9GRP:
name = "GroupBox";
break;
case GF_ISOM_ITUNE_ENCODER:
name = "EncoderBox";
break;
}
gf_isom_box_dump_start(a, name, trace);
if (!no_dump) {
switch (itune->type) {
case GF_ISOM_BOX_TYPE_DISK:
case GF_ISOM_BOX_TYPE_TRKN:
bs = gf_bs_new(itune->data->data, itune->data->dataSize, GF_BITSTREAM_READ);
gf_bs_read_int(bs, 16);
val = gf_bs_read_int(bs, 16);
if (itune->type==GF_ISOM_BOX_TYPE_DISK) {
fprintf(trace, " DiskNumber=\"%d\" NbDisks=\"%d\" ", val, gf_bs_read_int(bs, 16) );
} else {
fprintf(trace, " TrackNumber=\"%d\" NbTracks=\"%d\" ", val, gf_bs_read_int(bs, 16) );
}
gf_bs_del(bs);
break;
case GF_ISOM_BOX_TYPE_TMPO:
bs = gf_bs_new(itune->data->data, itune->data->dataSize, GF_BITSTREAM_READ);
fprintf(trace, " BPM=\"%d\" ", gf_bs_read_int(bs, 16) );
gf_bs_del(bs);
break;
case GF_ISOM_BOX_TYPE_CPIL:
fprintf(trace, " IsCompilation=\"%s\" ", (itune->data && itune->data->data && itune->data->data[0]) ? "yes" : "no");
break;
case GF_ISOM_BOX_TYPE_PGAP:
fprintf(trace, " IsGapeless=\"%s\" ", (itune->data && itune->data->data && itune->data->data[0]) ? "yes" : "no");
break;
default:
if (strcmp(name, "UnknownBox") && itune->data && itune->data->data) {
fprintf(trace, " value=\"");
if (itune->data && itune->data->data[0]) {
dump_data_string(trace, itune->data->data, itune->data->dataSize);
} else {
dump_data(trace, itune->data->data, itune->data->dataSize);
}
fprintf(trace, "\" ");
}
break;
}
}
fprintf(trace, ">\n");
gf_isom_box_dump_done(name, a, trace);
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_ADOBE
GF_Err abst_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_AdobeBootstrapInfoBox *p = (GF_AdobeBootstrapInfoBox*)a;
gf_isom_box_dump_start(a, "AdobeBootstrapBox", trace);
fprintf(trace, "BootstrapinfoVersion=\"%u\" Profile=\"%u\" Live=\"%u\" Update=\"%u\" TimeScale=\"%u\" CurrentMediaTime=\""LLU"\" SmpteTimeCodeOffset=\""LLU"\" ",
p->bootstrapinfo_version, p->profile, p->live, p->update, p->time_scale, p->current_media_time, p->smpte_time_code_offset);
if (p->movie_identifier)
fprintf(trace, "MovieIdentifier=\"%s\" ", p->movie_identifier);
if (p->drm_data)
fprintf(trace, "DrmData=\"%s\" ", p->drm_data);
if (p->meta_data)
fprintf(trace, "MetaData=\"%s\" ", p->meta_data);
fprintf(trace, ">\n");
for (i=0; i<p->server_entry_count; i++) {
char *str = (char*)gf_list_get(p->server_entry_table, i);
fprintf(trace, "<ServerEntry>%s</ServerEntry>\n", str);
}
for (i=0; i<p->quality_entry_count; i++) {
char *str = (char*)gf_list_get(p->quality_entry_table, i);
fprintf(trace, "<QualityEntry>%s</QualityEntry>\n", str);
}
for (i=0; i<p->segment_run_table_count; i++)
gf_isom_box_dump(gf_list_get(p->segment_run_table_entries, i), trace);
for (i=0; i<p->fragment_run_table_count; i++)
gf_isom_box_dump(gf_list_get(p->fragment_run_table_entries, i), trace);
gf_isom_box_dump_done("AdobeBootstrapBox", a, trace);
return GF_OK;
}
GF_Err afra_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_AdobeFragRandomAccessBox *p = (GF_AdobeFragRandomAccessBox*)a;
gf_isom_box_dump_start(a, "AdobeFragmentRandomAccessBox", trace);
fprintf(trace, "LongIDs=\"%u\" LongOffsets=\"%u\" TimeScale=\"%u\">\n", p->long_ids, p->long_offsets, p->time_scale);
for (i=0; i<p->entry_count; i++) {
GF_AfraEntry *ae = (GF_AfraEntry *)gf_list_get(p->local_access_entries, i);
fprintf(trace, "<LocalAccessEntry Time=\""LLU"\" Offset=\""LLU"\"/>\n", ae->time, ae->offset);
}
for (i=0; i<p->global_entry_count; i++) {
GF_GlobalAfraEntry *gae = (GF_GlobalAfraEntry *)gf_list_get(p->global_access_entries, i);
fprintf(trace, "<GlobalAccessEntry Time=\""LLU"\" Segment=\"%u\" Fragment=\"%u\" AfraOffset=\""LLU"\" OffsetFromAfra=\""LLU"\"/>\n",
gae->time, gae->segment, gae->fragment, gae->afra_offset, gae->offset_from_afra);
}
gf_isom_box_dump_done("AdobeFragmentRandomAccessBox", a, trace);
return GF_OK;
}
GF_Err afrt_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_AdobeFragmentRunTableBox *p = (GF_AdobeFragmentRunTableBox*)a;
gf_isom_box_dump_start(a, "AdobeFragmentRunTableBox", trace);
fprintf(trace, "TimeScale=\"%u\">\n", p->timescale);
for (i=0; i<p->quality_entry_count; i++) {
char *str = (char*)gf_list_get(p->quality_segment_url_modifiers, i);
fprintf(trace, "<QualityEntry>%s</QualityEntry>\n", str);
}
for (i=0; i<p->fragment_run_entry_count; i++) {
GF_AdobeFragmentRunEntry *fre = (GF_AdobeFragmentRunEntry *)gf_list_get(p->fragment_run_entry_table, i);
fprintf(trace, "<FragmentRunEntry FirstFragment=\"%u\" FirstFragmentTimestamp=\""LLU"\" FirstFragmentDuration=\"%u\"", fre->first_fragment, fre->first_fragment_timestamp, fre->fragment_duration);
if (!fre->fragment_duration)
fprintf(trace, " DiscontinuityIndicator=\"%u\"", fre->discontinuity_indicator);
fprintf(trace, "/>\n");
}
gf_isom_box_dump_done("AdobeFragmentRunTableBox", a, trace);
return GF_OK;
}
GF_Err asrt_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_AdobeSegmentRunTableBox *p = (GF_AdobeSegmentRunTableBox*)a;
gf_isom_box_dump_start(a, "AdobeSegmentRunTableBox", trace);
fprintf(trace, ">\n");
for (i=0; i<p->quality_entry_count; i++) {
char *str = (char*)gf_list_get(p->quality_segment_url_modifiers, i);
fprintf(trace, "<QualityEntry>%s</QualityEntry>\n", str);
}
for (i=0; i<p->segment_run_entry_count; i++) {
GF_AdobeSegmentRunEntry *sre = (GF_AdobeSegmentRunEntry *)gf_list_get(p->segment_run_entry_table, i);
fprintf(trace, "<SegmentRunEntry FirstSegment=\"%u\" FragmentsPerSegment=\"%u\"/>\n", sre->first_segment, sre->fragment_per_segment);
}
gf_isom_box_dump_done("AdobeSegmentRunTableBox", a, trace);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_ADOBE*/
GF_Err ilst_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_Box *tag;
GF_Err e;
GF_ItemListBox *ptr;
ptr = (GF_ItemListBox *)a;
gf_isom_box_dump_start(a, "ItemListBox", trace);
fprintf(trace, ">\n");
i=0;
while ( (tag = (GF_Box*)gf_list_enum(ptr->other_boxes, &i))) {
e = ilst_item_dump(tag, trace);
if(e) return e;
}
gf_isom_box_dump_done("ItemListBox", NULL, trace);
return GF_OK;
}
GF_Err databox_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "data", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("data", a, trace);
return GF_OK;
}
GF_Err ohdr_dump(GF_Box *a, FILE * trace)
{
GF_OMADRMCommonHeaderBox *ptr = (GF_OMADRMCommonHeaderBox *)a;
gf_isom_box_dump_start(a, "OMADRMCommonHeaderBox", trace);
fprintf(trace, "EncryptionMethod=\"%d\" PaddingScheme=\"%d\" PlaintextLength=\""LLD"\" ",
ptr->EncryptionMethod, ptr->PaddingScheme, ptr->PlaintextLength);
if (ptr->RightsIssuerURL) fprintf(trace, "RightsIssuerURL=\"%s\" ", ptr->RightsIssuerURL);
if (ptr->ContentID) fprintf(trace, "ContentID=\"%s\" ", ptr->ContentID);
if (ptr->TextualHeaders) {
u32 i, offset;
char *start = ptr->TextualHeaders;
fprintf(trace, "TextualHeaders=\"");
i=offset=0;
while (i<ptr->TextualHeadersLen) {
if (start[i]==0) {
fprintf(trace, "%s ", start+offset);
offset=i+1;
}
i++;
}
fprintf(trace, "%s\" ", start+offset);
}
fprintf(trace, ">\n");
gf_isom_box_dump_done("OMADRMCommonHeaderBox", a, trace);
return GF_OK;
}
GF_Err grpi_dump(GF_Box *a, FILE * trace)
{
GF_OMADRMGroupIDBox *ptr = (GF_OMADRMGroupIDBox *)a;
gf_isom_box_dump_start(a, "OMADRMGroupIDBox", trace);
fprintf(trace, "GroupID=\"%s\" EncryptionMethod=\"%d\" GroupKey=\" ", ptr->GroupID, ptr->GKEncryptionMethod);
if (ptr->GroupKey)
dump_data(trace, ptr->GroupKey, ptr->GKLength);
fprintf(trace, "\">\n");
gf_isom_box_dump_done("OMADRMGroupIDBox", a, trace);
return GF_OK;
}
GF_Err mdri_dump(GF_Box *a, FILE * trace)
{
//GF_OMADRMMutableInformationBox *ptr = (GF_OMADRMMutableInformationBox*)a;
gf_isom_box_dump_start(a, "OMADRMMutableInformationBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("OMADRMMutableInformationBox", a, trace);
return GF_OK;
}
GF_Err odtt_dump(GF_Box *a, FILE * trace)
{
GF_OMADRMTransactionTrackingBox *ptr = (GF_OMADRMTransactionTrackingBox *)a;
gf_isom_box_dump_start(a, "OMADRMTransactionTrackingBox", trace);
fprintf(trace, "TransactionID=\"");
dump_data(trace, ptr->TransactionID, 16);
fprintf(trace, "\">\n");
gf_isom_box_dump_done("OMADRMTransactionTrackingBox", a, trace);
return GF_OK;
}
GF_Err odrb_dump(GF_Box *a, FILE * trace)
{
GF_OMADRMRightsObjectBox*ptr = (GF_OMADRMRightsObjectBox*)a;
gf_isom_box_dump_start(a, "OMADRMRightsObjectBox", trace);
fprintf(trace, "OMARightsObject=\"");
dump_data(trace, ptr->oma_ro, ptr->oma_ro_size);
fprintf(trace, "\">\n");
gf_isom_box_dump_done("OMADRMRightsObjectBox", a, trace);
return GF_OK;
}
GF_Err odkm_dump(GF_Box *a, FILE * trace)
{
GF_OMADRMKMSBox *ptr = (GF_OMADRMKMSBox*)a;
gf_isom_box_dump_start(a, "OMADRMKMSBox", trace);
fprintf(trace, ">\n");
if (ptr->hdr) gf_isom_box_dump((GF_Box *)ptr->hdr, trace);
if (ptr->fmt) gf_isom_box_dump((GF_Box *)ptr->fmt, trace);
gf_isom_box_dump_done("OMADRMKMSBox", a, trace);
return GF_OK;
}
GF_Err pasp_dump(GF_Box *a, FILE * trace)
{
GF_PixelAspectRatioBox *ptr = (GF_PixelAspectRatioBox*)a;
gf_isom_box_dump_start(a, "PixelAspectRatioBox", trace);
fprintf(trace, "hSpacing=\"%d\" vSpacing=\"%d\" >\n", ptr->hSpacing, ptr->vSpacing);
gf_isom_box_dump_done("PixelAspectRatioBox", a, trace);
return GF_OK;
}
GF_Err clap_dump(GF_Box *a, FILE * trace)
{
GF_CleanAppertureBox *ptr = (GF_CleanAppertureBox*)a;
gf_isom_box_dump_start(a, "CleanAppertureBox", trace);
fprintf(trace, "cleanApertureWidthN=\"%d\" cleanApertureWidthD=\"%d\" ", ptr->cleanApertureWidthN, ptr->cleanApertureWidthD);
fprintf(trace, "cleanApertureHeightN=\"%d\" cleanApertureHeightD=\"%d\" ", ptr->cleanApertureHeightN, ptr->cleanApertureHeightD);
fprintf(trace, "horizOffN=\"%d\" horizOffD=\"%d\" ", ptr->horizOffN, ptr->horizOffD);
fprintf(trace, "vertOffN=\"%d\" vertOffD=\"%d\"", ptr->vertOffN, ptr->vertOffD);
fprintf(trace, ">\n");
gf_isom_box_dump_done("CleanAppertureBox", a, trace);
return GF_OK;
}
GF_Err tsel_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_TrackSelectionBox *ptr = (GF_TrackSelectionBox *)a;
gf_isom_box_dump_start(a, "TrackSelectionBox", trace);
fprintf(trace, "switchGroup=\"%d\" >\n", ptr->switchGroup);
for (i=0; i<ptr->attributeListCount; i++) {
fprintf(trace, "<TrackSelectionCriteria value=\"%s\"/>\n", gf_4cc_to_str(ptr->attributeList[i]) );
}
if (!ptr->size)
fprintf(trace, "<TrackSelectionCriteria value=\"\"/>\n");
gf_isom_box_dump_done("TrackSelectionBox", a, trace);
return GF_OK;
}
GF_Err metx_dump(GF_Box *a, FILE * trace)
{
GF_MetaDataSampleEntryBox *ptr = (GF_MetaDataSampleEntryBox*)a;
const char *name;
switch (ptr->type) {
case GF_ISOM_BOX_TYPE_METX:
name = "XMLMetaDataSampleEntryBox";
break;
case GF_ISOM_BOX_TYPE_METT:
name = "TextMetaDataSampleEntryBox";
break;
case GF_ISOM_BOX_TYPE_SBTT:
name = "SubtitleSampleEntryBox";
break;
case GF_ISOM_BOX_TYPE_STXT:
name = "SimpleTextSampleEntryBox";
break;
case GF_ISOM_BOX_TYPE_STPP:
name = "XMLSubtitleSampleEntryBox";
break;
default:
name = "UnknownTextSampleEntryBox";
break;
}
gf_isom_box_dump_start(a, name, trace);
if (ptr->type==GF_ISOM_BOX_TYPE_METX) {
fprintf(trace, "namespace=\"%s\" ", ptr->xml_namespace);
if (ptr->xml_schema_loc) fprintf(trace, "schema_location=\"%s\" ", ptr->xml_schema_loc);
if (ptr->content_encoding) fprintf(trace, "content_encoding=\"%s\" ", ptr->content_encoding);
} else if (ptr->type==GF_ISOM_BOX_TYPE_STPP) {
fprintf(trace, "namespace=\"%s\" ", ptr->xml_namespace);
if (ptr->xml_schema_loc) fprintf(trace, "schema_location=\"%s\" ", ptr->xml_schema_loc);
if (ptr->mime_type) fprintf(trace, "auxiliary_mime_types=\"%s\" ", ptr->mime_type);
}
//mett, sbtt, stxt
else {
fprintf(trace, "mime_type=\"%s\" ", ptr->mime_type);
if (ptr->content_encoding) fprintf(trace, "content_encoding=\"%s\" ", ptr->content_encoding);
}
fprintf(trace, ">\n");
if ((ptr->type!=GF_ISOM_BOX_TYPE_METX) && (ptr->type!=GF_ISOM_BOX_TYPE_STPP) ) {
if (ptr->config) gf_isom_box_dump(ptr->config, trace);
}
gf_isom_box_array_dump(ptr->protections, trace);
gf_isom_box_dump_done(name, a, trace);
return GF_OK;
}
GF_Err txtc_dump(GF_Box *a, FILE * trace)
{
GF_TextConfigBox *ptr = (GF_TextConfigBox*)a;
const char *name = "TextConfigBox";
gf_isom_box_dump_start(a, name, trace);
fprintf(trace, ">\n");
if (ptr->config) fprintf(trace, "<![CDATA[%s]]>", ptr->config);
gf_isom_box_dump_done(name, a, trace);
return GF_OK;
}
GF_Err dims_dump(GF_Box *a, FILE * trace)
{
GF_DIMSSampleEntryBox *p = (GF_DIMSSampleEntryBox*)a;
gf_isom_box_dump_start(a, "DIMSSampleEntryBox", trace);
fprintf(trace, "dataReferenceIndex=\"%d\">\n", p->dataReferenceIndex);
if (p->config) gf_isom_box_dump(p->config, trace);
if (p->scripts) gf_isom_box_dump(p->scripts, trace);
gf_isom_box_array_dump(p->protections, trace);
gf_isom_box_dump_done("DIMSSampleEntryBox", a, trace);
return GF_OK;
}
GF_Err diST_dump(GF_Box *a, FILE * trace)
{
GF_DIMSScriptTypesBox *p = (GF_DIMSScriptTypesBox*)a;
gf_isom_box_dump_start(a, "DIMSScriptTypesBox", trace);
fprintf(trace, "types=\"%s\">\n", p->content_script_types);
gf_isom_box_dump_done("DIMSScriptTypesBox", a, trace);
return GF_OK;
}
GF_Err dimC_dump(GF_Box *a, FILE * trace)
{
GF_DIMSSceneConfigBox *p = (GF_DIMSSceneConfigBox *)a;
gf_isom_box_dump_start(a, "DIMSSceneConfigBox", trace);
fprintf(trace, "profile=\"%d\" level=\"%d\" pathComponents=\"%d\" useFullRequestHosts=\"%d\" streamType=\"%d\" containsRedundant=\"%d\" textEncoding=\"%s\" contentEncoding=\"%s\" >\n",
p->profile, p->level, p->pathComponents, p->fullRequestHost, p->streamType, p->containsRedundant, p->textEncoding, p->contentEncoding);
gf_isom_box_dump_done("DIMSSceneConfigBox", a, trace);
return GF_OK;
}
GF_Err dac3_dump(GF_Box *a, FILE * trace)
{
GF_AC3ConfigBox *p = (GF_AC3ConfigBox *)a;
if (p->cfg.is_ec3) {
u32 i;
a->type = GF_ISOM_BOX_TYPE_DEC3;
gf_isom_box_dump_start(a, "EC3SpecificBox", trace);
a->type = GF_ISOM_BOX_TYPE_DAC3;
fprintf(trace, "nb_streams=\"%d\" data_rate=\"%d\">\n", p->cfg.nb_streams, p->cfg.brcode);
for (i=0; i<p->cfg.nb_streams; i++) {
fprintf(trace, "<EC3StreamConfig fscod=\"%d\" bsid=\"%d\" bsmod=\"%d\" acmod=\"%d\" lfon=\"%d\" num_sub_dep=\"%d\" chan_loc=\"%d\"/>\n",
p->cfg.streams[i].fscod, p->cfg.streams[i].bsid, p->cfg.streams[i].bsmod, p->cfg.streams[i].acmod, p->cfg.streams[i].lfon, p->cfg.streams[i].nb_dep_sub, p->cfg.streams[i].chan_loc);
}
gf_isom_box_dump_done("EC3SpecificBox", a, trace);
} else {
gf_isom_box_dump_start(a, "AC3SpecificBox", trace);
fprintf(trace, "fscod=\"%d\" bsid=\"%d\" bsmod=\"%d\" acmod=\"%d\" lfon=\"%d\" bit_rate_code=\"%d\">\n",
p->cfg.streams[0].fscod, p->cfg.streams[0].bsid, p->cfg.streams[0].bsmod, p->cfg.streams[0].acmod, p->cfg.streams[0].lfon, p->cfg.brcode);
gf_isom_box_dump_done("AC3SpecificBox", a, trace);
}
return GF_OK;
}
GF_Err lsrc_dump(GF_Box *a, FILE * trace)
{
GF_LASERConfigurationBox *p = (GF_LASERConfigurationBox *)a;
gf_isom_box_dump_start(a, "LASeRConfigurationBox", trace);
dump_data_attribute(trace, "LASeRHeader", p->hdr, p->hdr_size);
fprintf(trace, ">");
gf_isom_box_dump_done("LASeRConfigurationBox", a, trace);
return GF_OK;
}
GF_Err lsr1_dump(GF_Box *a, FILE * trace)
{
GF_LASeRSampleEntryBox *p = (GF_LASeRSampleEntryBox*)a;
gf_isom_box_dump_start(a, "LASeRSampleEntryBox", trace);
fprintf(trace, "DataReferenceIndex=\"%d\">\n", p->dataReferenceIndex);
if (p->lsr_config) gf_isom_box_dump(p->lsr_config, trace);
if (p->descr) gf_isom_box_dump(p->descr, trace);
gf_isom_box_dump_done("LASeRSampleEntryBox", a, trace);
return GF_OK;
}
GF_Err sidx_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SegmentIndexBox *p = (GF_SegmentIndexBox *)a;
gf_isom_box_dump_start(a, "SegmentIndexBox", trace);
fprintf(trace, "reference_ID=\"%d\" timescale=\"%d\" earliest_presentation_time=\""LLD"\" first_offset=\""LLD"\" ", p->reference_ID, p->timescale, p->earliest_presentation_time, p->first_offset);
fprintf(trace, ">\n");
for (i=0; i<p->nb_refs; i++) {
fprintf(trace, "<Reference type=\"%d\" size=\"%d\" duration=\"%d\" startsWithSAP=\"%d\" SAP_type=\"%d\" SAPDeltaTime=\"%d\"/>\n", p->refs[i].reference_type, p->refs[i].reference_size, p->refs[i].subsegment_duration, p->refs[i].starts_with_SAP, p->refs[i].SAP_type, p->refs[i].SAP_delta_time);
}
if (!p->size) {
fprintf(trace, "<Reference type=\"\" size=\"\" duration=\"\" startsWithSAP=\"\" SAP_type=\"\" SAPDeltaTime=\"\"/>\n");
}
gf_isom_box_dump_done("SegmentIndexBox", a, trace);
return GF_OK;
}
GF_Err ssix_dump(GF_Box *a, FILE * trace)
{
u32 i, j;
GF_SubsegmentIndexBox *p = (GF_SubsegmentIndexBox *)a;
gf_isom_box_dump_start(a, "SubsegmentIndexBox", trace);
fprintf(trace, "subsegment_count=\"%d\" >\n", p->subsegment_count);
for (i = 0; i < p->subsegment_count; i++) {
fprintf(trace, "<Subsegment range_count=\"%d\">\n", p->subsegments[i].range_count);
for (j = 0; j < p->subsegments[i].range_count; j++) {
fprintf(trace, "<Range level=\"%d\" range_size=\"%d\"/>\n", p->subsegments[i].levels[j], p->subsegments[i].range_sizes[j]);
}
fprintf(trace, "</Subsegment>\n");
}
if (!p->size) {
fprintf(trace, "<Subsegment range_count=\"\">\n");
fprintf(trace, "<Range level=\"\" range_size=\"\"/>\n");
fprintf(trace, "</Subsegment>\n");
}
gf_isom_box_dump_done("SubsegmentIndexBox", a, trace);
return GF_OK;
}
GF_Err leva_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_LevelAssignmentBox *p = (GF_LevelAssignmentBox *)a;
gf_isom_box_dump_start(a, "LevelAssignmentBox", trace);
fprintf(trace, "level_count=\"%d\" >\n", p->level_count);
for (i = 0; i < p->level_count; i++) {
fprintf(trace, "<Assignement track_id=\"%d\" padding_flag=\"%d\" assignement_type=\"%d\" grouping_type=\"%s\" grouping_type_parameter=\"%d\" sub_track_id=\"%d\" />\n", p->levels[i].track_id, p->levels[i].padding_flag, p->levels[i].type, gf_4cc_to_str(p->levels[i].grouping_type) , p->levels[i].grouping_type_parameter, p->levels[i].sub_track_id);
}
if (!p->size) {
fprintf(trace, "<Assignement track_id=\"\" padding_flag=\"\" assignement_type=\"\" grouping_type=\"\" grouping_type_parameter=\"\" sub_track_id=\"\" />\n");
}
gf_isom_box_dump_done("LevelAssignmentBox", a, trace);
return GF_OK;
}
GF_Err strk_dump(GF_Box *a, FILE * trace)
{
GF_SubTrackBox *p = (GF_SubTrackBox *)a;
gf_isom_box_dump_start(a, "SubTrackBox", trace);
fprintf(trace, ">\n");
if (p->info) {
gf_isom_box_dump(p->info, trace);
}
gf_isom_box_dump_done("SubTrackBox", a, trace);
return GF_OK;
}
GF_Err stri_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SubTrackInformationBox *p = (GF_SubTrackInformationBox *)a;
gf_isom_box_dump_start(a, "SubTrackInformationBox", trace);
fprintf(trace, "switch_group=\"%d\" alternate_group=\"%d\" sub_track_id=\"%d\">\n", p->switch_group, p->alternate_group, p->sub_track_id);
for (i = 0; i < p->attribute_count; i++) {
fprintf(trace, "<SubTrackInformationAttribute value=\"%s\"/>\n", gf_4cc_to_str(p->attribute_list[i]) );
}
if (!p->size)
fprintf(trace, "<SubTrackInformationAttribute value=\"\"/>\n");
gf_isom_box_dump_done("SubTrackInformationBox", a, trace);
return GF_OK;
}
GF_Err stsg_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SubTrackSampleGroupBox *p = (GF_SubTrackSampleGroupBox *)a;
gf_isom_box_dump_start(a, "SubTrackSampleGroupBox", trace);
if (p->grouping_type)
fprintf(trace, "grouping_type=\"%s\"", gf_4cc_to_str(p->grouping_type) );
fprintf(trace, ">\n");
for (i = 0; i < p->nb_groups; i++) {
fprintf(trace, "<SubTrackSampleGroupBoxEntry group_description_index=\"%d\"/>\n", p->group_description_index[i]);
}
if (!p->size)
fprintf(trace, "<SubTrackSampleGroupBoxEntry group_description_index=\"\"/>\n");
gf_isom_box_dump_done("SubTrackSampleGroupBox", a, trace);
return GF_OK;
}
GF_Err pcrb_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_PcrInfoBox *p = (GF_PcrInfoBox *)a;
gf_isom_box_dump_start(a, "MPEG2TSPCRInfoBox", trace);
fprintf(trace, "subsegment_count=\"%d\">\n", p->subsegment_count);
for (i=0; i<p->subsegment_count; i++) {
fprintf(trace, "<PCRInfo PCR=\""LLU"\" />\n", p->pcr_values[i]);
}
if (!p->size) {
fprintf(trace, "<PCRInfo PCR=\"\" />\n");
}
gf_isom_box_dump_done("MPEG2TSPCRInfoBox", a, trace);
return GF_OK;
}
GF_Err subs_dump(GF_Box *a, FILE * trace)
{
u32 entry_count, i, j;
u16 subsample_count;
GF_SubSampleInfoEntry *pSamp;
GF_SubSampleEntry *pSubSamp;
GF_SubSampleInformationBox *ptr = (GF_SubSampleInformationBox *) a;
if (!a) return GF_BAD_PARAM;
entry_count = gf_list_count(ptr->Samples);
gf_isom_box_dump_start(a, "SubSampleInformationBox", trace);
fprintf(trace, "EntryCount=\"%d\">\n", entry_count);
for (i=0; i<entry_count; i++) {
pSamp = (GF_SubSampleInfoEntry*) gf_list_get(ptr->Samples, i);
subsample_count = gf_list_count(pSamp->SubSamples);
fprintf(trace, "<SampleEntry SampleDelta=\"%d\" SubSampleCount=\"%d\">\n", pSamp->sample_delta, subsample_count);
for (j=0; j<subsample_count; j++) {
pSubSamp = (GF_SubSampleEntry*) gf_list_get(pSamp->SubSamples, j);
fprintf(trace, "<SubSample Size=\"%u\" Priority=\"%u\" Discardable=\"%d\" Reserved=\"%08X\"/>\n", pSubSamp->subsample_size, pSubSamp->subsample_priority, pSubSamp->discardable, pSubSamp->reserved);
}
fprintf(trace, "</SampleEntry>\n");
}
if (!ptr->size) {
fprintf(trace, "<SampleEntry SampleDelta=\"\" SubSampleCount=\"\">\n");
fprintf(trace, "<SubSample Size=\"\" Priority=\"\" Discardable=\"\" Reserved=\"\"/>\n");
fprintf(trace, "</SampleEntry>\n");
}
gf_isom_box_dump_done("SubSampleInformationBox", a, trace);
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_FRAGMENTS
GF_Err tfdt_dump(GF_Box *a, FILE * trace)
{
GF_TFBaseMediaDecodeTimeBox *ptr = (GF_TFBaseMediaDecodeTimeBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "TrackFragmentBaseMediaDecodeTimeBox", trace);
fprintf(trace, "baseMediaDecodeTime=\""LLD"\">\n", ptr->baseMediaDecodeTime);
gf_isom_box_dump_done("TrackFragmentBaseMediaDecodeTimeBox", a, trace);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_FRAGMENTS*/
GF_Err rvcc_dump(GF_Box *a, FILE * trace)
{
GF_RVCConfigurationBox *ptr = (GF_RVCConfigurationBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "RVCConfigurationBox", trace);
fprintf(trace, "predefined=\"%d\"", ptr->predefined_rvc_config);
if (! ptr->predefined_rvc_config) fprintf(trace, " rvc_meta_idx=\"%d\"", ptr->rvc_meta_idx);
fprintf(trace, ">\n");
gf_isom_box_dump_done("RVCConfigurationBox", a, trace);
return GF_OK;
}
GF_Err sbgp_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SampleGroupBox *ptr = (GF_SampleGroupBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "SampleGroupBox", trace);
if (ptr->grouping_type)
fprintf(trace, "grouping_type=\"%s\"", gf_4cc_to_str(ptr->grouping_type) );
if (ptr->version==1) {
if (isalnum(ptr->grouping_type_parameter&0xFF)) {
fprintf(trace, " grouping_type_parameter=\"%s\"", gf_4cc_to_str(ptr->grouping_type_parameter) );
} else {
fprintf(trace, " grouping_type_parameter=\"%d\"", ptr->grouping_type_parameter);
}
}
fprintf(trace, ">\n");
for (i=0; i<ptr->entry_count; i++) {
fprintf(trace, "<SampleGroupBoxEntry sample_count=\"%d\" group_description_index=\"%d\"/>\n", ptr->sample_entries[i].sample_count, ptr->sample_entries[i].group_description_index );
}
if (!ptr->size) {
fprintf(trace, "<SampleGroupBoxEntry sample_count=\"\" group_description_index=\"\"/>\n");
}
gf_isom_box_dump_done("SampleGroupBox", a, trace);
return GF_OK;
}
static void oinf_entry_dump(GF_OperatingPointsInformation *ptr, FILE * trace)
{
u32 i, count;
if (!ptr) {
fprintf(trace, "<OperatingPointsInformation scalability_mask=\"Multiview|Spatial scalability|Auxilary|unknown\" num_profile_tier_level=\"\" num_operating_points=\"\" dependency_layers=\"\">\n");
fprintf(trace, " <ProfileTierLevel general_profile_space=\"\" general_tier_flag=\"\" general_profile_idc=\"\" general_profile_compatibility_flags=\"\" general_constraint_indicator_flags=\"\" />\n");
fprintf(trace, "<OperatingPoint output_layer_set_idx=\"\" max_temporal_id=\"\" layer_count=\"\" minPicWidth=\"\" minPicHeight=\"\" maxPicWidth=\"\" maxPicHeight=\"\" maxChromaFormat=\"\" maxBitDepth=\"\" frame_rate_info_flag=\"\" bit_rate_info_flag=\"\" avgFrameRate=\"\" constantFrameRate=\"\" maxBitRate=\"\" avgBitRate=\"\"/>\n");
fprintf(trace, "<Layer dependent_layerID=\"\" num_layers_dependent_on=\"\" dependent_on_layerID=\"\" dimension_identifier=\"\"/>\n");
fprintf(trace, "</OperatingPointsInformation>\n");
return;
}
fprintf(trace, "<OperatingPointsInformation");
fprintf(trace, " scalability_mask=\"%u (", ptr->scalability_mask);
switch (ptr->scalability_mask) {
case 2:
fprintf(trace, "Multiview");
break;
case 4:
fprintf(trace, "Spatial scalability");
break;
case 8:
fprintf(trace, "Auxilary");
break;
default:
fprintf(trace, "unknown");
}
fprintf(trace, ")\" num_profile_tier_level=\"%u\"", gf_list_count(ptr->profile_tier_levels) );
fprintf(trace, " num_operating_points=\"%u\" dependency_layers=\"%u\"", gf_list_count(ptr->operating_points), gf_list_count(ptr->dependency_layers));
fprintf(trace, ">\n");
count=gf_list_count(ptr->profile_tier_levels);
for (i = 0; i < count; i++) {
LHEVC_ProfileTierLevel *ptl = (LHEVC_ProfileTierLevel *)gf_list_get(ptr->profile_tier_levels, i);
fprintf(trace, " <ProfileTierLevel general_profile_space=\"%u\" general_tier_flag=\"%u\" general_profile_idc=\"%u\" general_profile_compatibility_flags=\"%X\" general_constraint_indicator_flags=\""LLX"\" />\n", ptl->general_profile_space, ptl->general_tier_flag, ptl->general_profile_idc, ptl->general_profile_compatibility_flags, ptl->general_constraint_indicator_flags);
}
count=gf_list_count(ptr->operating_points);
for (i = 0; i < count; i++) {
LHEVC_OperatingPoint *op = (LHEVC_OperatingPoint *)gf_list_get(ptr->operating_points, i);
fprintf(trace, "<OperatingPoint output_layer_set_idx=\"%u\"", op->output_layer_set_idx);
fprintf(trace, " max_temporal_id=\"%u\" layer_count=\"%u\"", op->max_temporal_id, op->layer_count);
fprintf(trace, " minPicWidth=\"%u\" minPicHeight=\"%u\"", op->minPicWidth, op->minPicHeight);
fprintf(trace, " maxPicWidth=\"%u\" maxPicHeight=\"%u\"", op->maxPicWidth, op->maxPicHeight);
fprintf(trace, " maxChromaFormat=\"%u\" maxBitDepth=\"%u\"", op->maxChromaFormat, op->maxBitDepth);
fprintf(trace, " frame_rate_info_flag=\"%u\" bit_rate_info_flag=\"%u\"", op->frame_rate_info_flag, op->bit_rate_info_flag);
if (op->frame_rate_info_flag)
fprintf(trace, " avgFrameRate=\"%u\" constantFrameRate=\"%u\"", op->avgFrameRate, op->constantFrameRate);
if (op->bit_rate_info_flag)
fprintf(trace, " maxBitRate=\"%u\" avgBitRate=\"%u\"", op->maxBitRate, op->avgBitRate);
fprintf(trace, "/>\n");
}
count=gf_list_count(ptr->dependency_layers);
for (i = 0; i < count; i++) {
u32 j;
LHEVC_DependentLayer *dep = (LHEVC_DependentLayer *)gf_list_get(ptr->dependency_layers, i);
fprintf(trace, "<Layer dependent_layerID=\"%u\" num_layers_dependent_on=\"%u\"", dep->dependent_layerID, dep->num_layers_dependent_on);
if (dep->num_layers_dependent_on) {
fprintf(trace, " dependent_on_layerID=\"");
for (j = 0; j < dep->num_layers_dependent_on; j++)
fprintf(trace, "%d ", dep->dependent_on_layerID[j]);
fprintf(trace, "\"");
}
fprintf(trace, " dimension_identifier=\"");
for (j = 0; j < 16; j++)
if (ptr->scalability_mask & (1 << j))
fprintf(trace, "%d ", dep->dimension_identifier[j]);
fprintf(trace, "\"/>\n");
}
fprintf(trace, "</OperatingPointsInformation>\n");
return;
}
static void linf_dump(GF_LHVCLayerInformation *ptr, FILE * trace)
{
u32 i, count;
if (!ptr) {
fprintf(trace, "<LayerInformation num_layers=\"\">\n");
fprintf(trace, "<LayerInfoItem layer_id=\"\" min_temporalId=\"\" max_temporalId=\"\" sub_layer_presence_flags=\"\"/>\n");
fprintf(trace, "</LayerInformation>\n");
return;
}
count = gf_list_count(ptr->num_layers_in_track);
fprintf(trace, "<LayerInformation num_layers=\"%d\">\n", count );
for (i = 0; i < count; i++) {
LHVCLayerInfoItem *li = (LHVCLayerInfoItem *)gf_list_get(ptr->num_layers_in_track, i);
fprintf(trace, "<LayerInfoItem layer_id=\"%d\" min_temporalId=\"%d\" max_temporalId=\"%d\" sub_layer_presence_flags=\"%d\"/>\n", li->layer_id, li->min_TemporalId, li->max_TemporalId, li->sub_layer_presence_flags);
}
fprintf(trace, "</LayerInformation>\n");
return;
}
static void trif_dump(FILE * trace, char *data, u32 data_size)
{
GF_BitStream *bs;
u32 id, independent, filter_disabled;
Bool full_picture, has_dep, tile_group;
if (!data) {
fprintf(trace, "<TileRegionGroupEntry ID=\"\" tileGroup=\"\" independent=\"\" full_picture=\"\" filter_disabled=\"\" x=\"\" y=\"\" w=\"\" h=\"\">\n");
fprintf(trace, "<TileRegionDependency tileID=\"\"/>\n");
fprintf(trace, "</TileRegionGroupEntry>\n");
return;
}
bs = gf_bs_new(data, data_size, GF_BITSTREAM_READ);
id = gf_bs_read_u16(bs);
tile_group = gf_bs_read_int(bs, 1);
fprintf(trace, "<TileRegionGroupEntry ID=\"%d\" tileGroup=\"%d\" ", id, tile_group);
if (tile_group) {
independent = gf_bs_read_int(bs, 2);
full_picture = (Bool)gf_bs_read_int(bs, 1);
filter_disabled = gf_bs_read_int(bs, 1);
has_dep = gf_bs_read_int(bs, 1);
gf_bs_read_int(bs, 2);
fprintf(trace, "independent=\"%d\" full_picture=\"%d\" filter_disabled=\"%d\" ", independent, full_picture, filter_disabled);
if (!full_picture) {
fprintf(trace, "x=\"%d\" y=\"%d\" ", gf_bs_read_u16(bs), gf_bs_read_u16(bs));
}
fprintf(trace, "w=\"%d\" h=\"%d\" ", gf_bs_read_u16(bs), gf_bs_read_u16(bs));
if (!has_dep) {
fprintf(trace, "/>\n");
} else {
u32 count = gf_bs_read_u16(bs);
fprintf(trace, ">\n");
while (count) {
count--;
fprintf(trace, "<TileRegionDependency tileID=\"%d\"/>\n", gf_bs_read_u16(bs) );
}
fprintf(trace, "</TileRegionGroupEntry>\n");
}
}
gf_bs_del(bs);
}
static void nalm_dump(FILE * trace, char *data, u32 data_size)
{
GF_BitStream *bs;
Bool rle, large_size;
u32 entry_count;
if (!data) {
fprintf(trace, "<NALUMap rle=\"\" large_size=\"\">\n");
fprintf(trace, "<NALUMapEntry NALU_startNumber=\"\" groupID=\"\"/>\n");
fprintf(trace, "</NALUMap>\n");
return;
}
bs = gf_bs_new(data, data_size, GF_BITSTREAM_READ);
gf_bs_read_int(bs, 6);
large_size = gf_bs_read_int(bs, 1);
rle = gf_bs_read_int(bs, 1);
entry_count = gf_bs_read_int(bs, large_size ? 16 : 8);
fprintf(trace, "<NALUMap rle=\"%d\" large_size=\"%d\">\n", rle, large_size);
while (entry_count) {
u32 ID;
fprintf(trace, "<NALUMapEntry ");
if (rle) {
u32 start_num = gf_bs_read_int(bs, large_size ? 16 : 8);
fprintf(trace, "NALU_startNumber=\"%d\" ", start_num);
}
ID = gf_bs_read_u16(bs);
fprintf(trace, "groupID=\"%d\"/>\n", ID);
entry_count--;
}
gf_bs_del(bs);
fprintf(trace, "</NALUMap>\n");
return;
}
GF_Err sgpd_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SampleGroupDescriptionBox *ptr = (GF_SampleGroupDescriptionBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "SampleGroupDescriptionBox", trace);
if (ptr->grouping_type)
fprintf(trace, "grouping_type=\"%s\"", gf_4cc_to_str(ptr->grouping_type) );
if (ptr->version==1) fprintf(trace, " default_length=\"%d\"", ptr->default_length);
if ((ptr->version>=2) && ptr->default_description_index) fprintf(trace, " default_group_index=\"%d\"", ptr->default_description_index);
fprintf(trace, ">\n");
for (i=0; i<gf_list_count(ptr->group_descriptions); i++) {
void *entry = gf_list_get(ptr->group_descriptions, i);
switch (ptr->grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
fprintf(trace, "<RollRecoveryEntry roll_distance=\"%d\" />\n", ((GF_RollRecoveryEntry*)entry)->roll_distance );
break;
case GF_ISOM_SAMPLE_GROUP_PROL:
fprintf(trace, "<AudioPreRollEntry roll_distance=\"%d\" />\n", ((GF_RollRecoveryEntry*)entry)->roll_distance );
break;
case GF_ISOM_SAMPLE_GROUP_TELE:
fprintf(trace, "<TemporalLevelEntry level_independently_decodable=\"%d\"/>\n", ((GF_TemporalLevelEntry*)entry)->level_independently_decodable);
break;
case GF_ISOM_SAMPLE_GROUP_RAP:
fprintf(trace, "<VisualRandomAccessEntry num_leading_samples_known=\"%s\"", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known ? "yes" : "no");
if (((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known)
fprintf(trace, " num_leading_samples=\"%d\"", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples);
fprintf(trace, "/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_SYNC:
fprintf(trace, "<SyncSampleGroupEntry NAL_unit_type=\"%d\"/>\n", ((GF_SYNCEntry*)entry)->NALU_type);
break;
case GF_ISOM_SAMPLE_GROUP_SEIG:
fprintf(trace, "<CENCSampleEncryptionGroupEntry IsEncrypted=\"%d\" IV_size=\"%d\" KID=\"", ((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected, ((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size);
dump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->KID, 16);
if ((((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected == 1) && !((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size) {
fprintf(trace, "\" constant_IV_size=\"%d\" constant_IV=\"", ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size);
dump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV, ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size);
}
fprintf(trace, "\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_OINF:
oinf_entry_dump(entry, trace);
break;
case GF_ISOM_SAMPLE_GROUP_LINF:
linf_dump(entry, trace);
break;
case GF_ISOM_SAMPLE_GROUP_TRIF:
trif_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
break;
case GF_ISOM_SAMPLE_GROUP_NALM:
nalm_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
break;
case GF_ISOM_SAMPLE_GROUP_SAP:
fprintf(trace, "<SAPEntry dependent_flag=\"%d\" SAP_type=\"%d\" />\n", ((GF_SAPEntry*)entry)->dependent_flag, ((GF_SAPEntry*)entry)->SAP_type);
break;
default:
fprintf(trace, "<DefaultSampleGroupDescriptionEntry size=\"%d\" data=\"", ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
dump_data(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
fprintf(trace, "\"/>\n");
}
}
if (!ptr->size) {
switch (ptr->grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
fprintf(trace, "<RollRecoveryEntry roll_distance=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_PROL:
fprintf(trace, "<AudioPreRollEntry roll_distance=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_TELE:
fprintf(trace, "<TemporalLevelEntry level_independently_decodable=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_RAP:
fprintf(trace, "<VisualRandomAccessEntry num_leading_samples_known=\"yes|no\" num_leading_samples=\"\" />\n");
break;
case GF_ISOM_SAMPLE_GROUP_SYNC:
fprintf(trace, "<SyncSampleGroupEntry NAL_unit_type=\"\" />\n");
break;
case GF_ISOM_SAMPLE_GROUP_SEIG:
fprintf(trace, "<CENCSampleEncryptionGroupEntry IsEncrypted=\"\" IV_size=\"\" KID=\"\" constant_IV_size=\"\" constant_IV=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_OINF:
oinf_entry_dump(NULL, trace);
break;
case GF_ISOM_SAMPLE_GROUP_LINF:
linf_dump(NULL, trace);
break;
case GF_ISOM_SAMPLE_GROUP_TRIF:
trif_dump(trace, NULL, 0);
break;
case GF_ISOM_SAMPLE_GROUP_NALM:
nalm_dump(trace, NULL, 0);
break;
case GF_ISOM_SAMPLE_GROUP_SAP:
fprintf(trace, "<SAPEntry dependent_flag=\"\" SAP_type=\"\" />\n");
break;
default:
fprintf(trace, "<DefaultSampleGroupDescriptionEntry size=\"\" data=\"\"/>\n");
}
}
gf_isom_box_dump_done("SampleGroupDescriptionBox", a, trace);
return GF_OK;
}
GF_Err saiz_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SampleAuxiliaryInfoSizeBox *ptr = (GF_SampleAuxiliaryInfoSizeBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "SampleAuxiliaryInfoSizeBox", trace);
fprintf(trace, "default_sample_info_size=\"%d\" sample_count=\"%d\"", ptr->default_sample_info_size, ptr->sample_count);
if (ptr->flags & 1) {
if (isalnum(ptr->aux_info_type>>24)) {
fprintf(trace, " aux_info_type=\"%s\" aux_info_type_parameter=\"%d\"", gf_4cc_to_str(ptr->aux_info_type), ptr->aux_info_type_parameter);
} else {
fprintf(trace, " aux_info_type=\"%d\" aux_info_type_parameter=\"%d\"", ptr->aux_info_type, ptr->aux_info_type_parameter);
}
}
fprintf(trace, ">\n");
if (ptr->default_sample_info_size==0) {
for (i=0; i<ptr->sample_count; i++) {
fprintf(trace, "<SAISize size=\"%d\" />\n", ptr->sample_info_size[i]);
}
}
if (!ptr->size) {
fprintf(trace, "<SAISize size=\"\" />\n");
}
gf_isom_box_dump_done("SampleAuxiliaryInfoSizeBox", a, trace);
return GF_OK;
}
GF_Err saio_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SampleAuxiliaryInfoOffsetBox *ptr = (GF_SampleAuxiliaryInfoOffsetBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "SampleAuxiliaryInfoOffsetBox", trace);
fprintf(trace, "entry_count=\"%d\"", ptr->entry_count);
if (ptr->flags & 1) {
if (isalnum(ptr->aux_info_type>>24)) {
fprintf(trace, " aux_info_type=\"%s\" aux_info_type_parameter=\"%d\"", gf_4cc_to_str(ptr->aux_info_type), ptr->aux_info_type_parameter);
} else {
fprintf(trace, " aux_info_type=\"%d\" aux_info_type_parameter=\"%d\"", ptr->aux_info_type, ptr->aux_info_type_parameter);
}
}
fprintf(trace, ">\n");
if (ptr->version==0) {
for (i=0; i<ptr->entry_count; i++) {
fprintf(trace, "<SAIChunkOffset offset=\"%d\"/>\n", ptr->offsets[i]);
}
} else {
for (i=0; i<ptr->entry_count; i++) {
fprintf(trace, "<SAIChunkOffset offset=\""LLD"\"/>\n", ptr->offsets_large[i]);
}
}
if (!ptr->size) {
fprintf(trace, "<SAIChunkOffset offset=\"\"/>\n");
}
gf_isom_box_dump_done("SampleAuxiliaryInfoOffsetBox", a, trace);
return GF_OK;
}
GF_Err pssh_dump(GF_Box *a, FILE * trace)
{
GF_ProtectionSystemHeaderBox *ptr = (GF_ProtectionSystemHeaderBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "ProtectionSystemHeaderBox", trace);
fprintf(trace, "SystemID=\"");
dump_data_hex(trace, (char *) ptr->SystemID, 16);
fprintf(trace, "\">\n");
if (ptr->KID_count) {
u32 i;
for (i=0; i<ptr->KID_count; i++) {
fprintf(trace, " <PSSHKey KID=\"");
dump_data_hex(trace, (char *) ptr->KIDs[i], 16);
fprintf(trace, "\"/>\n");
}
}
if (ptr->private_data_size) {
fprintf(trace, " <PSSHData size=\"%d\" value=\"", ptr->private_data_size);
dump_data_hex(trace, (char *) ptr->private_data, ptr->private_data_size);
fprintf(trace, "\"/>\n");
}
if (!ptr->size) {
fprintf(trace, " <PSSHKey KID=\"\"/>\n");
fprintf(trace, " <PSSHData size=\"\" value=\"\"/>\n");
}
gf_isom_box_dump_done("ProtectionSystemHeaderBox", a, trace);
return GF_OK;
}
GF_Err tenc_dump(GF_Box *a, FILE * trace)
{
GF_TrackEncryptionBox *ptr = (GF_TrackEncryptionBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "TrackEncryptionBox", trace);
fprintf(trace, "isEncrypted=\"%d\"", ptr->isProtected);
if (ptr->Per_Sample_IV_Size)
fprintf(trace, " IV_size=\"%d\" KID=\"", ptr->Per_Sample_IV_Size);
else {
fprintf(trace, " constant_IV_size=\"%d\" constant_IV=\"", ptr->constant_IV_size);
dump_data_hex(trace, (char *) ptr->constant_IV, ptr->constant_IV_size);
fprintf(trace, "\" KID=\"");
}
dump_data_hex(trace, (char *) ptr->KID, 16);
if (ptr->version)
fprintf(trace, "\" crypt_byte_block=\"%d\" skip_byte_block=\"%d", ptr->crypt_byte_block, ptr->skip_byte_block);
fprintf(trace, "\">\n");
gf_isom_box_dump_done("TrackEncryptionBox", a, trace);
return GF_OK;
}
GF_Err piff_pssh_dump(GF_Box *a, FILE * trace)
{
GF_PIFFProtectionSystemHeaderBox *ptr = (GF_PIFFProtectionSystemHeaderBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "PIFFProtectionSystemHeaderBox", trace);
fprintf(trace, "SystemID=\"");
dump_data_hex(trace, (char *) ptr->SystemID, 16);
fprintf(trace, "\" PrivateData=\"");
dump_data_hex(trace, (char *) ptr->private_data, ptr->private_data_size);
fprintf(trace, "\">\n");
gf_isom_box_dump_done("PIFFProtectionSystemHeaderBox", a, trace);
return GF_OK;
}
GF_Err piff_tenc_dump(GF_Box *a, FILE * trace)
{
GF_PIFFTrackEncryptionBox *ptr = (GF_PIFFTrackEncryptionBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "PIFFTrackEncryptionBox", trace);
fprintf(trace, "AlgorithmID=\"%d\" IV_size=\"%d\" KID=\"", ptr->AlgorithmID, ptr->IV_size);
dump_data_hex(trace,(char *) ptr->KID, 16);
fprintf(trace, "\">\n");
gf_isom_box_dump_done("PIFFTrackEncryptionBox", a, trace);
return GF_OK;
}
GF_Err piff_psec_dump(GF_Box *a, FILE * trace)
{
u32 i, j, sample_count;
GF_SampleEncryptionBox *ptr = (GF_SampleEncryptionBox *) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "PIFFSampleEncryptionBox", trace);
sample_count = gf_list_count(ptr->samp_aux_info);
fprintf(trace, "sampleCount=\"%d\"", sample_count);
if (ptr->flags & 1) {
fprintf(trace, " AlgorithmID=\"%d\" IV_size=\"%d\" KID=\"", ptr->AlgorithmID, ptr->IV_size);
dump_data(trace, (char *) ptr->KID, 16);
fprintf(trace, "\"");
}
fprintf(trace, ">\n");
if (sample_count) {
for (i=0; i<sample_count; i++) {
GF_CENCSampleAuxInfo *cenc_sample = (GF_CENCSampleAuxInfo *)gf_list_get(ptr->samp_aux_info, i);
if (cenc_sample) {
if (!strlen((char *)cenc_sample->IV)) continue;
fprintf(trace, "<PIFFSampleEncryptionEntry IV_size=\"%u\" IV=\"", cenc_sample->IV_size);
dump_data_hex(trace, (char *) cenc_sample->IV, cenc_sample->IV_size);
if (ptr->flags & 0x2) {
fprintf(trace, "\" SubsampleCount=\"%d\"", cenc_sample->subsample_count);
fprintf(trace, ">\n");
for (j=0; j<cenc_sample->subsample_count; j++) {
fprintf(trace, "<PIFFSubSampleEncryptionEntry NumClearBytes=\"%d\" NumEncryptedBytes=\"%d\"/>\n", cenc_sample->subsamples[j].bytes_clear_data, cenc_sample->subsamples[j].bytes_encrypted_data);
}
}
fprintf(trace, "</PIFFSampleEncryptionEntry>\n");
}
}
}
if (!ptr->size) {
fprintf(trace, "<PIFFSampleEncryptionEntry IV=\"\" SubsampleCount=\"\">\n");
fprintf(trace, "<PIFFSubSampleEncryptionEntry NumClearBytes=\"\" NumEncryptedBytes=\"\"/>\n");
fprintf(trace, "</PIFFSampleEncryptionEntry>\n");
}
gf_isom_box_dump_done("PIFFSampleEncryptionBox", a, trace);
return GF_OK;
}
GF_Err senc_dump(GF_Box *a, FILE * trace)
{
u32 i, j, sample_count;
GF_SampleEncryptionBox *ptr = (GF_SampleEncryptionBox *) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "SampleEncryptionBox", trace);
sample_count = gf_list_count(ptr->samp_aux_info);
fprintf(trace, "sampleCount=\"%d\">\n", sample_count);
//WARNING - PSEC (UUID) IS TYPECASTED TO SENC (FULL BOX) SO WE CANNOT USE USUAL FULL BOX FUNCTIONS
fprintf(trace, "<FullBoxInfo Version=\"%d\" Flags=\"0x%X\"/>\n", ptr->version, ptr->flags);
for (i=0; i<sample_count; i++) {
GF_CENCSampleAuxInfo *cenc_sample = (GF_CENCSampleAuxInfo *)gf_list_get(ptr->samp_aux_info, i);
if (cenc_sample) {
fprintf(trace, "<SampleEncryptionEntry sampleNumber=\"%d\" IV_size=\"%u\" IV=\"", i+1, cenc_sample->IV_size);
dump_data_hex(trace, (char *) cenc_sample->IV, cenc_sample->IV_size);
fprintf(trace, "\"");
if (ptr->flags & 0x2) {
fprintf(trace, " SubsampleCount=\"%d\"", cenc_sample->subsample_count);
fprintf(trace, ">\n");
for (j=0; j<cenc_sample->subsample_count; j++) {
fprintf(trace, "<SubSampleEncryptionEntry NumClearBytes=\"%d\" NumEncryptedBytes=\"%d\"/>\n", cenc_sample->subsamples[j].bytes_clear_data, cenc_sample->subsamples[j].bytes_encrypted_data);
}
} else {
fprintf(trace, ">\n");
}
fprintf(trace, "</SampleEncryptionEntry>\n");
}
}
if (!ptr->size) {
fprintf(trace, "<SampleEncryptionEntry sampleCount=\"\" IV=\"\" SubsampleCount=\"\">\n");
fprintf(trace, "<SubSampleEncryptionEntry NumClearBytes=\"\" NumEncryptedBytes=\"\"/>\n");
fprintf(trace, "</SampleEncryptionEntry>\n");
}
gf_isom_box_dump_done("SampleEncryptionBox", a, trace);
return GF_OK;
}
GF_Err prft_dump(GF_Box *a, FILE * trace)
{
Double fracs;
GF_ProducerReferenceTimeBox *ptr = (GF_ProducerReferenceTimeBox *) a;
time_t secs;
struct tm t;
secs = (ptr->ntp >> 32) - GF_NTP_SEC_1900_TO_1970;
if (secs < 0) {
if (ptr->size) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("NTP time is not valid, using value 0\n"));
}
secs = 0;
}
t = *gmtime(&secs);
fracs = (Double) (ptr->ntp & 0xFFFFFFFFULL);
fracs /= 0xFFFFFFFF;
fracs *= 1000;
gf_isom_box_dump_start(a, "ProducerReferenceTimeBox", trace);
fprintf(trace, "referenceTrackID=\"%d\" timestamp=\""LLU"\" NTP=\""LLU"\" UTC=\"%d-%02d-%02dT%02d:%02d:%02d.%03dZ\">\n", ptr->refTrackID, ptr->timestamp, ptr->ntp, 1900+t.tm_year, t.tm_mon+1, t.tm_mday, t.tm_hour, t.tm_min, (u32) t.tm_sec, (u32) fracs);
gf_isom_box_dump_done("ProducerReferenceTimeBox", a, trace);
return GF_OK;
}
GF_Err adkm_dump(GF_Box *a, FILE * trace)
{
GF_AdobeDRMKeyManagementSystemBox *ptr = (GF_AdobeDRMKeyManagementSystemBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "AdobeDRMKeyManagementSystemBox", trace);
fprintf(trace, ">\n");
if (ptr->header) gf_isom_box_dump((GF_Box *)ptr->header, trace);
if (ptr->au_format) gf_isom_box_dump((GF_Box *)ptr->au_format, trace);
gf_isom_box_dump_done("AdobeDRMKeyManagementSystemBox", a, trace);
return GF_OK;
}
GF_Err ahdr_dump(GF_Box *a, FILE * trace)
{
GF_AdobeDRMHeaderBox *ptr = (GF_AdobeDRMHeaderBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "AdobeDRMHeaderBox", trace);
fprintf(trace, ">\n");
if (ptr->std_enc_params) gf_isom_box_dump((GF_Box *)ptr->std_enc_params, trace);
gf_isom_box_dump_done("AdobeDRMHeaderBox", a, trace);
return GF_OK;
}
GF_Err aprm_dump(GF_Box *a, FILE * trace)
{
GF_AdobeStdEncryptionParamsBox *ptr = (GF_AdobeStdEncryptionParamsBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "AdobeStdEncryptionParamsBox", trace);
fprintf(trace, ">\n");
if (ptr->enc_info) gf_isom_box_dump((GF_Box *)ptr->enc_info, trace);
if (ptr->key_info) gf_isom_box_dump((GF_Box *)ptr->key_info, trace);
gf_isom_box_dump_done("AdobeStdEncryptionParamsBox", a, trace);
return GF_OK;
}
GF_Err aeib_dump(GF_Box *a, FILE * trace)
{
GF_AdobeEncryptionInfoBox *ptr = (GF_AdobeEncryptionInfoBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "AdobeEncryptionInfoBox", trace);
fprintf(trace, "EncryptionAlgorithm=\"%s\" KeyLength=\"%d\">\n", ptr->enc_algo, ptr->key_length);
gf_isom_box_dump_done("AdobeEncryptionInfoBox", a, trace);
return GF_OK;
}
GF_Err akey_dump(GF_Box *a, FILE * trace)
{
GF_AdobeKeyInfoBox *ptr = (GF_AdobeKeyInfoBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "AdobeKeyInfoBox", trace);
fprintf(trace, ">\n");
if (ptr->params) gf_isom_box_dump((GF_Box *)ptr->params, trace);
gf_isom_box_dump_done("AdobeKeyInfoBox", a, trace);
return GF_OK;
}
GF_Err flxs_dump(GF_Box *a, FILE * trace)
{
GF_AdobeFlashAccessParamsBox *ptr = (GF_AdobeFlashAccessParamsBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "AdobeFlashAccessParamsBox", trace);
fprintf(trace, ">\n");
if (ptr->metadata)
fprintf(trace, "<FmrmsV2Metadata=\"%s\"/>\n", ptr->metadata);
gf_isom_box_dump_done("AdobeFlashAccessParamsBox", a, trace);
return GF_OK;
}
GF_Err adaf_dump(GF_Box *a, FILE * trace)
{
GF_AdobeDRMAUFormatBox *ptr = (GF_AdobeDRMAUFormatBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "AdobeDRMAUFormatBox ", trace);
fprintf(trace, "SelectiveEncryption=\"%d\" IV_length=\"%d\">\n", ptr->selective_enc ? 1 : 0, ptr->IV_length);
gf_isom_box_dump_done("AdobeDRMAUFormatBox", a, trace);
return GF_OK;
}
/* Image File Format dump */
GF_Err ispe_dump(GF_Box *a, FILE * trace)
{
GF_ImageSpatialExtentsPropertyBox *ptr = (GF_ImageSpatialExtentsPropertyBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "ImageSpatialExtentsPropertyBox", trace);
fprintf(trace, "image_width=\"%d\" image_height=\"%d\">\n", ptr->image_width, ptr->image_height);
gf_isom_box_dump_done("ImageSpatialExtentsPropertyBox", a, trace);
return GF_OK;
}
GF_Err colr_dump(GF_Box *a, FILE * trace)
{
GF_ColourInformationBox *ptr = (GF_ColourInformationBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "ColourInformationBox", trace);
fprintf(trace, "colour_type=\"%s\" colour_primaries=\"%d\" transfer_characteristics=\"%d\" matrix_coefficients=\"%d\" full_range_flag=\"%d\">\n", gf_4cc_to_str(ptr->colour_type), ptr->colour_primaries, ptr->transfer_characteristics, ptr->matrix_coefficients, ptr->full_range_flag);
gf_isom_box_dump_done("ColourInformationBox", a, trace);
return GF_OK;
}
GF_Err pixi_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_PixelInformationPropertyBox *ptr = (GF_PixelInformationPropertyBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "PixelInformationPropertyBox", trace);
fprintf(trace, ">\n");
for (i = 0; i < ptr->num_channels; i++) {
fprintf(trace, "<BitPerChannel bits_per_channel=\"%d\"/>\n", ptr->bits_per_channel[i]);
}
if (!ptr->size)
fprintf(trace, "<BitPerChannel bits_per_channel=\"\"/>\n");
gf_isom_box_dump_done("PixelInformationPropertyBox", a, trace);
return GF_OK;
}
GF_Err rloc_dump(GF_Box *a, FILE * trace)
{
GF_RelativeLocationPropertyBox *ptr = (GF_RelativeLocationPropertyBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "RelativeLocationPropertyBox", trace);
fprintf(trace, "horizontal_offset=\"%d\" vertical_offset=\"%d\">\n", ptr->horizontal_offset, ptr->vertical_offset);
gf_isom_box_dump_done("RelativeLocationPropertyBox", a, trace);
return GF_OK;
}
GF_Err irot_dump(GF_Box *a, FILE * trace)
{
GF_ImageRotationBox *ptr = (GF_ImageRotationBox *)a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "ImageRotationBox", trace);
fprintf(trace, "angle=\"%d\">\n", (ptr->angle*90));
gf_isom_box_dump_done("ImageRotationBox", a, trace);
return GF_OK;
}
GF_Err ipco_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "ItemPropertyContainerBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("ItemPropertyContainerBox", a, trace);
return GF_OK;
}
GF_Err iprp_dump(GF_Box *a, FILE * trace)
{
GF_ItemPropertiesBox *ptr = (GF_ItemPropertiesBox *)a;
gf_isom_box_dump_start(a, "ItemPropertiesBox", trace);
fprintf(trace, ">\n");
if (ptr->property_container) gf_isom_box_dump(ptr->property_container, trace);
if (ptr->property_association) gf_isom_box_dump(ptr->property_association, trace);
gf_isom_box_dump_done("ItemPropertiesBox", a, trace);
return GF_OK;
}
GF_Err ipma_dump(GF_Box *a, FILE * trace)
{
u32 i, j;
GF_ItemPropertyAssociationBox *ptr = (GF_ItemPropertyAssociationBox *)a;
u32 entry_count = gf_list_count(ptr->entries);
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "ItemPropertyAssociationBox", trace);
fprintf(trace, "entry_count=\"%d\">\n", entry_count);
for (i = 0; i < entry_count; i++) {
GF_ItemPropertyAssociationEntry *entry = (GF_ItemPropertyAssociationEntry *)gf_list_get(ptr->entries, i);
u32 association_count = gf_list_count(entry->essential);
fprintf(trace, "<AssociationEntry item_ID=\"%d\" association_count=\"%d\">\n", entry->item_id, association_count);
for (j = 0; j < association_count; j++) {
Bool *ess = (Bool *)gf_list_get(entry->essential, j);
u32 *prop_index = (u32 *)gf_list_get(entry->property_index, j);
fprintf(trace, "<Property index=\"%d\" essential=\"%d\"/>\n", *prop_index, *ess);
}
fprintf(trace, "</AssociationEntry>\n");
}
if (!ptr->size) {
fprintf(trace, "<AssociationEntry item_ID=\"\" association_count=\"\">\n");
fprintf(trace, "<Property index=\"\" essential=\"\"/>\n");
fprintf(trace, "</AssociationEntry>\n");
}
gf_isom_box_dump_done("ItemPropertyAssociationBox", a, trace);
return GF_OK;
}
GF_Err auxc_dump(GF_Box *a, FILE * trace)
{
GF_AuxiliaryTypePropertyBox *ptr = (GF_AuxiliaryTypePropertyBox *)a;
gf_isom_box_dump_start(a, "AuxiliaryTypePropertyBox", trace);
fprintf(trace, "aux_type=\"%s\" ", ptr->aux_urn);
dump_data_attribute(trace, "aux_subtype", ptr->data, ptr->data_size);
fprintf(trace, ">\n");
gf_isom_box_dump_done("AuxiliaryTypePropertyBox", a, trace);
return GF_OK;
}
GF_Err oinf_dump(GF_Box *a, FILE * trace)
{
GF_OINFPropertyBox *ptr = (GF_OINFPropertyBox *)a;
gf_isom_box_dump_start(a, "OperatingPointsInformationPropertyBox", trace);
fprintf(trace, ">\n");
oinf_entry_dump(ptr->oinf, trace);
gf_isom_box_dump_done("OperatingPointsInformationPropertyBox", a, trace);
return GF_OK;
}
GF_Err tols_dump(GF_Box *a, FILE * trace)
{
GF_TargetOLSPropertyBox *ptr = (GF_TargetOLSPropertyBox *)a;
gf_isom_box_dump_start(a, "TargetOLSPropertyBox", trace);
fprintf(trace, "target_ols_index=\"%d\">\n", ptr->target_ols_index);
gf_isom_box_dump_done("TargetOLSPropertyBox", a, trace);
return GF_OK;
}
GF_Err trgr_dump(GF_Box *a, FILE * trace)
{
GF_TrackGroupBox *ptr = (GF_TrackGroupBox *) a;
gf_isom_box_dump_start(a, "TrackGroupBox", trace);
fprintf(trace, ">\n");
gf_isom_box_array_dump(ptr->groups, trace);
gf_isom_box_dump_done("TrackGroupBox", a, trace);
return GF_OK;
}
GF_Err trgt_dump(GF_Box *a, FILE * trace)
{
GF_TrackGroupTypeBox *ptr = (GF_TrackGroupTypeBox *) a;
a->type = ptr->group_type;
gf_isom_box_dump_start(a, "TrackGroupTypeBox", trace);
a->type = GF_ISOM_BOX_TYPE_TRGT;
fprintf(trace, "track_group_id=\"%d\">\n", ptr->track_group_id);
gf_isom_box_dump_done("TrackGroupTypeBox", a, trace);
return GF_OK;
}
GF_Err grpl_dump(GF_Box *a, FILE * trace)
{
gf_isom_box_dump_start(a, "GroupListBox", trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done("GroupListBox", a, trace);
return GF_OK;
}
GF_Err grptype_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_EntityToGroupTypeBox *ptr = (GF_EntityToGroupTypeBox *) a;
a->type = ptr->grouping_type;
gf_isom_box_dump_start(a, "EntityToGroupTypeBox", trace);
a->type = GF_ISOM_BOX_TYPE_GRPT;
fprintf(trace, "group_id=\"%d\">\n", ptr->group_id);
for (i=0; i<ptr->entity_id_count ; i++)
fprintf(trace, "<EntityToGroupTypeBoxEntry EntityID=\"%d\"/>\n", ptr->entity_ids[i]);
if (!ptr->size)
fprintf(trace, "<EntityToGroupTypeBoxEntry EntityID=\"\"/>\n");
gf_isom_box_dump_done("EntityToGroupTypeBox", a, trace);
return GF_OK;
}
GF_Err stvi_dump(GF_Box *a, FILE * trace)
{
GF_StereoVideoBox *ptr = (GF_StereoVideoBox *) a;
gf_isom_box_dump_start(a, "StereoVideoBox", trace);
fprintf(trace, "single_view_allowed=\"%d\" stereo_scheme=\"%d\" ", ptr->single_view_allowed, ptr->stereo_scheme);
dump_data_attribute(trace, "stereo_indication_type", ptr->stereo_indication_type, ptr->sit_len);
fprintf(trace, ">\n");
gf_isom_box_dump_done("StereoVideoBox", a, trace);
return GF_OK;
}
GF_Err def_cont_box_dump(GF_Box *a, FILE *trace)
{
char *name = "SubTrackDefinitionBox"; //only one using generic box container for now
gf_isom_box_dump_start(a, name, trace);
fprintf(trace, ">\n");
gf_isom_box_dump_done(name, a, trace);
return GF_OK;
}
GF_Err fiin_dump(GF_Box *a, FILE * trace)
{
FDItemInformationBox *ptr = (FDItemInformationBox *) a;
gf_isom_box_dump_start(a, "FDItemInformationBox", trace);
fprintf(trace, ">\n");
if (ptr->partition_entries)
gf_isom_box_array_dump(ptr->partition_entries, trace);
if (ptr->session_info)
gf_isom_box_dump(ptr->session_info, trace);
if (ptr->group_id_to_name)
gf_isom_box_dump(ptr->group_id_to_name, trace);
gf_isom_box_dump_done("FDItemInformationBox", a, trace);
return GF_OK;
}
GF_Err fecr_dump(GF_Box *a, FILE * trace)
{
u32 i;
char *box_name;
FECReservoirBox *ptr = (FECReservoirBox *) a;
if (a->type==GF_ISOM_BOX_TYPE_FIRE) {
box_name = "FILEReservoirBox";
} else {
box_name = "FECReservoirBox";
}
gf_isom_box_dump_start(a, box_name, trace);
fprintf(trace, ">\n");
for (i=0; i<ptr->nb_entries; i++) {
fprintf(trace, "<%sEntry itemID=\"%d\" symbol_count=\"%d\"/>\n", box_name, ptr->entries[i].item_id, ptr->entries[i].symbol_count);
}
if (!ptr->size) {
fprintf(trace, "<%sEntry itemID=\"\" symbol_count=\"\"/>\n", box_name);
}
gf_isom_box_dump_done(box_name, a, trace);
return GF_OK;
}
GF_Err gitn_dump(GF_Box *a, FILE * trace)
{
u32 i;
GroupIdToNameBox *ptr = (GroupIdToNameBox *) a;
gf_isom_box_dump_start(a, "GroupIdToNameBox", trace);
fprintf(trace, ">\n");
for (i=0; i<ptr->nb_entries; i++) {
fprintf(trace, "<GroupIdToNameBoxEntry groupID=\"%d\" name=\"%s\"/>\n", ptr->entries[i].group_id, ptr->entries[i].name);
}
if (!ptr->size) {
fprintf(trace, "<GroupIdToNameBoxEntryEntry groupID=\"\" name=\"\"/>\n");
}
gf_isom_box_dump_done("GroupIdToNameBox", a, trace);
return GF_OK;
}
GF_Err paen_dump(GF_Box *a, FILE * trace)
{
FDPartitionEntryBox *ptr = (FDPartitionEntryBox *) a;
gf_isom_box_dump_start(a, "FDPartitionEntryBox", trace);
fprintf(trace, ">\n");
if (ptr->blocks_and_symbols)
gf_isom_box_dump(ptr->blocks_and_symbols, trace);
if (ptr->FEC_symbol_locations)
gf_isom_box_dump(ptr->FEC_symbol_locations, trace);
if (ptr->FEC_symbol_locations)
gf_isom_box_dump(ptr->FEC_symbol_locations, trace);
gf_isom_box_dump_done("FDPartitionEntryBox", a, trace);
return GF_OK;
}
GF_Err fpar_dump(GF_Box *a, FILE * trace)
{
u32 i;
FilePartitionBox *ptr = (FilePartitionBox *) a;
gf_isom_box_dump_start(a, "FilePartitionBox", trace);
fprintf(trace, "itemID=\"%d\" FEC_encoding_ID=\"%d\" FEC_instance_ID=\"%d\" max_source_block_length=\"%d\" encoding_symbol_length=\"%d\" max_number_of_encoding_symbols=\"%d\" ", ptr->itemID, ptr->FEC_encoding_ID, ptr->FEC_instance_ID, ptr->max_source_block_length, ptr->encoding_symbol_length, ptr->max_number_of_encoding_symbols);
if (ptr->scheme_specific_info)
dump_data_attribute(trace, "scheme_specific_info", (char*)ptr->scheme_specific_info, (u32)strlen(ptr->scheme_specific_info) );
fprintf(trace, ">\n");
for (i=0; i<ptr->nb_entries; i++) {
fprintf(trace, "<FilePartitionBoxEntry block_count=\"%d\" block_size=\"%d\"/>\n", ptr->entries[i].block_count, ptr->entries[i].block_size);
}
if (!ptr->size) {
fprintf(trace, "<FilePartitionBoxEntry block_count=\"\" block_size=\"\"/>\n");
}
gf_isom_box_dump_done("FilePartitionBox", a, trace);
return GF_OK;
}
GF_Err segr_dump(GF_Box *a, FILE * trace)
{
u32 i, k;
FDSessionGroupBox *ptr = (FDSessionGroupBox *) a;
gf_isom_box_dump_start(a, "FDSessionGroupBox", trace);
fprintf(trace, ">\n");
for (i=0; i<ptr->num_session_groups; i++) {
fprintf(trace, "<FDSessionGroupBoxEntry groupIDs=\"");
for (k=0; k<ptr->session_groups[i].nb_groups; k++) {
fprintf(trace, "%d ", ptr->session_groups[i].group_ids[k]);
}
fprintf(trace, "\" channels=\"");
for (k=0; k<ptr->session_groups[i].nb_channels; k++) {
fprintf(trace, "%d ", ptr->session_groups[i].channels[k]);
}
fprintf(trace, "\"/>\n");
}
if (!ptr->size) {
fprintf(trace, "<FDSessionGroupBoxEntry groupIDs=\"\" channels=\"\"/>\n");
}
gf_isom_box_dump_done("FDSessionGroupBox", a, trace);
return GF_OK;
}
GF_Err srpp_dump(GF_Box *a, FILE * trace)
{
GF_SRTPProcessBox *ptr = (GF_SRTPProcessBox *) a;
gf_isom_box_dump_start(a, "SRTPProcessBox", trace);
fprintf(trace, "encryption_algorithm_rtp=\"%d\" encryption_algorithm_rtcp=\"%d\" integrity_algorithm_rtp=\"%d\" integrity_algorithm_rtcp=\"%d\">\n", ptr->encryption_algorithm_rtp, ptr->encryption_algorithm_rtcp, ptr->integrity_algorithm_rtp, ptr->integrity_algorithm_rtcp);
if (ptr->info) gf_isom_box_dump(ptr->info, trace);
if (ptr->scheme_type) gf_isom_box_dump(ptr->scheme_type, trace);
gf_isom_box_dump_done("SRTPProcessBox", a, trace);
return GF_OK;
}
#ifndef GPAC_DISABLE_ISOM_HINTING
GF_Err fdpa_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_FDpacketBox *ptr = (GF_FDpacketBox *) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "FDpacketBox", trace);
fprintf(trace, "sender_current_time_present=\"%d\" expected_residual_time_present=\"%d\" session_close_bit=\"%d\" object_close_bit=\"%d\" transport_object_identifier=\"%d\">\n", ptr->info.sender_current_time_present, ptr->info.expected_residual_time_present, ptr->info.session_close_bit, ptr->info.object_close_bit, ptr->info.transport_object_identifier);
for (i=0; i<ptr->header_ext_count; i++) {
fprintf(trace, "<FDHeaderExt type=\"%d\"", ptr->headers[i].header_extension_type);
if (ptr->headers[i].header_extension_type > 127) {
dump_data_attribute(trace, "content", (char *) ptr->headers[i].content, 3);
} else if (ptr->headers[i].data_length) {
dump_data_attribute(trace, "data", ptr->headers[i].data, ptr->headers[i].data_length);
}
fprintf(trace, "/>\n");
}
if (!ptr->size) {
fprintf(trace, "<FDHeaderExt type=\"\" content=\"\" data=\"\"/>\n");
}
gf_isom_box_dump_done("FDpacketBox", a, trace);
return GF_OK;
}
GF_Err extr_dump(GF_Box *a, FILE * trace)
{
GF_ExtraDataBox *ptr = (GF_ExtraDataBox *) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "ExtraDataBox", trace);
dump_data_attribute(trace, "data", ptr->data, ptr->data_length);
fprintf(trace, ">\n");
if (ptr->feci) {
gf_isom_box_dump((GF_Box *)ptr->feci, trace);
}
gf_isom_box_dump_done("ExtraDataBox", a, trace);
return GF_OK;
}
GF_Err fdsa_dump(GF_Box *a, FILE * trace)
{
GF_Err e;
GF_HintSample *ptr = (GF_HintSample *) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "FDSampleBox", trace);
fprintf(trace, ">\n");
e = gf_isom_box_array_dump(ptr->packetTable, trace);
if (e) return e;
if (ptr->extra_data) {
e = gf_isom_box_dump((GF_Box *)ptr->extra_data, trace);
if (e) return e;
}
gf_isom_box_dump_done("FDSampleBox", a, trace);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_HINTING*/
GF_Err trik_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_TrickPlayBox *p = (GF_TrickPlayBox *) a;
gf_isom_box_dump_start(a, "TrickPlayBox", trace);
fprintf(trace, ">\n");
for (i=0; i<p->entry_count; i++) {
fprintf(trace, "<TrickPlayBoxEntry pic_type=\"%d\" dependency_level=\"%d\"/>\n", p->entries[i].pic_type, p->entries[i].dependency_level);
}
if (!p->size)
fprintf(trace, "<TrickPlayBoxEntry pic_type=\"\" dependency_level=\"\"/>\n");
gf_isom_box_dump_done("TrickPlayBox", a, trace);
return GF_OK;
}
GF_Err bloc_dump(GF_Box *a, FILE * trace)
{
GF_BaseLocationBox *p = (GF_BaseLocationBox *) a;
gf_isom_box_dump_start(a, "BaseLocationBox", trace);
fprintf(trace, "baseLocation=\"%s\" basePurlLocation=\"%s\">\n", p->baseLocation, p->basePurlLocation);
gf_isom_box_dump_done("BaseLocationBox", a, trace);
return GF_OK;
}
GF_Err ainf_dump(GF_Box *a, FILE * trace)
{
GF_AssetInformationBox *p = (GF_AssetInformationBox *) a;
gf_isom_box_dump_start(a, "AssetInformationBox", trace);
fprintf(trace, "profile_version=\"%d\" APID=\"%s\">\n", p->profile_version, p->APID);
gf_isom_box_dump_done("AssetInformationBox", a, trace);
return GF_OK;
}
#endif /*GPAC_DISABLE_ISOM_DUMP*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_210_2 |
crossvul-cpp_data_bad_351_7 | /*
* card-gpk: Driver for GPK 4000 cards
*
* Copyright (C) 2002 Olaf Kirch <okir@suse.de>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef ENABLE_OPENSSL /* empty file without openssl */
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include "internal.h"
#include "cardctl.h"
#include "pkcs15.h"
#define GPK_SEL_MF 0x00
#define GPK_SEL_DF 0x01
#define GPK_SEL_EF 0x02
#define GPK_SEL_AID 0x04
#define GPK_FID_MF 0x3F00
#define GPK_FTYPE_SC 0x21
#define GPK_SIGN_RSA_MD5 0x11
#define GPK_SIGN_RSA_SHA 0x12
#define GPK_SIGN_RSA_SSL 0x18
#define GPK_VERIFY_RSA_MD5 0x21
#define GPK_VERIFY_RSA_SHA 0x22
#define GPK_AUTH_RSA_MD5 0x31
#define GPK_AUTH_RSA_SHA 0x32
#define GPK_AUTH_RSA_SSL 0x38
#define GPK_UNWRAP_RSA 0x77
#define GPK_MAX_PINS 8
#define GPK_HASH_CHUNK 62
/*
* GPK4000 private data
*/
struct gpk_private_data {
/* The GPK usually do file offsets in multiples of
* 4 bytes. This can be customized however. We
* should really query for this during gpk_init */
unsigned int offset_shift;
unsigned int offset_mask;
unsigned int locked : 1,
sample_card : 1;
/* access control bits of file most recently selected */
unsigned short int ac[3];
/* is non-zero if we should use secure messaging */
unsigned key_set : 1;
unsigned int key_reference;
u8 key[16];
/* crypto related data from set_security_env */
unsigned int sec_algorithm;
unsigned int sec_hash_len;
unsigned int sec_mod_len;
unsigned int sec_padding;
};
#define DRVDATA(card) ((struct gpk_private_data *) ((card)->drv_data))
static int gpk_get_info(sc_card_t *, int, int, u8 *, size_t);
/*
* ATRs of GPK4000 cards courtesy of libscez
*/
static struct sc_atr_table gpk_atrs[] = {
{ "3B:27:00:80:65:A2:04:01:01:37", NULL, "GPK 4K", SC_CARD_TYPE_GPK_GPK4000_s, 0, NULL },
{ "3B:27:00:80:65:A2:05:01:01:37", NULL, "GPK 4K", SC_CARD_TYPE_GPK_GPK4000_sp, 0, NULL },
{ "3B:27:00:80:65:A2:0C:01:01:37", NULL, "GPK 4K", SC_CARD_TYPE_GPK_GPK4000_su256, 0, NULL },
{ "3B:A7:00:40:14:80:65:A2:14:01:01:37", NULL, "GPK 4K", SC_CARD_TYPE_GPK_GPK4000_sdo, 0, NULL },
{ "3B:A7:00:40:18:80:65:A2:08:01:01:52", NULL, "GPK 8K", SC_CARD_TYPE_GPK_GPK8000_8K, 0, NULL },
{ "3B:A7:00:40:18:80:65:A2:09:01:01:52", NULL, "GPK 8K", SC_CARD_TYPE_GPK_GPK8000_16K, 0, NULL },
{ "3B:A7:00:40:18:80:65:A2:09:01:02:52", NULL, "GPK 16K", SC_CARD_TYPE_GPK_GPK16000, 0, NULL },
{ "3B:A7:00:40:18:80:65:A2:09:01:03:52", NULL, "GPK 16K", SC_CARD_TYPE_GPK_GPK16000, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
/*
* Driver and card ops structures
*/
static struct sc_card_operations gpk_ops, *iso_ops;
static struct sc_card_driver gpk_drv = {
"Gemplus GPK",
"gpk",
&gpk_ops,
NULL, 0, NULL
};
/*
* return 1 if this driver can handle the card
*/
static int
gpk_match_card(sc_card_t *card)
{
int i;
i = _sc_match_atr(card, gpk_atrs, &card->type);
if (i < 0) {
const u8 *hist_bytes = card->reader->atr_info.hist_bytes;
/* Gemplus GPK docs say we can use just the
* FMN and PRN fields of the historical bytes
* to recognize a GPK card
* See Table 43, pp. 188
* We'll use the first 2 bytes as well
*/
if ((card->reader->atr_info.hist_bytes_len >= 7)
&& (hist_bytes[0] == 0x80)
&& (hist_bytes[1] == 0x65)
&& (hist_bytes[2] == 0xa2)) { /* FMN */
if (hist_bytes[3] == 0x08) { /* PRN? */
card->type = SC_CARD_TYPE_GPK_GPK8000;
return 1;
}
if (hist_bytes[3] == 0x09) { /* PRN? */
card->type = SC_CARD_TYPE_GPK_GPK16000;
return 1;
}
}
return 0;
}
return 1;
}
/*
* Initialize the card struct
*/
static int
gpk_init(sc_card_t *card)
{
struct gpk_private_data *priv;
unsigned long exponent, flags, kg;
unsigned char info[13];
card->drv_data = priv = calloc(1, sizeof(*priv));
if (card->drv_data == NULL)
return SC_ERROR_OUT_OF_MEMORY;
/* read/write/update binary expect offset to be the
* number of 32 bit words.
* offset_shift is the shift value.
* offset_mask is the corresponding mask. */
priv->offset_shift = 2;
priv->offset_mask = 3;
card->cla = 0x00;
/* Set up algorithm info. GPK 16000 will do any RSA
* exponent, earlier ones are restricted to 0x10001 */
flags = SC_ALGORITHM_RSA_HASH_MD5 | SC_ALGORITHM_RSA_HASH_SHA1
| SC_ALGORITHM_RSA_HASH_MD5_SHA1;
flags |= SC_ALGORITHM_RSA_PAD_PKCS1 | SC_ALGORITHM_RSA_PAD_ANSI
| SC_ALGORITHM_RSA_PAD_ISO9796;
exponent = (card->type < SC_CARD_TYPE_GPK_GPK16000) ? 0x10001 : 0;
kg = (card->type >= SC_CARD_TYPE_GPK_GPK8000) ? SC_ALGORITHM_ONBOARD_KEY_GEN : 0;
_sc_card_add_rsa_alg(card, 512, flags|kg, exponent);
_sc_card_add_rsa_alg(card, 768, flags, exponent);
_sc_card_add_rsa_alg(card, 1024, flags|kg, exponent);
/* Inspect the LOCK byte */
if (gpk_get_info(card, 0x02, 0xA4, info, sizeof(info)) >= 0) {
if (info[12] & 0x40) {
priv->offset_shift = 0;
priv->offset_mask = 0;
}
if (info[12] & 0x10) {
/* DSA supported - add algo information.
* It's highly unlikely we'll ever see this.
*/
}
if (info[12] & 0x08) {
priv->locked = 1;
}
/* Sample cards use a transport key of "TEST KEYTEST KEY" */
if (!memcmp(info+5, "\x00\xff\x00", 3)) {
priv->sample_card = 1;
}
}
/* State that we have an RNG */
card->caps |= SC_CARD_CAP_RNG;
/* Make sure max send/receive size is 4 byte aligned and <256. */
card->max_recv_size = 252;
return SC_SUCCESS;
}
/*
* Card is being closed; discard any private data etc
*/
static int
gpk_finish(sc_card_t *card)
{
if (card->drv_data)
free(card->drv_data);
card->drv_data = NULL;
return 0;
}
/*
* Select a DF/EF
*/
static int
match_path(sc_card_t *card, unsigned short int **pathptr, size_t *pathlen,
int need_info)
{
unsigned short int *curptr, *ptr;
size_t curlen, len;
size_t i;
curptr = (unsigned short int *) card->cache.current_path.value;
curlen = card->cache.current_path.len;
ptr = *pathptr;
len = *pathlen;
if (curlen < 1 || len < 1)
return 0;
/* Make sure path starts with MF.
* Note the cached path should always begin with MF. */
if (ptr[0] != GPK_FID_MF || curptr[0] != GPK_FID_MF)
return 0;
for (i = 1; i < len && i < curlen; i++) {
if (ptr[i] != curptr[i])
break;
}
if (len < curlen) {
/* Caller asked us to select the DF, but the
* current file is some EF within the DF we're
* interested in. Say ACK */
if (len == 2)
goto okay;
/* Anything else won't work */
return 0;
}
/* In the case of an exact match:
* If the caller needs info on the file to be selected,
* make sure we at least select the file itself.
* If the DF matches the current DF, just return the
* FID */
if (i == len && need_info) {
if (i > 1) {
*pathptr = ptr + len - 1;
*pathlen = len - 1;
return 1;
}
/* bummer */
return 0;
}
okay:
*pathptr = ptr + i;
*pathlen = len - i;
return 1;
}
static void
ac_to_acl(unsigned int ac, sc_file_t *file, unsigned int op)
{
unsigned int npins, pin;
npins = (ac >> 14) & 3;
if (npins == 3) {
sc_file_add_acl_entry(file, op, SC_AC_NEVER,
SC_AC_KEY_REF_NONE);
return;
}
sc_file_add_acl_entry(file, op, SC_AC_NONE, SC_AC_KEY_REF_NONE);
pin = ac & 0xFF;
if (npins >= 1)
sc_file_add_acl_entry(file, op, SC_AC_CHV, (pin >> 4) & 0xF);
if (npins == 2)
sc_file_add_acl_entry(file, op, SC_AC_CHV, pin & 0xF);
/* Check whether secure messaging key is specified */
if (ac & 0x3F00)
sc_file_add_acl_entry(file, op, SC_AC_PRO, (ac & 0x3F00) >> 8);
}
/*
* Convert ACLs requested by the application to access condition
* bits supported by the GPK. Since these do not map 1:1 there's
* some fuzz involved.
*/
static void
acl_to_ac(sc_file_t *file, unsigned int op, u8 *ac)
{
const sc_acl_entry_t *acl;
unsigned int npins = 0;
ac[0] = ac[1] = 0;
if ((acl = sc_file_get_acl_entry(file, op)) == NULL)
return;
assert(acl->method != SC_AC_UNKNOWN);
switch (acl->method) {
case SC_AC_NEVER:
ac[0] = 0xC0;
return;
case SC_AC_NONE:
return;
}
while (acl) {
if (acl->method == SC_AC_CHV) {
/* Support up to 2 PINS only */
if (++npins >= 2)
continue;
ac[1] >>= 4;
ac[1] |= acl->key_ref << 4;
ac[0] += 0x40;
}
if (acl->method == SC_AC_PRO) {
ac[0] |= acl->key_ref & 0x1f;
}
acl = acl->next;
}
}
static int
gpk_parse_fci(sc_card_t *card,
const u8 *buf, size_t buflen,
sc_file_t *file)
{
const u8 *end, *next;
unsigned int tag, len;
end = buf + buflen;
for (; buf + 2 < end; buf = next) {
next = buf + 2 + buf[1];
if (next > end)
break;
tag = *buf++;
len = *buf++;
if (tag == 0x84) {
/* unknown purpose - usually the name, but
* the content looks weird, such as
* 84 0D A0 00 00 00 18 0F 00 00 01 63 00 01 04
*/
} else
if (tag == 0xC1 && len >= 2) {
/* Seems to be the file id, followed by something
* C1 04 02 00 00 00 */
file->id = (buf[0] << 8) | buf[1];
} else
if (tag == 0xC2) {
/* unknown purpose
* C2 01 01
*/
}
}
return 0;
}
static int
gpk_parse_fileinfo(sc_card_t *card,
const u8 *buf, size_t buflen,
sc_file_t *file)
{
const u8 *sp, *end, *next;
int i, rc;
memset(file, 0, sizeof(*file));
for (i = 0; i < SC_MAX_AC_OPS; i++)
sc_file_add_acl_entry(file, i, SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE);
end = buf + buflen;
for (sp = buf; sp + 2 < end; sp = next) {
next = sp + 2 + sp[1];
if (next > end)
break;
if (sp[0] == 0x84) {
/* ignore if name is longer than what it should be */
if (sp[1] > sizeof(file->name))
continue;
memset(file->name, 0, sizeof(file->name));
memcpy(file->name, sp+2, sp[1]);
} else
if (sp[0] == 0x85) {
unsigned int ac[3], n;
file->id = (sp[4] << 8) | sp[5];
file->size = (sp[8] << 8) | sp[9];
file->record_length = sp[7];
/* Map ACLs. Note the third AC byte is
* valid of EFs only */
for (n = 0; n < 3; n++)
ac[n] = (sp[10+2*n] << 8) | sp[11+2*n];
/* Examine file type */
switch (sp[6] & 7) {
case 0x01: case 0x02: case 0x03: case 0x04:
case 0x05: case 0x06: case 0x07:
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = sp[6] & 7;
ac_to_acl(ac[0], file, SC_AC_OP_UPDATE);
ac_to_acl(ac[1], file, SC_AC_OP_WRITE);
ac_to_acl(ac[2], file, SC_AC_OP_READ);
break;
case 0x00: /* 0x38 is DF */
file->type = SC_FILE_TYPE_DF;
/* Icky: the GPK uses different ACLs
* for creating data files and
* 'sensitive' i.e. key files */
ac_to_acl(ac[0], file, SC_AC_OP_LOCK);
ac_to_acl(ac[1], file, SC_AC_OP_CREATE);
sc_file_add_acl_entry(file, SC_AC_OP_SELECT,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_DELETE,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_LIST_FILES,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
break;
}
} else
if (sp[0] == 0x6f) {
/* oops - this is a directory with an IADF.
* This happens with the personalized GemSafe cards
* for instance. */
file->type = SC_FILE_TYPE_DF;
rc = gpk_parse_fci(card, sp + 2, sp[1], file);
if (rc < 0)
return rc;
}
}
if (file->record_length)
file->record_count = file->size / file->record_length;
file->magic = SC_FILE_MAGIC;
return 0;
}
static int
gpk_select(sc_card_t *card, int kind,
const u8 *buf, size_t buflen,
sc_file_t **file)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_apdu_t apdu;
u8 resbuf[256];
int r;
/* If we're about to select a DF, invalidate secure messaging keys */
if (kind == GPK_SEL_MF || kind == GPK_SEL_DF) {
memset(priv->key, 0, sizeof(priv->key));
priv->key_set = 0;
}
/* do the apdu thing */
memset(&apdu, 0, sizeof(apdu));
apdu.cla = 0x00;
apdu.cse = SC_APDU_CASE_3_SHORT;
apdu.ins = 0xA4;
apdu.p1 = kind;
apdu.p2 = 0;
apdu.data = buf;
apdu.datalen = buflen;
apdu.lc = apdu.datalen;
if (file) {
apdu.cse = SC_APDU_CASE_4_SHORT;
apdu.resp = resbuf;
apdu.resplen = sizeof(resbuf);
apdu.le = sizeof(resbuf);
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
/* Nothing we can say about it... invalidate
* path cache */
if (kind == GPK_SEL_AID) {
card->cache.current_path.len = 0;
}
if (file == NULL)
return 0;
*file = sc_file_new();
r = gpk_parse_fileinfo(card, apdu.resp, apdu.resplen, *file);
if (r < 0) {
sc_file_free(*file);
*file = NULL;
}
return r;
}
static int
gpk_select_id(sc_card_t *card, int kind, unsigned int fid,
sc_file_t **file)
{
sc_path_t *cp = &card->cache.current_path;
u8 fbuf[2];
int r;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"gpk_select_id(0x%04X, kind=%u)\n", fid, kind);
fbuf[0] = fid >> 8;
fbuf[1] = fid & 0xff;
r = gpk_select(card, kind, fbuf, 2, file);
/* Fix up the path cache.
* NB we never cache the ID of an EF, just the DF path */
if (r == 0) {
unsigned short int *path;
switch (kind) {
case GPK_SEL_MF:
cp->len = 0;
/* fallthru */
case GPK_SEL_DF:
assert(cp->len + 1 <= SC_MAX_PATH_SIZE / 2);
path = (unsigned short int *) cp->value;
path[cp->len++] = fid;
}
} else {
cp->len = 0;
}
return r;
}
static int
gpk_select_file(sc_card_t *card, const sc_path_t *path,
sc_file_t **file)
{
unsigned short int pathtmp[SC_MAX_PATH_SIZE/2];
unsigned short int *pathptr;
size_t pathlen, n;
int locked = 0, r = 0, use_relative = 0, retry = 1;
u8 leaf_type;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Handle the AID case first */
if (path->type == SC_PATH_TYPE_DF_NAME) {
if (path->len > 16)
return SC_ERROR_INVALID_ARGUMENTS;
r = gpk_select(card, GPK_SEL_AID,
path->value, path->len, file);
goto done;
}
/* Now we know we're dealing with 16bit FIDs, either as
* an absolute path name (SC_PATH_TYPE_PATH) or a relative
* FID (SC_PATH_TYPE_FILE_ID)
*
* The API should really tell us whether this is a DF or EF
* we're selecting. All we can do is read tea leaves...
*/
leaf_type = GPK_SEL_EF;
try_again:
if ((path->len & 1) || path->len > sizeof(pathtmp))
return SC_ERROR_INVALID_ARGUMENTS;
pathptr = pathtmp;
for (n = 0; n < path->len; n += 2)
pathptr[n>>1] = (path->value[n] << 8)|path->value[n+1];
pathlen = path->len >> 1;
/* See whether we can skip an initial portion of the
* (absolute) path */
if (path->type == SC_PATH_TYPE_PATH) {
/* Do not retry selecting if this cannot be a DF */
if ((pathptr[0] == GPK_FID_MF && pathlen > 2)
|| (pathptr[0] != GPK_FID_MF && pathlen > 1))
retry = 0;
use_relative = match_path(card, &pathptr, &pathlen, file != 0);
if (pathlen == 0)
goto done;
} else {
/* SC_PATH_TYPE_FILEID */
if (pathlen > 1)
return SC_ERROR_INVALID_ARGUMENTS;
use_relative = 1;
}
if (pathlen == 1 && pathptr[0] == GPK_FID_MF) {
/* Select just the MF */
leaf_type = GPK_SEL_MF;
} else {
if (!locked++) {
r = sc_lock(card);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "sc_lock() failed");
}
/* Do we need to select the MF first? */
if (!use_relative) {
r = gpk_select_id(card, GPK_SEL_MF, GPK_FID_MF, NULL);
if (r)
sc_unlock(card);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Unable to select MF");
/* Consume the MF FID if it's there */
if (pathptr[0] == GPK_FID_MF) {
pathptr++;
pathlen--;
}
if (pathlen == 0)
goto done;
}
/* Next comes a DF, if at all.
* This loop can deal with nesting levels > 1 even
* though the GPK4000 doesn't support it. */
while (pathlen > 1) {
r = gpk_select_id(card, GPK_SEL_DF, pathptr[0], NULL);
if (r)
sc_unlock(card);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Unable to select DF");
pathptr++;
pathlen--;
}
}
/* Remaining component will be a DF or EF. How do we find out?
* All we can do is try */
r = gpk_select_id(card, leaf_type, pathptr[0], file);
if (r) {
/* Did we guess EF, and were wrong? If so, invalidate
* path cache and try again; this time aiming for a DF */
if (leaf_type == GPK_SEL_EF && retry) {
card->cache.current_path.len = 0;
leaf_type = GPK_SEL_DF;
goto try_again;
}
}
done:
if (locked)
sc_unlock(card);
return r;
}
/*
* GPK versions of {read,write,update}_binary functions.
* Required because by default the GPKs do word offsets
*/
static int
gpk_read_binary(sc_card_t *card, unsigned int offset,
u8 *buf, size_t count, unsigned long flags)
{
struct gpk_private_data *priv = DRVDATA(card);
if (offset & priv->offset_mask) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid file offset (not a multiple of %d)",
priv->offset_mask + 1);
return SC_ERROR_INVALID_ARGUMENTS;
}
return iso_ops->read_binary(card, offset >> priv->offset_shift,
buf, count, flags);
}
static int
gpk_write_binary(sc_card_t *card, unsigned int offset,
const u8 *buf, size_t count, unsigned long flags)
{
struct gpk_private_data *priv = DRVDATA(card);
if (offset & priv->offset_mask) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid file offset (not a multiple of %d)",
priv->offset_mask + 1);
return SC_ERROR_INVALID_ARGUMENTS;
}
return iso_ops->write_binary(card, offset >> priv->offset_shift,
buf, count, flags);
}
static int
gpk_update_binary(sc_card_t *card, unsigned int offset,
const u8 *buf, size_t count, unsigned long flags)
{
struct gpk_private_data *priv = DRVDATA(card);
if (offset & priv->offset_mask) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid file offset (not a multiple of %d)",
priv->offset_mask + 1);
return SC_ERROR_INVALID_ARGUMENTS;
}
return iso_ops->update_binary(card, offset >> priv->offset_shift,
buf, count, flags);
}
/*
* Secure messaging
*/
static int
gpk_compute_crycks(sc_card_t *card, sc_apdu_t *apdu,
u8 *crycks1)
{
struct gpk_private_data *priv = DRVDATA(card);
u8 in[8], out[8], block[64];
unsigned int len = 0, i;
int r = SC_SUCCESS, outl;
EVP_CIPHER_CTX *ctx = NULL;
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
return SC_ERROR_INTERNAL;
/* Fill block with 0x00 and then with the data. */
memset(block, 0x00, sizeof(block));
block[len++] = apdu->cla;
block[len++] = apdu->ins;
block[len++] = apdu->p1;
block[len++] = apdu->p2;
block[len++] = apdu->lc + 3;
if ((i = apdu->datalen) + len > sizeof(block))
i = sizeof(block) - len;
memcpy(block+len, apdu->data, i);
len += i;
/* Set IV */
memset(in, 0x00, 8);
EVP_EncryptInit_ex(ctx, EVP_des_ede_cbc(), NULL, priv->key, in);
for (i = 0; i < len; i += 8) {
if (!EVP_EncryptUpdate(ctx, out, &outl, &block[i], 8)) {
r = SC_ERROR_INTERNAL;
break;
}
}
EVP_CIPHER_CTX_free(ctx);
memcpy((u8 *) (apdu->data + apdu->datalen), out + 5, 3);
apdu->datalen += 3;
apdu->lc += 3;
apdu->le += 3;
if (crycks1)
memcpy(crycks1, out, 3);
sc_mem_clear(in, sizeof(in));
sc_mem_clear(out, sizeof(out));
sc_mem_clear(block, sizeof(block));
return r;
}
/*
* Verify secure messaging response
*/
static int
gpk_verify_crycks(sc_card_t *card, sc_apdu_t *apdu, u8 *crycks)
{
if (apdu->resplen < 3
|| memcmp(apdu->resp + apdu->resplen - 3, crycks, 3)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Invalid secure messaging reply\n");
return SC_ERROR_UNKNOWN_DATA_RECEIVED;
}
apdu->resplen -= 3;
return 0;
}
/*
* Create a file or directory.
* This is a bit tricky because we abuse the ef_structure
* field to transport file types that are non-standard
* (the GPK4000 has lots of bizarre file types).
*/
static int
gpk_create_file(sc_card_t *card, sc_file_t *file)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_apdu_t apdu;
u8 data[28+3], crycks[3], resp[3];
size_t datalen, namelen;
int r;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"gpk_create_file(0x%04X)\n", file->id);
/* Prepare APDU */
memset(&apdu, 0, sizeof(apdu));
apdu.cla = 0x80; /* assume no secure messaging */
apdu.cse = SC_APDU_CASE_3_SHORT;
apdu.ins = 0xE0;
apdu.p2 = 0x00;
/* clear data */
memset(data, 0, sizeof(data));
datalen = 12;
/* FID */
data[0] = file->id >> 8;
data[1] = file->id & 0xFF;
/* encode ACLs */
if (file->type == SC_FILE_TYPE_DF) {
/* The GPK4000 has separate AC bits for
* creating sensitive files and creating
* data files. Since OpenSC has just the notion
* of "file" we use the same ACL for both AC words
*/
apdu.p1 = 0x01; /* create DF */
data[2] = 0x38;
acl_to_ac(file, SC_AC_OP_CREATE, data + 6);
acl_to_ac(file, SC_AC_OP_CREATE, data + 8);
if ((namelen = file->namelen) != 0) {
if (namelen > 16)
return SC_ERROR_INVALID_ARGUMENTS;
memcpy(data+datalen, file->name, namelen);
data[5] = namelen;
datalen += namelen;
}
} else {
apdu.p1 = 0x02; /* create EF */
data[2] = file->ef_structure;
data[3] = file->record_length;
data[4] = file->size >> 8;
data[5] = file->size & 0xff;
acl_to_ac(file, SC_AC_OP_UPDATE, data + 6);
acl_to_ac(file, SC_AC_OP_WRITE, data + 8);
acl_to_ac(file, SC_AC_OP_READ, data + 10);
}
apdu.data = data;
apdu.datalen = datalen;
apdu.lc = datalen;
if (priv->key_set) {
apdu.cla = 0x84;
apdu.cse = SC_APDU_CASE_4_SHORT;
r = gpk_compute_crycks(card, &apdu, crycks);
if (r)
return r;
apdu.resp = resp;
apdu.resplen = sizeof(resp); /* XXX? */
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
/* verify secure messaging response */
if (priv->key_set)
r = gpk_verify_crycks(card, &apdu, crycks);
return r;
}
/*
* Set the secure messaging key following a Select FileKey
*/
static int
gpk_set_filekey(const u8 *key, const u8 *challenge,
const u8 *r_rn, u8 *kats)
{
int r = SC_SUCCESS, outl;
EVP_CIPHER_CTX * ctx = NULL;
u8 out[16];
memcpy(out, key+8, 8);
memcpy(out+8, key, 8);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
return SC_ERROR_INTERNAL;
EVP_EncryptInit_ex(ctx, EVP_des_ede(), NULL, key, NULL);
if (!EVP_EncryptUpdate(ctx, kats, &outl, r_rn+4, 8))
r = SC_ERROR_INTERNAL;
if (!EVP_CIPHER_CTX_cleanup(ctx))
r = SC_ERROR_INTERNAL;
if (r == SC_SUCCESS) {
EVP_CIPHER_CTX_init(ctx);
EVP_EncryptInit_ex(ctx, EVP_des_ede(), NULL, out, NULL);
if (!EVP_EncryptUpdate(ctx, kats+8, &outl, r_rn+4, 8))
r = SC_ERROR_INTERNAL;
if (!EVP_CIPHER_CTX_cleanup(ctx))
r = SC_ERROR_INTERNAL;
}
memset(out, 0, sizeof(out));
/* Verify Cryptogram presented by the card terminal
* XXX: what is the appropriate error code to return
* here? INVALID_ARGS doesn't seem quite right
*/
if (r == SC_SUCCESS) {
EVP_CIPHER_CTX_init(ctx);
EVP_EncryptInit_ex(ctx, EVP_des_ede(), NULL, kats, NULL);
if (!EVP_EncryptUpdate(ctx, out, &outl, challenge, 8))
r = SC_ERROR_INTERNAL;
if (memcmp(r_rn, out+4, 4) != 0)
r = SC_ERROR_INVALID_ARGUMENTS;
}
if (ctx)
EVP_CIPHER_CTX_free(ctx);
sc_mem_clear(out, sizeof(out));
return r;
}
/*
* Verify a key presented by the user for secure messaging
*/
static int
gpk_select_key(sc_card_t *card, int key_sfi, const u8 *buf, size_t buflen)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_apdu_t apdu;
u8 rnd[8], resp[258];
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (buflen != 16)
return SC_ERROR_INVALID_ARGUMENTS;
/* now do the SelFk */
RAND_bytes(rnd, sizeof(rnd));
memset(&apdu, 0, sizeof(apdu));
apdu.cla = 0x80;
apdu.cse = SC_APDU_CASE_4_SHORT;
apdu.ins = 0x28;
apdu.p1 = 0;
apdu.p2 = key_sfi;
apdu.data = rnd;
apdu.datalen = sizeof(rnd);
apdu.lc = apdu.datalen;
apdu.resp = resp;
apdu.resplen = sizeof(resp);
apdu.le = 12;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
if (apdu.resplen != 12) {
r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
} else
if ((r = gpk_set_filekey(buf, rnd, resp, priv->key)) == 0) {
priv->key_set = 1;
priv->key_reference = key_sfi;
}
sc_mem_clear(resp, sizeof(resp));
return r;
}
/*
* Select a security environment (Set Crypto Context in GPK docs).
* When we get here, the PK file has already been selected.
*
* Issue: the GPK distinguishes between "signing" and
* "card internal authentication". I don't know whether this
* makes any difference in practice...
*
* Issue: it seems that sc_compute_signature() does not hash
* the data for the caller. So what is the purpose of HASH_SHA
* and other flags?
*/
static int
gpk_set_security_env(sc_card_t *card,
const sc_security_env_t *env,
int se_num)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_apdu_t apdu;
unsigned int context, algorithm;
unsigned int file_id;
u8 sysrec[7];
int r;
/* According to several sources from GemPlus, they don't
* have off the shelf cards that do DSA. So I won't bother
* with implementing this stuff here. */
algorithm = SC_ALGORITHM_RSA;
if (env->flags & SC_SEC_ENV_ALG_PRESENT)
algorithm = env->algorithm;
if (algorithm != SC_ALGORITHM_RSA) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Algorithm not supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
priv->sec_algorithm = algorithm;
/* If there's a key reference, it must be 0 */
if ((env->flags & SC_SEC_ENV_KEY_REF_PRESENT)
&& (env->key_ref_len != 1 || env->key_ref[0] != 0)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unknown key referenced.\n");
return SC_ERROR_NOT_SUPPORTED;
}
/* Right now, the OpenSC flags do not support any padding
* other than PKCS#1. */
if (env->flags & SC_ALGORITHM_RSA_PAD_PKCS1)
priv->sec_padding = 0;
else if (env->flags & SC_ALGORITHM_RSA_PAD_ANSI)
priv->sec_padding = 1;
else if (env->flags & SC_ALGORITHM_RSA_PAD_ISO9796)
priv->sec_padding = 2;
else {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Padding algorithm not supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
switch (env->operation) {
case SC_SEC_OPERATION_SIGN:
/* Again, the following may not make any difference
* because we don't do any hashing on-card. But
* what the hell, we have all those nice macros,
* so why not use them :)
*/
if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) {
context = GPK_SIGN_RSA_SHA;
priv->sec_hash_len = 20;
} else
if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_MD5_SHA1) {
context = GPK_SIGN_RSA_SSL;
priv->sec_hash_len = 36;
} else
if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_MD5) {
context = GPK_SIGN_RSA_MD5;
priv->sec_hash_len = 16;
} else {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported signature algorithm");
return SC_ERROR_NOT_SUPPORTED;
}
break;
case SC_SEC_OPERATION_DECIPHER:
context = GPK_UNWRAP_RSA;
break;
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Crypto operation not supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
/* Get the file ID */
if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT) {
if (env->file_ref.len != 2) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File reference: invalid length.\n");
return SC_ERROR_INVALID_ARGUMENTS;
}
file_id = (env->file_ref.value[0] << 8)
| env->file_ref.value[1];
} else {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File reference missing.\n");
return SC_ERROR_INVALID_ARGUMENTS;
}
/* Select the PK file. The caller has already selected
* the DF. */
r = gpk_select_id(card, GPK_SEL_EF, file_id, NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Failed to select PK file");
/* Read the sys record of the PK file to find out the key length */
r = sc_read_record(card, 1, sysrec, sizeof(sysrec),
SC_RECORD_BY_REC_NR);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Failed to read PK sysrec");
if (r != 7 || sysrec[0] != 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "First record of file is not the sysrec");
return SC_ERROR_OBJECT_NOT_VALID;
}
if (sysrec[5] != 0x00) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Public key is not an RSA key");
return SC_ERROR_OBJECT_NOT_VALID;
}
switch (sysrec[1]) {
case 0x00: priv->sec_mod_len = 512 / 8; break;
case 0x10: priv->sec_mod_len = 768 / 8; break;
case 0x11: priv->sec_mod_len = 1024 / 8; break;
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported modulus length");
return SC_ERROR_OBJECT_NOT_VALID;
}
/* Now do SelectCryptoContext */
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_1;
apdu.cla = 0x80;
apdu.ins = 0xA6;
apdu.p1 = file_id & 0x1f;
apdu.p2 = context;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
return r;
}
/*
* Restore security environment
* Not sure what this is supposed to do.
*/
static int
gpk_restore_security_env(sc_card_t *card, int se_num)
{
return 0;
}
/*
* Revert buffer (needed for all GPK crypto operations because
* they want LSB byte order internally
*/
static int
reverse(u8 *out, size_t outlen, const u8 *in, size_t inlen)
{
if (inlen > outlen)
return SC_ERROR_BUFFER_TOO_SMALL;
outlen = inlen;
while (inlen--)
*out++ = in[inlen];
return outlen;
}
/*
* Use the card's on-board hashing functions to hash some data
*/
#ifdef dontuse
static int
gpk_hash(sc_card_t *card, const u8 *data, size_t datalen)
{
sc_apdu_t apdu;
unsigned int count, chain, len;
int r;
chain = 0x01;
for (count = 0; count < datalen; count += len) {
unsigned char buffer[GPK_HASH_CHUNK+2];
if ((len = datalen - count) > GPK_HASH_CHUNK)
len = GPK_HASH_CHUNK;
else
chain |= 0x10;
buffer[0] = 0x55;
buffer[1] = len;
memcpy(buffer+2, data + count, len);
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_3_SHORT;
apdu.cla = 0x80;
apdu.ins = 0xDA;
apdu.p1 = chain;
apdu.p2 = len;
apdu.lc = len + 2;
apdu.data= buffer;
apdu.datalen = len + 2;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
chain = 0;
}
return 0;
}
#endif
/*
* Send the hashed data to the card.
*/
static int
gpk_init_hashed(sc_card_t *card, const u8 *digest, unsigned int len)
{
sc_apdu_t apdu;
u8 tsegid[64];
int r;
r = reverse(tsegid, sizeof(tsegid), digest, len);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Failed to reverse buffer");
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_3_SHORT;
apdu.cla = 0x80;
apdu.ins = 0xEA;
apdu.lc = len;
apdu.data= tsegid;
apdu.datalen = len;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
return r;
}
/*
* Compute a signature.
* Note we hash everything manually and send it to the card.
*/
static int
gpk_compute_signature(sc_card_t *card, const u8 *data,
size_t data_len, u8 * out, size_t outlen)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_apdu_t apdu;
u8 cardsig[1024/8];
int r;
if (data_len > priv->sec_mod_len) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Data length (%"SC_FORMAT_LEN_SIZE_T"u) does not match key modulus %u.\n",
data_len, priv->sec_mod_len);
return SC_ERROR_INTERNAL;
}
if (sizeof(cardsig) < priv->sec_mod_len)
return SC_ERROR_BUFFER_TOO_SMALL;
r = gpk_init_hashed(card, data, data_len);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Failed to send hash to card");
/* Now sign the hash.
* The GPK has Internal Authenticate and PK_Sign. I am not
* sure what the difference between the two is. */
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.cla = 0x80;
apdu.ins = 0x86;
apdu.p2 = priv->sec_padding;
apdu.resp= cardsig;
apdu.resplen = sizeof(cardsig);
apdu.le = priv->sec_mod_len;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
/* The GPK returns the signature as little endian numbers.
* Need to revert these */
r = reverse(out, outlen, cardsig, apdu.resplen);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Failed to reverse signature");
return r;
}
/*
* Decrypt some RSA encrypted piece of data.
* Due to legal restrictions, the GPK will not let you see the
* full cleartext block, just the last N bytes.
* The GPK documentation refers to N as the MaxSessionKey size,
* probably because this feature limits the maximum size of an
* SSL session key you will be able to decrypt using this card.
*/
static int
gpk_decipher(sc_card_t *card, const u8 *in, size_t inlen,
u8 *out, size_t outlen)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_apdu_t apdu;
u8 buffer[256];
int r;
if (inlen != priv->sec_mod_len) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Data length (%"SC_FORMAT_LEN_SIZE_T"u) does not match key modulus %u.\n",
inlen, priv->sec_mod_len);
return SC_ERROR_INVALID_ARGUMENTS;
}
/* First revert the cryptogram */
r = reverse(buffer, sizeof(buffer), in, inlen);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Cryptogram too large");
in = buffer;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x1C, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = inlen;
apdu.data = in;
apdu.datalen = inlen;
apdu.le = 256; /* give me all you got :) */
apdu.resp = buffer;
apdu.resplen = sizeof(buffer);
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
/* Reverse the data we got back */
r = reverse(out, outlen, buffer, apdu.resplen);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Failed to reverse buffer");
return r;
}
/*
* Erase card
*/
static int
gpk_erase_card(sc_card_t *card)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_apdu_t apdu;
u8 offset;
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
switch (card->type) {
case SC_CARD_TYPE_GPK_GPK4000_su256:
case SC_CARD_TYPE_GPK_GPK4000_sdo:
offset = 0x6B; /* courtesy gemplus hotline */
break;
case SC_CARD_TYPE_GPK_GPK4000_s:
offset = 7;
break;
case SC_CARD_TYPE_GPK_GPK8000:
case SC_CARD_TYPE_GPK_GPK8000_8K:
case SC_CARD_TYPE_GPK_GPK8000_16K:
case SC_CARD_TYPE_GPK_GPK16000:
offset = 0;
break;
default:
return SC_ERROR_NOT_SUPPORTED;
}
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_1;
apdu.cla = 0xDB;
apdu.ins = 0xDE;
apdu.p2 = offset;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
priv->key_set = 0;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
/*
* Lock a file Access Condition.
*
* File must be selected, and we assume that any authentication
* that needs to be presented in order to allow this operation
* have been presented (ACs from the DF; AC1 for sensitive files,
* AC2 for normal files).
*/
static int
gpk_lock(sc_card_t *card, struct sc_cardctl_gpk_lock *args)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_file_t *file = args->file;
sc_apdu_t apdu;
u8 data[8], crycks[3], resp[3];
int r;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"gpk_lock(0x%04X, %u)\n", file->id, args->operation);
memset(data, 0, sizeof(data));
data[0] = file->id >> 8;
data[1] = file->id;
switch (args->operation) {
case SC_AC_OP_UPDATE:
data[2] = 0x40; break;
case SC_AC_OP_WRITE:
data[3] = 0x40; break;
case SC_AC_OP_READ:
data[4] = 0x40; break;
default:
return SC_ERROR_INVALID_ARGUMENTS;
}
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_3_SHORT;
apdu.cla = 0x80;
apdu.ins = 0x16;
apdu.p1 = (file->type == SC_FILE_TYPE_DF)? 1 : 2;
apdu.p2 = 0;
apdu.lc = 5;
apdu.datalen = 5;
apdu.data = data;
if (priv->key_set) {
apdu.cla = 0x84;
apdu.cse = SC_APDU_CASE_4_SHORT;
r = gpk_compute_crycks(card, &apdu, crycks);
if (r)
return r;
apdu.resp = resp;
apdu.resplen = sizeof(resp); /* XXX? */
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
if (priv->key_set)
r = gpk_verify_crycks(card, &apdu, crycks);
return r;
}
/*
* Initialize the private portion of a public key file
*/
static int
gpk_pkfile_init(sc_card_t *card, struct sc_cardctl_gpk_pkinit *args)
{
sc_apdu_t apdu;
int r;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"gpk_pkfile_init(%u)\n", args->privlen);
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_1;
apdu.cla = 0x80;
apdu.ins = 0x12;
apdu.p1 = args->file->id & 0x1F;
apdu.p2 = args->privlen / 4;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
return r;
}
/*
* Initialize the private portion of a public key file
*/
static int
gpk_generate_key(sc_card_t *card, struct sc_cardctl_gpk_genkey *args)
{
sc_apdu_t apdu;
int r;
u8 buffer[256];
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"gpk_generate_key(%u)\n", args->privlen);
if (args->privlen != 512 && args->privlen != 1024) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Key generation not supported for key length %d",
args->privlen);
return SC_ERROR_NOT_SUPPORTED;
}
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.cla = 0x80;
apdu.ins = 0xD2;
apdu.p1 = 0x80 | (args->fid & 0x1F);
apdu.p2 = (args->privlen == 1024) ? 0x11 : 0;
apdu.le = args->privlen / 8 + 2;
apdu.resp = buffer;
apdu.resplen = 256;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
/* Return the public key, inverted.
* The first two bytes must be stripped off. */
if (args->pubkey_len && apdu.resplen > 2) {
r = reverse(args->pubkey, args->pubkey_len,
buffer + 2, apdu.resplen - 2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Failed to reverse buffer");
args->pubkey_len = r;
}
return r;
}
/*
* Store a private key component
*/
static int
gpk_pkfile_load(sc_card_t *card, struct sc_cardctl_gpk_pkload *args)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_apdu_t apdu;
unsigned int n;
u8 temp[256];
int r = SC_SUCCESS, outl;
EVP_CIPHER_CTX * ctx;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "gpk_pkfile_load(fid=%04x, len=%d, datalen=%d)\n",
args->file->id, args->len, args->datalen);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
return SC_ERROR_INTERNAL;
if (0) {
sc_log_hex(card->ctx, "Sending (cleartext)",
args->data, args->datalen);
}
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_3_SHORT;
apdu.cla = 0x80;
apdu.ins = 0x18;
apdu.p1 = args->file->id & 0x1F;
apdu.p2 = args->len;
apdu.lc = args->datalen;
/* encrypt the private key material */
assert(args->datalen <= sizeof(temp));
if (!priv->key_set) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "No secure messaging key set!\n");
return SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
}
EVP_EncryptInit_ex(ctx, EVP_des_ede(), NULL, priv->key, NULL);
for (n = 0; n < args->datalen; n += 8) {
if (!EVP_EncryptUpdate(ctx, temp+n, &outl, args->data + n, 8)) {
r = SC_ERROR_INTERNAL;
break;
}
}
if (ctx)
EVP_CIPHER_CTX_free(ctx);
if (r != SC_SUCCESS)
return SC_ERROR_INTERNAL;
apdu.data = temp;
apdu.datalen = args->datalen;
/* Forget the key. The card seems to forget it, too :) */
priv->key_set = 0;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/*
* This function lets pkcs15init query for the transport key
*/
static int
gpk_get_default_key(sc_card_t *card, struct sc_cardctl_default_key *data)
{
if (data->method == SC_AC_PRO && data->key_ref == 1) {
if (data->len < 16)
return SC_ERROR_BUFFER_TOO_SMALL;
memcpy(data->key_data, "TEST KEYTEST KEY", 16);
data->len = 16;
return 0;
}
return SC_ERROR_NO_DEFAULT_KEY;
}
/*
* GetInfo call
*/
static int gpk_get_info(sc_card_t *card, int p1, int p2, u8 *buf,
size_t buflen)
{
sc_apdu_t apdu;
int r, retry = 0;
/* We may have to retry the get info command. It
* returns 6B00 if a previous command returned a 61xx response,
* but the host failed to collect the results.
*
* Note the additional sc_lock/sc_unlock pair, which
* is required to prevent sc_transmit_apdu from
* calling logout(), which in turn does a SELECT MF
* without collecting the response :)
*/
r = sc_lock(card);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "sc_lock() failed");
do {
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.cla = 0x80;
apdu.ins = 0xC0;
apdu.p1 = p1;
apdu.p2 = p2;
apdu.le = buflen;
apdu.resp = buf;
apdu.resplen = buflen;
if ((r = sc_transmit_apdu(card, &apdu)) < 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "APDU transmit failed: %s",
sc_strerror(r));
sc_unlock(card);
return r;
}
} while (apdu.sw1 == 0x6B && apdu.sw2 == 0x00 && retry++ < 1);
sc_unlock(card);
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
return r;
}
static int gpk_get_serialnr(sc_card_t *card, sc_serial_number_t *serial)
{
int r;
u8 rbuf[10];
sc_apdu_t apdu;
if (card->type != SC_CARD_TYPE_GPK_GPK16000)
return SC_ERROR_NOT_SUPPORTED;
if (!serial)
return SC_ERROR_INVALID_ARGUMENTS;
/* see if we have cached serial number */
if (card->serialnr.len) {
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
/* get serial number via Get CSN */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xb8, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 8;
apdu.lc = 0;
apdu.datalen = 0;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00)
return SC_ERROR_INTERNAL;
/* cache serial number */
memcpy(card->serialnr.value, apdu.resp, apdu.resplen);
card->serialnr.len = apdu.resplen;
/* copy and return serial number */
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
/*
* Dispatch card_ctl calls
*/
static int
gpk_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
switch (cmd) {
case SC_CARDCTL_ERASE_CARD:
return gpk_erase_card(card);
case SC_CARDCTL_GET_DEFAULT_KEY:
return gpk_get_default_key(card,
(struct sc_cardctl_default_key *) ptr);
case SC_CARDCTL_GPK_VARIANT:
*(int *) ptr = card->type;
return 0;
case SC_CARDCTL_GPK_LOCK:
return gpk_lock(card, (struct sc_cardctl_gpk_lock *) ptr);
case SC_CARDCTL_GPK_PKINIT:
return gpk_pkfile_init(card,
(struct sc_cardctl_gpk_pkinit *) ptr);
case SC_CARDCTL_GPK_PKLOAD:
return gpk_pkfile_load(card,
(struct sc_cardctl_gpk_pkload *) ptr);
case SC_CARDCTL_GPK_IS_LOCKED:
*(int *) ptr = DRVDATA(card)->locked;
return 0;
case SC_CARDCTL_GPK_GENERATE_KEY:
return gpk_generate_key(card,
(struct sc_cardctl_gpk_genkey *) ptr);
case SC_CARDCTL_GET_SERIALNR:
return gpk_get_serialnr(card, (sc_serial_number_t *) ptr);
}
return SC_ERROR_NOT_SUPPORTED;
}
static int
gpk_build_pin_apdu(sc_card_t *card, sc_apdu_t *apdu, struct sc_pin_cmd_data *data)
{
static u8 sbuf[8];
int r;
if (data->pin_type != SC_AC_CHV)
return SC_ERROR_INVALID_ARGUMENTS;
/* XXX deal with secure messaging here */
memset(apdu, 0, sizeof(*apdu));
apdu->cse = SC_APDU_CASE_3_SHORT;
data->flags |= SC_PIN_CMD_NEED_PADDING;
switch (data->cmd) {
case SC_PIN_CMD_VERIFY:
/* Copy PIN to buffer and pad */
data->pin1.encoding = SC_PIN_ENCODING_ASCII;
data->pin1.pad_length = 8;
data->pin1.pad_char = 0x00;
data->pin1.offset = 5;
r = sc_build_pin(sbuf, 8, &data->pin1, 1);
if (r < 0)
return r;
apdu->cla = 0x00;
apdu->ins = 0x20;
apdu->p1 = 0x00;
break;
case SC_PIN_CMD_CHANGE:
case SC_PIN_CMD_UNBLOCK:
/* Copy PINs to buffer, BCD-encoded, and pad */
data->pin1.encoding = SC_PIN_ENCODING_BCD;
data->pin1.pad_length = 8;
data->pin1.pad_char = 0x00;
data->pin1.offset = 5;
data->pin2.encoding = SC_PIN_ENCODING_BCD;
data->pin2.pad_length = 8;
data->pin2.pad_char = 0x00;
data->pin2.offset = 5 + 4;
if ((r = sc_build_pin(sbuf, 4, &data->pin1, 1)) < 0
|| (r = sc_build_pin(sbuf + 4, 4, &data->pin2, 1)) < 0)
return r;
apdu->cla = 0x80;
apdu->ins = 0x24;
apdu->p1 = (data->cmd == SC_PIN_CMD_CHANGE)? 0x00 : 0x01;
break;
default:
return SC_ERROR_NOT_SUPPORTED;
}
apdu->p2 = data->pin_reference & 7;
apdu->lc = 8;
apdu->datalen = 8;
apdu->data = sbuf;
return 0;
}
static int
gpk_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left)
{
sc_apdu_t apdu;
int r;
/* Special case - External Authenticate */
if (data->cmd == SC_PIN_CMD_VERIFY
&& data->pin_type == SC_AC_PRO)
return gpk_select_key(card,
data->pin_reference,
data->pin1.data,
data->pin1.len);
r = gpk_build_pin_apdu(card, &apdu, data);
if (r < 0)
return r;
data->apdu = &apdu;
return iso_ops->pin_cmd(card, data, tries_left);
}
/*
* Initialize the driver struct
*/
static struct sc_card_driver *
sc_get_driver(void)
{
struct sc_card_driver *iso_drv;
iso_drv = sc_get_iso7816_driver();
iso_ops = iso_drv->ops;
gpk_ops = *iso_ops;
gpk_ops.match_card = gpk_match_card;
gpk_ops.init = gpk_init;
gpk_ops.finish = gpk_finish;
gpk_ops.select_file = gpk_select_file;
gpk_ops.read_binary = gpk_read_binary;
gpk_ops.write_binary = gpk_write_binary;
gpk_ops.update_binary = gpk_update_binary;
gpk_ops.create_file = gpk_create_file;
/* gpk_ops.check_sw = gpk_check_sw; */
gpk_ops.card_ctl = gpk_card_ctl;
gpk_ops.set_security_env= gpk_set_security_env;
gpk_ops.restore_security_env= gpk_restore_security_env;
gpk_ops.compute_signature= gpk_compute_signature;
gpk_ops.decipher = gpk_decipher;
gpk_ops.pin_cmd = gpk_pin_cmd;
return &gpk_drv;
}
struct sc_card_driver *
sc_get_gpk_driver(void)
{
return sc_get_driver();
}
#endif /* ENABLE_OPENSSL */
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_351_7 |
crossvul-cpp_data_bad_2706_0 | /*
* Copyright (c) 1990, 1991, 1993, 1994, 1995, 1996, 1997
* 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: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Extensively modified by Motonori Shindo (mshindo@mshindo.net) for more
* complete PPP support.
*/
/* \summary: Point to Point Protocol (PPP) printer */
/*
* TODO:
* o resolve XXX as much as possible
* o MP support
* o BAP support
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#ifdef __bsdi__
#include <net/slcompress.h>
#include <net/if_ppp.h>
#endif
#include <stdlib.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "ppp.h"
#include "chdlc.h"
#include "ethertype.h"
#include "oui.h"
/*
* The following constatns are defined by IANA. Please refer to
* http://www.isi.edu/in-notes/iana/assignments/ppp-numbers
* for the up-to-date information.
*/
/* Protocol Codes defined in ppp.h */
static const struct tok ppptype2str[] = {
{ PPP_IP, "IP" },
{ PPP_OSI, "OSI" },
{ PPP_NS, "NS" },
{ PPP_DECNET, "DECNET" },
{ PPP_APPLE, "APPLE" },
{ PPP_IPX, "IPX" },
{ PPP_VJC, "VJC IP" },
{ PPP_VJNC, "VJNC IP" },
{ PPP_BRPDU, "BRPDU" },
{ PPP_STII, "STII" },
{ PPP_VINES, "VINES" },
{ PPP_MPLS_UCAST, "MPLS" },
{ PPP_MPLS_MCAST, "MPLS" },
{ PPP_COMP, "Compressed"},
{ PPP_ML, "MLPPP"},
{ PPP_IPV6, "IP6"},
{ PPP_HELLO, "HELLO" },
{ PPP_LUXCOM, "LUXCOM" },
{ PPP_SNS, "SNS" },
{ PPP_IPCP, "IPCP" },
{ PPP_OSICP, "OSICP" },
{ PPP_NSCP, "NSCP" },
{ PPP_DECNETCP, "DECNETCP" },
{ PPP_APPLECP, "APPLECP" },
{ PPP_IPXCP, "IPXCP" },
{ PPP_STIICP, "STIICP" },
{ PPP_VINESCP, "VINESCP" },
{ PPP_IPV6CP, "IP6CP" },
{ PPP_MPLSCP, "MPLSCP" },
{ PPP_LCP, "LCP" },
{ PPP_PAP, "PAP" },
{ PPP_LQM, "LQM" },
{ PPP_CHAP, "CHAP" },
{ PPP_EAP, "EAP" },
{ PPP_SPAP, "SPAP" },
{ PPP_SPAP_OLD, "Old-SPAP" },
{ PPP_BACP, "BACP" },
{ PPP_BAP, "BAP" },
{ PPP_MPCP, "MLPPP-CP" },
{ PPP_CCP, "CCP" },
{ 0, NULL }
};
/* Control Protocols (LCP/IPCP/CCP etc.) Codes defined in RFC 1661 */
#define CPCODES_VEXT 0 /* Vendor-Specific (RFC2153) */
#define CPCODES_CONF_REQ 1 /* Configure-Request */
#define CPCODES_CONF_ACK 2 /* Configure-Ack */
#define CPCODES_CONF_NAK 3 /* Configure-Nak */
#define CPCODES_CONF_REJ 4 /* Configure-Reject */
#define CPCODES_TERM_REQ 5 /* Terminate-Request */
#define CPCODES_TERM_ACK 6 /* Terminate-Ack */
#define CPCODES_CODE_REJ 7 /* Code-Reject */
#define CPCODES_PROT_REJ 8 /* Protocol-Reject (LCP only) */
#define CPCODES_ECHO_REQ 9 /* Echo-Request (LCP only) */
#define CPCODES_ECHO_RPL 10 /* Echo-Reply (LCP only) */
#define CPCODES_DISC_REQ 11 /* Discard-Request (LCP only) */
#define CPCODES_ID 12 /* Identification (LCP only) RFC1570 */
#define CPCODES_TIME_REM 13 /* Time-Remaining (LCP only) RFC1570 */
#define CPCODES_RESET_REQ 14 /* Reset-Request (CCP only) RFC1962 */
#define CPCODES_RESET_REP 15 /* Reset-Reply (CCP only) */
static const struct tok cpcodes[] = {
{CPCODES_VEXT, "Vendor-Extension"}, /* RFC2153 */
{CPCODES_CONF_REQ, "Conf-Request"},
{CPCODES_CONF_ACK, "Conf-Ack"},
{CPCODES_CONF_NAK, "Conf-Nack"},
{CPCODES_CONF_REJ, "Conf-Reject"},
{CPCODES_TERM_REQ, "Term-Request"},
{CPCODES_TERM_ACK, "Term-Ack"},
{CPCODES_CODE_REJ, "Code-Reject"},
{CPCODES_PROT_REJ, "Prot-Reject"},
{CPCODES_ECHO_REQ, "Echo-Request"},
{CPCODES_ECHO_RPL, "Echo-Reply"},
{CPCODES_DISC_REQ, "Disc-Req"},
{CPCODES_ID, "Ident"}, /* RFC1570 */
{CPCODES_TIME_REM, "Time-Rem"}, /* RFC1570 */
{CPCODES_RESET_REQ, "Reset-Req"}, /* RFC1962 */
{CPCODES_RESET_REP, "Reset-Ack"}, /* RFC1962 */
{0, NULL}
};
/* LCP Config Options */
#define LCPOPT_VEXT 0
#define LCPOPT_MRU 1
#define LCPOPT_ACCM 2
#define LCPOPT_AP 3
#define LCPOPT_QP 4
#define LCPOPT_MN 5
#define LCPOPT_DEP6 6
#define LCPOPT_PFC 7
#define LCPOPT_ACFC 8
#define LCPOPT_FCSALT 9
#define LCPOPT_SDP 10
#define LCPOPT_NUMMODE 11
#define LCPOPT_DEP12 12
#define LCPOPT_CBACK 13
#define LCPOPT_DEP14 14
#define LCPOPT_DEP15 15
#define LCPOPT_DEP16 16
#define LCPOPT_MLMRRU 17
#define LCPOPT_MLSSNHF 18
#define LCPOPT_MLED 19
#define LCPOPT_PROP 20
#define LCPOPT_DCEID 21
#define LCPOPT_MPP 22
#define LCPOPT_LD 23
#define LCPOPT_LCPAOPT 24
#define LCPOPT_COBS 25
#define LCPOPT_PE 26
#define LCPOPT_MLHF 27
#define LCPOPT_I18N 28
#define LCPOPT_SDLOS 29
#define LCPOPT_PPPMUX 30
#define LCPOPT_MIN LCPOPT_VEXT
#define LCPOPT_MAX LCPOPT_PPPMUX
static const char *lcpconfopts[] = {
"Vend-Ext", /* (0) */
"MRU", /* (1) */
"ACCM", /* (2) */
"Auth-Prot", /* (3) */
"Qual-Prot", /* (4) */
"Magic-Num", /* (5) */
"deprecated(6)", /* used to be a Quality Protocol */
"PFC", /* (7) */
"ACFC", /* (8) */
"FCS-Alt", /* (9) */
"SDP", /* (10) */
"Num-Mode", /* (11) */
"deprecated(12)", /* used to be a Multi-Link-Procedure*/
"Call-Back", /* (13) */
"deprecated(14)", /* used to be a Connect-Time */
"deprecated(15)", /* used to be a Compund-Frames */
"deprecated(16)", /* used to be a Nominal-Data-Encap */
"MRRU", /* (17) */
"12-Bit seq #", /* (18) */
"End-Disc", /* (19) */
"Proprietary", /* (20) */
"DCE-Id", /* (21) */
"MP+", /* (22) */
"Link-Disc", /* (23) */
"LCP-Auth-Opt", /* (24) */
"COBS", /* (25) */
"Prefix-elision", /* (26) */
"Multilink-header-Form",/* (27) */
"I18N", /* (28) */
"SDL-over-SONET/SDH", /* (29) */
"PPP-Muxing", /* (30) */
};
/* ECP - to be supported */
/* CCP Config Options */
#define CCPOPT_OUI 0 /* RFC1962 */
#define CCPOPT_PRED1 1 /* RFC1962 */
#define CCPOPT_PRED2 2 /* RFC1962 */
#define CCPOPT_PJUMP 3 /* RFC1962 */
/* 4-15 unassigned */
#define CCPOPT_HPPPC 16 /* RFC1962 */
#define CCPOPT_STACLZS 17 /* RFC1974 */
#define CCPOPT_MPPC 18 /* RFC2118 */
#define CCPOPT_GFZA 19 /* RFC1962 */
#define CCPOPT_V42BIS 20 /* RFC1962 */
#define CCPOPT_BSDCOMP 21 /* RFC1977 */
/* 22 unassigned */
#define CCPOPT_LZSDCP 23 /* RFC1967 */
#define CCPOPT_MVRCA 24 /* RFC1975 */
#define CCPOPT_DEC 25 /* RFC1976 */
#define CCPOPT_DEFLATE 26 /* RFC1979 */
/* 27-254 unassigned */
#define CCPOPT_RESV 255 /* RFC1962 */
static const struct tok ccpconfopts_values[] = {
{ CCPOPT_OUI, "OUI" },
{ CCPOPT_PRED1, "Pred-1" },
{ CCPOPT_PRED2, "Pred-2" },
{ CCPOPT_PJUMP, "Puddle" },
{ CCPOPT_HPPPC, "HP-PPC" },
{ CCPOPT_STACLZS, "Stac-LZS" },
{ CCPOPT_MPPC, "MPPC" },
{ CCPOPT_GFZA, "Gand-FZA" },
{ CCPOPT_V42BIS, "V.42bis" },
{ CCPOPT_BSDCOMP, "BSD-Comp" },
{ CCPOPT_LZSDCP, "LZS-DCP" },
{ CCPOPT_MVRCA, "MVRCA" },
{ CCPOPT_DEC, "DEC" },
{ CCPOPT_DEFLATE, "Deflate" },
{ CCPOPT_RESV, "Reserved"},
{0, NULL}
};
/* BACP Config Options */
#define BACPOPT_FPEER 1 /* RFC2125 */
static const struct tok bacconfopts_values[] = {
{ BACPOPT_FPEER, "Favored-Peer" },
{0, NULL}
};
/* SDCP - to be supported */
/* IPCP Config Options */
#define IPCPOPT_2ADDR 1 /* RFC1172, RFC1332 (deprecated) */
#define IPCPOPT_IPCOMP 2 /* RFC1332 */
#define IPCPOPT_ADDR 3 /* RFC1332 */
#define IPCPOPT_MOBILE4 4 /* RFC2290 */
#define IPCPOPT_PRIDNS 129 /* RFC1877 */
#define IPCPOPT_PRINBNS 130 /* RFC1877 */
#define IPCPOPT_SECDNS 131 /* RFC1877 */
#define IPCPOPT_SECNBNS 132 /* RFC1877 */
static const struct tok ipcpopt_values[] = {
{ IPCPOPT_2ADDR, "IP-Addrs" },
{ IPCPOPT_IPCOMP, "IP-Comp" },
{ IPCPOPT_ADDR, "IP-Addr" },
{ IPCPOPT_MOBILE4, "Home-Addr" },
{ IPCPOPT_PRIDNS, "Pri-DNS" },
{ IPCPOPT_PRINBNS, "Pri-NBNS" },
{ IPCPOPT_SECDNS, "Sec-DNS" },
{ IPCPOPT_SECNBNS, "Sec-NBNS" },
{ 0, NULL }
};
#define IPCPOPT_IPCOMP_HDRCOMP 0x61 /* rfc3544 */
#define IPCPOPT_IPCOMP_MINLEN 14
static const struct tok ipcpopt_compproto_values[] = {
{ PPP_VJC, "VJ-Comp" },
{ IPCPOPT_IPCOMP_HDRCOMP, "IP Header Compression" },
{ 0, NULL }
};
static const struct tok ipcpopt_compproto_subopt_values[] = {
{ 1, "RTP-Compression" },
{ 2, "Enhanced RTP-Compression" },
{ 0, NULL }
};
/* IP6CP Config Options */
#define IP6CP_IFID 1
static const struct tok ip6cpopt_values[] = {
{ IP6CP_IFID, "Interface-ID" },
{ 0, NULL }
};
/* ATCP - to be supported */
/* OSINLCP - to be supported */
/* BVCP - to be supported */
/* BCP - to be supported */
/* IPXCP - to be supported */
/* MPLSCP - to be supported */
/* Auth Algorithms */
/* 0-4 Reserved (RFC1994) */
#define AUTHALG_CHAPMD5 5 /* RFC1994 */
#define AUTHALG_MSCHAP1 128 /* RFC2433 */
#define AUTHALG_MSCHAP2 129 /* RFC2795 */
static const struct tok authalg_values[] = {
{ AUTHALG_CHAPMD5, "MD5" },
{ AUTHALG_MSCHAP1, "MS-CHAPv1" },
{ AUTHALG_MSCHAP2, "MS-CHAPv2" },
{ 0, NULL }
};
/* FCS Alternatives - to be supported */
/* Multilink Endpoint Discriminator (RFC1717) */
#define MEDCLASS_NULL 0 /* Null Class */
#define MEDCLASS_LOCAL 1 /* Locally Assigned */
#define MEDCLASS_IPV4 2 /* Internet Protocol (IPv4) */
#define MEDCLASS_MAC 3 /* IEEE 802.1 global MAC address */
#define MEDCLASS_MNB 4 /* PPP Magic Number Block */
#define MEDCLASS_PSNDN 5 /* Public Switched Network Director Number */
/* PPP LCP Callback */
#define CALLBACK_AUTH 0 /* Location determined by user auth */
#define CALLBACK_DSTR 1 /* Dialing string */
#define CALLBACK_LID 2 /* Location identifier */
#define CALLBACK_E164 3 /* E.164 number */
#define CALLBACK_X500 4 /* X.500 distinguished name */
#define CALLBACK_CBCP 6 /* Location is determined during CBCP nego */
static const struct tok ppp_callback_values[] = {
{ CALLBACK_AUTH, "UserAuth" },
{ CALLBACK_DSTR, "DialString" },
{ CALLBACK_LID, "LocalID" },
{ CALLBACK_E164, "E.164" },
{ CALLBACK_X500, "X.500" },
{ CALLBACK_CBCP, "CBCP" },
{ 0, NULL }
};
/* CHAP */
#define CHAP_CHAL 1
#define CHAP_RESP 2
#define CHAP_SUCC 3
#define CHAP_FAIL 4
static const struct tok chapcode_values[] = {
{ CHAP_CHAL, "Challenge" },
{ CHAP_RESP, "Response" },
{ CHAP_SUCC, "Success" },
{ CHAP_FAIL, "Fail" },
{ 0, NULL}
};
/* PAP */
#define PAP_AREQ 1
#define PAP_AACK 2
#define PAP_ANAK 3
static const struct tok papcode_values[] = {
{ PAP_AREQ, "Auth-Req" },
{ PAP_AACK, "Auth-ACK" },
{ PAP_ANAK, "Auth-NACK" },
{ 0, NULL }
};
/* BAP */
#define BAP_CALLREQ 1
#define BAP_CALLRES 2
#define BAP_CBREQ 3
#define BAP_CBRES 4
#define BAP_LDQREQ 5
#define BAP_LDQRES 6
#define BAP_CSIND 7
#define BAP_CSRES 8
static int print_lcp_config_options(netdissect_options *, const u_char *p, int);
static int print_ipcp_config_options(netdissect_options *, const u_char *p, int);
static int print_ip6cp_config_options(netdissect_options *, const u_char *p, int);
static int print_ccp_config_options(netdissect_options *, const u_char *p, int);
static int print_bacp_config_options(netdissect_options *, const u_char *p, int);
static void handle_ppp(netdissect_options *, u_int proto, const u_char *p, int length);
/* generic Control Protocol (e.g. LCP, IPCP, CCP, etc.) handler */
static void
handle_ctrl_proto(netdissect_options *ndo,
u_int proto, const u_char *pptr, int length)
{
const char *typestr;
u_int code, len;
int (*pfunc)(netdissect_options *, const u_char *, int);
int x, j;
const u_char *tptr;
tptr=pptr;
typestr = tok2str(ppptype2str, "unknown ctrl-proto (0x%04x)", proto);
ND_PRINT((ndo, "%s, ", typestr));
if (length < 4) /* FIXME weak boundary checking */
goto trunc;
ND_TCHECK2(*tptr, 2);
code = *tptr++;
ND_PRINT((ndo, "%s (0x%02x), id %u, length %u",
tok2str(cpcodes, "Unknown Opcode",code),
code,
*tptr++, /* ID */
length + 2));
if (!ndo->ndo_vflag)
return;
if (length <= 4)
return; /* there may be a NULL confreq etc. */
ND_TCHECK2(*tptr, 2);
len = EXTRACT_16BITS(tptr);
tptr += 2;
ND_PRINT((ndo, "\n\tencoded length %u (=Option(s) length %u)", len, len - 4));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr - 2, "\n\t", 6);
switch (code) {
case CPCODES_VEXT:
if (length < 11)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
tptr += 4;
ND_TCHECK2(*tptr, 3);
ND_PRINT((ndo, " Vendor: %s (%u)",
tok2str(oui_values,"Unknown",EXTRACT_24BITS(tptr)),
EXTRACT_24BITS(tptr)));
/* XXX: need to decode Kind and Value(s)? */
break;
case CPCODES_CONF_REQ:
case CPCODES_CONF_ACK:
case CPCODES_CONF_NAK:
case CPCODES_CONF_REJ:
x = len - 4; /* Code(1), Identifier(1) and Length(2) */
do {
switch (proto) {
case PPP_LCP:
pfunc = print_lcp_config_options;
break;
case PPP_IPCP:
pfunc = print_ipcp_config_options;
break;
case PPP_IPV6CP:
pfunc = print_ip6cp_config_options;
break;
case PPP_CCP:
pfunc = print_ccp_config_options;
break;
case PPP_BACP:
pfunc = print_bacp_config_options;
break;
default:
/*
* No print routine for the options for
* this protocol.
*/
pfunc = NULL;
break;
}
if (pfunc == NULL) /* catch the above null pointer if unknown CP */
break;
if ((j = (*pfunc)(ndo, tptr, len)) == 0)
break;
x -= j;
tptr += j;
} while (x > 0);
break;
case CPCODES_TERM_REQ:
case CPCODES_TERM_ACK:
/* XXX: need to decode Data? */
break;
case CPCODES_CODE_REJ:
/* XXX: need to decode Rejected-Packet? */
break;
case CPCODES_PROT_REJ:
if (length < 6)
break;
ND_TCHECK2(*tptr, 2);
ND_PRINT((ndo, "\n\t Rejected %s Protocol (0x%04x)",
tok2str(ppptype2str,"unknown", EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr)));
/* XXX: need to decode Rejected-Information? - hexdump for now */
if (len > 6) {
ND_PRINT((ndo, "\n\t Rejected Packet"));
print_unknown_data(ndo, tptr + 2, "\n\t ", len - 2);
}
break;
case CPCODES_ECHO_REQ:
case CPCODES_ECHO_RPL:
case CPCODES_DISC_REQ:
if (length < 8)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
/* XXX: need to decode Data? - hexdump for now */
if (len > 8) {
ND_PRINT((ndo, "\n\t -----trailing data-----"));
ND_TCHECK2(tptr[4], len - 8);
print_unknown_data(ndo, tptr + 4, "\n\t ", len - 8);
}
break;
case CPCODES_ID:
if (length < 8)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
/* RFC 1661 says this is intended to be human readable */
if (len > 8) {
ND_PRINT((ndo, "\n\t Message\n\t "));
if (fn_printn(ndo, tptr + 4, len - 4, ndo->ndo_snapend))
goto trunc;
}
break;
case CPCODES_TIME_REM:
if (length < 12)
break;
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Magic-Num 0x%08x", EXTRACT_32BITS(tptr)));
ND_TCHECK2(*(tptr + 4), 4);
ND_PRINT((ndo, ", Seconds-Remaining %us", EXTRACT_32BITS(tptr + 4)));
/* XXX: need to decode Message? */
break;
default:
/* XXX this is dirty but we do not get the
* original pointer passed to the begin
* the PPP packet */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr - 2, "\n\t ", length + 2);
break;
}
return;
trunc:
ND_PRINT((ndo, "[|%s]", typestr));
}
/* LCP config options */
static int
print_lcp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX))
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
lcpconfopts[opt], opt, len));
else
ND_PRINT((ndo, "\n\tunknown LCP option 0x%02x", opt));
return 0;
}
if ((opt >= LCPOPT_MIN) && (opt <= LCPOPT_MAX))
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", lcpconfopts[opt], opt, len));
else {
ND_PRINT((ndo, "\n\tunknown LCP option 0x%02x", opt));
return len;
}
switch (opt) {
case LCPOPT_VEXT:
if (len < 6) {
ND_PRINT((ndo, " (length bogus, should be >= 6)"));
return len;
}
ND_TCHECK2(*(p + 2), 3);
ND_PRINT((ndo, ": Vendor: %s (%u)",
tok2str(oui_values,"Unknown",EXTRACT_24BITS(p+2)),
EXTRACT_24BITS(p + 2)));
#if 0
ND_TCHECK(p[5]);
ND_PRINT((ndo, ", kind: 0x%02x", p[5]));
ND_PRINT((ndo, ", Value: 0x"));
for (i = 0; i < len - 6; i++) {
ND_TCHECK(p[6 + i]);
ND_PRINT((ndo, "%02x", p[6 + i]));
}
#endif
break;
case LCPOPT_MRU:
if (len != 4) {
ND_PRINT((ndo, " (length bogus, should be = 4)"));
return len;
}
ND_TCHECK2(*(p + 2), 2);
ND_PRINT((ndo, ": %u", EXTRACT_16BITS(p + 2)));
break;
case LCPOPT_ACCM:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return len;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": 0x%08x", EXTRACT_32BITS(p + 2)));
break;
case LCPOPT_AP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK2(*(p + 2), 2);
ND_PRINT((ndo, ": %s", tok2str(ppptype2str, "Unknown Auth Proto (0x04x)", EXTRACT_16BITS(p + 2))));
switch (EXTRACT_16BITS(p+2)) {
case PPP_CHAP:
ND_TCHECK(p[4]);
ND_PRINT((ndo, ", %s", tok2str(authalg_values, "Unknown Auth Alg %u", p[4])));
break;
case PPP_PAP: /* fall through */
case PPP_EAP:
case PPP_SPAP:
case PPP_SPAP_OLD:
break;
default:
print_unknown_data(ndo, p, "\n\t", len);
}
break;
case LCPOPT_QP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return 0;
}
ND_TCHECK2(*(p + 2), 2);
if (EXTRACT_16BITS(p+2) == PPP_LQM)
ND_PRINT((ndo, ": LQR"));
else
ND_PRINT((ndo, ": unknown"));
break;
case LCPOPT_MN:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return 0;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": 0x%08x", EXTRACT_32BITS(p + 2)));
break;
case LCPOPT_PFC:
break;
case LCPOPT_ACFC:
break;
case LCPOPT_LD:
if (len != 4) {
ND_PRINT((ndo, " (length bogus, should be = 4)"));
return 0;
}
ND_TCHECK2(*(p + 2), 2);
ND_PRINT((ndo, ": 0x%04x", EXTRACT_16BITS(p + 2)));
break;
case LCPOPT_CBACK:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return 0;
}
ND_PRINT((ndo, ": "));
ND_TCHECK(p[2]);
ND_PRINT((ndo, ": Callback Operation %s (%u)",
tok2str(ppp_callback_values, "Unknown", p[2]),
p[2]));
break;
case LCPOPT_MLMRRU:
if (len != 4) {
ND_PRINT((ndo, " (length bogus, should be = 4)"));
return 0;
}
ND_TCHECK2(*(p + 2), 2);
ND_PRINT((ndo, ": %u", EXTRACT_16BITS(p + 2)));
break;
case LCPOPT_MLED:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return 0;
}
ND_TCHECK(p[2]);
switch (p[2]) { /* class */
case MEDCLASS_NULL:
ND_PRINT((ndo, ": Null"));
break;
case MEDCLASS_LOCAL:
ND_PRINT((ndo, ": Local")); /* XXX */
break;
case MEDCLASS_IPV4:
if (len != 7) {
ND_PRINT((ndo, " (length bogus, should be = 7)"));
return 0;
}
ND_TCHECK2(*(p + 3), 4);
ND_PRINT((ndo, ": IPv4 %s", ipaddr_string(ndo, p + 3)));
break;
case MEDCLASS_MAC:
if (len != 9) {
ND_PRINT((ndo, " (length bogus, should be = 9)"));
return 0;
}
ND_TCHECK2(*(p + 3), 6);
ND_PRINT((ndo, ": MAC %s", etheraddr_string(ndo, p + 3)));
break;
case MEDCLASS_MNB:
ND_PRINT((ndo, ": Magic-Num-Block")); /* XXX */
break;
case MEDCLASS_PSNDN:
ND_PRINT((ndo, ": PSNDN")); /* XXX */
break;
default:
ND_PRINT((ndo, ": Unknown class %u", p[2]));
break;
}
break;
/* XXX: to be supported */
#if 0
case LCPOPT_DEP6:
case LCPOPT_FCSALT:
case LCPOPT_SDP:
case LCPOPT_NUMMODE:
case LCPOPT_DEP12:
case LCPOPT_DEP14:
case LCPOPT_DEP15:
case LCPOPT_DEP16:
case LCPOPT_MLSSNHF:
case LCPOPT_PROP:
case LCPOPT_DCEID:
case LCPOPT_MPP:
case LCPOPT_LCPAOPT:
case LCPOPT_COBS:
case LCPOPT_PE:
case LCPOPT_MLHF:
case LCPOPT_I18N:
case LCPOPT_SDLOS:
case LCPOPT_PPPMUX:
break;
#endif
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|lcp]"));
return 0;
}
/* ML-PPP*/
static const struct tok ppp_ml_flag_values[] = {
{ 0x80, "begin" },
{ 0x40, "end" },
{ 0, NULL }
};
static void
handle_mlppp(netdissect_options *ndo,
const u_char *p, int length)
{
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "MLPPP, "));
ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u",
(EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */
bittok2str(ppp_ml_flag_values, "none", *p & 0xc0),
length));
}
/* CHAP */
static void
handle_chap(netdissect_options *ndo,
const u_char *p, int length)
{
u_int code, len;
int val_size, name_size, msg_size;
const u_char *p0;
int i;
p0 = p;
if (length < 1) {
ND_PRINT((ndo, "[|chap]"));
return;
} else if (length < 4) {
ND_TCHECK(*p);
ND_PRINT((ndo, "[|chap 0x%02x]", *p));
return;
}
ND_TCHECK(*p);
code = *p;
ND_PRINT((ndo, "CHAP, %s (0x%02x)",
tok2str(chapcode_values,"unknown",code),
code));
p++;
ND_TCHECK(*p);
ND_PRINT((ndo, ", id %u", *p)); /* ID */
p++;
ND_TCHECK2(*p, 2);
len = EXTRACT_16BITS(p);
p += 2;
/*
* Note that this is a generic CHAP decoding routine. Since we
* don't know which flavor of CHAP (i.e. CHAP-MD5, MS-CHAPv1,
* MS-CHAPv2) is used at this point, we can't decode packet
* specifically to each algorithms. Instead, we simply decode
* the GCD (Gratest Common Denominator) for all algorithms.
*/
switch (code) {
case CHAP_CHAL:
case CHAP_RESP:
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
val_size = *p; /* value size */
p++;
if (length - (p - p0) < val_size)
return;
ND_PRINT((ndo, ", Value "));
for (i = 0; i < val_size; i++) {
ND_TCHECK(*p);
ND_PRINT((ndo, "%02x", *p++));
}
name_size = len - (p - p0);
ND_PRINT((ndo, ", Name "));
for (i = 0; i < name_size; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
case CHAP_SUCC:
case CHAP_FAIL:
msg_size = len - (p - p0);
ND_PRINT((ndo, ", Msg "));
for (i = 0; i< msg_size; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
}
return;
trunc:
ND_PRINT((ndo, "[|chap]"));
}
/* PAP (see RFC 1334) */
static void
handle_pap(netdissect_options *ndo,
const u_char *p, int length)
{
u_int code, len;
int peerid_len, passwd_len, msg_len;
const u_char *p0;
int i;
p0 = p;
if (length < 1) {
ND_PRINT((ndo, "[|pap]"));
return;
} else if (length < 4) {
ND_TCHECK(*p);
ND_PRINT((ndo, "[|pap 0x%02x]", *p));
return;
}
ND_TCHECK(*p);
code = *p;
ND_PRINT((ndo, "PAP, %s (0x%02x)",
tok2str(papcode_values, "unknown", code),
code));
p++;
ND_TCHECK(*p);
ND_PRINT((ndo, ", id %u", *p)); /* ID */
p++;
ND_TCHECK2(*p, 2);
len = EXTRACT_16BITS(p);
p += 2;
if ((int)len > length) {
ND_PRINT((ndo, ", length %u > packet size", len));
return;
}
length = len;
if (length < (p - p0)) {
ND_PRINT((ndo, ", length %u < PAP header length", length));
return;
}
switch (code) {
case PAP_AREQ:
/* A valid Authenticate-Request is 6 or more octets long. */
if (len < 6)
goto trunc;
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
peerid_len = *p; /* Peer-ID Length */
p++;
if (length - (p - p0) < peerid_len)
return;
ND_PRINT((ndo, ", Peer "));
for (i = 0; i < peerid_len; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
passwd_len = *p; /* Password Length */
p++;
if (length - (p - p0) < passwd_len)
return;
ND_PRINT((ndo, ", Name "));
for (i = 0; i < passwd_len; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
case PAP_AACK:
case PAP_ANAK:
/* Although some implementations ignore truncation at
* this point and at least one generates a truncated
* packet, RFC 1334 section 2.2.2 clearly states that
* both AACK and ANAK are at least 5 bytes long.
*/
if (len < 5)
goto trunc;
if (length - (p - p0) < 1)
return;
ND_TCHECK(*p);
msg_len = *p; /* Msg-Length */
p++;
if (length - (p - p0) < msg_len)
return;
ND_PRINT((ndo, ", Msg "));
for (i = 0; i< msg_len; i++) {
ND_TCHECK(*p);
safeputchar(ndo, *p++);
}
break;
}
return;
trunc:
ND_PRINT((ndo, "[|pap]"));
}
/* BAP */
static void
handle_bap(netdissect_options *ndo _U_,
const u_char *p _U_, int length _U_)
{
/* XXX: to be supported!! */
}
/* IPCP config options */
static int
print_ipcp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
u_int compproto, ipcomp_subopttotallen, ipcomp_subopt, ipcomp_suboptlen;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ipcpopt_values,"unknown",opt),
opt,
len));
switch (opt) {
case IPCPOPT_2ADDR: /* deprecated */
if (len != 10) {
ND_PRINT((ndo, " (length bogus, should be = 10)"));
return len;
}
ND_TCHECK2(*(p + 6), 4);
ND_PRINT((ndo, ": src %s, dst %s",
ipaddr_string(ndo, p + 2),
ipaddr_string(ndo, p + 6)));
break;
case IPCPOPT_IPCOMP:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return 0;
}
ND_TCHECK2(*(p + 2), 2);
compproto = EXTRACT_16BITS(p+2);
ND_PRINT((ndo, ": %s (0x%02x):",
tok2str(ipcpopt_compproto_values, "Unknown", compproto),
compproto));
switch (compproto) {
case PPP_VJC:
/* XXX: VJ-Comp parameters should be decoded */
break;
case IPCPOPT_IPCOMP_HDRCOMP:
if (len < IPCPOPT_IPCOMP_MINLEN) {
ND_PRINT((ndo, " (length bogus, should be >= %u)",
IPCPOPT_IPCOMP_MINLEN));
return 0;
}
ND_TCHECK2(*(p + 2), IPCPOPT_IPCOMP_MINLEN);
ND_PRINT((ndo, "\n\t TCP Space %u, non-TCP Space %u" \
", maxPeriod %u, maxTime %u, maxHdr %u",
EXTRACT_16BITS(p+4),
EXTRACT_16BITS(p+6),
EXTRACT_16BITS(p+8),
EXTRACT_16BITS(p+10),
EXTRACT_16BITS(p+12)));
/* suboptions present ? */
if (len > IPCPOPT_IPCOMP_MINLEN) {
ipcomp_subopttotallen = len - IPCPOPT_IPCOMP_MINLEN;
p += IPCPOPT_IPCOMP_MINLEN;
ND_PRINT((ndo, "\n\t Suboptions, length %u", ipcomp_subopttotallen));
while (ipcomp_subopttotallen >= 2) {
ND_TCHECK2(*p, 2);
ipcomp_subopt = *p;
ipcomp_suboptlen = *(p+1);
/* sanity check */
if (ipcomp_subopt == 0 ||
ipcomp_suboptlen == 0 )
break;
/* XXX: just display the suboptions for now */
ND_PRINT((ndo, "\n\t\t%s Suboption #%u, length %u",
tok2str(ipcpopt_compproto_subopt_values,
"Unknown",
ipcomp_subopt),
ipcomp_subopt,
ipcomp_suboptlen));
ipcomp_subopttotallen -= ipcomp_suboptlen;
p += ipcomp_suboptlen;
}
}
break;
default:
break;
}
break;
case IPCPOPT_ADDR: /* those options share the same format - fall through */
case IPCPOPT_MOBILE4:
case IPCPOPT_PRIDNS:
case IPCPOPT_PRINBNS:
case IPCPOPT_SECDNS:
case IPCPOPT_SECNBNS:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return 0;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": %s", ipaddr_string(ndo, p + 2)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ipcp]"));
return 0;
}
/* IP6CP config options */
static int
print_ip6cp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ip6cpopt_values,"unknown",opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ip6cpopt_values,"unknown",opt),
opt,
len));
switch (opt) {
case IP6CP_IFID:
if (len != 10) {
ND_PRINT((ndo, " (length bogus, should be = 10)"));
return len;
}
ND_TCHECK2(*(p + 2), 8);
ND_PRINT((ndo, ": %04x:%04x:%04x:%04x",
EXTRACT_16BITS(p + 2),
EXTRACT_16BITS(p + 4),
EXTRACT_16BITS(p + 6),
EXTRACT_16BITS(p + 8)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ip6cp]"));
return 0;
}
/* CCP config options */
static int
print_ccp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(ccpconfopts_values, "Unknown", opt),
opt,
len));
switch (opt) {
case CCPOPT_BSDCOMP:
if (len < 3) {
ND_PRINT((ndo, " (length bogus, should be >= 3)"));
return len;
}
ND_TCHECK2(*(p + 2), 1);
ND_PRINT((ndo, ": Version: %u, Dictionary Bits: %u",
p[2] >> 5, p[2] & 0x1f));
break;
case CCPOPT_MVRCA:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK2(*(p + 2), 1);
ND_PRINT((ndo, ": Features: %u, PxP: %s, History: %u, #CTX-ID: %u",
(p[2] & 0xc0) >> 6,
(p[2] & 0x20) ? "Enabled" : "Disabled",
p[2] & 0x1f, p[3]));
break;
case CCPOPT_DEFLATE:
if (len < 4) {
ND_PRINT((ndo, " (length bogus, should be >= 4)"));
return len;
}
ND_TCHECK2(*(p + 2), 1);
ND_PRINT((ndo, ": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u",
(p[2] & 0xf0) >> 4,
((p[2] & 0x0f) == 8) ? "zlib" : "unknown",
p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03));
break;
/* XXX: to be supported */
#if 0
case CCPOPT_OUI:
case CCPOPT_PRED1:
case CCPOPT_PRED2:
case CCPOPT_PJUMP:
case CCPOPT_HPPPC:
case CCPOPT_STACLZS:
case CCPOPT_MPPC:
case CCPOPT_GFZA:
case CCPOPT_V42BIS:
case CCPOPT_LZSDCP:
case CCPOPT_DEC:
case CCPOPT_RESV:
break;
#endif
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|ccp]"));
return 0;
}
/* BACP config options */
static int
print_bacp_config_options(netdissect_options *ndo,
const u_char *p, int length)
{
int len, opt;
if (length < 2)
return 0;
ND_TCHECK2(*p, 2);
len = p[1];
opt = p[0];
if (length < len)
return 0;
if (len < 2) {
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)",
tok2str(bacconfopts_values, "Unknown", opt),
opt,
len));
return 0;
}
ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u",
tok2str(bacconfopts_values, "Unknown", opt),
opt,
len));
switch (opt) {
case BACPOPT_FPEER:
if (len != 6) {
ND_PRINT((ndo, " (length bogus, should be = 6)"));
return len;
}
ND_TCHECK2(*(p + 2), 4);
ND_PRINT((ndo, ": Magic-Num 0x%08x", EXTRACT_32BITS(p + 2)));
break;
default:
/*
* Unknown option; dump it as raw bytes now if we're
* not going to do so below.
*/
if (ndo->ndo_vflag < 2)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */
return len;
trunc:
ND_PRINT((ndo, "[|bacp]"));
return 0;
}
static void
ppp_hdlc(netdissect_options *ndo,
const u_char *p, int length)
{
u_char *b, *t, c;
const u_char *s;
int i, proto;
const void *se;
if (length <= 0)
return;
b = (u_char *)malloc(length);
if (b == NULL)
return;
/*
* Unescape all the data into a temporary, private, buffer.
* Do this so that we dont overwrite the original packet
* contents.
*/
for (s = p, t = b, i = length; i > 0 && ND_TTEST(*s); i--) {
c = *s++;
if (c == 0x7d) {
if (i <= 1 || !ND_TTEST(*s))
break;
i--;
c = *s++ ^ 0x20;
}
*t++ = c;
}
se = ndo->ndo_snapend;
ndo->ndo_snapend = t;
length = t - b;
/* now lets guess about the payload codepoint format */
if (length < 1)
goto trunc;
proto = *b; /* start with a one-octet codepoint guess */
switch (proto) {
case PPP_IP:
ip_print(ndo, b + 1, length - 1);
goto cleanup;
case PPP_IPV6:
ip6_print(ndo, b + 1, length - 1);
goto cleanup;
default: /* no luck - try next guess */
break;
}
if (length < 2)
goto trunc;
proto = EXTRACT_16BITS(b); /* next guess - load two octets */
switch (proto) {
case (PPP_ADDRESS << 8 | PPP_CONTROL): /* looks like a PPP frame */
if (length < 4)
goto trunc;
proto = EXTRACT_16BITS(b+2); /* load the PPP proto-id */
handle_ppp(ndo, proto, b + 4, length - 4);
break;
default: /* last guess - proto must be a PPP proto-id */
handle_ppp(ndo, proto, b + 2, length - 2);
break;
}
cleanup:
ndo->ndo_snapend = se;
free(b);
return;
trunc:
ndo->ndo_snapend = se;
free(b);
ND_PRINT((ndo, "[|ppp]"));
}
/* PPP */
static void
handle_ppp(netdissect_options *ndo,
u_int proto, const u_char *p, int length)
{
if ((proto & 0xff00) == 0x7e00) { /* is this an escape code ? */
ppp_hdlc(ndo, p - 1, length);
return;
}
switch (proto) {
case PPP_LCP: /* fall through */
case PPP_IPCP:
case PPP_OSICP:
case PPP_MPLSCP:
case PPP_IPV6CP:
case PPP_CCP:
case PPP_BACP:
handle_ctrl_proto(ndo, proto, p, length);
break;
case PPP_ML:
handle_mlppp(ndo, p, length);
break;
case PPP_CHAP:
handle_chap(ndo, p, length);
break;
case PPP_PAP:
handle_pap(ndo, p, length);
break;
case PPP_BAP: /* XXX: not yet completed */
handle_bap(ndo, p, length);
break;
case ETHERTYPE_IP: /*XXX*/
case PPP_VJNC:
case PPP_IP:
ip_print(ndo, p, length);
break;
case ETHERTYPE_IPV6: /*XXX*/
case PPP_IPV6:
ip6_print(ndo, p, length);
break;
case ETHERTYPE_IPX: /*XXX*/
case PPP_IPX:
ipx_print(ndo, p, length);
break;
case PPP_OSI:
isoclns_print(ndo, p, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(ndo, p, length);
break;
case PPP_COMP:
ND_PRINT((ndo, "compressed PPP data"));
break;
default:
ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto)));
print_unknown_data(ndo, p, "\n\t", length);
break;
}
}
/* Standard PPP printer */
u_int
ppp_print(netdissect_options *ndo,
register const u_char *p, u_int length)
{
u_int proto,ppp_header;
u_int olen = length; /* _o_riginal length */
u_int hdr_len = 0;
/*
* Here, we assume that p points to the Address and Control
* field (if they present).
*/
if (length < 2)
goto trunc;
ND_TCHECK2(*p, 2);
ppp_header = EXTRACT_16BITS(p);
switch(ppp_header) {
case (PPP_WITHDIRECTION_IN << 8 | PPP_CONTROL):
if (ndo->ndo_eflag) ND_PRINT((ndo, "In "));
p += 2;
length -= 2;
hdr_len += 2;
break;
case (PPP_WITHDIRECTION_OUT << 8 | PPP_CONTROL):
if (ndo->ndo_eflag) ND_PRINT((ndo, "Out "));
p += 2;
length -= 2;
hdr_len += 2;
break;
case (PPP_ADDRESS << 8 | PPP_CONTROL):
p += 2; /* ACFC not used */
length -= 2;
hdr_len += 2;
break;
default:
break;
}
if (length < 2)
goto trunc;
ND_TCHECK(*p);
if (*p % 2) {
proto = *p; /* PFC is used */
p++;
length--;
hdr_len++;
} else {
ND_TCHECK2(*p, 2);
proto = EXTRACT_16BITS(p);
p += 2;
length -= 2;
hdr_len += 2;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%s (0x%04x), length %u: ",
tok2str(ppptype2str, "unknown", proto),
proto,
olen));
handle_ppp(ndo, proto, p, length);
return (hdr_len);
trunc:
ND_PRINT((ndo, "[|ppp]"));
return (0);
}
/* PPP I/F printer */
u_int
ppp_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
register u_int length = h->len;
register u_int caplen = h->caplen;
if (caplen < PPP_HDRLEN) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen);
}
#if 0
/*
* XXX: seems to assume that there are 2 octets prepended to an
* actual PPP frame. The 1st octet looks like Input/Output flag
* while 2nd octet is unknown, at least to me
* (mshindo@mshindo.net).
*
* That was what the original tcpdump code did.
*
* FreeBSD's "if_ppp.c" *does* set the first octet to 1 for outbound
* packets and 0 for inbound packets - but only if the
* protocol field has the 0x8000 bit set (i.e., it's a network
* control protocol); it does so before running the packet through
* "bpf_filter" to see if it should be discarded, and to see
* if we should update the time we sent the most recent packet...
*
* ...but it puts the original address field back after doing
* so.
*
* NetBSD's "if_ppp.c" doesn't set the first octet in that fashion.
*
* I don't know if any PPP implementation handed up to a BPF
* device packets with the first octet being 1 for outbound and
* 0 for inbound packets, so I (guy@alum.mit.edu) don't know
* whether that ever needs to be checked or not.
*
* Note that NetBSD has a DLT_PPP_SERIAL, which it uses for PPP,
* and its tcpdump appears to assume that the frame always
* begins with an address field and a control field, and that
* the address field might be 0x0f or 0x8f, for Cisco
* point-to-point with HDLC framing as per section 4.3.1 of RFC
* 1547, as well as 0xff, for PPP in HDLC-like framing as per
* RFC 1662.
*
* (Is the Cisco framing in question what DLT_C_HDLC, in
* BSD/OS, is?)
*/
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%c %4d %02x ", p[0] ? 'O' : 'I', length, p[1]));
#endif
ppp_print(ndo, p, length);
return (0);
}
/*
* PPP I/F printer to use if we know that RFC 1662-style PPP in HDLC-like
* framing, or Cisco PPP with HDLC framing as per section 4.3.1 of RFC 1547,
* is being used (i.e., we don't check for PPP_ADDRESS and PPP_CONTROL,
* discard them *if* those are the first two octets, and parse the remaining
* packet as a PPP packet, as "ppp_print()" does).
*
* This handles, for example, DLT_PPP_SERIAL in NetBSD.
*/
u_int
ppp_hdlc_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
register u_int length = h->len;
register u_int caplen = h->caplen;
u_int proto;
u_int hdrlen = 0;
if (caplen < 2) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen);
}
switch (p[0]) {
case PPP_ADDRESS:
if (caplen < 4) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen);
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x %02x %d ", p[0], p[1], length));
p += 2;
length -= 2;
hdrlen += 2;
proto = EXTRACT_16BITS(p);
p += 2;
length -= 2;
hdrlen += 2;
ND_PRINT((ndo, "%s: ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", proto)));
handle_ppp(ndo, proto, p, length);
break;
case CHDLC_UNICAST:
case CHDLC_BCAST:
return (chdlc_if_print(ndo, h, p));
default:
if (caplen < 4) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen);
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x %02x %d ", p[0], p[1], length));
p += 2;
hdrlen += 2;
/*
* XXX - NetBSD's "ppp_netbsd_serial_if_print()" treats
* the next two octets as an Ethernet type; does that
* ever happen?
*/
ND_PRINT((ndo, "unknown addr %02x; ctrl %02x", p[0], p[1]));
break;
}
return (hdrlen);
}
#define PPP_BSDI_HDRLEN 24
/* BSD/OS specific PPP printer */
u_int
ppp_bsdos_if_print(netdissect_options *ndo _U_,
const struct pcap_pkthdr *h _U_, register const u_char *p _U_)
{
register int hdrlength;
#ifdef __bsdi__
register u_int length = h->len;
register u_int caplen = h->caplen;
uint16_t ptype;
const u_char *q;
int i;
if (caplen < PPP_BSDI_HDRLEN) {
ND_PRINT((ndo, "[|ppp]"));
return (caplen)
}
hdrlength = 0;
#if 0
if (p[0] == PPP_ADDRESS && p[1] == PPP_CONTROL) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x %02x ", p[0], p[1]));
p += 2;
hdrlength = 2;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%d ", length));
/* Retrieve the protocol type */
if (*p & 01) {
/* Compressed protocol field */
ptype = *p;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x ", ptype));
p++;
hdrlength += 1;
} else {
/* Un-compressed protocol field */
ptype = EXTRACT_16BITS(p);
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%04x ", ptype));
p += 2;
hdrlength += 2;
}
#else
ptype = 0; /*XXX*/
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%c ", p[SLC_DIR] ? 'O' : 'I'));
if (p[SLC_LLHL]) {
/* link level header */
struct ppp_header *ph;
q = p + SLC_BPFHDRLEN;
ph = (struct ppp_header *)q;
if (ph->phdr_addr == PPP_ADDRESS
&& ph->phdr_ctl == PPP_CONTROL) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%02x %02x ", q[0], q[1]));
ptype = EXTRACT_16BITS(&ph->phdr_type);
if (ndo->ndo_eflag && (ptype == PPP_VJC || ptype == PPP_VJNC)) {
ND_PRINT((ndo, "%s ", tok2str(ppptype2str,
"proto-#%d", ptype)));
}
} else {
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "LLH=["));
for (i = 0; i < p[SLC_LLHL]; i++)
ND_PRINT((ndo, "%02x", q[i]));
ND_PRINT((ndo, "] "));
}
}
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%d ", length));
if (p[SLC_CHL]) {
q = p + SLC_BPFHDRLEN + p[SLC_LLHL];
switch (ptype) {
case PPP_VJC:
ptype = vjc_print(ndo, q, ptype);
hdrlength = PPP_BSDI_HDRLEN;
p += hdrlength;
switch (ptype) {
case PPP_IP:
ip_print(ndo, p, length);
break;
case PPP_IPV6:
ip6_print(ndo, p, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(ndo, p, length);
break;
}
goto printx;
case PPP_VJNC:
ptype = vjc_print(ndo, q, ptype);
hdrlength = PPP_BSDI_HDRLEN;
p += hdrlength;
switch (ptype) {
case PPP_IP:
ip_print(ndo, p, length);
break;
case PPP_IPV6:
ip6_print(ndo, p, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(ndo, p, length);
break;
}
goto printx;
default:
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "CH=["));
for (i = 0; i < p[SLC_LLHL]; i++)
ND_PRINT((ndo, "%02x", q[i]));
ND_PRINT((ndo, "] "));
}
break;
}
}
hdrlength = PPP_BSDI_HDRLEN;
#endif
length -= hdrlength;
p += hdrlength;
switch (ptype) {
case PPP_IP:
ip_print(p, length);
break;
case PPP_IPV6:
ip6_print(ndo, p, length);
break;
case PPP_MPLS_UCAST:
case PPP_MPLS_MCAST:
mpls_print(ndo, p, length);
break;
default:
ND_PRINT((ndo, "%s ", tok2str(ppptype2str, "unknown PPP protocol (0x%04x)", ptype)));
}
printx:
#else /* __bsdi */
hdrlength = 0;
#endif /* __bsdi__ */
return (hdrlength);
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2706_0 |
crossvul-cpp_data_bad_2719_0 | /*
* Copyright (C) 1999 WIDE Project.
* 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 project 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 PROJECT 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 PROJECT 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.
*
* Extensively modified by Hannes Gredler (hannes@gredler.at) for more
* complete BGP support.
*/
/* \summary: Border Gateway Protocol (BGP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "af.h"
#include "l2vpn.h"
struct bgp {
uint8_t bgp_marker[16];
uint16_t bgp_len;
uint8_t bgp_type;
};
#define BGP_SIZE 19 /* unaligned */
#define BGP_OPEN 1
#define BGP_UPDATE 2
#define BGP_NOTIFICATION 3
#define BGP_KEEPALIVE 4
#define BGP_ROUTE_REFRESH 5
static const struct tok bgp_msg_values[] = {
{ BGP_OPEN, "Open"},
{ BGP_UPDATE, "Update"},
{ BGP_NOTIFICATION, "Notification"},
{ BGP_KEEPALIVE, "Keepalive"},
{ BGP_ROUTE_REFRESH, "Route Refresh"},
{ 0, NULL}
};
struct bgp_open {
uint8_t bgpo_marker[16];
uint16_t bgpo_len;
uint8_t bgpo_type;
uint8_t bgpo_version;
uint16_t bgpo_myas;
uint16_t bgpo_holdtime;
uint32_t bgpo_id;
uint8_t bgpo_optlen;
/* options should follow */
};
#define BGP_OPEN_SIZE 29 /* unaligned */
struct bgp_opt {
uint8_t bgpopt_type;
uint8_t bgpopt_len;
/* variable length */
};
#define BGP_OPT_SIZE 2 /* some compilers may pad to 4 bytes */
#define BGP_CAP_HEADER_SIZE 2 /* some compilers may pad to 4 bytes */
struct bgp_notification {
uint8_t bgpn_marker[16];
uint16_t bgpn_len;
uint8_t bgpn_type;
uint8_t bgpn_major;
uint8_t bgpn_minor;
};
#define BGP_NOTIFICATION_SIZE 21 /* unaligned */
struct bgp_route_refresh {
uint8_t bgp_marker[16];
uint16_t len;
uint8_t type;
uint8_t afi[2]; /* the compiler messes this structure up */
uint8_t res; /* when doing misaligned sequences of int8 and int16 */
uint8_t safi; /* afi should be int16 - so we have to access it using */
}; /* EXTRACT_16BITS(&bgp_route_refresh->afi) (sigh) */
#define BGP_ROUTE_REFRESH_SIZE 23
#define bgp_attr_lenlen(flags, p) \
(((flags) & 0x10) ? 2 : 1)
#define bgp_attr_len(flags, p) \
(((flags) & 0x10) ? EXTRACT_16BITS(p) : *(p))
#define BGPTYPE_ORIGIN 1
#define BGPTYPE_AS_PATH 2
#define BGPTYPE_NEXT_HOP 3
#define BGPTYPE_MULTI_EXIT_DISC 4
#define BGPTYPE_LOCAL_PREF 5
#define BGPTYPE_ATOMIC_AGGREGATE 6
#define BGPTYPE_AGGREGATOR 7
#define BGPTYPE_COMMUNITIES 8 /* RFC1997 */
#define BGPTYPE_ORIGINATOR_ID 9 /* RFC4456 */
#define BGPTYPE_CLUSTER_LIST 10 /* RFC4456 */
#define BGPTYPE_DPA 11 /* deprecated, draft-ietf-idr-bgp-dpa */
#define BGPTYPE_ADVERTISERS 12 /* deprecated RFC1863 */
#define BGPTYPE_RCID_PATH 13 /* deprecated RFC1863 */
#define BGPTYPE_MP_REACH_NLRI 14 /* RFC4760 */
#define BGPTYPE_MP_UNREACH_NLRI 15 /* RFC4760 */
#define BGPTYPE_EXTD_COMMUNITIES 16 /* RFC4360 */
#define BGPTYPE_AS4_PATH 17 /* RFC6793 */
#define BGPTYPE_AGGREGATOR4 18 /* RFC6793 */
#define BGPTYPE_PMSI_TUNNEL 22 /* RFC6514 */
#define BGPTYPE_TUNNEL_ENCAP 23 /* RFC5512 */
#define BGPTYPE_TRAFFIC_ENG 24 /* RFC5543 */
#define BGPTYPE_IPV6_EXTD_COMMUNITIES 25 /* RFC5701 */
#define BGPTYPE_AIGP 26 /* RFC7311 */
#define BGPTYPE_PE_DISTINGUISHER_LABEL 27 /* RFC6514 */
#define BGPTYPE_ENTROPY_LABEL 28 /* RFC6790 */
#define BGPTYPE_LARGE_COMMUNITY 32 /* draft-ietf-idr-large-community-05 */
#define BGPTYPE_ATTR_SET 128 /* RFC6368 */
#define BGP_MP_NLRI_MINSIZE 3 /* End of RIB Marker detection */
static const struct tok bgp_attr_values[] = {
{ BGPTYPE_ORIGIN, "Origin"},
{ BGPTYPE_AS_PATH, "AS Path"},
{ BGPTYPE_AS4_PATH, "AS4 Path"},
{ BGPTYPE_NEXT_HOP, "Next Hop"},
{ BGPTYPE_MULTI_EXIT_DISC, "Multi Exit Discriminator"},
{ BGPTYPE_LOCAL_PREF, "Local Preference"},
{ BGPTYPE_ATOMIC_AGGREGATE, "Atomic Aggregate"},
{ BGPTYPE_AGGREGATOR, "Aggregator"},
{ BGPTYPE_AGGREGATOR4, "Aggregator4"},
{ BGPTYPE_COMMUNITIES, "Community"},
{ BGPTYPE_ORIGINATOR_ID, "Originator ID"},
{ BGPTYPE_CLUSTER_LIST, "Cluster List"},
{ BGPTYPE_DPA, "DPA"},
{ BGPTYPE_ADVERTISERS, "Advertisers"},
{ BGPTYPE_RCID_PATH, "RCID Path / Cluster ID"},
{ BGPTYPE_MP_REACH_NLRI, "Multi-Protocol Reach NLRI"},
{ BGPTYPE_MP_UNREACH_NLRI, "Multi-Protocol Unreach NLRI"},
{ BGPTYPE_EXTD_COMMUNITIES, "Extended Community"},
{ BGPTYPE_PMSI_TUNNEL, "PMSI Tunnel"},
{ BGPTYPE_TUNNEL_ENCAP, "Tunnel Encapsulation"},
{ BGPTYPE_TRAFFIC_ENG, "Traffic Engineering"},
{ BGPTYPE_IPV6_EXTD_COMMUNITIES, "IPv6 Extended Community"},
{ BGPTYPE_AIGP, "Accumulated IGP Metric"},
{ BGPTYPE_PE_DISTINGUISHER_LABEL, "PE Distinguisher Label"},
{ BGPTYPE_ENTROPY_LABEL, "Entropy Label"},
{ BGPTYPE_LARGE_COMMUNITY, "Large Community"},
{ BGPTYPE_ATTR_SET, "Attribute Set"},
{ 255, "Reserved for development"},
{ 0, NULL}
};
#define BGP_AS_SET 1
#define BGP_AS_SEQUENCE 2
#define BGP_CONFED_AS_SEQUENCE 3 /* draft-ietf-idr-rfc3065bis-01 */
#define BGP_CONFED_AS_SET 4 /* draft-ietf-idr-rfc3065bis-01 */
#define BGP_AS_SEG_TYPE_MIN BGP_AS_SET
#define BGP_AS_SEG_TYPE_MAX BGP_CONFED_AS_SET
static const struct tok bgp_as_path_segment_open_values[] = {
{ BGP_AS_SEQUENCE, ""},
{ BGP_AS_SET, "{ "},
{ BGP_CONFED_AS_SEQUENCE, "( "},
{ BGP_CONFED_AS_SET, "({ "},
{ 0, NULL}
};
static const struct tok bgp_as_path_segment_close_values[] = {
{ BGP_AS_SEQUENCE, ""},
{ BGP_AS_SET, "}"},
{ BGP_CONFED_AS_SEQUENCE, ")"},
{ BGP_CONFED_AS_SET, "})"},
{ 0, NULL}
};
#define BGP_OPT_AUTH 1
#define BGP_OPT_CAP 2
static const struct tok bgp_opt_values[] = {
{ BGP_OPT_AUTH, "Authentication Information"},
{ BGP_OPT_CAP, "Capabilities Advertisement"},
{ 0, NULL}
};
#define BGP_CAPCODE_MP 1 /* RFC2858 */
#define BGP_CAPCODE_RR 2 /* RFC2918 */
#define BGP_CAPCODE_ORF 3 /* RFC5291 */
#define BGP_CAPCODE_MR 4 /* RFC3107 */
#define BGP_CAPCODE_EXT_NH 5 /* RFC5549 */
#define BGP_CAPCODE_RESTART 64 /* RFC4724 */
#define BGP_CAPCODE_AS_NEW 65 /* RFC6793 */
#define BGP_CAPCODE_DYN_CAP 67 /* draft-ietf-idr-dynamic-cap */
#define BGP_CAPCODE_MULTISESS 68 /* draft-ietf-idr-bgp-multisession */
#define BGP_CAPCODE_ADD_PATH 69 /* RFC7911 */
#define BGP_CAPCODE_ENH_RR 70 /* draft-keyur-bgp-enhanced-route-refresh */
#define BGP_CAPCODE_RR_CISCO 128
static const struct tok bgp_capcode_values[] = {
{ BGP_CAPCODE_MP, "Multiprotocol Extensions"},
{ BGP_CAPCODE_RR, "Route Refresh"},
{ BGP_CAPCODE_ORF, "Cooperative Route Filtering"},
{ BGP_CAPCODE_MR, "Multiple Routes to a Destination"},
{ BGP_CAPCODE_EXT_NH, "Extended Next Hop Encoding"},
{ BGP_CAPCODE_RESTART, "Graceful Restart"},
{ BGP_CAPCODE_AS_NEW, "32-Bit AS Number"},
{ BGP_CAPCODE_DYN_CAP, "Dynamic Capability"},
{ BGP_CAPCODE_MULTISESS, "Multisession BGP"},
{ BGP_CAPCODE_ADD_PATH, "Multiple Paths"},
{ BGP_CAPCODE_ENH_RR, "Enhanced Route Refresh"},
{ BGP_CAPCODE_RR_CISCO, "Route Refresh (Cisco)"},
{ 0, NULL}
};
#define BGP_NOTIFY_MAJOR_MSG 1
#define BGP_NOTIFY_MAJOR_OPEN 2
#define BGP_NOTIFY_MAJOR_UPDATE 3
#define BGP_NOTIFY_MAJOR_HOLDTIME 4
#define BGP_NOTIFY_MAJOR_FSM 5
#define BGP_NOTIFY_MAJOR_CEASE 6
#define BGP_NOTIFY_MAJOR_CAP 7
static const struct tok bgp_notify_major_values[] = {
{ BGP_NOTIFY_MAJOR_MSG, "Message Header Error"},
{ BGP_NOTIFY_MAJOR_OPEN, "OPEN Message Error"},
{ BGP_NOTIFY_MAJOR_UPDATE, "UPDATE Message Error"},
{ BGP_NOTIFY_MAJOR_HOLDTIME,"Hold Timer Expired"},
{ BGP_NOTIFY_MAJOR_FSM, "Finite State Machine Error"},
{ BGP_NOTIFY_MAJOR_CEASE, "Cease"},
{ BGP_NOTIFY_MAJOR_CAP, "Capability Message Error"},
{ 0, NULL}
};
/* draft-ietf-idr-cease-subcode-02 */
#define BGP_NOTIFY_MINOR_CEASE_MAXPRFX 1
/* draft-ietf-idr-shutdown-07 */
#define BGP_NOTIFY_MINOR_CEASE_SHUT 2
#define BGP_NOTIFY_MINOR_CEASE_RESET 4
#define BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN 128
static const struct tok bgp_notify_minor_cease_values[] = {
{ BGP_NOTIFY_MINOR_CEASE_MAXPRFX, "Maximum Number of Prefixes Reached"},
{ BGP_NOTIFY_MINOR_CEASE_SHUT, "Administrative Shutdown"},
{ 3, "Peer Unconfigured"},
{ BGP_NOTIFY_MINOR_CEASE_RESET, "Administrative Reset"},
{ 5, "Connection Rejected"},
{ 6, "Other Configuration Change"},
{ 7, "Connection Collision Resolution"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_msg_values[] = {
{ 1, "Connection Not Synchronized"},
{ 2, "Bad Message Length"},
{ 3, "Bad Message Type"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_open_values[] = {
{ 1, "Unsupported Version Number"},
{ 2, "Bad Peer AS"},
{ 3, "Bad BGP Identifier"},
{ 4, "Unsupported Optional Parameter"},
{ 5, "Authentication Failure"},
{ 6, "Unacceptable Hold Time"},
{ 7, "Capability Message Error"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_update_values[] = {
{ 1, "Malformed Attribute List"},
{ 2, "Unrecognized Well-known Attribute"},
{ 3, "Missing Well-known Attribute"},
{ 4, "Attribute Flags Error"},
{ 5, "Attribute Length Error"},
{ 6, "Invalid ORIGIN Attribute"},
{ 7, "AS Routing Loop"},
{ 8, "Invalid NEXT_HOP Attribute"},
{ 9, "Optional Attribute Error"},
{ 10, "Invalid Network Field"},
{ 11, "Malformed AS_PATH"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_fsm_values[] = {
{ 0, "Unspecified Error"},
{ 1, "In OpenSent State"},
{ 2, "In OpenConfirm State"},
{ 3, "In Established State"},
{ 0, NULL }
};
static const struct tok bgp_notify_minor_cap_values[] = {
{ 1, "Invalid Action Value" },
{ 2, "Invalid Capability Length" },
{ 3, "Malformed Capability Value" },
{ 4, "Unsupported Capability Code" },
{ 0, NULL }
};
static const struct tok bgp_origin_values[] = {
{ 0, "IGP"},
{ 1, "EGP"},
{ 2, "Incomplete"},
{ 0, NULL}
};
#define BGP_PMSI_TUNNEL_RSVP_P2MP 1
#define BGP_PMSI_TUNNEL_LDP_P2MP 2
#define BGP_PMSI_TUNNEL_PIM_SSM 3
#define BGP_PMSI_TUNNEL_PIM_SM 4
#define BGP_PMSI_TUNNEL_PIM_BIDIR 5
#define BGP_PMSI_TUNNEL_INGRESS 6
#define BGP_PMSI_TUNNEL_LDP_MP2MP 7
static const struct tok bgp_pmsi_tunnel_values[] = {
{ BGP_PMSI_TUNNEL_RSVP_P2MP, "RSVP-TE P2MP LSP"},
{ BGP_PMSI_TUNNEL_LDP_P2MP, "LDP P2MP LSP"},
{ BGP_PMSI_TUNNEL_PIM_SSM, "PIM-SSM Tree"},
{ BGP_PMSI_TUNNEL_PIM_SM, "PIM-SM Tree"},
{ BGP_PMSI_TUNNEL_PIM_BIDIR, "PIM-Bidir Tree"},
{ BGP_PMSI_TUNNEL_INGRESS, "Ingress Replication"},
{ BGP_PMSI_TUNNEL_LDP_MP2MP, "LDP MP2MP LSP"},
{ 0, NULL}
};
static const struct tok bgp_pmsi_flag_values[] = {
{ 0x01, "Leaf Information required"},
{ 0, NULL}
};
#define BGP_AIGP_TLV 1
static const struct tok bgp_aigp_values[] = {
{ BGP_AIGP_TLV, "AIGP"},
{ 0, NULL}
};
/* Subsequent address family identifier, RFC2283 section 7 */
#define SAFNUM_RES 0
#define SAFNUM_UNICAST 1
#define SAFNUM_MULTICAST 2
#define SAFNUM_UNIMULTICAST 3 /* deprecated now */
/* labeled BGP RFC3107 */
#define SAFNUM_LABUNICAST 4
/* RFC6514 */
#define SAFNUM_MULTICAST_VPN 5
/* draft-nalawade-kapoor-tunnel-safi */
#define SAFNUM_TUNNEL 64
/* RFC4761 */
#define SAFNUM_VPLS 65
/* RFC6037 */
#define SAFNUM_MDT 66
/* RFC4364 */
#define SAFNUM_VPNUNICAST 128
/* RFC6513 */
#define SAFNUM_VPNMULTICAST 129
#define SAFNUM_VPNUNIMULTICAST 130 /* deprecated now */
/* RFC4684 */
#define SAFNUM_RT_ROUTING_INFO 132
#define BGP_VPN_RD_LEN 8
static const struct tok bgp_safi_values[] = {
{ SAFNUM_RES, "Reserved"},
{ SAFNUM_UNICAST, "Unicast"},
{ SAFNUM_MULTICAST, "Multicast"},
{ SAFNUM_UNIMULTICAST, "Unicast+Multicast"},
{ SAFNUM_LABUNICAST, "labeled Unicast"},
{ SAFNUM_TUNNEL, "Tunnel"},
{ SAFNUM_VPLS, "VPLS"},
{ SAFNUM_MDT, "MDT"},
{ SAFNUM_VPNUNICAST, "labeled VPN Unicast"},
{ SAFNUM_VPNMULTICAST, "labeled VPN Multicast"},
{ SAFNUM_VPNUNIMULTICAST, "labeled VPN Unicast+Multicast"},
{ SAFNUM_RT_ROUTING_INFO, "Route Target Routing Information"},
{ SAFNUM_MULTICAST_VPN, "Multicast VPN"},
{ 0, NULL }
};
/* well-known community */
#define BGP_COMMUNITY_NO_EXPORT 0xffffff01
#define BGP_COMMUNITY_NO_ADVERT 0xffffff02
#define BGP_COMMUNITY_NO_EXPORT_SUBCONFED 0xffffff03
/* Extended community type - draft-ietf-idr-bgp-ext-communities-05 */
#define BGP_EXT_COM_RT_0 0x0002 /* Route Target,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_RT_1 0x0102 /* Route Target,Format IP address:AN(2bytes) */
#define BGP_EXT_COM_RT_2 0x0202 /* Route Target,Format AN(4bytes):local(2bytes) */
#define BGP_EXT_COM_RO_0 0x0003 /* Route Origin,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_RO_1 0x0103 /* Route Origin,Format IP address:AN(2bytes) */
#define BGP_EXT_COM_RO_2 0x0203 /* Route Origin,Format AN(4bytes):local(2bytes) */
#define BGP_EXT_COM_LINKBAND 0x4004 /* Link Bandwidth,Format AS(2B):Bandwidth(4B) */
/* rfc2547 bgp-mpls-vpns */
#define BGP_EXT_COM_VPN_ORIGIN 0x0005 /* OSPF Domain ID / VPN of Origin - draft-rosen-vpns-ospf-bgp-mpls */
#define BGP_EXT_COM_VPN_ORIGIN2 0x0105 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_VPN_ORIGIN3 0x0205 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_VPN_ORIGIN4 0x8005 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_OSPF_RTYPE 0x0306 /* OSPF Route Type,Format Area(4B):RouteType(1B):Options(1B) */
#define BGP_EXT_COM_OSPF_RTYPE2 0x8000 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_OSPF_RID 0x0107 /* OSPF Router ID,Format RouterID(4B):Unused(2B) */
#define BGP_EXT_COM_OSPF_RID2 0x8001 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_L2INFO 0x800a /* draft-kompella-ppvpn-l2vpn */
#define BGP_EXT_COM_SOURCE_AS 0x0009 /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */
#define BGP_EXT_COM_VRF_RT_IMP 0x010b /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */
#define BGP_EXT_COM_L2VPN_RT_0 0x000a /* L2VPN Identifier,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_L2VPN_RT_1 0xF10a /* L2VPN Identifier,Format IP address:AN(2bytes) */
/* http://www.cisco.com/en/US/tech/tk436/tk428/technologies_tech_note09186a00801eb09a.shtml */
#define BGP_EXT_COM_EIGRP_GEN 0x8800
#define BGP_EXT_COM_EIGRP_METRIC_AS_DELAY 0x8801
#define BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW 0x8802
#define BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU 0x8803
#define BGP_EXT_COM_EIGRP_EXT_REMAS_REMID 0x8804
#define BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC 0x8805
static const struct tok bgp_extd_comm_flag_values[] = {
{ 0x8000, "vendor-specific"},
{ 0x4000, "non-transitive"},
{ 0, NULL},
};
static const struct tok bgp_extd_comm_subtype_values[] = {
{ BGP_EXT_COM_RT_0, "target"},
{ BGP_EXT_COM_RT_1, "target"},
{ BGP_EXT_COM_RT_2, "target"},
{ BGP_EXT_COM_RO_0, "origin"},
{ BGP_EXT_COM_RO_1, "origin"},
{ BGP_EXT_COM_RO_2, "origin"},
{ BGP_EXT_COM_LINKBAND, "link-BW"},
{ BGP_EXT_COM_VPN_ORIGIN, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN2, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN3, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN4, "ospf-domain"},
{ BGP_EXT_COM_OSPF_RTYPE, "ospf-route-type"},
{ BGP_EXT_COM_OSPF_RTYPE2, "ospf-route-type"},
{ BGP_EXT_COM_OSPF_RID, "ospf-router-id"},
{ BGP_EXT_COM_OSPF_RID2, "ospf-router-id"},
{ BGP_EXT_COM_L2INFO, "layer2-info"},
{ BGP_EXT_COM_EIGRP_GEN , "eigrp-general-route (flag, tag)" },
{ BGP_EXT_COM_EIGRP_METRIC_AS_DELAY , "eigrp-route-metric (AS, delay)" },
{ BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW , "eigrp-route-metric (reliability, nexthop, bandwidth)" },
{ BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU , "eigrp-route-metric (load, MTU)" },
{ BGP_EXT_COM_EIGRP_EXT_REMAS_REMID , "eigrp-external-route (remote-AS, remote-ID)" },
{ BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC , "eigrp-external-route (remote-proto, remote-metric)" },
{ BGP_EXT_COM_SOURCE_AS, "source-AS" },
{ BGP_EXT_COM_VRF_RT_IMP, "vrf-route-import"},
{ BGP_EXT_COM_L2VPN_RT_0, "l2vpn-id"},
{ BGP_EXT_COM_L2VPN_RT_1, "l2vpn-id"},
{ 0, NULL},
};
/* OSPF codes for BGP_EXT_COM_OSPF_RTYPE draft-rosen-vpns-ospf-bgp-mpls */
#define BGP_OSPF_RTYPE_RTR 1 /* OSPF Router LSA */
#define BGP_OSPF_RTYPE_NET 2 /* OSPF Network LSA */
#define BGP_OSPF_RTYPE_SUM 3 /* OSPF Summary LSA */
#define BGP_OSPF_RTYPE_EXT 5 /* OSPF External LSA, note that ASBR doesn't apply to MPLS-VPN */
#define BGP_OSPF_RTYPE_NSSA 7 /* OSPF NSSA External*/
#define BGP_OSPF_RTYPE_SHAM 129 /* OSPF-MPLS-VPN Sham link */
#define BGP_OSPF_RTYPE_METRIC_TYPE 0x1 /* LSB of RTYPE Options Field */
static const struct tok bgp_extd_comm_ospf_rtype_values[] = {
{ BGP_OSPF_RTYPE_RTR, "Router" },
{ BGP_OSPF_RTYPE_NET, "Network" },
{ BGP_OSPF_RTYPE_SUM, "Summary" },
{ BGP_OSPF_RTYPE_EXT, "External" },
{ BGP_OSPF_RTYPE_NSSA,"NSSA External" },
{ BGP_OSPF_RTYPE_SHAM,"MPLS-VPN Sham" },
{ 0, NULL },
};
/* ADD-PATH Send/Receive field values */
static const struct tok bgp_add_path_recvsend[] = {
{ 1, "Receive" },
{ 2, "Send" },
{ 3, "Both" },
{ 0, NULL },
};
static char astostr[20];
/*
* as_printf
*
* Convert an AS number into a string and return string pointer.
*
* Depending on bflag is set or not, AS number is converted into ASDOT notation
* or plain number notation.
*
*/
static char *
as_printf(netdissect_options *ndo,
char *str, int size, u_int asnum)
{
if (!ndo->ndo_bflag || asnum <= 0xFFFF) {
snprintf(str, size, "%u", asnum);
} else {
snprintf(str, size, "%u.%u", asnum >> 16, asnum & 0xFFFF);
}
return str;
}
#define ITEMCHECK(minlen) if (itemlen < minlen) goto badtlv;
int
decode_prefix4(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen, plenbytes;
ND_TCHECK(pptr[0]);
ITEMCHECK(1);
plen = pptr[0];
if (32 < plen)
return -1;
itemlen -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[1], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pptr[1], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d", ipaddr_string(ndo, &addr), plen);
return 1 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_prefix4(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen, plenbytes;
/* prefix length and label = 4 bytes */
ND_TCHECK2(pptr[0], 4);
ITEMCHECK(4);
plen = pptr[0]; /* get prefix length */
/* this is one of the weirdnesses of rfc3107
the label length (actually the label + COS bits)
is added to the prefix length;
we also do only read out just one label -
there is no real application for advertisement of
stacked labels in a single BGP message
*/
if (24 > plen)
return -1;
plen-=24; /* adjust prefixlen - labellength */
if (32 < plen)
return -1;
itemlen -= 4;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[4], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pptr[4], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "%s/%d, label:%u %s",
ipaddr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 4 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
/*
* bgp_vpn_ip_print
*
* print an ipv4 or ipv6 address into a buffer dependend on address length.
*/
static char *
bgp_vpn_ip_print(netdissect_options *ndo,
const u_char *pptr, u_int addr_length)
{
/* worst case string is s fully formatted v6 address */
static char addr[sizeof("1234:5678:89ab:cdef:1234:5678:89ab:cdef")];
char *pos = addr;
switch(addr_length) {
case (sizeof(struct in_addr) << 3): /* 32 */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
snprintf(pos, sizeof(addr), "%s", ipaddr_string(ndo, pptr));
break;
case (sizeof(struct in6_addr) << 3): /* 128 */
ND_TCHECK2(pptr[0], sizeof(struct in6_addr));
snprintf(pos, sizeof(addr), "%s", ip6addr_string(ndo, pptr));
break;
default:
snprintf(pos, sizeof(addr), "bogus address length %u", addr_length);
break;
}
pos += strlen(pos);
trunc:
*(pos) = '\0';
return (addr);
}
/*
* bgp_vpn_sg_print
*
* print an multicast s,g entry into a buffer.
* the s,g entry is encoded like this.
*
* +-----------------------------------+
* | Multicast Source Length (1 octet) |
* +-----------------------------------+
* | Multicast Source (Variable) |
* +-----------------------------------+
* | Multicast Group Length (1 octet) |
* +-----------------------------------+
* | Multicast Group (Variable) |
* +-----------------------------------+
*
* return the number of bytes read from the wire.
*/
static int
bgp_vpn_sg_print(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr_length;
u_int total_length, offset;
total_length = 0;
/* Source address length, encoded in bits */
ND_TCHECK2(pptr[0], 1);
addr_length = *pptr++;
/* Source address */
ND_TCHECK2(pptr[0], (addr_length >> 3));
total_length += (addr_length >> 3) + 1;
offset = strlen(buf);
if (addr_length) {
snprintf(buf + offset, buflen - offset, ", Source %s",
bgp_vpn_ip_print(ndo, pptr, addr_length));
pptr += (addr_length >> 3);
}
/* Group address length, encoded in bits */
ND_TCHECK2(pptr[0], 1);
addr_length = *pptr++;
/* Group address */
ND_TCHECK2(pptr[0], (addr_length >> 3));
total_length += (addr_length >> 3) + 1;
offset = strlen(buf);
if (addr_length) {
snprintf(buf + offset, buflen - offset, ", Group %s",
bgp_vpn_ip_print(ndo, pptr, addr_length));
pptr += (addr_length >> 3);
}
trunc:
return (total_length);
}
/* RDs and RTs share the same semantics
* we use bgp_vpn_rd_print for
* printing route targets inside a NLRI */
char *
bgp_vpn_rd_print(netdissect_options *ndo,
const u_char *pptr)
{
/* allocate space for the largest possible string */
static char rd[sizeof("xxxxxxxxxx:xxxxx (xxx.xxx.xxx.xxx:xxxxx)")];
char *pos = rd;
/* ok lets load the RD format */
switch (EXTRACT_16BITS(pptr)) {
/* 2-byte-AS:number fmt*/
case 0:
snprintf(pos, sizeof(rd) - (pos - rd), "%u:%u (= %u.%u.%u.%u)",
EXTRACT_16BITS(pptr+2),
EXTRACT_32BITS(pptr+4),
*(pptr+4), *(pptr+5), *(pptr+6), *(pptr+7));
break;
/* IP-address:AS fmt*/
case 1:
snprintf(pos, sizeof(rd) - (pos - rd), "%u.%u.%u.%u:%u",
*(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6));
break;
/* 4-byte-AS:number fmt*/
case 2:
snprintf(pos, sizeof(rd) - (pos - rd), "%s:%u (%u.%u.%u.%u:%u)",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+2)),
EXTRACT_16BITS(pptr+6), *(pptr+2), *(pptr+3), *(pptr+4),
*(pptr+5), EXTRACT_16BITS(pptr+6));
break;
default:
snprintf(pos, sizeof(rd) - (pos - rd), "unknown RD format");
break;
}
pos += strlen(pos);
*(pos) = '\0';
return (rd);
}
static int
decode_rt_routing_info(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_target[8];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if (0 == plen) {
snprintf(buf, buflen, "default route target");
return 1;
}
if (32 > plen)
return -1;
plen-=32; /* adjust prefix length */
if (64 < plen)
return -1;
memset(&route_target, 0, sizeof(route_target));
ND_TCHECK2(pptr[1], (plen + 7) / 8);
memcpy(&route_target, &pptr[1], (plen + 7) / 8);
if (plen % 8) {
((u_char *)&route_target)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "origin AS: %s, route target %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+1)),
bgp_vpn_rd_print(ndo, (u_char *)&route_target));
return 5 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_labeled_vpn_prefix4(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (32 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
((u_char *)&addr)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
ipaddr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
/*
* +-------------------------------+
* | |
* | RD:IPv4-address (12 octets) |
* | |
* +-------------------------------+
* | MDT Group-address (4 octets) |
* +-------------------------------+
*/
#define MDT_VPN_NLRI_LEN 16
static int
decode_mdt_vpn_nlri(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
const u_char *rd;
const u_char *vpn_ip;
ND_TCHECK(pptr[0]);
/* if the NLRI is not predefined length, quit.*/
if (*pptr != MDT_VPN_NLRI_LEN * 8)
return -1;
pptr++;
/* RD */
ND_TCHECK2(pptr[0], 8);
rd = pptr;
pptr+=8;
/* IPv4 address */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
vpn_ip = pptr;
pptr+=sizeof(struct in_addr);
/* MDT Group Address */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
snprintf(buf, buflen, "RD: %s, VPN IP Address: %s, MC Group Address: %s",
bgp_vpn_rd_print(ndo, rd), ipaddr_string(ndo, vpn_ip), ipaddr_string(ndo, pptr));
return MDT_VPN_NLRI_LEN + 1;
trunc:
return -2;
}
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI 1
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI 2
#define BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI 3
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF 4
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE 5
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN 6
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN 7
static const struct tok bgp_multicast_vpn_route_type_values[] = {
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI, "Intra-AS I-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI, "Inter-AS I-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI, "S-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF, "Intra-AS Segment-Leaf"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE, "Source-Active"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN, "Shared Tree Join"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN, "Source Tree Join"},
{ 0, NULL}
};
static int
decode_multicast_vpn(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_type, route_length, addr_length, sg_length;
u_int offset;
ND_TCHECK2(pptr[0], 2);
route_type = *pptr++;
route_length = *pptr++;
snprintf(buf, buflen, "Route-Type: %s (%u), length: %u",
tok2str(bgp_multicast_vpn_route_type_values,
"Unknown", route_type),
route_type, route_length);
switch(route_type) {
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s",
bgp_vpn_rd_print(ndo, pptr),
bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN,
(route_length - BGP_VPN_RD_LEN) << 3));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s",
bgp_vpn_rd_print(ndo, pptr),
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s",
bgp_vpn_rd_print(ndo, pptr));
pptr += BGP_VPN_RD_LEN;
sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen);
addr_length = route_length - sg_length;
ND_TCHECK2(pptr[0], addr_length);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", Originator %s",
bgp_vpn_ip_print(ndo, pptr, addr_length << 3));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s",
bgp_vpn_rd_print(ndo, pptr));
pptr += BGP_VPN_RD_LEN;
bgp_vpn_sg_print(ndo, pptr, buf, buflen);
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */
case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s",
bgp_vpn_rd_print(ndo, pptr),
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));
pptr += BGP_VPN_RD_LEN;
bgp_vpn_sg_print(ndo, pptr, buf, buflen);
break;
/*
* no per route-type printing yet.
*/
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF:
default:
break;
}
return route_length + 2;
trunc:
return -2;
}
/*
* As I remember, some versions of systems have an snprintf() that
* returns -1 if the buffer would have overflowed. If the return
* value is negative, set buflen to 0, to indicate that we've filled
* the buffer up.
*
* If the return value is greater than buflen, that means that
* the buffer would have overflowed; again, set buflen to 0 in
* that case.
*/
#define UPDATE_BUF_BUFLEN(buf, buflen, stringlen) \
if (stringlen<0) \
buflen=0; \
else if ((u_int)stringlen>buflen) \
buflen=0; \
else { \
buflen-=stringlen; \
buf+=stringlen; \
}
static int
decode_labeled_vpn_l2(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
int plen,tlen,stringlen,tlv_type,tlv_len,ttlv_len;
ND_TCHECK2(pptr[0], 2);
plen=EXTRACT_16BITS(pptr);
tlen=plen;
pptr+=2;
/* Old and new L2VPN NLRI share AFI/SAFI
* -> Assume a 12 Byte-length NLRI is auto-discovery-only
* and > 17 as old format. Complain for the middle case
*/
if (plen==12) {
/* assume AD-only with RD, BGPNH */
ND_TCHECK2(pptr[0],12);
buf[0]='\0';
stringlen=snprintf(buf, buflen, "RD: %s, BGPNH: %s",
bgp_vpn_rd_print(ndo, pptr),
ipaddr_string(ndo, pptr+8)
);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
pptr+=12;
tlen-=12;
return plen;
} else if (plen>17) {
/* assume old format */
/* RD, ID, LBLKOFF, LBLBASE */
ND_TCHECK2(pptr[0],15);
buf[0]='\0';
stringlen=snprintf(buf, buflen, "RD: %s, CE-ID: %u, Label-Block Offset: %u, Label Base %u",
bgp_vpn_rd_print(ndo, pptr),
EXTRACT_16BITS(pptr+8),
EXTRACT_16BITS(pptr+10),
EXTRACT_24BITS(pptr+12)>>4); /* the label is offsetted by 4 bits so lets shift it right */
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
pptr+=15;
tlen-=15;
/* ok now the variable part - lets read out TLVs*/
while (tlen>0) {
if (tlen < 3)
return -1;
ND_TCHECK2(pptr[0], 3);
tlv_type=*pptr++;
tlv_len=EXTRACT_16BITS(pptr);
ttlv_len=tlv_len;
pptr+=2;
switch(tlv_type) {
case 1:
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "\n\t\tcircuit status vector (%u) length: %u: 0x",
tlv_type,
tlv_len);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
ttlv_len=ttlv_len/8+1; /* how many bytes do we need to read ? */
while (ttlv_len>0) {
ND_TCHECK(pptr[0]);
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "%02x",*pptr++);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
ttlv_len--;
}
break;
default:
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "\n\t\tunknown TLV #%u, length: %u",
tlv_type,
tlv_len);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
break;
}
tlen-=(tlv_len<<3); /* the tlv-length is expressed in bits so lets shift it right */
}
return plen+2;
} else {
/* complain bitterly ? */
/* fall through */
goto trunc;
}
trunc:
return -2;
}
int
decode_prefix6(netdissect_options *ndo,
const u_char *pd, u_int itemlen, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen, plenbytes;
ND_TCHECK(pd[0]);
ITEMCHECK(1);
plen = pd[0];
if (128 < plen)
return -1;
itemlen -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pd[1], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pd[1], plenbytes);
if (plen % 8) {
addr.s6_addr[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d", ip6addr_string(ndo, &addr), plen);
return 1 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_prefix6(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen, plenbytes;
/* prefix length and label = 4 bytes */
ND_TCHECK2(pptr[0], 4);
ITEMCHECK(4);
plen = pptr[0]; /* get prefix length */
if (24 > plen)
return -1;
plen-=24; /* adjust prefixlen - labellength */
if (128 < plen)
return -1;
itemlen -= 4;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[4], plenbytes);
memcpy(&addr, &pptr[4], plenbytes);
if (plen % 8) {
addr.s6_addr[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "%s/%d, label:%u %s",
ip6addr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 4 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_vpn_prefix6(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (128 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
addr.s6_addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
ip6addr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_clnp_prefix(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr[19];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if (152 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[4], (plen + 7) / 8);
memcpy(&addr, &pptr[4], (plen + 7) / 8);
if (plen % 8) {
addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d",
isonsap_string(ndo, addr,(plen + 7) / 8),
plen);
return 1 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_labeled_vpn_clnp_prefix(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr[19];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (152 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
isonsap_string(ndo, addr,(plen + 7) / 8),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
/*
* bgp_attr_get_as_size
*
* Try to find the size of the ASs encoded in an as-path. It is not obvious, as
* both Old speakers that do not support 4 byte AS, and the new speakers that do
* support, exchange AS-Path with the same path-attribute type value 0x02.
*/
static int
bgp_attr_get_as_size(netdissect_options *ndo,
uint8_t bgpa_type, const u_char *pptr, int len)
{
const u_char *tptr = pptr;
/*
* If the path attribute is the optional AS4 path type, then we already
* know, that ASs must be encoded in 4 byte format.
*/
if (bgpa_type == BGPTYPE_AS4_PATH) {
return 4;
}
/*
* Let us assume that ASs are of 2 bytes in size, and check if the AS-Path
* TLV is good. If not, ask the caller to try with AS encoded as 4 bytes
* each.
*/
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
/*
* If we do not find a valid segment type, our guess might be wrong.
*/
if (tptr[0] < BGP_AS_SEG_TYPE_MIN || tptr[0] > BGP_AS_SEG_TYPE_MAX) {
goto trunc;
}
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * 2;
}
/*
* If we correctly reached end of the AS path attribute data content,
* then most likely ASs were indeed encoded as 2 bytes.
*/
if (tptr == pptr + len) {
return 2;
}
trunc:
/*
* We can come here, either we did not have enough data, or if we
* try to decode 4 byte ASs in 2 byte format. Either way, return 4,
* so that calller can try to decode each AS as of 4 bytes. If indeed
* there was not enough data, it will crib and end the parse anyways.
*/
return 4;
}
static int
bgp_attr_print(netdissect_options *ndo,
u_int atype, const u_char *pptr, u_int len)
{
int i;
uint16_t af;
uint8_t safi, snpa, nhlen;
union { /* copy buffer for bandwidth values */
float f;
uint32_t i;
} bw;
int advance;
u_int tlen;
const u_char *tptr;
char buf[MAXHOSTNAMELEN + 100];
int as_size;
tptr = pptr;
tlen=len;
switch (atype) {
case BGPTYPE_ORIGIN:
if (len != 1)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK(*tptr);
ND_PRINT((ndo, "%s", tok2str(bgp_origin_values,
"Unknown Origin Typecode",
tptr[0])));
}
break;
/*
* Process AS4 byte path and AS2 byte path attributes here.
*/
case BGPTYPE_AS4_PATH:
case BGPTYPE_AS_PATH:
if (len % 2) {
ND_PRINT((ndo, "invalid len"));
break;
}
if (!len) {
ND_PRINT((ndo, "empty"));
break;
}
/*
* BGP updates exchanged between New speakers that support 4
* byte AS, ASs are always encoded in 4 bytes. There is no
* definitive way to find this, just by the packet's
* contents. So, check for packet's TLV's sanity assuming
* 2 bytes first, and it does not pass, assume that ASs are
* encoded in 4 bytes format and move on.
*/
as_size = bgp_attr_get_as_size(ndo, atype, pptr, len);
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
for (i = 0; i < tptr[1] * as_size; i += as_size) {
ND_TCHECK2(tptr[2 + i], as_size);
ND_PRINT((ndo, "%s ",
as_printf(ndo, astostr, sizeof(astostr),
as_size == 2 ?
EXTRACT_16BITS(&tptr[2 + i]) :
EXTRACT_32BITS(&tptr[2 + i]))));
}
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * as_size;
}
break;
case BGPTYPE_NEXT_HOP:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
}
break;
case BGPTYPE_MULTI_EXIT_DISC:
case BGPTYPE_LOCAL_PREF:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr)));
}
break;
case BGPTYPE_ATOMIC_AGGREGATE:
if (len != 0)
ND_PRINT((ndo, "invalid len"));
break;
case BGPTYPE_AGGREGATOR:
/*
* Depending on the AS encoded is of 2 bytes or of 4 bytes,
* the length of this PA can be either 6 bytes or 8 bytes.
*/
if (len != 6 && len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], len);
if (len == 6) {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)),
ipaddr_string(ndo, tptr + 2)));
} else {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4)));
}
break;
case BGPTYPE_AGGREGATOR4:
if (len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)),
ipaddr_string(ndo, tptr + 4)));
break;
case BGPTYPE_COMMUNITIES:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint32_t comm;
ND_TCHECK2(tptr[0], 4);
comm = EXTRACT_32BITS(tptr);
switch (comm) {
case BGP_COMMUNITY_NO_EXPORT:
ND_PRINT((ndo, " NO_EXPORT"));
break;
case BGP_COMMUNITY_NO_ADVERT:
ND_PRINT((ndo, " NO_ADVERTISE"));
break;
case BGP_COMMUNITY_NO_EXPORT_SUBCONFED:
ND_PRINT((ndo, " NO_EXPORT_SUBCONFED"));
break;
default:
ND_PRINT((ndo, "%u:%u%s",
(comm >> 16) & 0xffff,
comm & 0xffff,
(tlen>4) ? ", " : ""));
break;
}
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_ORIGINATOR_ID:
if (len != 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
break;
case BGPTYPE_CLUSTER_LIST:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s%s",
ipaddr_string(ndo, tptr),
(tlen>4) ? ", " : ""));
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_MP_REACH_NLRI:
ND_TCHECK2(tptr[0], 3);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
goto done;
break;
}
tptr +=3;
ND_TCHECK(tptr[0]);
nhlen = tptr[0];
tlen = nhlen;
tptr++;
if (tlen) {
int nnh = 0;
ND_PRINT((ndo, "\n\t nexthop: "));
while (tlen > 0) {
if ( nnh++ > 0 ) {
ND_PRINT((ndo, ", " ));
}
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
tlen -= sizeof(struct in_addr);
tptr += sizeof(struct in_addr);
}
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
if (tlen < (int)sizeof(struct in6_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr));
ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr)));
tlen -= sizeof(struct in6_addr);
tptr += sizeof(struct in6_addr);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
tlen -= (sizeof(struct in_addr));
tptr += (sizeof(struct in_addr));
}
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen)));
tptr += tlen;
tlen = 0;
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < BGP_VPN_RD_LEN+1) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN)));
/* rfc986 mapped IPv4 address ? */
if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601)
ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4)));
/* rfc1888 mapped IPv6 address ? */
else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000)
ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3)));
tptr += tlen;
tlen = 0;
}
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
tptr += tlen;
tlen = 0;
goto done;
break;
}
}
}
ND_PRINT((ndo, ", nh-length: %u", nhlen));
tptr += tlen;
ND_TCHECK(tptr[0]);
snpa = tptr[0];
tptr++;
if (snpa) {
ND_PRINT((ndo, "\n\t %u SNPA", snpa));
for (/*nothing*/; snpa > 0; snpa--) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "\n\t %d bytes", tptr[0]));
tptr += tptr[0] + 1;
}
} else {
ND_PRINT((ndo, ", no SNPA"));
}
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*tptr,tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
done:
break;
case BGPTYPE_MP_UNREACH_NLRI:
ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
if (len == BGP_MP_NLRI_MINSIZE)
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
tptr += 3;
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*(tptr-3),tlen);
ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr-3, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
break;
case BGPTYPE_EXTD_COMMUNITIES:
if (len % 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint16_t extd_comm;
ND_TCHECK2(tptr[0], 2);
extd_comm=EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]",
tok2str(bgp_extd_comm_subtype_values,
"unknown extd community typecode",
extd_comm),
extd_comm,
bittok2str(bgp_extd_comm_flag_values, "none", extd_comm)));
ND_TCHECK2(*(tptr+2), 6);
switch(extd_comm) {
case BGP_EXT_COM_RT_0:
case BGP_EXT_COM_RO_0:
case BGP_EXT_COM_L2VPN_RT_0:
ND_PRINT((ndo, ": %u:%u (= %s)",
EXTRACT_16BITS(tptr+2),
EXTRACT_32BITS(tptr+4),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_EXT_COM_RT_1:
case BGP_EXT_COM_RO_1:
case BGP_EXT_COM_L2VPN_RT_1:
case BGP_EXT_COM_VRF_RT_IMP:
ND_PRINT((ndo, ": %s:%u",
ipaddr_string(ndo, tptr+2),
EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_RT_2:
case BGP_EXT_COM_RO_2:
ND_PRINT((ndo, ": %s:%u",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_LINKBAND:
bw.i = EXTRACT_32BITS(tptr+2);
ND_PRINT((ndo, ": bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case BGP_EXT_COM_VPN_ORIGIN:
case BGP_EXT_COM_VPN_ORIGIN2:
case BGP_EXT_COM_VPN_ORIGIN3:
case BGP_EXT_COM_VPN_ORIGIN4:
case BGP_EXT_COM_OSPF_RID:
case BGP_EXT_COM_OSPF_RID2:
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2)));
break;
case BGP_EXT_COM_OSPF_RTYPE:
case BGP_EXT_COM_OSPF_RTYPE2:
ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s",
ipaddr_string(ndo, tptr+2),
tok2str(bgp_extd_comm_ospf_rtype_values,
"unknown (0x%02x)",
*(tptr+6)),
(*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "",
((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : ""));
break;
case BGP_EXT_COM_L2INFO:
ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u",
tok2str(l2vpn_encaps_values,
"unknown encaps",
*(tptr+2)),
*(tptr+3),
EXTRACT_16BITS(tptr+4)));
break;
case BGP_EXT_COM_SOURCE_AS:
ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2)));
break;
default:
ND_TCHECK2(*tptr,8);
print_unknown_data(ndo, tptr, "\n\t ", 8);
break;
}
tlen -=8;
tptr +=8;
}
break;
case BGPTYPE_PMSI_TUNNEL:
{
uint8_t tunnel_type, flags;
ND_TCHECK2(tptr[0], 5);
tunnel_type = *(tptr+1);
flags = *tptr;
tlen = len;
ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u",
tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type),
tunnel_type,
bittok2str(bgp_pmsi_flag_values, "none", flags),
EXTRACT_24BITS(tptr+2)>>4));
tptr +=5;
tlen -= 5;
switch (tunnel_type) {
case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */
case BGP_PMSI_TUNNEL_PIM_BIDIR:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Sender %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_PIM_SSM:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_INGRESS:
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s",
ipaddr_string(ndo, tptr)));
break;
case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */
case BGP_PMSI_TUNNEL_LDP_MP2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
case BGP_PMSI_TUNNEL_RSVP_P2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr, "\n\t ", tlen);
}
}
break;
}
case BGPTYPE_AIGP:
{
uint8_t type;
uint16_t length;
tlen = len;
while (tlen >= 3) {
ND_TCHECK2(tptr[0], 3);
type = *tptr;
length = EXTRACT_16BITS(tptr+1);
tptr += 3;
tlen -= 3;
ND_PRINT((ndo, "\n\t %s TLV (%u), length %u",
tok2str(bgp_aigp_values, "Unknown", type),
type, length));
if (length < 3)
goto trunc;
length -= 3;
/*
* Check if we can read the TLV data.
*/
ND_TCHECK2(tptr[3], length);
switch (type) {
case BGP_AIGP_TLV:
if (length < 8)
goto trunc;
ND_PRINT((ndo, ", metric %" PRIu64,
EXTRACT_64BITS(tptr)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr,"\n\t ", length);
}
}
tptr += length;
tlen -= length;
}
break;
}
case BGPTYPE_ATTR_SET:
ND_TCHECK2(tptr[0], 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, "\n\t Origin AS: %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr))));
tptr+=4;
len -=4;
while (len) {
u_int aflags, alenlen, alen;
ND_TCHECK2(tptr[0], 2);
if (len < 2)
goto trunc;
aflags = *tptr;
atype = *(tptr + 1);
tptr += 2;
len -= 2;
alenlen = bgp_attr_lenlen(aflags, tptr);
ND_TCHECK2(tptr[0], alenlen);
if (len < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, tptr);
tptr += alenlen;
len -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values,
"Unknown Attribute", atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
/* FIXME check for recursion */
if (!bgp_attr_print(ndo, atype, tptr, alen))
return 0;
tptr += alen;
len -= alen;
}
break;
case BGPTYPE_LARGE_COMMUNITY:
if (len == 0 || len % 12) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_PRINT((ndo, "\n\t "));
while (len > 0) {
ND_TCHECK2(*tptr, 12);
ND_PRINT((ndo, "%u:%u:%u%s",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
(len > 12) ? ", " : ""));
tptr += 12;
len -= 12;
}
break;
default:
ND_TCHECK2(*pptr,len);
ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr, "\n\t ", len);
break;
}
if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/
ND_TCHECK2(*pptr,len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return 1;
trunc:
return 0;
}
static void
bgp_capabilities_print(netdissect_options *ndo,
const u_char *opt, int caps_len)
{
int cap_type, cap_len, tcap_len, cap_offset;
int i = 0;
while (i < caps_len) {
ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE);
cap_type=opt[i];
cap_len=opt[i+1];
tcap_len=cap_len;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_capcode_values, "Unknown",
cap_type),
cap_type,
cap_len));
ND_TCHECK2(opt[i+2], cap_len);
switch (cap_type) {
case BGP_CAPCODE_MP:
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(opt+i+2)),
EXTRACT_16BITS(opt+i+2),
tok2str(bgp_safi_values, "Unknown",
opt[i+5]),
opt[i+5]));
break;
case BGP_CAPCODE_RESTART:
ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us",
((opt[i+2])&0x80) ? "R" : "none",
EXTRACT_16BITS(opt+i+2)&0xfff));
tcap_len-=2;
cap_offset=4;
while(tcap_len>=4) {
ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s",
tok2str(af_values,"Unknown",
EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",
opt[i+cap_offset+2]),
opt[i+cap_offset+2],
((opt[i+cap_offset+3])&0x80) ? "yes" : "no" ));
tcap_len-=4;
cap_offset+=4;
}
break;
case BGP_CAPCODE_RR:
case BGP_CAPCODE_RR_CISCO:
break;
case BGP_CAPCODE_AS_NEW:
/*
* Extract the 4 byte AS number encoded.
*/
if (cap_len == 4) {
ND_PRINT((ndo, "\n\t\t 4 Byte AS %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(opt + i + 2))));
}
break;
case BGP_CAPCODE_ADD_PATH:
cap_offset=2;
if (tcap_len == 0) {
ND_PRINT((ndo, " (bogus)")); /* length */
break;
}
while (tcap_len > 0) {
if (tcap_len < 4) {
ND_PRINT((ndo, "\n\t\t(invalid)"));
break;
}
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s",
tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]),
opt[i+cap_offset+2],
tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3])
));
tcap_len-=4;
cap_offset+=4;
}
break;
default:
ND_PRINT((ndo, "\n\t\tno decoder for Capability %u",
cap_type));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
break;
}
if (ndo->ndo_vflag > 1 && cap_len > 0) {
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
}
i += BGP_CAP_HEADER_SIZE + cap_len;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_open_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp_open bgpo;
struct bgp_opt bgpopt;
const u_char *opt;
int i;
ND_TCHECK2(dat[0], BGP_OPEN_SIZE);
memcpy(&bgpo, dat, BGP_OPEN_SIZE);
ND_PRINT((ndo, "\n\t Version %d, ", bgpo.bgpo_version));
ND_PRINT((ndo, "my AS %s, ",
as_printf(ndo, astostr, sizeof(astostr), ntohs(bgpo.bgpo_myas))));
ND_PRINT((ndo, "Holdtime %us, ", ntohs(bgpo.bgpo_holdtime)));
ND_PRINT((ndo, "ID %s", ipaddr_string(ndo, &bgpo.bgpo_id)));
ND_PRINT((ndo, "\n\t Optional parameters, length: %u", bgpo.bgpo_optlen));
/* some little sanity checking */
if (length < bgpo.bgpo_optlen+BGP_OPEN_SIZE)
return;
/* ugly! */
opt = &((const struct bgp_open *)dat)->bgpo_optlen;
opt++;
i = 0;
while (i < bgpo.bgpo_optlen) {
ND_TCHECK2(opt[i], BGP_OPT_SIZE);
memcpy(&bgpopt, &opt[i], BGP_OPT_SIZE);
if (i + 2 + bgpopt.bgpopt_len > bgpo.bgpo_optlen) {
ND_PRINT((ndo, "\n\t Option %d, length: %u", bgpopt.bgpopt_type, bgpopt.bgpopt_len));
break;
}
ND_PRINT((ndo, "\n\t Option %s (%u), length: %u",
tok2str(bgp_opt_values,"Unknown",
bgpopt.bgpopt_type),
bgpopt.bgpopt_type,
bgpopt.bgpopt_len));
/* now let's decode the options we know*/
switch(bgpopt.bgpopt_type) {
case BGP_OPT_CAP:
bgp_capabilities_print(ndo, &opt[i+BGP_OPT_SIZE],
bgpopt.bgpopt_len);
break;
case BGP_OPT_AUTH:
default:
ND_PRINT((ndo, "\n\t no decoder for option %u",
bgpopt.bgpopt_type));
break;
}
i += BGP_OPT_SIZE + bgpopt.bgpopt_len;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_update_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
const u_char *p;
int withdrawn_routes_len;
int len;
int i;
ND_TCHECK2(dat[0], BGP_SIZE);
if (length < BGP_SIZE)
goto trunc;
memcpy(&bgp, dat, BGP_SIZE);
p = dat + BGP_SIZE; /*XXX*/
length -= BGP_SIZE;
/* Unfeasible routes */
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
withdrawn_routes_len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len) {
/*
* Without keeping state from the original NLRI message,
* it's not possible to tell if this a v4 or v6 route,
* so only try to decode it if we're not v6 enabled.
*/
ND_TCHECK2(p[0], withdrawn_routes_len);
if (length < withdrawn_routes_len)
goto trunc;
ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len));
p += withdrawn_routes_len;
length -= withdrawn_routes_len;
}
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len == 0 && len == 0 && length == 0) {
/* No withdrawn routes, no path attributes, no NLRI */
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
return;
}
if (len) {
/* do something more useful!*/
while (len) {
int aflags, atype, alenlen, alen;
ND_TCHECK2(p[0], 2);
if (len < 2)
goto trunc;
if (length < 2)
goto trunc;
aflags = *p;
atype = *(p + 1);
p += 2;
len -= 2;
length -= 2;
alenlen = bgp_attr_lenlen(aflags, p);
ND_TCHECK2(p[0], alenlen);
if (len < alenlen)
goto trunc;
if (length < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, p);
p += alenlen;
len -= alenlen;
length -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values, "Unknown Attribute",
atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
if (len < alen)
goto trunc;
if (length < alen)
goto trunc;
if (!bgp_attr_print(ndo, atype, p, alen))
goto trunc;
p += alen;
len -= alen;
length -= alen;
}
}
if (length) {
/*
* XXX - what if they're using the "Advertisement of
* Multiple Paths in BGP" feature:
*
* https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/
*
* http://tools.ietf.org/html/draft-ietf-idr-add-paths-06
*/
ND_PRINT((ndo, "\n\t Updated routes:"));
while (length) {
char buf[MAXHOSTNAMELEN + 100];
i = decode_prefix4(ndo, p, length, buf, sizeof(buf));
if (i == -1) {
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
break;
} else if (i == -2)
goto trunc;
else if (i == -3)
goto trunc; /* bytes left, but not enough */
else {
ND_PRINT((ndo, "\n\t %s", buf));
p += i;
length -= i;
}
}
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_notification_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp_notification bgpn;
const u_char *tptr;
uint8_t shutdown_comm_length;
uint8_t remainder_offset;
ND_TCHECK2(dat[0], BGP_NOTIFICATION_SIZE);
memcpy(&bgpn, dat, BGP_NOTIFICATION_SIZE);
/* some little sanity checking */
if (length<BGP_NOTIFICATION_SIZE)
return;
ND_PRINT((ndo, ", %s (%u)",
tok2str(bgp_notify_major_values, "Unknown Error",
bgpn.bgpn_major),
bgpn.bgpn_major));
switch (bgpn.bgpn_major) {
case BGP_NOTIFY_MAJOR_MSG:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_msg_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_OPEN:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_open_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_UPDATE:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_update_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_FSM:
ND_PRINT((ndo, " subcode %s (%u)",
tok2str(bgp_notify_minor_fsm_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_CAP:
ND_PRINT((ndo, " subcode %s (%u)",
tok2str(bgp_notify_minor_cap_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_CEASE:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_cease_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
/* draft-ietf-idr-cease-subcode-02 mentions optionally 7 bytes
* for the maxprefix subtype, which may contain AFI, SAFI and MAXPREFIXES
*/
if(bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_MAXPRFX && length >= BGP_NOTIFICATION_SIZE + 7) {
tptr = dat + BGP_NOTIFICATION_SIZE;
ND_TCHECK2(*tptr, 7);
ND_PRINT((ndo, ", AFI %s (%u), SAFI %s (%u), Max Prefixes: %u",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr),
tok2str(bgp_safi_values, "Unknown", *(tptr+2)),
*(tptr+2),
EXTRACT_32BITS(tptr+3)));
}
/*
* draft-ietf-idr-shutdown describes a method to send a communication
* intended for human consumption regarding the Administrative Shutdown
*/
if ((bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_SHUT ||
bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_RESET) &&
length >= BGP_NOTIFICATION_SIZE + 1) {
tptr = dat + BGP_NOTIFICATION_SIZE;
ND_TCHECK2(*tptr, 1);
shutdown_comm_length = *(tptr);
remainder_offset = 0;
/* garbage, hexdump it all */
if (shutdown_comm_length > BGP_NOTIFY_MINOR_CEASE_ADMIN_SHUTDOWN_LEN ||
shutdown_comm_length > length - (BGP_NOTIFICATION_SIZE + 1)) {
ND_PRINT((ndo, ", invalid Shutdown Communication length"));
}
else if (shutdown_comm_length == 0) {
ND_PRINT((ndo, ", empty Shutdown Communication"));
remainder_offset += 1;
}
/* a proper shutdown communication */
else {
ND_TCHECK2(*(tptr+1), shutdown_comm_length);
ND_PRINT((ndo, ", Shutdown Communication (length: %u): \"", shutdown_comm_length));
(void)fn_printn(ndo, tptr+1, shutdown_comm_length, NULL);
ND_PRINT((ndo, "\""));
remainder_offset += shutdown_comm_length + 1;
}
/* if there is trailing data, hexdump it */
if(length - (remainder_offset + BGP_NOTIFICATION_SIZE) > 0) {
ND_PRINT((ndo, ", Data: (length: %u)", length - (remainder_offset + BGP_NOTIFICATION_SIZE)));
hex_print(ndo, "\n\t\t", tptr + remainder_offset, length - (remainder_offset + BGP_NOTIFICATION_SIZE));
}
}
break;
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_route_refresh_print(netdissect_options *ndo,
const u_char *pptr, int len)
{
const struct bgp_route_refresh *bgp_route_refresh_header;
ND_TCHECK2(pptr[0], BGP_ROUTE_REFRESH_SIZE);
/* some little sanity checking */
if (len<BGP_ROUTE_REFRESH_SIZE)
return;
bgp_route_refresh_header = (const struct bgp_route_refresh *)pptr;
ND_PRINT((ndo, "\n\t AFI %s (%u), SAFI %s (%u)",
tok2str(af_values,"Unknown",
/* this stinks but the compiler pads the structure
* weird */
EXTRACT_16BITS(&bgp_route_refresh_header->afi)),
EXTRACT_16BITS(&bgp_route_refresh_header->afi),
tok2str(bgp_safi_values,"Unknown",
bgp_route_refresh_header->safi),
bgp_route_refresh_header->safi));
if (ndo->ndo_vflag > 1) {
ND_TCHECK2(*pptr, len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static int
bgp_header_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
ND_TCHECK2(dat[0], BGP_SIZE);
memcpy(&bgp, dat, BGP_SIZE);
ND_PRINT((ndo, "\n\t%s Message (%u), length: %u",
tok2str(bgp_msg_values, "Unknown", bgp.bgp_type),
bgp.bgp_type,
length));
switch (bgp.bgp_type) {
case BGP_OPEN:
bgp_open_print(ndo, dat, length);
break;
case BGP_UPDATE:
bgp_update_print(ndo, dat, length);
break;
case BGP_NOTIFICATION:
bgp_notification_print(ndo, dat, length);
break;
case BGP_KEEPALIVE:
break;
case BGP_ROUTE_REFRESH:
bgp_route_refresh_print(ndo, dat, length);
break;
default:
/* we have no decoder for the BGP message */
ND_TCHECK2(*dat, length);
ND_PRINT((ndo, "\n\t no Message %u decoder", bgp.bgp_type));
print_unknown_data(ndo, dat, "\n\t ", length);
break;
}
return 1;
trunc:
ND_PRINT((ndo, "[|BGP]"));
return 0;
}
void
bgp_print(netdissect_options *ndo,
const u_char *dat, int length)
{
const u_char *p;
const u_char *ep;
const u_char *start;
const u_char marker[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
};
struct bgp bgp;
uint16_t hlen;
ep = dat + length;
if (ndo->ndo_snapend < dat + length)
ep = ndo->ndo_snapend;
ND_PRINT((ndo, ": BGP"));
if (ndo->ndo_vflag < 1) /* lets be less chatty */
return;
p = dat;
start = p;
while (p < ep) {
if (!ND_TTEST2(p[0], 1))
break;
if (p[0] != 0xff) {
p++;
continue;
}
if (!ND_TTEST2(p[0], sizeof(marker)))
break;
if (memcmp(p, marker, sizeof(marker)) != 0) {
p++;
continue;
}
/* found BGP header */
ND_TCHECK2(p[0], BGP_SIZE); /*XXX*/
memcpy(&bgp, p, BGP_SIZE);
if (start != p)
ND_PRINT((ndo, " [|BGP]"));
hlen = ntohs(bgp.bgp_len);
if (hlen < BGP_SIZE) {
ND_PRINT((ndo, "\n[|BGP Bogus header length %u < %u]", hlen,
BGP_SIZE));
break;
}
if (ND_TTEST2(p[0], hlen)) {
if (!bgp_header_print(ndo, p, hlen))
return;
p += hlen;
start = p;
} else {
ND_PRINT((ndo, "\n[|BGP %s]",
tok2str(bgp_msg_values,
"Unknown Message Type",
bgp.bgp_type)));
break;
}
}
return;
trunc:
ND_PRINT((ndo, " [|BGP]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 4
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2719_0 |
crossvul-cpp_data_bad_2682_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 2000
* 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: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: Apple's DLT_PKTAP printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "extract.h"
#ifdef DLT_PKTAP
/*
* XXX - these are little-endian in the captures I've seen, but Apple
* no longer make any big-endian machines (Macs use x86, iOS machines
* use ARM and run it little-endian), so that might be by definition
* or they might be host-endian.
*
* If a big-endian PKTAP file ever shows up, and it comes from a
* big-endian machine, presumably these are host-endian, and we need
* to just fetch the fields directly in tcpdump but byte-swap them
* to host byte order in libpcap.
*/
typedef struct pktap_header {
uint32_t pkt_len; /* length of pktap header */
uint32_t pkt_rectype; /* type of record */
uint32_t pkt_dlt; /* DLT type of this packet */
char pkt_ifname[24]; /* interface name */
uint32_t pkt_flags;
uint32_t pkt_pfamily; /* "protocol family" */
uint32_t pkt_llhdrlen; /* link-layer header length? */
uint32_t pkt_lltrlrlen; /* link-layer trailer length? */
uint32_t pkt_pid; /* process ID */
char pkt_cmdname[20]; /* command name */
uint32_t pkt_svc_class; /* "service class" */
uint16_t pkt_iftype; /* "interface type" */
uint16_t pkt_ifunit; /* unit number of interface? */
uint32_t pkt_epid; /* "effective process ID" */
char pkt_ecmdname[20]; /* "effective command name" */
} pktap_header_t;
/*
* Record types.
*/
#define PKT_REC_NONE 0 /* nothing follows the header */
#define PKT_REC_PACKET 1 /* a packet follows the header */
static inline void
pktap_header_print(netdissect_options *ndo, const u_char *bp, u_int length)
{
const pktap_header_t *hdr;
uint32_t dlt, hdrlen;
const char *dltname;
hdr = (const pktap_header_t *)bp;
dlt = EXTRACT_LE_32BITS(&hdr->pkt_dlt);
hdrlen = EXTRACT_LE_32BITS(&hdr->pkt_len);
dltname = pcap_datalink_val_to_name(dlt);
if (!ndo->ndo_qflag) {
ND_PRINT((ndo,"DLT %s (%d) len %d",
(dltname != NULL ? dltname : "UNKNOWN"), dlt, hdrlen));
} else {
ND_PRINT((ndo,"%s", (dltname != NULL ? dltname : "UNKNOWN")));
}
ND_PRINT((ndo, ", length %u: ", length));
}
/*
* This is the top level routine of the printer. 'p' points
* to the ether header of the packet, 'h->ts' is the timestamp,
* 'h->len' is the length of the packet off the wire, and 'h->caplen'
* is the number of bytes actually captured.
*/
u_int
pktap_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
uint32_t dlt, hdrlen, rectype;
u_int caplen = h->caplen;
u_int length = h->len;
if_printer printer;
const pktap_header_t *hdr;
if (caplen < sizeof(pktap_header_t) || length < sizeof(pktap_header_t)) {
ND_PRINT((ndo, "[|pktap]"));
return (0);
}
hdr = (const pktap_header_t *)p;
dlt = EXTRACT_LE_32BITS(&hdr->pkt_dlt);
hdrlen = EXTRACT_LE_32BITS(&hdr->pkt_len);
if (hdrlen < sizeof(pktap_header_t)) {
/*
* Claimed header length < structure length.
* XXX - does this just mean some fields aren't
* being supplied, or is it truly an error (i.e.,
* is the length supplied so that the header can
* be expanded in the future)?
*/
ND_PRINT((ndo, "[|pktap]"));
return (0);
}
if (caplen < hdrlen || length < hdrlen) {
ND_PRINT((ndo, "[|pktap]"));
return (hdrlen);
}
if (ndo->ndo_eflag)
pktap_header_print(ndo, p, length);
length -= hdrlen;
caplen -= hdrlen;
p += hdrlen;
rectype = EXTRACT_LE_32BITS(&hdr->pkt_rectype);
switch (rectype) {
case PKT_REC_NONE:
ND_PRINT((ndo, "no data"));
break;
case PKT_REC_PACKET:
if ((printer = lookup_printer(dlt)) != NULL) {
hdrlen += printer(ndo, h, p);
} else {
if (!ndo->ndo_eflag)
pktap_header_print(ndo, (const u_char *)hdr,
length + hdrlen);
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
}
break;
}
return (hdrlen);
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
#endif /* DLT_PKTAP */
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2682_0 |
crossvul-cpp_data_bad_3358_2 | /*
* IPv6 library code, needed by static components when full IPv6 support is
* not configured or static. These functions are needed by GSO/GRO implementation.
*/
#include <linux/export.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/ip6_fib.h>
#include <net/addrconf.h>
#include <net/secure_seq.h>
#include <linux/netfilter.h>
static u32 __ipv6_select_ident(struct net *net, u32 hashrnd,
const struct in6_addr *dst,
const struct in6_addr *src)
{
u32 hash, id;
hash = __ipv6_addr_jhash(dst, hashrnd);
hash = __ipv6_addr_jhash(src, hash);
hash ^= net_hash_mix(net);
/* Treat id of 0 as unset and if we get 0 back from ip_idents_reserve,
* set the hight order instead thus minimizing possible future
* collisions.
*/
id = ip_idents_reserve(hash, 1);
if (unlikely(!id))
id = 1 << 31;
return id;
}
/* This function exists only for tap drivers that must support broken
* clients requesting UFO without specifying an IPv6 fragment ID.
*
* This is similar to ipv6_select_ident() but we use an independent hash
* seed to limit information leakage.
*
* The network header must be set before calling this.
*/
void ipv6_proxy_select_ident(struct net *net, struct sk_buff *skb)
{
static u32 ip6_proxy_idents_hashrnd __read_mostly;
struct in6_addr buf[2];
struct in6_addr *addrs;
u32 id;
addrs = skb_header_pointer(skb,
skb_network_offset(skb) +
offsetof(struct ipv6hdr, saddr),
sizeof(buf), buf);
if (!addrs)
return;
net_get_random_once(&ip6_proxy_idents_hashrnd,
sizeof(ip6_proxy_idents_hashrnd));
id = __ipv6_select_ident(net, ip6_proxy_idents_hashrnd,
&addrs[1], &addrs[0]);
skb_shinfo(skb)->ip6_frag_id = htonl(id);
}
EXPORT_SYMBOL_GPL(ipv6_proxy_select_ident);
__be32 ipv6_select_ident(struct net *net,
const struct in6_addr *daddr,
const struct in6_addr *saddr)
{
static u32 ip6_idents_hashrnd __read_mostly;
u32 id;
net_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd));
id = __ipv6_select_ident(net, ip6_idents_hashrnd, daddr, saddr);
return htonl(id);
}
EXPORT_SYMBOL(ipv6_select_ident);
int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr)
{
u16 offset = sizeof(struct ipv6hdr);
struct ipv6_opt_hdr *exthdr =
(struct ipv6_opt_hdr *)(ipv6_hdr(skb) + 1);
unsigned int packet_len = skb_tail_pointer(skb) -
skb_network_header(skb);
int found_rhdr = 0;
*nexthdr = &ipv6_hdr(skb)->nexthdr;
while (offset + 1 <= packet_len) {
switch (**nexthdr) {
case NEXTHDR_HOP:
break;
case NEXTHDR_ROUTING:
found_rhdr = 1;
break;
case NEXTHDR_DEST:
#if IS_ENABLED(CONFIG_IPV6_MIP6)
if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0)
break;
#endif
if (found_rhdr)
return offset;
break;
default:
return offset;
}
offset += ipv6_optlen(exthdr);
*nexthdr = &exthdr->nexthdr;
exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) +
offset);
}
return offset;
}
EXPORT_SYMBOL(ip6_find_1stfragopt);
#if IS_ENABLED(CONFIG_IPV6)
int ip6_dst_hoplimit(struct dst_entry *dst)
{
int hoplimit = dst_metric_raw(dst, RTAX_HOPLIMIT);
if (hoplimit == 0) {
struct net_device *dev = dst->dev;
struct inet6_dev *idev;
rcu_read_lock();
idev = __in6_dev_get(dev);
if (idev)
hoplimit = idev->cnf.hop_limit;
else
hoplimit = dev_net(dev)->ipv6.devconf_all->hop_limit;
rcu_read_unlock();
}
return hoplimit;
}
EXPORT_SYMBOL(ip6_dst_hoplimit);
#endif
int __ip6_local_out(struct net *net, struct sock *sk, struct sk_buff *skb)
{
int len;
len = skb->len - sizeof(struct ipv6hdr);
if (len > IPV6_MAXPLEN)
len = 0;
ipv6_hdr(skb)->payload_len = htons(len);
IP6CB(skb)->nhoff = offsetof(struct ipv6hdr, nexthdr);
/* if egress device is enslaved to an L3 master device pass the
* skb to its handler for processing
*/
skb = l3mdev_ip6_out(sk, skb);
if (unlikely(!skb))
return 0;
skb->protocol = htons(ETH_P_IPV6);
return nf_hook(NFPROTO_IPV6, NF_INET_LOCAL_OUT,
net, sk, skb, NULL, skb_dst(skb)->dev,
dst_output);
}
EXPORT_SYMBOL_GPL(__ip6_local_out);
int ip6_local_out(struct net *net, struct sock *sk, struct sk_buff *skb)
{
int err;
err = __ip6_local_out(net, sk, skb);
if (likely(err == 1))
err = dst_output(net, sk, skb);
return err;
}
EXPORT_SYMBOL_GPL(ip6_local_out);
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3358_2 |
crossvul-cpp_data_bad_4215_0 | /*
* ndpiReader.c
*
* Copyright (C) 2011-19 - ntop.org
*
* nDPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* nDPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with nDPI. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "ndpi_config.h"
#ifdef linux
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <sched.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#ifdef WIN32
#include <winsock2.h> /* winsock.h is included automatically */
#include <process.h>
#include <io.h>
#define getopt getopt____
#else
#include <unistd.h>
#include <netinet/in.h>
#endif
#include <string.h>
#include <stdarg.h>
#include <search.h>
#include <pcap.h>
#include <signal.h>
#include <pthread.h>
#include <sys/socket.h>
#include <assert.h>
#include <math.h>
#include "ndpi_api.h"
#include "uthash.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <libgen.h>
#include "reader_util.h"
#include "intrusion_detection.h"
/** Client parameters **/
static char *_pcap_file[MAX_NUM_READER_THREADS]; /**< Ingress pcap file/interfaces */
static FILE *playlist_fp[MAX_NUM_READER_THREADS] = { NULL }; /**< Ingress playlist */
static FILE *results_file = NULL;
static char *results_path = NULL;
static char * bpfFilter = NULL; /**< bpf filter */
static char *_protoFilePath = NULL; /**< Protocol file path */
static char *_customCategoryFilePath= NULL; /**< Custom categories file path */
static FILE *csv_fp = NULL; /**< for CSV export */
static u_int8_t live_capture = 0;
static u_int8_t undetected_flows_deleted = 0;
/** User preferences **/
u_int8_t enable_protocol_guess = 1, enable_payload_analyzer = 0;
u_int8_t verbose = 0, enable_joy_stats = 0;
int nDPI_LogLevel = 0;
char *_debug_protocols = NULL;
u_int8_t human_readeable_string_len = 5;
u_int8_t max_num_udp_dissected_pkts = 16 /* 8 is enough for most protocols, Signal requires more */, max_num_tcp_dissected_pkts = 80 /* due to telnet */;
static u_int32_t pcap_analysis_duration = (u_int32_t)-1;
static u_int16_t decode_tunnels = 0;
static u_int16_t num_loops = 1;
static u_int8_t shutdown_app = 0, quiet_mode = 0;
static u_int8_t num_threads = 1;
static struct timeval startup_time, begin, end;
#ifdef linux
static int core_affinity[MAX_NUM_READER_THREADS];
#endif
static struct timeval pcap_start = { 0, 0}, pcap_end = { 0, 0 };
/** Detection parameters **/
static time_t capture_for = 0;
static time_t capture_until = 0;
static u_int32_t num_flows;
static struct ndpi_detection_module_struct *ndpi_info_mod = NULL;
extern u_int32_t max_num_packets_per_flow, max_packet_payload_dissection, max_num_reported_top_payloads;
extern u_int16_t min_pattern_len, max_pattern_len;
extern void ndpi_self_check_host_match(); /* Self check function */
struct flow_info {
struct ndpi_flow_info *flow;
u_int16_t thread_id;
};
static struct flow_info *all_flows;
struct info_pair {
u_int32_t addr;
u_int8_t version; /* IP version */
char proto[16]; /*app level protocol*/
int count;
};
typedef struct node_a{
u_int32_t addr;
u_int8_t version; /* IP version */
char proto[16]; /*app level protocol*/
int count;
struct node_a *left, *right;
}addr_node;
struct port_stats {
u_int32_t port; /* we'll use this field as the key */
u_int32_t num_pkts, num_bytes;
u_int32_t num_flows;
u_int32_t num_addr; /*number of distinct IP addresses */
u_int32_t cumulative_addr; /*cumulative some of IP addresses */
addr_node *addr_tree; /* tree of distinct IP addresses */
struct info_pair top_ip_addrs[MAX_NUM_IP_ADDRESS];
u_int8_t hasTopHost; /* as boolean flag */
u_int32_t top_host; /* host that is contributed to > 95% of traffic */
u_int8_t version; /* top host's ip version */
char proto[16]; /* application level protocol of top host */
UT_hash_handle hh; /* makes this structure hashable */
};
struct port_stats *srcStats = NULL, *dstStats = NULL;
// struct to hold count of flows received by destination ports
struct port_flow_info {
u_int32_t port; /* key */
u_int32_t num_flows;
UT_hash_handle hh;
};
// struct to hold single packet tcp flows sent by source ip address
struct single_flow_info {
u_int32_t saddr; /* key */
u_int8_t version; /* IP version */
struct port_flow_info *ports;
u_int32_t tot_flows;
UT_hash_handle hh;
};
struct single_flow_info *scannerHosts = NULL;
// struct to hold top receiver hosts
struct receiver {
u_int32_t addr; /* key */
u_int8_t version; /* IP version */
u_int32_t num_pkts;
UT_hash_handle hh;
};
struct receiver *receivers = NULL, *topReceivers = NULL;
struct ndpi_packet_trailer {
u_int32_t magic; /* 0x19682017 */
u_int16_t master_protocol /* e.g. HTTP */, app_protocol /* e.g. FaceBook */;
char name[16];
};
static pcap_dumper_t *extcap_dumper = NULL;
static char extcap_buf[16384];
static char *extcap_capture_fifo = NULL;
static u_int16_t extcap_packet_filter = (u_int16_t)-1;
// struct associated to a workflow for a thread
struct reader_thread {
struct ndpi_workflow *workflow;
pthread_t pthread;
u_int64_t last_idle_scan_time;
u_int32_t idle_scan_idx;
u_int32_t num_idle_flows;
struct ndpi_flow_info *idle_flows[IDLE_SCAN_BUDGET];
};
// array for every thread created for a flow
static struct reader_thread ndpi_thread_info[MAX_NUM_READER_THREADS];
// ID tracking
typedef struct ndpi_id {
u_int8_t ip[4]; // Ip address
struct ndpi_id_struct *ndpi_id; // nDpi worker structure
} ndpi_id_t;
// used memory counters
u_int32_t current_ndpi_memory = 0, max_ndpi_memory = 0;
#ifdef USE_DPDK
static int dpdk_port_id = 0, dpdk_run_capture = 1;
#endif
void test_lib(); /* Forward */
extern void ndpi_report_payload_stats();
/* ********************************** */
#ifdef DEBUG_TRACE
FILE *trace = NULL;
#endif
/********************** FUNCTIONS ********************* */
/**
* @brief Set main components necessary to the detection
*/
static void setupDetection(u_int16_t thread_id, pcap_t * pcap_handle);
#if 0
static void reduceBDbits(uint32_t *bd, unsigned int len) {
int mask = 0;
int shift = 0;
unsigned int i = 0;
for(i = 0; i < len; i++)
mask = mask | bd[i];
mask = mask >> 8;
for(i = 0; i < 24 && mask; i++) {
mask = mask >> 1;
if (mask == 0) {
shift = i+1;
break;
}
}
for(i = 0; i < len; i++)
bd[i] = bd[i] >> shift;
}
#endif
/**
* @brief Get flow byte distribution mean and variance
*/
static void
flowGetBDMeanandVariance(struct ndpi_flow_info* flow) {
FILE *out = results_file ? results_file : stdout;
const uint32_t *array = NULL;
uint32_t tmp[256], i;
unsigned int num_bytes;
double mean = 0.0, variance = 0.0;
struct ndpi_entropy last_entropy = flow->last_entropy;
fflush(out);
/*
* Sum up the byte_count array for outbound and inbound flows,
* if this flow is bidirectional
*/
if (!flow->bidirectional) {
array = last_entropy.src2dst_byte_count;
num_bytes = last_entropy.src2dst_l4_bytes;
for (i=0; i<256; i++) {
tmp[i] = last_entropy.src2dst_byte_count[i];
}
if (last_entropy.src2dst_num_bytes != 0) {
mean = last_entropy.src2dst_bd_mean;
variance = last_entropy.src2dst_bd_variance/(last_entropy.src2dst_num_bytes - 1);
variance = sqrt(variance);
if (last_entropy.src2dst_num_bytes == 1) {
variance = 0.0;
}
}
} else {
for (i=0; i<256; i++) {
tmp[i] = last_entropy.src2dst_byte_count[i] + last_entropy.dst2src_byte_count[i];
}
array = tmp;
num_bytes = last_entropy.src2dst_l4_bytes + last_entropy.dst2src_l4_bytes;
if (last_entropy.src2dst_num_bytes + last_entropy.dst2src_num_bytes != 0) {
mean = ((double)last_entropy.src2dst_num_bytes)/((double)(last_entropy.src2dst_num_bytes+last_entropy.dst2src_num_bytes))*last_entropy.src2dst_bd_mean +
((double)last_entropy.dst2src_num_bytes)/((double)(last_entropy.dst2src_num_bytes+last_entropy.src2dst_num_bytes))*last_entropy.dst2src_bd_mean;
variance = ((double)last_entropy.src2dst_num_bytes)/((double)(last_entropy.src2dst_num_bytes+last_entropy.dst2src_num_bytes))*last_entropy.src2dst_bd_variance +
((double)last_entropy.dst2src_num_bytes)/((double)(last_entropy.dst2src_num_bytes+last_entropy.src2dst_num_bytes))*last_entropy.dst2src_bd_variance;
variance = variance/((double)(last_entropy.src2dst_num_bytes + last_entropy.dst2src_num_bytes - 1));
variance = sqrt(variance);
if (last_entropy.src2dst_num_bytes + last_entropy.dst2src_num_bytes == 1) {
variance = 0.0;
}
}
}
if(enable_joy_stats) {
#if 0
if(verbose > 1) {
reduceBDbits(tmp, 256);
array = tmp;
fprintf(out, " [byte_dist: ");
for(i = 0; i < 255; i++)
fprintf(out, "%u,", (unsigned char)array[i]);
fprintf(out, "%u]", (unsigned char)array[i]);
}
#endif
/* Output the mean */
if(num_bytes != 0) {
double entropy = ndpi_flow_get_byte_count_entropy(array, num_bytes);
if(csv_fp) {
fprintf(csv_fp, ",%.3f,%.3f,%.3f,%.3f", mean, variance, entropy, entropy * num_bytes);
} else {
fprintf(out, "[byte_dist_mean: %f", mean);
fprintf(out, "][byte_dist_std: %f]", variance);
fprintf(out, "[entropy: %f]", entropy);
fprintf(out, "[total_entropy: %f]", entropy * num_bytes);
}
} else {
if(csv_fp)
fprintf(csv_fp, ",%.3f,%.3f,%.3f,%.3f", 0.0, 0.0, 0.0, 0.0);
}
}
}
/**
* @brief Print help instructions
*/
static void help(u_int long_help) {
printf("Welcome to nDPI %s\n\n", ndpi_revision());
printf("ndpiReader "
#ifndef USE_DPDK
"-i <file|device> "
#endif
"[-f <filter>][-s <duration>][-m <duration>]\n"
" [-p <protos>][-l <loops> [-q][-d][-J][-h][-e <len>][-t][-v <level>]\n"
" [-n <threads>][-w <file>][-c <file>][-C <file>][-j <file>][-x <file>]\n"
" [-T <num>][-U <num>]\n\n"
"Usage:\n"
" -i <file.pcap|device> | Specify a pcap file/playlist to read packets from or a\n"
" | device for live capture (comma-separated list)\n"
" -f <BPF filter> | Specify a BPF filter for filtering selected traffic\n"
" -s <duration> | Maximum capture duration in seconds (live traffic capture only)\n"
" -m <duration> | Split analysis duration in <duration> max seconds\n"
" -p <file>.protos | Specify a protocol file (eg. protos.txt)\n"
" -l <num loops> | Number of detection loops (test only)\n"
" -n <num threads> | Number of threads. Default: number of interfaces in -i.\n"
" | Ignored with pcap files.\n"
#ifdef linux
" -g <id:id...> | Thread affinity mask (one core id per thread)\n"
#endif
" -d | Disable protocol guess and use only DPI\n"
" -e <len> | Min human readeable string match len. Default %u\n"
" -q | Quiet mode\n"
" -J | Display flow SPLT (sequence of packet length and time)\n"
" | and BD (byte distribution). See https://github.com/cisco/joy\n"
" -t | Dissect GTP/TZSP tunnels\n"
" -P <a>:<b>:<c>:<d>:<e> | Enable payload analysis:\n"
" | <a> = min pattern len to search\n"
" | <b> = max pattern len to search\n"
" | <c> = max num packets per flow\n"
" | <d> = max packet payload dissection\n"
" | <d> = max num reported payloads\n"
" | Default: %u:%u:%u:%u:%u\n"
" -r | Print nDPI version and git revision\n"
" -c <path> | Load custom categories from the specified file\n"
" -C <path> | Write output in CSV format on the specified file\n"
" -w <path> | Write test output on the specified file. This is useful for\n"
" | testing purposes in order to compare results across runs\n"
" -h | This help\n"
" -v <1|2|3> | Verbose 'unknown protocol' packet print.\n"
" | 1 = verbose\n"
" | 2 = very verbose\n"
" | 3 = port stats\n"
" -V <1-4> | nDPI logging level\n"
" | 1 - trace, 2 - debug, 3 - full debug\n"
" | >3 - full debug + dbg_proto = all\n"
" -T <num> | Max number of TCP processed packets before giving up [default: %u]\n"
" -U <num> | Max number of UDP processed packets before giving up [default: %u]\n"
,
human_readeable_string_len,
min_pattern_len, max_pattern_len, max_num_packets_per_flow, max_packet_payload_dissection,
max_num_reported_top_payloads, max_num_tcp_dissected_pkts, max_num_udp_dissected_pkts);
#ifndef WIN32
printf("\nExcap (wireshark) options:\n"
" --extcap-interfaces\n"
" --extcap-version\n"
" --extcap-dlts\n"
" --extcap-interface <name>\n"
" --extcap-config\n"
" --capture\n"
" --extcap-capture-filter\n"
" --fifo <path to file or pipe>\n"
" --debug\n"
" --dbg-proto proto|num[,...]\n"
);
#endif
if(long_help) {
NDPI_PROTOCOL_BITMASK all;
printf("\n\nnDPI supported protocols:\n");
printf("%3s %-22s %-8s %-12s %s\n", "Id", "Protocol", "Layer_4", "Breed", "Category");
num_threads = 1;
NDPI_BITMASK_SET_ALL(all);
ndpi_set_protocol_detection_bitmask2(ndpi_info_mod, &all);
ndpi_dump_protocols(ndpi_info_mod);
}
exit(!long_help);
}
static struct option longopts[] = {
/* mandatory extcap options */
{ "extcap-interfaces", no_argument, NULL, '0'},
{ "extcap-version", optional_argument, NULL, '1'},
{ "extcap-dlts", no_argument, NULL, '2'},
{ "extcap-interface", required_argument, NULL, '3'},
{ "extcap-config", no_argument, NULL, '4'},
{ "capture", no_argument, NULL, '5'},
{ "extcap-capture-filter", required_argument, NULL, '6'},
{ "fifo", required_argument, NULL, '7'},
{ "debug", no_argument, NULL, '8'},
{ "dbg-proto", required_argument, NULL, 257},
{ "ndpi-proto-filter", required_argument, NULL, '9'},
/* ndpiReader options */
{ "enable-protocol-guess", no_argument, NULL, 'd'},
{ "categories", required_argument, NULL, 'c'},
{ "csv-dump", required_argument, NULL, 'C'},
{ "interface", required_argument, NULL, 'i'},
{ "filter", required_argument, NULL, 'f'},
{ "cpu-bind", required_argument, NULL, 'g'},
{ "loops", required_argument, NULL, 'l'},
{ "num-threads", required_argument, NULL, 'n'},
{ "protos", required_argument, NULL, 'p'},
{ "capture-duration", required_argument, NULL, 's'},
{ "decode-tunnels", no_argument, NULL, 't'},
{ "revision", no_argument, NULL, 'r'},
{ "verbose", no_argument, NULL, 'v'},
{ "version", no_argument, NULL, 'V'},
{ "help", no_argument, NULL, 'h'},
{ "joy", required_argument, NULL, 'J'},
{ "payload-analysis", required_argument, NULL, 'P'},
{ "result-path", required_argument, NULL, 'w'},
{ "quiet", no_argument, NULL, 'q'},
{0, 0, 0, 0}
};
/* ********************************** */
void extcap_interfaces() {
printf("extcap {version=%s}\n", ndpi_revision());
printf("interface {value=ndpi}{display=nDPI interface}\n");
exit(0);
}
/* ********************************** */
void extcap_dlts() {
u_int dlts_number = DLT_EN10MB;
printf("dlt {number=%u}{name=%s}{display=%s}\n", dlts_number, "ndpi", "nDPI Interface");
exit(0);
}
/* ********************************** */
struct ndpi_proto_sorter {
int id;
char name[16];
};
/* ********************************** */
int cmpProto(const void *_a, const void *_b) {
struct ndpi_proto_sorter *a = (struct ndpi_proto_sorter*)_a;
struct ndpi_proto_sorter *b = (struct ndpi_proto_sorter*)_b;
return(strcmp(a->name, b->name));
}
/* ********************************** */
int cmpFlows(const void *_a, const void *_b) {
struct ndpi_flow_info *fa = ((struct flow_info*)_a)->flow;
struct ndpi_flow_info *fb = ((struct flow_info*)_b)->flow;
uint64_t a_size = fa->src2dst_bytes + fa->dst2src_bytes;
uint64_t b_size = fb->src2dst_bytes + fb->dst2src_bytes;
if(a_size != b_size)
return a_size < b_size ? 1 : -1;
// copy from ndpi_workflow_node_cmp();
if(fa->ip_version < fb->ip_version ) return(-1); else { if(fa->ip_version > fb->ip_version ) return(1); }
if(fa->protocol < fb->protocol ) return(-1); else { if(fa->protocol > fb->protocol ) return(1); }
if(htonl(fa->src_ip) < htonl(fb->src_ip) ) return(-1); else { if(htonl(fa->src_ip) > htonl(fb->src_ip) ) return(1); }
if(htons(fa->src_port) < htons(fb->src_port)) return(-1); else { if(htons(fa->src_port) > htons(fb->src_port)) return(1); }
if(htonl(fa->dst_ip) < htonl(fb->dst_ip) ) return(-1); else { if(htonl(fa->dst_ip) > htonl(fb->dst_ip) ) return(1); }
if(htons(fa->dst_port) < htons(fb->dst_port)) return(-1); else { if(htons(fa->dst_port) > htons(fb->dst_port)) return(1); }
return(0);
}
/* ********************************** */
void extcap_config() {
int i, argidx = 0;
struct ndpi_proto_sorter *protos;
u_int ndpi_num_supported_protocols = ndpi_get_ndpi_num_supported_protocols(ndpi_info_mod);
ndpi_proto_defaults_t *proto_defaults = ndpi_get_proto_defaults(ndpi_info_mod);
/* -i <interface> */
printf("arg {number=%d}{call=-i}{display=Capture Interface}{type=string}"
"{tooltip=The interface name}\n", argidx++);
printf("arg {number=%d}{call=-i}{display=Pcap File to Analyze}{type=fileselect}"
"{tooltip=The pcap file to analyze (if the interface is unspecified)}\n", argidx++);
protos = (struct ndpi_proto_sorter*)malloc(sizeof(struct ndpi_proto_sorter) * ndpi_num_supported_protocols);
if(!protos) exit(0);
for(i=0; i<(int) ndpi_num_supported_protocols; i++) {
protos[i].id = i;
snprintf(protos[i].name, sizeof(protos[i].name), "%s", proto_defaults[i].protoName);
}
qsort(protos, ndpi_num_supported_protocols, sizeof(struct ndpi_proto_sorter), cmpProto);
printf("arg {number=%d}{call=-9}{display=nDPI Protocol Filter}{type=selector}"
"{tooltip=nDPI Protocol to be filtered}\n", argidx);
printf("value {arg=%d}{value=%d}{display=%s}\n", argidx, -1, "All Protocols (no nDPI filtering)");
for(i=0; i<(int)ndpi_num_supported_protocols; i++)
printf("value {arg=%d}{value=%d}{display=%s (%d)}\n", argidx, protos[i].id,
protos[i].name, protos[i].id);
free(protos);
exit(0);
}
/* ********************************** */
void extcap_capture() {
#ifdef DEBUG_TRACE
if(trace) fprintf(trace, " #### %s #### \n", __FUNCTION__);
#endif
if((extcap_dumper = pcap_dump_open(pcap_open_dead(DLT_EN10MB, 16384 /* MTU */),
extcap_capture_fifo)) == NULL) {
fprintf(stderr, "Unable to open the pcap dumper on %s", extcap_capture_fifo);
#ifdef DEBUG_TRACE
if(trace) fprintf(trace, "Unable to open the pcap dumper on %s\n",
extcap_capture_fifo);
#endif
return;
}
#ifdef DEBUG_TRACE
if(trace) fprintf(trace, "Starting packet capture [%p]\n", extcap_dumper);
#endif
}
/* ********************************** */
void printCSVHeader() {
if(!csv_fp) return;
fprintf(csv_fp, "#flow_id,protocol,first_seen,last_seen,duration,src_ip,src_port,dst_ip,dst_port,ndpi_proto_num,ndpi_proto,server_name,");
fprintf(csv_fp, "benign_score,dos_slow_score,dos_goldeneye_score,dos_hulk_score,ddos_score,hearthbleed_score,ftp_patator_score,ssh_patator_score,infiltration_score,");
fprintf(csv_fp, "c_to_s_pkts,c_to_s_bytes,c_to_s_goodput_bytes,s_to_c_pkts,s_to_c_bytes,s_to_c_goodput_bytes,");
fprintf(csv_fp, "data_ratio,str_data_ratio,c_to_s_goodput_ratio,s_to_c_goodput_ratio,");
/* IAT (Inter Arrival Time) */
fprintf(csv_fp, "iat_flow_min,iat_flow_avg,iat_flow_max,iat_flow_stddev,");
fprintf(csv_fp, "iat_c_to_s_min,iat_c_to_s_avg,iat_c_to_s_max,iat_c_to_s_stddev,");
fprintf(csv_fp, "iat_s_to_c_min,iat_s_to_c_avg,iat_s_to_c_max,iat_s_to_c_stddev,");
/* Packet Length */
fprintf(csv_fp, "pktlen_c_to_s_min,pktlen_c_to_s_avg,pktlen_c_to_s_max,pktlen_c_to_s_stddev,");
fprintf(csv_fp, "pktlen_s_to_c_min,pktlen_s_to_c_avg,pktlen_s_to_c_max,pktlen_s_to_c_stddev,");
/* TCP flags */
fprintf(csv_fp, "cwr,ece,urg,ack,psh,rst,syn,fin,");
fprintf(csv_fp, "c_to_s_cwr,c_to_s_ece,c_to_s_urg,c_to_s_ack,c_to_s_psh,c_to_s_rst,c_to_s_syn,c_to_s_fin,");
fprintf(csv_fp, "s_to_c_cwr,s_to_c_ece,s_to_c_urg,s_to_c_ack,s_to_c_psh,s_to_c_rst,s_to_c_syn,s_to_c_fin,");
/* TCP window */
fprintf(csv_fp, "c_to_s_init_win,s_to_c_init_win,");
/* Flow info */
fprintf(csv_fp, "client_info,server_info,");
fprintf(csv_fp, "tls_version,ja3c,tls_client_unsafe,");
fprintf(csv_fp, "ja3s,tls_server_unsafe,");
fprintf(csv_fp, "tls_alpn,tls_supported_versions,");
fprintf(csv_fp, "tls_issuerDN,tls_subjectDN,");
fprintf(csv_fp, "ssh_client_hassh,ssh_server_hassh,flow_info");
/* Joy */
if(enable_joy_stats) {
fprintf(csv_fp, ",byte_dist_mean,byte_dist_std,entropy,total_entropy");
}
fprintf(csv_fp, "\n");
}
/* ********************************** */
/**
* @brief Option parser
*/
static void parseOptions(int argc, char **argv) {
int option_idx = 0, do_capture = 0;
char *__pcap_file = NULL, *bind_mask = NULL;
int thread_id, opt;
#ifdef linux
u_int num_cores = sysconf(_SC_NPROCESSORS_ONLN);
#endif
#ifdef DEBUG_TRACE
trace = fopen("/tmp/ndpiReader.log", "a");
if(trace) fprintf(trace, " #### %s #### \n", __FUNCTION__);
#endif
#ifdef USE_DPDK
{
int ret = rte_eal_init(argc, argv);
if(ret < 0)
rte_exit(EXIT_FAILURE, "Error with EAL initialization\n");
argc -= ret, argv += ret;
}
#endif
while((opt = getopt_long(argc, argv, "e:c:C:df:g:i:hp:P:l:s:tv:V:n:Jrp:w:q0123:456:7:89:m:T:U:",
longopts, &option_idx)) != EOF) {
#ifdef DEBUG_TRACE
if(trace) fprintf(trace, " #### -%c [%s] #### \n", opt, optarg ? optarg : "");
#endif
switch (opt) {
case 'd':
enable_protocol_guess = 0;
break;
case 'e':
human_readeable_string_len = atoi(optarg);
break;
case 'i':
case '3':
_pcap_file[0] = optarg;
break;
case 'm':
pcap_analysis_duration = atol(optarg);
break;
case 'f':
case '6':
bpfFilter = optarg;
break;
case 'g':
bind_mask = optarg;
break;
case 'l':
num_loops = atoi(optarg);
break;
case 'n':
num_threads = atoi(optarg);
break;
case 'p':
_protoFilePath = optarg;
break;
case 'c':
_customCategoryFilePath = optarg;
break;
case 'C':
if((csv_fp = fopen(optarg, "w")) == NULL)
printf("Unable to write on CSV file %s\n", optarg);
break;
case 's':
capture_for = atoi(optarg);
capture_until = capture_for + time(NULL);
break;
case 't':
decode_tunnels = 1;
break;
case 'r':
printf("ndpiReader - nDPI (%s)\n", ndpi_revision());
exit(0);
case 'v':
verbose = atoi(optarg);
break;
case 'V':
nDPI_LogLevel = atoi(optarg);
if(nDPI_LogLevel < 0) nDPI_LogLevel = 0;
if(nDPI_LogLevel > 3) {
nDPI_LogLevel = 3;
_debug_protocols = strdup("all");
}
break;
case 'h':
help(1);
break;
case 'J':
enable_joy_stats = 1;
break;
case 'P':
{
int _min_pattern_len, _max_pattern_len,
_max_num_packets_per_flow, _max_packet_payload_dissection,
_max_num_reported_top_payloads;
enable_payload_analyzer = 1;
if(sscanf(optarg, "%d:%d:%d:%d:%d", &_min_pattern_len, &_max_pattern_len,
&_max_num_packets_per_flow,
&_max_packet_payload_dissection,
&_max_num_reported_top_payloads) == 5) {
min_pattern_len = _min_pattern_len, max_pattern_len = _max_pattern_len;
max_num_packets_per_flow = _max_num_packets_per_flow, max_packet_payload_dissection = _max_packet_payload_dissection;
max_num_reported_top_payloads = _max_num_reported_top_payloads;
if(min_pattern_len > max_pattern_len) min_pattern_len = max_pattern_len;
if(min_pattern_len < 2) min_pattern_len = 2;
if(max_pattern_len > 16) max_pattern_len = 16;
if(max_num_packets_per_flow == 0) max_num_packets_per_flow = 1;
if(max_packet_payload_dissection < 4) max_packet_payload_dissection = 4;
if(max_num_reported_top_payloads == 0) max_num_reported_top_payloads = 1;
} else {
printf("Invalid -P format. Ignored\n");
help(0);
}
}
break;
case 'w':
results_path = strdup(optarg);
if((results_file = fopen(results_path, "w")) == NULL) {
printf("Unable to write in file %s: quitting\n", results_path);
return;
}
break;
case 'q':
quiet_mode = 1;
nDPI_LogLevel = 0;
break;
/* Extcap */
case '0':
extcap_interfaces();
break;
case '1':
printf("extcap {version=%s}\n", ndpi_revision());
break;
case '2':
extcap_dlts();
break;
case '4':
extcap_config();
break;
case '5':
do_capture = 1;
break;
case '7':
extcap_capture_fifo = strdup(optarg);
break;
case '8':
nDPI_LogLevel = NDPI_LOG_DEBUG_EXTRA;
_debug_protocols = strdup("all");
break;
case '9':
extcap_packet_filter = ndpi_get_proto_by_name(ndpi_info_mod, optarg);
if(extcap_packet_filter == NDPI_PROTOCOL_UNKNOWN) extcap_packet_filter = atoi(optarg);
break;
case 257:
_debug_protocols = strdup(optarg);
break;
case 'T':
max_num_tcp_dissected_pkts = atoi(optarg);
if(max_num_tcp_dissected_pkts < 3) max_num_tcp_dissected_pkts = 3;
break;
case 'U':
max_num_udp_dissected_pkts = atoi(optarg);
if(max_num_udp_dissected_pkts < 3) max_num_udp_dissected_pkts = 3;
break;
default:
help(0);
break;
}
}
if(_pcap_file[0] == NULL)
help(0);
if(csv_fp)
printCSVHeader();
#ifndef USE_DPDK
if(strchr(_pcap_file[0], ',')) { /* multiple ingress interfaces */
num_threads = 0; /* setting number of threads = number of interfaces */
__pcap_file = strtok(_pcap_file[0], ",");
while(__pcap_file != NULL && num_threads < MAX_NUM_READER_THREADS) {
_pcap_file[num_threads++] = __pcap_file;
__pcap_file = strtok(NULL, ",");
}
} else {
if(num_threads > MAX_NUM_READER_THREADS) num_threads = MAX_NUM_READER_THREADS;
for(thread_id = 1; thread_id < num_threads; thread_id++)
_pcap_file[thread_id] = _pcap_file[0];
}
#ifdef linux
for(thread_id = 0; thread_id < num_threads; thread_id++)
core_affinity[thread_id] = -1;
if(num_cores > 1 && bind_mask != NULL) {
char *core_id = strtok(bind_mask, ":");
thread_id = 0;
while(core_id != NULL && thread_id < num_threads) {
core_affinity[thread_id++] = atoi(core_id) % num_cores;
core_id = strtok(NULL, ":");
}
}
#endif
#endif
#ifdef DEBUG_TRACE
if(trace) fclose(trace);
#endif
}
/* ********************************** */
/**
* @brief From IPPROTO to string NAME
*/
static char* ipProto2Name(u_int16_t proto_id) {
static char proto[8];
switch(proto_id) {
case IPPROTO_TCP:
return("TCP");
break;
case IPPROTO_UDP:
return("UDP");
break;
case IPPROTO_ICMP:
return("ICMP");
break;
case IPPROTO_ICMPV6:
return("ICMPV6");
break;
case 112:
return("VRRP");
break;
case IPPROTO_IGMP:
return("IGMP");
break;
}
snprintf(proto, sizeof(proto), "%u", proto_id);
return(proto);
}
/* ********************************** */
#if 0
/**
* @brief A faster replacement for inet_ntoa().
*/
char* intoaV4(u_int32_t addr, char* buf, u_int16_t bufLen) {
char *cp;
int n;
cp = &buf[bufLen];
*--cp = '\0';
n = 4;
do {
u_int byte = addr & 0xff;
*--cp = byte % 10 + '0';
byte /= 10;
if(byte > 0) {
*--cp = byte % 10 + '0';
byte /= 10;
if(byte > 0)
*--cp = byte + '0';
}
if(n > 1)
*--cp = '.';
addr >>= 8;
} while (--n > 0);
return(cp);
}
#endif
/* ********************************** */
static char* print_cipher(ndpi_cipher_weakness c) {
switch(c) {
case ndpi_cipher_insecure:
return(" (INSECURE)");
break;
case ndpi_cipher_weak:
return(" (WEAK)");
break;
default:
return("");
}
}
/* ********************************** */
static char* is_unsafe_cipher(ndpi_cipher_weakness c) {
switch(c) {
case ndpi_cipher_insecure:
return("INSECURE");
break;
case ndpi_cipher_weak:
return("WEAK");
break;
default:
return("OK");
}
}
/* ********************************** */
/**
* @brief Print the flow
*/
static void printFlow(u_int16_t id, struct ndpi_flow_info *flow, u_int16_t thread_id) {
FILE *out = results_file ? results_file : stdout;
u_int8_t known_tls;
char buf[32], buf1[64];
u_int i;
double dos_ge_score;
double dos_slow_score;
double dos_hulk_score;
double ddos_score;
double hearthbleed_score;
double ftp_patator_score;
double ssh_patator_score;
double inf_score;
if(csv_fp != NULL) {
float data_ratio = ndpi_data_ratio(flow->src2dst_bytes, flow->dst2src_bytes);
double f = (double)flow->first_seen, l = (double)flow->last_seen;
/* PLEASE KEEP IN SYNC WITH printCSVHeader() */
dos_ge_score = Dos_goldeneye_score(flow);
dos_slow_score = Dos_slow_score(flow);
dos_hulk_score = Dos_hulk_score(flow);
ddos_score = Ddos_score(flow);
hearthbleed_score = Hearthbleed_score(flow);
ftp_patator_score = Ftp_patator_score(flow);
ssh_patator_score = Ssh_patator_score(flow);
inf_score = Infiltration_score(flow);
double benign_score = dos_ge_score < 1 && dos_slow_score < 1 && \
dos_hulk_score < 1 && ddos_score < 1 && hearthbleed_score < 1 && \
ftp_patator_score < 1 && ssh_patator_score < 1 && inf_score < 1 ? 1.1 : 0;
fprintf(csv_fp, "%u,%u,%.3f,%.3f,%.3f,%s,%u,%s,%u,",
flow->flow_id,
flow->protocol,
f/1000.0, l/1000.0,
(l-f)/1000.0,
flow->src_name, ntohs(flow->src_port),
flow->dst_name, ntohs(flow->dst_port)
);
fprintf(csv_fp, "%s,",
ndpi_protocol2id(ndpi_thread_info[thread_id].workflow->ndpi_struct,
flow->detected_protocol, buf, sizeof(buf)));
fprintf(csv_fp, "%s,%s,",
ndpi_protocol2name(ndpi_thread_info[thread_id].workflow->ndpi_struct,
flow->detected_protocol, buf, sizeof(buf)),
flow->host_server_name);
fprintf(csv_fp, "%.4lf,%.4lf,%.4lf,%.4lf,%.4lf,%.4lf,%.4lf,%.4lf,%.4lf,", \
benign_score, dos_slow_score, dos_ge_score, dos_hulk_score, \
ddos_score, hearthbleed_score, ftp_patator_score, \
ssh_patator_score, inf_score);
fprintf(csv_fp, "%u,%llu,%llu,", flow->src2dst_packets,
(long long unsigned int) flow->src2dst_bytes, (long long unsigned int) flow->src2dst_goodput_bytes);
fprintf(csv_fp, "%u,%llu,%llu,", flow->dst2src_packets,
(long long unsigned int) flow->dst2src_bytes, (long long unsigned int) flow->dst2src_goodput_bytes);
fprintf(csv_fp, "%.3f,%s,", data_ratio, ndpi_data_ratio2str(data_ratio));
fprintf(csv_fp, "%.1f,%.1f,", 100.0*((float)flow->src2dst_goodput_bytes / (float)(flow->src2dst_bytes+1)),
100.0*((float)flow->dst2src_goodput_bytes / (float)(flow->dst2src_bytes+1)));
/* IAT (Inter Arrival Time) */
fprintf(csv_fp, "%u,%.1f,%u,%.1f,",
ndpi_data_min(flow->iat_flow), ndpi_data_average(flow->iat_flow), ndpi_data_max(flow->iat_flow), ndpi_data_stddev(flow->iat_flow));
fprintf(csv_fp, "%u,%.1f,%u,%.1f,%u,%.1f,%u,%.1f,",
ndpi_data_min(flow->iat_c_to_s), ndpi_data_average(flow->iat_c_to_s), ndpi_data_max(flow->iat_c_to_s), ndpi_data_stddev(flow->iat_c_to_s),
ndpi_data_min(flow->iat_s_to_c), ndpi_data_average(flow->iat_s_to_c), ndpi_data_max(flow->iat_s_to_c), ndpi_data_stddev(flow->iat_s_to_c));
/* Packet Length */
fprintf(csv_fp, "%u,%.1f,%u,%.1f,%u,%.1f,%u,%.1f,",
ndpi_data_min(flow->pktlen_c_to_s), ndpi_data_average(flow->pktlen_c_to_s), ndpi_data_max(flow->pktlen_c_to_s), ndpi_data_stddev(flow->pktlen_c_to_s),
ndpi_data_min(flow->pktlen_s_to_c), ndpi_data_average(flow->pktlen_s_to_c), ndpi_data_max(flow->pktlen_s_to_c), ndpi_data_stddev(flow->pktlen_s_to_c));
/* TCP flags */
fprintf(csv_fp, "%d,%d,%d,%d,%d,%d,%d,%d,", flow->cwr_count, flow->ece_count, flow->urg_count, flow->ack_count, flow->psh_count, flow->rst_count, flow->syn_count, flow->fin_count);
fprintf(csv_fp, "%d,%d,%d,%d,%d,%d,%d,%d,", flow->src2dst_cwr_count, flow->src2dst_ece_count, flow->src2dst_urg_count, flow->src2dst_ack_count, flow->src2dst_psh_count, flow->src2dst_rst_count, flow->src2dst_syn_count, flow->src2dst_fin_count);
fprintf(csv_fp, "%d,%d,%d,%d,%d,%d,%d,%d,", flow->dst2src_cwr_count, flow->ece_count, flow->urg_count, flow->ack_count, flow->psh_count, flow->rst_count, flow->syn_count, flow->fin_count);
/* TCP window */
fprintf(csv_fp, "%u,%u,", flow->c_to_s_init_win, flow->s_to_c_init_win);
fprintf(csv_fp, "%s,%s,",
(flow->ssh_tls.client_requested_server_name[0] != '\0') ? flow->ssh_tls.client_requested_server_name : "",
(flow->ssh_tls.server_info[0] != '\0') ? flow->ssh_tls.server_info : "");
fprintf(csv_fp, "%s,%s,%s,%s,%s,",
(flow->ssh_tls.ssl_version != 0) ? ndpi_ssl_version2str(flow->ssh_tls.ssl_version, &known_tls) : "0",
(flow->ssh_tls.ja3_client[0] != '\0') ? flow->ssh_tls.ja3_client : "",
(flow->ssh_tls.ja3_client[0] != '\0') ? is_unsafe_cipher(flow->ssh_tls.client_unsafe_cipher) : "0",
(flow->ssh_tls.ja3_server[0] != '\0') ? flow->ssh_tls.ja3_server : "",
(flow->ssh_tls.ja3_server[0] != '\0') ? is_unsafe_cipher(flow->ssh_tls.server_unsafe_cipher) : "0");
fprintf(csv_fp, "%s,%s,",
flow->ssh_tls.tls_alpn ? flow->ssh_tls.tls_alpn : "",
flow->ssh_tls.tls_supported_versions ? flow->ssh_tls.tls_supported_versions : ""
);
fprintf(csv_fp, "%s,%s,",
flow->ssh_tls.tls_issuerDN ? flow->ssh_tls.tls_issuerDN : "",
flow->ssh_tls.tls_subjectDN ? flow->ssh_tls.tls_subjectDN : ""
);
fprintf(csv_fp, "%s,%s",
(flow->ssh_tls.client_hassh[0] != '\0') ? flow->ssh_tls.client_hassh : "",
(flow->ssh_tls.server_hassh[0] != '\0') ? flow->ssh_tls.server_hassh : ""
);
fprintf(csv_fp, ",%s", flow->info);
}
if((verbose != 1) && (verbose != 2)) {
if(csv_fp && enable_joy_stats) {
flowGetBDMeanandVariance(flow);
}
if(csv_fp)
fprintf(csv_fp, "\n");
return;
}
if(csv_fp || (verbose > 1)) {
#if 1
fprintf(out, "\t%u", id);
#else
fprintf(out, "\t%u(%u)", id, flow->flow_id);
#endif
fprintf(out, "\t%s ", ipProto2Name(flow->protocol));
fprintf(out, "%s%s%s:%u %s %s%s%s:%u ",
(flow->ip_version == 6) ? "[" : "",
flow->src_name, (flow->ip_version == 6) ? "]" : "", ntohs(flow->src_port),
flow->bidirectional ? "<->" : "->",
(flow->ip_version == 6) ? "[" : "",
flow->dst_name, (flow->ip_version == 6) ? "]" : "", ntohs(flow->dst_port)
);
if(flow->vlan_id > 0) fprintf(out, "[VLAN: %u]", flow->vlan_id);
if(enable_payload_analyzer) fprintf(out, "[flowId: %u]", flow->flow_id);
}
if(enable_joy_stats) {
/* Print entropy values for monitored flows. */
flowGetBDMeanandVariance(flow);
fflush(out);
fprintf(out, "[score: %.4f]", flow->entropy.score);
}
if(csv_fp) fprintf(csv_fp, "\n");
fprintf(out, "[proto: ");
if(flow->tunnel_type != ndpi_no_tunnel)
fprintf(out, "%s:", ndpi_tunnel2str(flow->tunnel_type));
fprintf(out, "%s/%s]",
ndpi_protocol2id(ndpi_thread_info[thread_id].workflow->ndpi_struct,
flow->detected_protocol, buf, sizeof(buf)),
ndpi_protocol2name(ndpi_thread_info[thread_id].workflow->ndpi_struct,
flow->detected_protocol, buf1, sizeof(buf1)));
if(flow->detected_protocol.category != 0)
fprintf(out, "[cat: %s/%u]",
ndpi_category_get_name(ndpi_thread_info[thread_id].workflow->ndpi_struct,
flow->detected_protocol.category),
(unsigned int)flow->detected_protocol.category);
fprintf(out, "[%u pkts/%llu bytes ", flow->src2dst_packets, (long long unsigned int) flow->src2dst_bytes);
fprintf(out, "%s %u pkts/%llu bytes]",
(flow->dst2src_packets > 0) ? "<->" : "->",
flow->dst2src_packets, (long long unsigned int) flow->dst2src_bytes);
fprintf(out, "[Goodput ratio: %.0f/%.0f]",
100.0*((float)flow->src2dst_goodput_bytes / (float)(flow->src2dst_bytes+1)),
100.0*((float)flow->dst2src_goodput_bytes / (float)(flow->dst2src_bytes+1)));
if(flow->last_seen > flow->first_seen)
fprintf(out, "[%.2f sec]", ((float)(flow->last_seen - flow->first_seen))/(float)1000);
else
fprintf(out, "[< 1 sec]");
if(flow->telnet.username[0] != '\0') fprintf(out, "[Username: %s]", flow->telnet.username);
if(flow->telnet.password[0] != '\0') fprintf(out, "[Password: %s]", flow->telnet.password);
if(flow->host_server_name[0] != '\0') fprintf(out, "[Host: %s]", flow->host_server_name);
if(flow->info[0] != '\0') fprintf(out, "[%s]", flow->info);
if(flow->flow_extra_info[0] != '\0') fprintf(out, "[%s]", flow->flow_extra_info);
if((flow->src2dst_packets+flow->dst2src_packets) > 5) {
if(flow->iat_c_to_s && flow->iat_s_to_c) {
float data_ratio = ndpi_data_ratio(flow->src2dst_bytes, flow->dst2src_bytes);
fprintf(out, "[bytes ratio: %.3f (%s)]", data_ratio, ndpi_data_ratio2str(data_ratio));
/* IAT (Inter Arrival Time) */
fprintf(out, "[IAT c2s/s2c min/avg/max/stddev: %u/%u %.0f/%.0f %u/%u %.0f/%.0f]",
ndpi_data_min(flow->iat_c_to_s), ndpi_data_min(flow->iat_s_to_c),
(float)ndpi_data_average(flow->iat_c_to_s), (float)ndpi_data_average(flow->iat_s_to_c),
ndpi_data_max(flow->iat_c_to_s), ndpi_data_max(flow->iat_s_to_c),
(float)ndpi_data_stddev(flow->iat_c_to_s), (float)ndpi_data_stddev(flow->iat_s_to_c));
/* Packet Length */
fprintf(out, "[Pkt Len c2s/s2c min/avg/max/stddev: %u/%u %.0f/%.0f %u/%u %.0f/%.0f]",
ndpi_data_min(flow->pktlen_c_to_s), ndpi_data_min(flow->pktlen_s_to_c),
ndpi_data_average(flow->pktlen_c_to_s), ndpi_data_average(flow->pktlen_s_to_c),
ndpi_data_max(flow->pktlen_c_to_s), ndpi_data_max(flow->pktlen_s_to_c),
ndpi_data_stddev(flow->pktlen_c_to_s), ndpi_data_stddev(flow->pktlen_s_to_c));
}
}
if(flow->http.url[0] != '\0') {
ndpi_risk_enum risk = ndpi_validate_url(flow->http.url);
if(risk != NDPI_NO_RISK)
NDPI_SET_BIT(flow->risk, risk);
fprintf(out, "[URL: %s[StatusCode: %u]",
flow->http.url, flow->http.response_status_code);
if(flow->http.content_type[0] != '\0')
fprintf(out, "[ContentType: %s]", flow->http.content_type);
if(flow->http.user_agent[0] != '\0')
fprintf(out, "[UserAgent: %s]", flow->http.user_agent);
}
if(flow->risk) {
u_int i;
fprintf(out, "[Risk: ");
for(i=0; i<NDPI_MAX_RISK; i++)
if(NDPI_ISSET_BIT(flow->risk, i))
fprintf(out, "** %s **", ndpi_risk2str(i));
fprintf(out, "]");
}
if(flow->ssh_tls.ssl_version != 0) fprintf(out, "[%s]", ndpi_ssl_version2str(flow->ssh_tls.ssl_version, &known_tls));
if(flow->ssh_tls.client_requested_server_name[0] != '\0') fprintf(out, "[Client: %s]", flow->ssh_tls.client_requested_server_name);
if(flow->ssh_tls.client_hassh[0] != '\0') fprintf(out, "[HASSH-C: %s]", flow->ssh_tls.client_hassh);
if(flow->ssh_tls.ja3_client[0] != '\0') fprintf(out, "[JA3C: %s%s]", flow->ssh_tls.ja3_client,
print_cipher(flow->ssh_tls.client_unsafe_cipher));
if(flow->ssh_tls.server_info[0] != '\0') fprintf(out, "[Server: %s]", flow->ssh_tls.server_info);
if(flow->ssh_tls.server_names) fprintf(out, "[ServerNames: %s]", flow->ssh_tls.server_names);
if(flow->ssh_tls.server_hassh[0] != '\0') fprintf(out, "[HASSH-S: %s]", flow->ssh_tls.server_hassh);
if(flow->ssh_tls.ja3_server[0] != '\0') fprintf(out, "[JA3S: %s%s]", flow->ssh_tls.ja3_server,
print_cipher(flow->ssh_tls.server_unsafe_cipher));
if(flow->ssh_tls.tls_issuerDN) fprintf(out, "[Issuer: %s]", flow->ssh_tls.tls_issuerDN);
if(flow->ssh_tls.tls_subjectDN) fprintf(out, "[Subject: %s]", flow->ssh_tls.tls_subjectDN);
if((flow->detected_protocol.master_protocol == NDPI_PROTOCOL_TLS)
|| (flow->detected_protocol.app_protocol == NDPI_PROTOCOL_TLS)) {
if(flow->ssh_tls.sha1_cert_fingerprint_set) {
fprintf(out, "[Certificate SHA-1: ");
for(i=0; i<20; i++)
fprintf(out, "%s%02X", (i > 0) ? ":" : "",
flow->ssh_tls.sha1_cert_fingerprint[i] & 0xFF);
fprintf(out, "]");
}
}
if(flow->ssh_tls.notBefore && flow->ssh_tls.notAfter) {
char notBefore[32], notAfter[32];
struct tm a, b;
struct tm *before = gmtime_r(&flow->ssh_tls.notBefore, &a);
struct tm *after = gmtime_r(&flow->ssh_tls.notAfter, &b);
strftime(notBefore, sizeof(notBefore), "%F %T", before);
strftime(notAfter, sizeof(notAfter), "%F %T", after);
fprintf(out, "[Validity: %s - %s]", notBefore, notAfter);
}
if(flow->ssh_tls.server_cipher != '\0') fprintf(out, "[Cipher: %s]", ndpi_cipher2str(flow->ssh_tls.server_cipher));
if(flow->bittorent_hash[0] != '\0') fprintf(out, "[BT Hash: %s]", flow->bittorent_hash);
if(flow->dhcp_fingerprint[0] != '\0') fprintf(out, "[DHCP Fingerprint: %s]", flow->dhcp_fingerprint);
if(flow->has_human_readeable_strings) fprintf(out, "[PLAIN TEXT (%s)]", flow->human_readeable_string_buffer);
fprintf(out, "\n");
}
/* ********************************** */
/**
* @brief Unknown Proto Walker
*/
static void node_print_unknown_proto_walker(const void *node,
ndpi_VISIT which, int depth, void *user_data) {
struct ndpi_flow_info *flow = *(struct ndpi_flow_info**)node;
u_int16_t thread_id = *((u_int16_t*)user_data);
if((flow->detected_protocol.master_protocol != NDPI_PROTOCOL_UNKNOWN)
|| (flow->detected_protocol.app_protocol != NDPI_PROTOCOL_UNKNOWN))
return;
if((which == ndpi_preorder) || (which == ndpi_leaf)) {
/* Avoid walking the same node multiple times */
all_flows[num_flows].thread_id = thread_id, all_flows[num_flows].flow = flow;
num_flows++;
}
}
/* ********************************** */
/**
* @brief Known Proto Walker
*/
static void node_print_known_proto_walker(const void *node,
ndpi_VISIT which, int depth, void *user_data) {
struct ndpi_flow_info *flow = *(struct ndpi_flow_info**)node;
u_int16_t thread_id = *((u_int16_t*)user_data);
if((flow->detected_protocol.master_protocol == NDPI_PROTOCOL_UNKNOWN)
&& (flow->detected_protocol.app_protocol == NDPI_PROTOCOL_UNKNOWN))
return;
if((which == ndpi_preorder) || (which == ndpi_leaf)) {
/* Avoid walking the same node multiple times */
all_flows[num_flows].thread_id = thread_id, all_flows[num_flows].flow = flow;
num_flows++;
}
}
/* ********************************** */
/**
* @brief Proto Guess Walker
*/
static void node_proto_guess_walker(const void *node, ndpi_VISIT which, int depth, void *user_data) {
struct ndpi_flow_info *flow = *(struct ndpi_flow_info **) node;
u_int16_t thread_id = *((u_int16_t *) user_data), proto;
if((which == ndpi_preorder) || (which == ndpi_leaf)) { /* Avoid walking the same node multiple times */
if((!flow->detection_completed) && flow->ndpi_flow) {
u_int8_t proto_guessed;
flow->detected_protocol = ndpi_detection_giveup(ndpi_thread_info[0].workflow->ndpi_struct,
flow->ndpi_flow, enable_protocol_guess, &proto_guessed);
}
process_ndpi_collected_info(ndpi_thread_info[thread_id].workflow, flow);
proto = flow->detected_protocol.app_protocol ? flow->detected_protocol.app_protocol : flow->detected_protocol.master_protocol;
ndpi_thread_info[thread_id].workflow->stats.protocol_counter[proto] += flow->src2dst_packets + flow->dst2src_packets;
ndpi_thread_info[thread_id].workflow->stats.protocol_counter_bytes[proto] += flow->src2dst_bytes + flow->dst2src_bytes;
ndpi_thread_info[thread_id].workflow->stats.protocol_flows[proto]++;
}
}
/* *********************************************** */
void updateScanners(struct single_flow_info **scanners, u_int32_t saddr,
u_int8_t version, u_int32_t dport) {
struct single_flow_info *f;
struct port_flow_info *p;
HASH_FIND_INT(*scanners, (int *)&saddr, f);
if(f == NULL) {
f = (struct single_flow_info*)malloc(sizeof(struct single_flow_info));
if(!f) return;
f->saddr = saddr;
f->version = version;
f->tot_flows = 1;
f->ports = NULL;
p = (struct port_flow_info*)malloc(sizeof(struct port_flow_info));
if(!p) {
free(f);
return;
} else
p->port = dport, p->num_flows = 1;
HASH_ADD_INT(f->ports, port, p);
HASH_ADD_INT(*scanners, saddr, f);
} else{
struct port_flow_info *pp;
f->tot_flows++;
HASH_FIND_INT(f->ports, (int *)&dport, pp);
if(pp == NULL) {
pp = (struct port_flow_info*)malloc(sizeof(struct port_flow_info));
if(!pp) return;
pp->port = dport, pp->num_flows = 1;
HASH_ADD_INT(f->ports, port, pp);
} else
pp->num_flows++;
}
}
/* *********************************************** */
int updateIpTree(u_int32_t key, u_int8_t version,
addr_node **vrootp, const char *proto) {
addr_node *q;
addr_node **rootp = vrootp;
if(rootp == (addr_node **)0)
return 0;
while(*rootp != (addr_node *)0) {
/* Knuth's T1: */
if((version == (*rootp)->version) && (key == (*rootp)->addr)) {
/* T2: */
return ++((*rootp)->count);
}
rootp = (key < (*rootp)->addr) ?
&(*rootp)->left : /* T3: follow left branch */
&(*rootp)->right; /* T4: follow right branch */
}
q = (addr_node *) malloc(sizeof(addr_node)); /* T5: key not found */
if(q != (addr_node *)0) { /* make new node */
*rootp = q; /* link new node to old */
q->addr = key;
q->version = version;
strncpy(q->proto, proto, sizeof(q->proto));
q->count = UPDATED_TREE;
q->left = q->right = (addr_node *)0;
return q->count;
}
return(0);
}
/* *********************************************** */
void freeIpTree(addr_node *root) {
if(root == NULL)
return;
freeIpTree(root->left);
freeIpTree(root->right);
free(root);
}
/* *********************************************** */
void updateTopIpAddress(u_int32_t addr, u_int8_t version, const char *proto,
int count, struct info_pair top[], int size) {
struct info_pair pair;
int min = count;
int update = 0;
int min_i = 0;
int i;
if(count == 0) return;
pair.addr = addr;
pair.version = version;
pair.count = count;
strncpy(pair.proto, proto, sizeof(pair.proto));
for(i=0; i<size; i++) {
/* if the same ip with a bigger
count just update it */
if(top[i].addr == addr) {
top[i].count = count;
return;
}
/* if array is not full yet
add it to the first empty place */
if(top[i].count == 0) {
top[i] = pair;
return;
}
}
/* if bigger than the smallest one, replace it */
for(i=0; i<size; i++) {
if(top[i].count < count && top[i].count < min) {
min = top[i].count;
min_i = i;
update = 1;
}
}
if(update)
top[min_i] = pair;
}
/* *********************************************** */
static void updatePortStats(struct port_stats **stats, u_int32_t port,
u_int32_t addr, u_int8_t version,
u_int32_t num_pkts, u_int32_t num_bytes,
const char *proto) {
struct port_stats *s = NULL;
int count = 0;
HASH_FIND_INT(*stats, &port, s);
if(s == NULL) {
s = (struct port_stats*)calloc(1, sizeof(struct port_stats));
if(!s) return;
s->port = port, s->num_pkts = num_pkts, s->num_bytes = num_bytes;
s->num_addr = 1, s->cumulative_addr = 1; s->num_flows = 1;
updateTopIpAddress(addr, version, proto, 1, s->top_ip_addrs, MAX_NUM_IP_ADDRESS);
s->addr_tree = (addr_node *) malloc(sizeof(addr_node));
if(!s->addr_tree) {
free(s);
return;
}
s->addr_tree->addr = addr;
s->addr_tree->version = version;
strncpy(s->addr_tree->proto, proto, sizeof(s->addr_tree->proto));
s->addr_tree->count = 1;
s->addr_tree->left = NULL;
s->addr_tree->right = NULL;
HASH_ADD_INT(*stats, port, s);
}
else{
count = updateIpTree(addr, version, &(*s).addr_tree, proto);
if(count == UPDATED_TREE) s->num_addr++;
if(count) {
s->cumulative_addr++;
updateTopIpAddress(addr, version, proto, count, s->top_ip_addrs, MAX_NUM_IP_ADDRESS);
}
s->num_pkts += num_pkts, s->num_bytes += num_bytes, s->num_flows++;
}
}
/* *********************************************** */
/* @brief heuristic choice for receiver stats */
static int acceptable(u_int32_t num_pkts){
return num_pkts > 5;
}
/* *********************************************** */
#if 0
static int receivers_sort(void *_a, void *_b) {
struct receiver *a = (struct receiver *)_a;
struct receiver *b = (struct receiver *)_b;
return(b->num_pkts - a->num_pkts);
}
#endif
/* *********************************************** */
static int receivers_sort_asc(void *_a, void *_b) {
struct receiver *a = (struct receiver *)_a;
struct receiver *b = (struct receiver *)_b;
return(a->num_pkts - b->num_pkts);
}
/* ***************************************************** */
/*@brief removes first (size - max) elements from hash table.
* hash table is ordered in ascending order.
*/
static struct receiver *cutBackTo(struct receiver **rcvrs, u_int32_t size, u_int32_t max) {
struct receiver *r, *tmp;
int i=0;
int count;
if(size < max) //return the original table
return *rcvrs;
count = size - max;
HASH_ITER(hh, *rcvrs, r, tmp) {
if(i++ == count)
return r;
HASH_DEL(*rcvrs, r);
free(r);
}
return(NULL);
}
/* *********************************************** */
/*@brief merge first table to the second table.
* if element already in the second table
* then updates its value
* else adds it to the second table
*/
static void mergeTables(struct receiver **primary, struct receiver **secondary) {
struct receiver *r, *s, *tmp;
HASH_ITER(hh, *primary, r, tmp) {
HASH_FIND_INT(*secondary, (int *)&(r->addr), s);
if(s == NULL){
s = (struct receiver *)malloc(sizeof(struct receiver));
if(!s) return;
s->addr = r->addr;
s->version = r->version;
s->num_pkts = r->num_pkts;
HASH_ADD_INT(*secondary, addr, s);
}
else
s->num_pkts += r->num_pkts;
HASH_DEL(*primary, r);
free(r);
}
}
/* *********************************************** */
static void deleteReceivers(struct receiver *rcvrs) {
struct receiver *current, *tmp;
HASH_ITER(hh, rcvrs, current, tmp) {
HASH_DEL(rcvrs, current);
free(current);
}
}
/* *********************************************** */
/* implementation of: https://jeroen.massar.ch/presentations/files/FloCon2010-TopK.pdf
*
* if(table1.size < max1 || acceptable){
* create new element and add to the table1
* if(table1.size > max2) {
* cut table1 back to max1
* merge table 1 to table2
* if(table2.size > max1)
* cut table2 back to max1
* }
* }
* else
* update table1
*/
static void updateReceivers(struct receiver **rcvrs, u_int32_t dst_addr,
u_int8_t version, u_int32_t num_pkts,
struct receiver **topRcvrs) {
struct receiver *r;
u_int32_t size;
int a;
HASH_FIND_INT(*rcvrs, (int *)&dst_addr, r);
if(r == NULL) {
if(((size = HASH_COUNT(*rcvrs)) < MAX_TABLE_SIZE_1)
|| ((a = acceptable(num_pkts)) != 0)){
r = (struct receiver *)malloc(sizeof(struct receiver));
if(!r) return;
r->addr = dst_addr;
r->version = version;
r->num_pkts = num_pkts;
HASH_ADD_INT(*rcvrs, addr, r);
if((size = HASH_COUNT(*rcvrs)) > MAX_TABLE_SIZE_2){
HASH_SORT(*rcvrs, receivers_sort_asc);
*rcvrs = cutBackTo(rcvrs, size, MAX_TABLE_SIZE_1);
mergeTables(rcvrs, topRcvrs);
if((size = HASH_COUNT(*topRcvrs)) > MAX_TABLE_SIZE_1){
HASH_SORT(*topRcvrs, receivers_sort_asc);
*topRcvrs = cutBackTo(topRcvrs, size, MAX_TABLE_SIZE_1);
}
*rcvrs = NULL;
}
}
}
else
r->num_pkts += num_pkts;
}
/* *********************************************** */
static void deleteScanners(struct single_flow_info *scanners) {
struct single_flow_info *s, *tmp;
struct port_flow_info *p, *tmp2;
HASH_ITER(hh, scanners, s, tmp) {
HASH_ITER(hh, s->ports, p, tmp2) {
if(s->ports) HASH_DEL(s->ports, p);
free(p);
}
HASH_DEL(scanners, s);
free(s);
}
}
/* *********************************************** */
static void deletePortsStats(struct port_stats *stats) {
struct port_stats *current_port, *tmp;
HASH_ITER(hh, stats, current_port, tmp) {
HASH_DEL(stats, current_port);
freeIpTree(current_port->addr_tree);
free(current_port);
}
}
/* *********************************************** */
/**
* @brief Ports stats
*/
static void port_stats_walker(const void *node, ndpi_VISIT which, int depth, void *user_data) {
if((which == ndpi_preorder) || (which == ndpi_leaf)) { /* Avoid walking the same node multiple times */
struct ndpi_flow_info *flow = *(struct ndpi_flow_info **) node;
u_int16_t thread_id = *(int *)user_data;
u_int16_t sport, dport;
char proto[16];
int r;
sport = ntohs(flow->src_port), dport = ntohs(flow->dst_port);
/* get app level protocol */
if(flow->detected_protocol.master_protocol)
ndpi_protocol2name(ndpi_thread_info[thread_id].workflow->ndpi_struct,
flow->detected_protocol, proto, sizeof(proto));
else
strncpy(proto, ndpi_get_proto_name(ndpi_thread_info[thread_id].workflow->ndpi_struct,
flow->detected_protocol.app_protocol),sizeof(proto));
if(((r = strcmp(ipProto2Name(flow->protocol), "TCP")) == 0)
&& (flow->src2dst_packets == 1) && (flow->dst2src_packets == 0)) {
updateScanners(&scannerHosts, flow->src_ip, flow->ip_version, dport);
}
updateReceivers(&receivers, flow->dst_ip, flow->ip_version,
flow->src2dst_packets, &topReceivers);
updatePortStats(&srcStats, sport, flow->src_ip, flow->ip_version,
flow->src2dst_packets, flow->src2dst_bytes, proto);
updatePortStats(&dstStats, dport, flow->dst_ip, flow->ip_version,
flow->dst2src_packets, flow->dst2src_bytes, proto);
}
}
/* *********************************************** */
/**
* @brief Idle Scan Walker
*/
static void node_idle_scan_walker(const void *node, ndpi_VISIT which, int depth, void *user_data) {
struct ndpi_flow_info *flow = *(struct ndpi_flow_info **) node;
u_int16_t thread_id = *((u_int16_t *) user_data);
if(ndpi_thread_info[thread_id].num_idle_flows == IDLE_SCAN_BUDGET) /* TODO optimise with a budget-based walk */
return;
if((which == ndpi_preorder) || (which == ndpi_leaf)) { /* Avoid walking the same node multiple times */
if(flow->last_seen + MAX_IDLE_TIME < ndpi_thread_info[thread_id].workflow->last_time) {
/* update stats */
node_proto_guess_walker(node, which, depth, user_data);
if((flow->detected_protocol.app_protocol == NDPI_PROTOCOL_UNKNOWN) && !undetected_flows_deleted)
undetected_flows_deleted = 1;
ndpi_free_flow_info_half(flow);
ndpi_free_flow_data_analysis(flow);
ndpi_free_flow_tls_data(flow);
ndpi_thread_info[thread_id].workflow->stats.ndpi_flow_count--;
/* adding to a queue (we can't delete it from the tree inline ) */
ndpi_thread_info[thread_id].idle_flows[ndpi_thread_info[thread_id].num_idle_flows++] = flow;
}
}
}
/* *********************************************** */
/**
* @brief On Protocol Discover - demo callback
*/
static void on_protocol_discovered(struct ndpi_workflow * workflow,
struct ndpi_flow_info * flow,
void * udata) {
;
}
/* *********************************************** */
#if 0
/**
* @brief Print debug
*/
static void debug_printf(u_int32_t protocol, void *id_struct,
ndpi_log_level_t log_level,
const char *format, ...) {
va_list va_ap;
struct tm result;
if(log_level <= nDPI_LogLevel) {
char buf[8192], out_buf[8192];
char theDate[32];
const char *extra_msg = "";
time_t theTime = time(NULL);
va_start (va_ap, format);
if(log_level == NDPI_LOG_ERROR)
extra_msg = "ERROR: ";
else if(log_level == NDPI_LOG_TRACE)
extra_msg = "TRACE: ";
else
extra_msg = "DEBUG: ";
memset(buf, 0, sizeof(buf));
strftime(theDate, 32, "%d/%b/%Y %H:%M:%S", localtime_r(&theTime,&result));
vsnprintf(buf, sizeof(buf)-1, format, va_ap);
snprintf(out_buf, sizeof(out_buf), "%s %s%s", theDate, extra_msg, buf);
printf("%s", out_buf);
fflush(stdout);
}
va_end(va_ap);
}
#endif
/* *********************************************** */
/**
* @brief Setup for detection begin
*/
static void setupDetection(u_int16_t thread_id, pcap_t * pcap_handle) {
NDPI_PROTOCOL_BITMASK all;
struct ndpi_workflow_prefs prefs;
memset(&prefs, 0, sizeof(prefs));
prefs.decode_tunnels = decode_tunnels;
prefs.num_roots = NUM_ROOTS;
prefs.max_ndpi_flows = MAX_NDPI_FLOWS;
prefs.quiet_mode = quiet_mode;
memset(&ndpi_thread_info[thread_id], 0, sizeof(ndpi_thread_info[thread_id]));
ndpi_thread_info[thread_id].workflow = ndpi_workflow_init(&prefs, pcap_handle);
/* Preferences */
ndpi_workflow_set_flow_detected_callback(ndpi_thread_info[thread_id].workflow,
on_protocol_discovered,
(void *)(uintptr_t)thread_id);
// enable all protocols
NDPI_BITMASK_SET_ALL(all);
ndpi_set_protocol_detection_bitmask2(ndpi_thread_info[thread_id].workflow->ndpi_struct, &all);
// clear memory for results
memset(ndpi_thread_info[thread_id].workflow->stats.protocol_counter, 0,
sizeof(ndpi_thread_info[thread_id].workflow->stats.protocol_counter));
memset(ndpi_thread_info[thread_id].workflow->stats.protocol_counter_bytes, 0,
sizeof(ndpi_thread_info[thread_id].workflow->stats.protocol_counter_bytes));
memset(ndpi_thread_info[thread_id].workflow->stats.protocol_flows, 0,
sizeof(ndpi_thread_info[thread_id].workflow->stats.protocol_flows));
if(_protoFilePath != NULL)
ndpi_load_protocols_file(ndpi_thread_info[thread_id].workflow->ndpi_struct, _protoFilePath);
if(_customCategoryFilePath)
ndpi_load_categories_file(ndpi_thread_info[thread_id].workflow->ndpi_struct, _customCategoryFilePath);
ndpi_finalize_initalization(ndpi_thread_info[thread_id].workflow->ndpi_struct);
}
/* *********************************************** */
/**
* @brief End of detection and free flow
*/
static void terminateDetection(u_int16_t thread_id) {
ndpi_workflow_free(ndpi_thread_info[thread_id].workflow);
}
/* *********************************************** */
/**
* @brief Traffic stats format
*/
char* formatTraffic(float numBits, int bits, char *buf) {
char unit;
if(bits)
unit = 'b';
else
unit = 'B';
if(numBits < 1024) {
snprintf(buf, 32, "%lu %c", (unsigned long)numBits, unit);
} else if(numBits < (1024*1024)) {
snprintf(buf, 32, "%.2f K%c", (float)(numBits)/1024, unit);
} else {
float tmpMBits = ((float)numBits)/(1024*1024);
if(tmpMBits < 1024) {
snprintf(buf, 32, "%.2f M%c", tmpMBits, unit);
} else {
tmpMBits /= 1024;
if(tmpMBits < 1024) {
snprintf(buf, 32, "%.2f G%c", tmpMBits, unit);
} else {
snprintf(buf, 32, "%.2f T%c", (float)(tmpMBits)/1024, unit);
}
}
}
return(buf);
}
/* *********************************************** */
/**
* @brief Packets stats format
*/
char* formatPackets(float numPkts, char *buf) {
if(numPkts < 1000) {
snprintf(buf, 32, "%.2f", numPkts);
} else if(numPkts < (1000*1000)) {
snprintf(buf, 32, "%.2f K", numPkts/1000);
} else {
numPkts /= (1000*1000);
snprintf(buf, 32, "%.2f M", numPkts);
}
return(buf);
}
/* *********************************************** */
/**
* @brief Bytes stats format
*/
char* formatBytes(u_int32_t howMuch, char *buf, u_int buf_len) {
char unit = 'B';
if(howMuch < 1024) {
snprintf(buf, buf_len, "%lu %c", (unsigned long)howMuch, unit);
} else if(howMuch < (1024*1024)) {
snprintf(buf, buf_len, "%.2f K%c", (float)(howMuch)/1024, unit);
} else {
float tmpGB = ((float)howMuch)/(1024*1024);
if(tmpGB < 1024) {
snprintf(buf, buf_len, "%.2f M%c", tmpGB, unit);
} else {
tmpGB /= 1024;
snprintf(buf, buf_len, "%.2f G%c", tmpGB, unit);
}
}
return(buf);
}
/* *********************************************** */
static int port_stats_sort(void *_a, void *_b) {
struct port_stats *a = (struct port_stats*)_a;
struct port_stats *b = (struct port_stats*)_b;
if(b->num_pkts == 0 && a->num_pkts == 0)
return(b->num_flows - a->num_flows);
return(b->num_pkts - a->num_pkts);
}
/* *********************************************** */
static int info_pair_cmp (const void *_a, const void *_b)
{
struct info_pair *a = (struct info_pair *)_a;
struct info_pair *b = (struct info_pair *)_b;
return b->count - a->count;
}
/* *********************************************** */
void printPortStats(struct port_stats *stats) {
struct port_stats *s, *tmp;
char addr_name[48];
int i = 0, j = 0;
HASH_ITER(hh, stats, s, tmp) {
i++;
printf("\t%2d\tPort %5u\t[%u IP address(es)/%u flows/%u pkts/%u bytes]\n\t\tTop IP Stats:\n",
i, s->port, s->num_addr, s->num_flows, s->num_pkts, s->num_bytes);
qsort(&s->top_ip_addrs[0], MAX_NUM_IP_ADDRESS, sizeof(struct info_pair), info_pair_cmp);
for(j=0; j<MAX_NUM_IP_ADDRESS; j++) {
if(s->top_ip_addrs[j].count != 0) {
if(s->top_ip_addrs[j].version == IPVERSION) {
inet_ntop(AF_INET, &(s->top_ip_addrs[j].addr), addr_name, sizeof(addr_name));
} else {
inet_ntop(AF_INET6, &(s->top_ip_addrs[j].addr), addr_name, sizeof(addr_name));
}
printf("\t\t%-36s ~ %.2f%%\n", addr_name,
((s->top_ip_addrs[j].count) * 100.0) / s->cumulative_addr);
}
}
printf("\n");
if(i >= 10) break;
}
}
/* *********************************************** */
static void printFlowsStats() {
int thread_id;
u_int32_t total_flows = 0;
FILE *out = results_file ? results_file : stdout;
if(enable_payload_analyzer)
ndpi_report_payload_stats();
for(thread_id = 0; thread_id < num_threads; thread_id++)
total_flows += ndpi_thread_info[thread_id].workflow->num_allocated_flows;
if((all_flows = (struct flow_info*)malloc(sizeof(struct flow_info)*total_flows)) == NULL) {
fprintf(out, "Fatal error: not enough memory\n");
exit(-1);
}
if(verbose) {
ndpi_host_ja3_fingerprints *ja3ByHostsHashT = NULL; // outer hash table
ndpi_ja3_fingerprints_host *hostByJA3C_ht = NULL; // for client
ndpi_ja3_fingerprints_host *hostByJA3S_ht = NULL; // for server
int i;
ndpi_host_ja3_fingerprints *ja3ByHost_element = NULL;
ndpi_ja3_info *info_of_element = NULL;
ndpi_host_ja3_fingerprints *tmp = NULL;
ndpi_ja3_info *tmp2 = NULL;
unsigned int num_ja3_client;
unsigned int num_ja3_server;
fprintf(out, "\n");
num_flows = 0;
for(thread_id = 0; thread_id < num_threads; thread_id++) {
for(i=0; i<NUM_ROOTS; i++)
ndpi_twalk(ndpi_thread_info[thread_id].workflow->ndpi_flows_root[i],
node_print_known_proto_walker, &thread_id);
}
if((verbose == 2) || (verbose == 3)) {
for(i = 0; i < num_flows; i++) {
ndpi_host_ja3_fingerprints *ja3ByHostFound = NULL;
ndpi_ja3_fingerprints_host *hostByJA3Found = NULL;
//check if this is a ssh-ssl flow
if(all_flows[i].flow->ssh_tls.ja3_client[0] != '\0'){
//looking if the host is already in the hash table
HASH_FIND_INT(ja3ByHostsHashT, &(all_flows[i].flow->src_ip), ja3ByHostFound);
//host ip -> ja3
if(ja3ByHostFound == NULL){
//adding the new host
ndpi_host_ja3_fingerprints *newHost = malloc(sizeof(ndpi_host_ja3_fingerprints));
newHost->host_client_info_hasht = NULL;
newHost->host_server_info_hasht = NULL;
newHost->ip_string = all_flows[i].flow->src_name;
newHost->ip = all_flows[i].flow->src_ip;
newHost->dns_name = all_flows[i].flow->ssh_tls.client_requested_server_name;
ndpi_ja3_info *newJA3 = malloc(sizeof(ndpi_ja3_info));
newJA3->ja3 = all_flows[i].flow->ssh_tls.ja3_client;
newJA3->unsafe_cipher = all_flows[i].flow->ssh_tls.client_unsafe_cipher;
//adding the new ja3 fingerprint
HASH_ADD_KEYPTR(hh, newHost->host_client_info_hasht,
newJA3->ja3, strlen(newJA3->ja3), newJA3);
//adding the new host
HASH_ADD_INT(ja3ByHostsHashT, ip, newHost);
} else {
//host already in the hash table
ndpi_ja3_info *infoFound = NULL;
HASH_FIND_STR(ja3ByHostFound->host_client_info_hasht,
all_flows[i].flow->ssh_tls.ja3_client, infoFound);
if(infoFound == NULL){
ndpi_ja3_info *newJA3 = malloc(sizeof(ndpi_ja3_info));
newJA3->ja3 = all_flows[i].flow->ssh_tls.ja3_client;
newJA3->unsafe_cipher = all_flows[i].flow->ssh_tls.client_unsafe_cipher;
HASH_ADD_KEYPTR(hh, ja3ByHostFound->host_client_info_hasht,
newJA3->ja3, strlen(newJA3->ja3), newJA3);
}
}
//ja3 -> host ip
HASH_FIND_STR(hostByJA3C_ht, all_flows[i].flow->ssh_tls.ja3_client, hostByJA3Found);
if(hostByJA3Found == NULL){
ndpi_ip_dns *newHost = malloc(sizeof(ndpi_ip_dns));
newHost->ip = all_flows[i].flow->src_ip;
newHost->ip_string = all_flows[i].flow->src_name;
newHost->dns_name = all_flows[i].flow->ssh_tls.client_requested_server_name;;
ndpi_ja3_fingerprints_host *newElement = malloc(sizeof(ndpi_ja3_fingerprints_host));
newElement->ja3 = all_flows[i].flow->ssh_tls.ja3_client;
newElement->unsafe_cipher = all_flows[i].flow->ssh_tls.client_unsafe_cipher;
newElement->ipToDNS_ht = NULL;
HASH_ADD_INT(newElement->ipToDNS_ht, ip, newHost);
HASH_ADD_KEYPTR(hh, hostByJA3C_ht, newElement->ja3, strlen(newElement->ja3),
newElement);
} else {
ndpi_ip_dns *innerElement = NULL;
HASH_FIND_INT(hostByJA3Found->ipToDNS_ht, &(all_flows[i].flow->src_ip), innerElement);
if(innerElement == NULL){
ndpi_ip_dns *newInnerElement = malloc(sizeof(ndpi_ip_dns));
newInnerElement->ip = all_flows[i].flow->src_ip;
newInnerElement->ip_string = all_flows[i].flow->src_name;
newInnerElement->dns_name = all_flows[i].flow->ssh_tls.client_requested_server_name;
HASH_ADD_INT(hostByJA3Found->ipToDNS_ht, ip, newInnerElement);
}
}
}
if(all_flows[i].flow->ssh_tls.ja3_server[0] != '\0'){
//looking if the host is already in the hash table
HASH_FIND_INT(ja3ByHostsHashT, &(all_flows[i].flow->dst_ip), ja3ByHostFound);
if(ja3ByHostFound == NULL){
//adding the new host in the hash table
ndpi_host_ja3_fingerprints *newHost = malloc(sizeof(ndpi_host_ja3_fingerprints));
newHost->host_client_info_hasht = NULL;
newHost->host_server_info_hasht = NULL;
newHost->ip_string = all_flows[i].flow->dst_name;
newHost->ip = all_flows[i].flow->dst_ip;
newHost->dns_name = all_flows[i].flow->ssh_tls.server_info;
ndpi_ja3_info *newJA3 = malloc(sizeof(ndpi_ja3_info));
newJA3->ja3 = all_flows[i].flow->ssh_tls.ja3_server;
newJA3->unsafe_cipher = all_flows[i].flow->ssh_tls.server_unsafe_cipher;
//adding the new ja3 fingerprint
HASH_ADD_KEYPTR(hh, newHost->host_server_info_hasht, newJA3->ja3,
strlen(newJA3->ja3), newJA3);
//adding the new host
HASH_ADD_INT(ja3ByHostsHashT, ip, newHost);
} else {
//host already in the hashtable
ndpi_ja3_info *infoFound = NULL;
HASH_FIND_STR(ja3ByHostFound->host_server_info_hasht,
all_flows[i].flow->ssh_tls.ja3_server, infoFound);
if(infoFound == NULL){
ndpi_ja3_info *newJA3 = malloc(sizeof(ndpi_ja3_info));
newJA3->ja3 = all_flows[i].flow->ssh_tls.ja3_server;
newJA3->unsafe_cipher = all_flows[i].flow->ssh_tls.server_unsafe_cipher;
HASH_ADD_KEYPTR(hh, ja3ByHostFound->host_server_info_hasht,
newJA3->ja3, strlen(newJA3->ja3), newJA3);
}
}
HASH_FIND_STR(hostByJA3S_ht, all_flows[i].flow->ssh_tls.ja3_server, hostByJA3Found);
if(hostByJA3Found == NULL){
ndpi_ip_dns *newHost = malloc(sizeof(ndpi_ip_dns));
newHost->ip = all_flows[i].flow->dst_ip;
newHost->ip_string = all_flows[i].flow->dst_name;
newHost->dns_name = all_flows[i].flow->ssh_tls.server_info;;
ndpi_ja3_fingerprints_host *newElement = malloc(sizeof(ndpi_ja3_fingerprints_host));
newElement->ja3 = all_flows[i].flow->ssh_tls.ja3_server;
newElement->unsafe_cipher = all_flows[i].flow->ssh_tls.server_unsafe_cipher;
newElement->ipToDNS_ht = NULL;
HASH_ADD_INT(newElement->ipToDNS_ht, ip, newHost);
HASH_ADD_KEYPTR(hh, hostByJA3S_ht, newElement->ja3, strlen(newElement->ja3),
newElement);
} else {
ndpi_ip_dns *innerElement = NULL;
HASH_FIND_INT(hostByJA3Found->ipToDNS_ht, &(all_flows[i].flow->dst_ip), innerElement);
if(innerElement == NULL){
ndpi_ip_dns *newInnerElement = malloc(sizeof(ndpi_ip_dns));
newInnerElement->ip = all_flows[i].flow->dst_ip;
newInnerElement->ip_string = all_flows[i].flow->dst_name;
newInnerElement->dns_name = all_flows[i].flow->ssh_tls.server_info;
HASH_ADD_INT(hostByJA3Found->ipToDNS_ht, ip, newInnerElement);
}
}
}
}
if(ja3ByHostsHashT) {
ndpi_ja3_fingerprints_host *hostByJA3Element = NULL;
ndpi_ja3_fingerprints_host *tmp3 = NULL;
ndpi_ip_dns *innerHashEl = NULL;
ndpi_ip_dns *tmp4 = NULL;
if(verbose == 2) {
/* for each host the number of flow with a ja3 fingerprint is printed */
i = 1;
fprintf(out, "JA3 Host Stats: \n");
fprintf(out, "\t\t IP %-24s \t %-10s \n", "Address", "# JA3C");
for(ja3ByHost_element = ja3ByHostsHashT; ja3ByHost_element != NULL;
ja3ByHost_element = ja3ByHost_element->hh.next) {
num_ja3_client = HASH_COUNT(ja3ByHost_element->host_client_info_hasht);
num_ja3_server = HASH_COUNT(ja3ByHost_element->host_server_info_hasht);
if(num_ja3_client > 0) {
fprintf(out, "\t%d\t %-24s \t %-7u\n",
i,
ja3ByHost_element->ip_string,
num_ja3_client
);
i++;
}
}
} else if(verbose == 3) {
int i = 1;
int againstRepeat;
ndpi_ja3_fingerprints_host *hostByJA3Element = NULL;
ndpi_ja3_fingerprints_host *tmp3 = NULL;
ndpi_ip_dns *innerHashEl = NULL;
ndpi_ip_dns *tmp4 = NULL;
//for each host it is printted the JA3C and JA3S, along the server name (if any)
//and the security status
fprintf(out, "JA3C/JA3S Host Stats: \n");
fprintf(out, "\t%-7s %-24s %-34s %s\n", "", "IP", "JA3C", "JA3S");
//reminder
//ja3ByHostsHashT: hash table <ip, (ja3, ht_client, ht_server)>
//ja3ByHost_element: element of ja3ByHostsHashT
//info_of_element: element of the inner hash table of ja3ByHost_element
HASH_ITER(hh, ja3ByHostsHashT, ja3ByHost_element, tmp) {
num_ja3_client = HASH_COUNT(ja3ByHost_element->host_client_info_hasht);
num_ja3_server = HASH_COUNT(ja3ByHost_element->host_server_info_hasht);
againstRepeat = 0;
if(num_ja3_client > 0) {
HASH_ITER(hh, ja3ByHost_element->host_client_info_hasht, info_of_element, tmp2) {
fprintf(out, "\t%-7d %-24s %s %s\n",
i,
ja3ByHost_element->ip_string,
info_of_element->ja3,
print_cipher(info_of_element->unsafe_cipher)
);
againstRepeat = 1;
i++;
}
}
if(num_ja3_server > 0) {
HASH_ITER(hh, ja3ByHost_element->host_server_info_hasht, info_of_element, tmp2) {
fprintf(out, "\t%-7d %-24s %-34s %s %s %s%s%s\n",
i,
ja3ByHost_element->ip_string,
"",
info_of_element->ja3,
print_cipher(info_of_element->unsafe_cipher),
ja3ByHost_element->dns_name[0] ? "[" : "",
ja3ByHost_element->dns_name,
ja3ByHost_element->dns_name[0] ? "]" : ""
);
i++;
}
}
}
i = 1;
fprintf(out, "\nIP/JA3 Distribution:\n");
fprintf(out, "%-15s %-39s %-26s\n", "", "JA3", "IP");
HASH_ITER(hh, hostByJA3C_ht, hostByJA3Element, tmp3) {
againstRepeat = 0;
HASH_ITER(hh, hostByJA3Element->ipToDNS_ht, innerHashEl, tmp4) {
if(againstRepeat == 0) {
fprintf(out, "\t%-7d JA3C %s",
i,
hostByJA3Element->ja3
);
fprintf(out, " %-15s %s\n",
innerHashEl->ip_string,
print_cipher(hostByJA3Element->unsafe_cipher)
);
againstRepeat = 1;
i++;
} else {
fprintf(out, "\t%45s", "");
fprintf(out, " %-15s %s\n",
innerHashEl->ip_string,
print_cipher(hostByJA3Element->unsafe_cipher)
);
}
}
}
HASH_ITER(hh, hostByJA3S_ht, hostByJA3Element, tmp3) {
againstRepeat = 0;
HASH_ITER(hh, hostByJA3Element->ipToDNS_ht, innerHashEl, tmp4) {
if(againstRepeat == 0) {
fprintf(out, "\t%-7d JA3S %s",
i,
hostByJA3Element->ja3
);
fprintf(out, " %-15s %-10s %s%s%s\n",
innerHashEl->ip_string,
print_cipher(hostByJA3Element->unsafe_cipher),
innerHashEl->dns_name[0] ? "[" : "",
innerHashEl->dns_name,
innerHashEl->dns_name[0] ? "]" : ""
);
againstRepeat = 1;
i++;
} else {
fprintf(out, "\t%45s", "");
fprintf(out, " %-15s %-10s %s%s%s\n",
innerHashEl->ip_string,
print_cipher(hostByJA3Element->unsafe_cipher),
innerHashEl->dns_name[0] ? "[" : "",
innerHashEl->dns_name,
innerHashEl->dns_name[0] ? "]" : ""
);
}
}
}
}
fprintf(out, "\n\n");
//freeing the hash table
HASH_ITER(hh, ja3ByHostsHashT, ja3ByHost_element, tmp) {
HASH_ITER(hh, ja3ByHost_element->host_client_info_hasht, info_of_element, tmp2) {
if(ja3ByHost_element->host_client_info_hasht)
HASH_DEL(ja3ByHost_element->host_client_info_hasht, info_of_element);
free(info_of_element);
}
HASH_ITER(hh, ja3ByHost_element->host_server_info_hasht, info_of_element, tmp2) {
if(ja3ByHost_element->host_server_info_hasht)
HASH_DEL(ja3ByHost_element->host_server_info_hasht, info_of_element);
free(info_of_element);
}
HASH_DEL(ja3ByHostsHashT, ja3ByHost_element);
free(ja3ByHost_element);
}
HASH_ITER(hh, hostByJA3C_ht, hostByJA3Element, tmp3) {
HASH_ITER(hh, hostByJA3C_ht->ipToDNS_ht, innerHashEl, tmp4) {
if(hostByJA3Element->ipToDNS_ht)
HASH_DEL(hostByJA3Element->ipToDNS_ht, innerHashEl);
free(innerHashEl);
}
HASH_DEL(hostByJA3C_ht, hostByJA3Element);
free(hostByJA3Element);
}
hostByJA3Element = NULL;
HASH_ITER(hh, hostByJA3S_ht, hostByJA3Element, tmp3) {
HASH_ITER(hh, hostByJA3S_ht->ipToDNS_ht, innerHashEl, tmp4) {
if(hostByJA3Element->ipToDNS_ht)
HASH_DEL(hostByJA3Element->ipToDNS_ht, innerHashEl);
free(innerHashEl);
}
HASH_DEL(hostByJA3S_ht, hostByJA3Element);
free(hostByJA3Element);
}
}
}
/* Print all flows stats */
qsort(all_flows, num_flows, sizeof(struct flow_info), cmpFlows);
if(verbose > 1) {
for(i=0; i<num_flows; i++)
printFlow(i+1, all_flows[i].flow, all_flows[i].thread_id);
}
for(thread_id = 0; thread_id < num_threads; thread_id++) {
if(ndpi_thread_info[thread_id].workflow->stats.protocol_counter[0 /* 0 = Unknown */] > 0) {
fprintf(out, "\n\nUndetected flows:%s\n",
undetected_flows_deleted ? " (expired flows are not listed below)" : "");
break;
}
}
num_flows = 0;
for(thread_id = 0; thread_id < num_threads; thread_id++) {
if(ndpi_thread_info[thread_id].workflow->stats.protocol_counter[0] > 0) {
for(i=0; i<NUM_ROOTS; i++)
ndpi_twalk(ndpi_thread_info[thread_id].workflow->ndpi_flows_root[i],
node_print_unknown_proto_walker, &thread_id);
}
}
qsort(all_flows, num_flows, sizeof(struct flow_info), cmpFlows);
for(i=0; i<num_flows; i++)
printFlow(i+1, all_flows[i].flow, all_flows[i].thread_id);
} else if(csv_fp != NULL) {
int i;
num_flows = 0;
for(thread_id = 0; thread_id < num_threads; thread_id++) {
for(i=0; i<NUM_ROOTS; i++)
ndpi_twalk(ndpi_thread_info[thread_id].workflow->ndpi_flows_root[i],
node_print_known_proto_walker, &thread_id);
}
for(i=0; i<num_flows; i++)
printFlow(i+1, all_flows[i].flow, all_flows[i].thread_id);
}
free(all_flows);
}
/* *********************************************** */
/**
* @brief Print result
*/
static void printResults(u_int64_t processing_time_usec, u_int64_t setup_time_usec) {
u_int32_t i;
u_int64_t total_flow_bytes = 0;
u_int32_t avg_pkt_size = 0;
struct ndpi_stats cumulative_stats;
int thread_id;
char buf[32];
long long unsigned int breed_stats[NUM_BREEDS] = { 0 };
memset(&cumulative_stats, 0, sizeof(cumulative_stats));
for(thread_id = 0; thread_id < num_threads; thread_id++) {
if((ndpi_thread_info[thread_id].workflow->stats.total_wire_bytes == 0)
&& (ndpi_thread_info[thread_id].workflow->stats.raw_packet_count == 0))
continue;
for(i=0; i<NUM_ROOTS; i++) {
ndpi_twalk(ndpi_thread_info[thread_id].workflow->ndpi_flows_root[i],
node_proto_guess_walker, &thread_id);
if(verbose == 3)
ndpi_twalk(ndpi_thread_info[thread_id].workflow->ndpi_flows_root[i],
port_stats_walker, &thread_id);
}
/* Stats aggregation */
cumulative_stats.guessed_flow_protocols += ndpi_thread_info[thread_id].workflow->stats.guessed_flow_protocols;
cumulative_stats.raw_packet_count += ndpi_thread_info[thread_id].workflow->stats.raw_packet_count;
cumulative_stats.ip_packet_count += ndpi_thread_info[thread_id].workflow->stats.ip_packet_count;
cumulative_stats.total_wire_bytes += ndpi_thread_info[thread_id].workflow->stats.total_wire_bytes;
cumulative_stats.total_ip_bytes += ndpi_thread_info[thread_id].workflow->stats.total_ip_bytes;
cumulative_stats.total_discarded_bytes += ndpi_thread_info[thread_id].workflow->stats.total_discarded_bytes;
for(i = 0; i < ndpi_get_num_supported_protocols(ndpi_thread_info[0].workflow->ndpi_struct); i++) {
cumulative_stats.protocol_counter[i] += ndpi_thread_info[thread_id].workflow->stats.protocol_counter[i];
cumulative_stats.protocol_counter_bytes[i] += ndpi_thread_info[thread_id].workflow->stats.protocol_counter_bytes[i];
cumulative_stats.protocol_flows[i] += ndpi_thread_info[thread_id].workflow->stats.protocol_flows[i];
}
cumulative_stats.ndpi_flow_count += ndpi_thread_info[thread_id].workflow->stats.ndpi_flow_count;
cumulative_stats.tcp_count += ndpi_thread_info[thread_id].workflow->stats.tcp_count;
cumulative_stats.udp_count += ndpi_thread_info[thread_id].workflow->stats.udp_count;
cumulative_stats.mpls_count += ndpi_thread_info[thread_id].workflow->stats.mpls_count;
cumulative_stats.pppoe_count += ndpi_thread_info[thread_id].workflow->stats.pppoe_count;
cumulative_stats.vlan_count += ndpi_thread_info[thread_id].workflow->stats.vlan_count;
cumulative_stats.fragmented_count += ndpi_thread_info[thread_id].workflow->stats.fragmented_count;
for(i = 0; i < sizeof(cumulative_stats.packet_len)/sizeof(cumulative_stats.packet_len[0]); i++)
cumulative_stats.packet_len[i] += ndpi_thread_info[thread_id].workflow->stats.packet_len[i];
cumulative_stats.max_packet_len += ndpi_thread_info[thread_id].workflow->stats.max_packet_len;
}
if(cumulative_stats.total_wire_bytes == 0)
goto free_stats;
if(!quiet_mode) {
printf("\nnDPI Memory statistics:\n");
printf("\tnDPI Memory (once): %-13s\n", formatBytes(ndpi_get_ndpi_detection_module_size(), buf, sizeof(buf)));
printf("\tFlow Memory (per flow): %-13s\n", formatBytes(sizeof(struct ndpi_flow_struct), buf, sizeof(buf)));
printf("\tActual Memory: %-13s\n", formatBytes(current_ndpi_memory, buf, sizeof(buf)));
printf("\tPeak Memory: %-13s\n", formatBytes(max_ndpi_memory, buf, sizeof(buf)));
printf("\tSetup Time: %lu msec\n", (unsigned long)(setup_time_usec/1000));
printf("\tPacket Processing Time: %lu msec\n", (unsigned long)(processing_time_usec/1000));
printf("\nTraffic statistics:\n");
printf("\tEthernet bytes: %-13llu (includes ethernet CRC/IFC/trailer)\n",
(long long unsigned int)cumulative_stats.total_wire_bytes);
printf("\tDiscarded bytes: %-13llu\n",
(long long unsigned int)cumulative_stats.total_discarded_bytes);
printf("\tIP packets: %-13llu of %llu packets total\n",
(long long unsigned int)cumulative_stats.ip_packet_count,
(long long unsigned int)cumulative_stats.raw_packet_count);
/* In order to prevent Floating point exception in case of no traffic*/
if(cumulative_stats.total_ip_bytes && cumulative_stats.raw_packet_count)
avg_pkt_size = (unsigned int)(cumulative_stats.total_ip_bytes/cumulative_stats.raw_packet_count);
printf("\tIP bytes: %-13llu (avg pkt size %u bytes)\n",
(long long unsigned int)cumulative_stats.total_ip_bytes,avg_pkt_size);
printf("\tUnique flows: %-13u\n", cumulative_stats.ndpi_flow_count);
printf("\tTCP Packets: %-13lu\n", (unsigned long)cumulative_stats.tcp_count);
printf("\tUDP Packets: %-13lu\n", (unsigned long)cumulative_stats.udp_count);
printf("\tVLAN Packets: %-13lu\n", (unsigned long)cumulative_stats.vlan_count);
printf("\tMPLS Packets: %-13lu\n", (unsigned long)cumulative_stats.mpls_count);
printf("\tPPPoE Packets: %-13lu\n", (unsigned long)cumulative_stats.pppoe_count);
printf("\tFragmented Packets: %-13lu\n", (unsigned long)cumulative_stats.fragmented_count);
printf("\tMax Packet size: %-13u\n", cumulative_stats.max_packet_len);
printf("\tPacket Len < 64: %-13lu\n", (unsigned long)cumulative_stats.packet_len[0]);
printf("\tPacket Len 64-128: %-13lu\n", (unsigned long)cumulative_stats.packet_len[1]);
printf("\tPacket Len 128-256: %-13lu\n", (unsigned long)cumulative_stats.packet_len[2]);
printf("\tPacket Len 256-1024: %-13lu\n", (unsigned long)cumulative_stats.packet_len[3]);
printf("\tPacket Len 1024-1500: %-13lu\n", (unsigned long)cumulative_stats.packet_len[4]);
printf("\tPacket Len > 1500: %-13lu\n", (unsigned long)cumulative_stats.packet_len[5]);
if(processing_time_usec > 0) {
char buf[32], buf1[32], when[64];
float t = (float)(cumulative_stats.ip_packet_count*1000000)/(float)processing_time_usec;
float b = (float)(cumulative_stats.total_wire_bytes * 8 *1000000)/(float)processing_time_usec;
float traffic_duration;
struct tm result;
if(live_capture) traffic_duration = processing_time_usec;
else traffic_duration = (pcap_end.tv_sec*1000000 + pcap_end.tv_usec) - (pcap_start.tv_sec*1000000 + pcap_start.tv_usec);
printf("\tnDPI throughput: %s pps / %s/sec\n", formatPackets(t, buf), formatTraffic(b, 1, buf1));
if(traffic_duration != 0) {
t = (float)(cumulative_stats.ip_packet_count*1000000)/(float)traffic_duration;
b = (float)(cumulative_stats.total_wire_bytes * 8 *1000000)/(float)traffic_duration;
} else {
t = 0;
b = 0;
}
strftime(when, sizeof(when), "%d/%b/%Y %H:%M:%S", localtime_r(&pcap_start.tv_sec, &result));
printf("\tAnalysis begin: %s\n", when);
strftime(when, sizeof(when), "%d/%b/%Y %H:%M:%S", localtime_r(&pcap_end.tv_sec, &result));
printf("\tAnalysis end: %s\n", when);
printf("\tTraffic throughput: %s pps / %s/sec\n", formatPackets(t, buf), formatTraffic(b, 1, buf1));
printf("\tTraffic duration: %.3f sec\n", traffic_duration/1000000);
}
if(enable_protocol_guess)
printf("\tGuessed flow protos: %-13u\n", cumulative_stats.guessed_flow_protocols);
}
if(!quiet_mode) printf("\n\nDetected protocols:\n");
for(i = 0; i <= ndpi_get_num_supported_protocols(ndpi_thread_info[0].workflow->ndpi_struct); i++) {
ndpi_protocol_breed_t breed = ndpi_get_proto_breed(ndpi_thread_info[0].workflow->ndpi_struct, i);
if(cumulative_stats.protocol_counter[i] > 0) {
breed_stats[breed] += (long long unsigned int)cumulative_stats.protocol_counter_bytes[i];
if(results_file)
fprintf(results_file, "%s\t%llu\t%llu\t%u\n",
ndpi_get_proto_name(ndpi_thread_info[0].workflow->ndpi_struct, i),
(long long unsigned int)cumulative_stats.protocol_counter[i],
(long long unsigned int)cumulative_stats.protocol_counter_bytes[i],
cumulative_stats.protocol_flows[i]);
if((!quiet_mode)) {
printf("\t%-20s packets: %-13llu bytes: %-13llu "
"flows: %-13u\n",
ndpi_get_proto_name(ndpi_thread_info[0].workflow->ndpi_struct, i),
(long long unsigned int)cumulative_stats.protocol_counter[i],
(long long unsigned int)cumulative_stats.protocol_counter_bytes[i],
cumulative_stats.protocol_flows[i]);
}
total_flow_bytes += cumulative_stats.protocol_counter_bytes[i];
}
}
if((!quiet_mode)) {
printf("\n\nProtocol statistics:\n");
for(i=0; i < NUM_BREEDS; i++) {
if(breed_stats[i] > 0) {
printf("\t%-20s %13llu bytes\n",
ndpi_get_proto_breed_name(ndpi_thread_info[0].workflow->ndpi_struct, i),
breed_stats[i]);
}
}
}
// printf("\n\nTotal Flow Traffic: %llu (diff: %llu)\n", total_flow_bytes, cumulative_stats.total_ip_bytes-total_flow_bytes);
printFlowsStats();
if(verbose == 3) {
HASH_SORT(srcStats, port_stats_sort);
HASH_SORT(dstStats, port_stats_sort);
printf("\n\nSource Ports Stats:\n");
printPortStats(srcStats);
printf("\nDestination Ports Stats:\n");
printPortStats(dstStats);
}
free_stats:
if(scannerHosts) {
deleteScanners(scannerHosts);
scannerHosts = NULL;
}
if(receivers) {
deleteReceivers(receivers);
receivers = NULL;
}
if(topReceivers) {
deleteReceivers(topReceivers);
topReceivers = NULL;
}
if(srcStats) {
deletePortsStats(srcStats);
srcStats = NULL;
}
if(dstStats) {
deletePortsStats(dstStats);
dstStats = NULL;
}
}
/**
* @brief Force a pcap_dispatch() or pcap_loop() call to return
*/
static void breakPcapLoop(u_int16_t thread_id) {
#ifdef USE_DPDK
dpdk_run_capture = 0;
#else
if(ndpi_thread_info[thread_id].workflow->pcap_handle != NULL) {
pcap_breakloop(ndpi_thread_info[thread_id].workflow->pcap_handle);
}
#endif
}
/**
* @brief Sigproc is executed for each packet in the pcap file
*/
void sigproc(int sig) {
static int called = 0;
int thread_id;
if(called) return; else called = 1;
shutdown_app = 1;
for(thread_id=0; thread_id<num_threads; thread_id++)
breakPcapLoop(thread_id);
}
/**
* @brief Get the next pcap file from a passed playlist
*/
static int getNextPcapFileFromPlaylist(u_int16_t thread_id, char filename[], u_int32_t filename_len) {
if(playlist_fp[thread_id] == NULL) {
if((playlist_fp[thread_id] = fopen(_pcap_file[thread_id], "r")) == NULL)
return -1;
}
next_line:
if(fgets(filename, filename_len, playlist_fp[thread_id])) {
int l = strlen(filename);
if(filename[0] == '\0' || filename[0] == '#') goto next_line;
if(filename[l-1] == '\n') filename[l-1] = '\0';
return 0;
} else {
fclose(playlist_fp[thread_id]);
playlist_fp[thread_id] = NULL;
return -1;
}
}
/**
* @brief Configure the pcap handle
*/
static void configurePcapHandle(pcap_t * pcap_handle) {
if(bpfFilter != NULL) {
struct bpf_program fcode;
if(pcap_compile(pcap_handle, &fcode, bpfFilter, 1, 0xFFFFFF00) < 0) {
printf("pcap_compile error: '%s'\n", pcap_geterr(pcap_handle));
} else {
if(pcap_setfilter(pcap_handle, &fcode) < 0) {
printf("pcap_setfilter error: '%s'\n", pcap_geterr(pcap_handle));
} else
printf("Successfully set BPF filter to '%s'\n", bpfFilter);
}
}
}
/**
* @brief Open a pcap file or a specified device - Always returns a valid pcap_t
*/
static pcap_t * openPcapFileOrDevice(u_int16_t thread_id, const u_char * pcap_file) {
u_int snaplen = 1536;
int promisc = 1;
char pcap_error_buffer[PCAP_ERRBUF_SIZE];
pcap_t * pcap_handle = NULL;
/* trying to open a live interface */
#ifdef USE_DPDK
struct rte_mempool *mbuf_pool = rte_pktmbuf_pool_create("MBUF_POOL", NUM_MBUFS,
MBUF_CACHE_SIZE, 0,
RTE_MBUF_DEFAULT_BUF_SIZE,
rte_socket_id());
if(mbuf_pool == NULL)
rte_exit(EXIT_FAILURE, "Cannot create mbuf pool: are hugepages ok?\n");
if(dpdk_port_init(dpdk_port_id, mbuf_pool) != 0)
rte_exit(EXIT_FAILURE, "DPDK: Cannot init port %u: please see README.dpdk\n", dpdk_port_id);
#else
/* Trying to open the interface */
if((pcap_handle = pcap_open_live((char*)pcap_file, snaplen,
promisc, 500, pcap_error_buffer)) == NULL) {
capture_for = capture_until = 0;
live_capture = 0;
num_threads = 1; /* Open pcap files in single threads mode */
/* Trying to open a pcap file */
if((pcap_handle = pcap_open_offline((char*)pcap_file, pcap_error_buffer)) == NULL) {
char filename[256] = { 0 };
if(strstr((char*)pcap_file, (char*)".pcap"))
printf("ERROR: could not open pcap file %s: %s\n", pcap_file, pcap_error_buffer);
/* Trying to open as a playlist as last attempt */
else if((getNextPcapFileFromPlaylist(thread_id, filename, sizeof(filename)) != 0)
|| ((pcap_handle = pcap_open_offline(filename, pcap_error_buffer)) == NULL)) {
/* This probably was a bad interface name, printing a generic error */
printf("ERROR: could not open %s: %s\n", filename, pcap_error_buffer);
exit(-1);
} else {
if((!quiet_mode))
printf("Reading packets from playlist %s...\n", pcap_file);
}
} else {
if((!quiet_mode))
printf("Reading packets from pcap file %s...\n", pcap_file);
}
} else {
live_capture = 1;
if((!quiet_mode)) {
#ifdef USE_DPDK
printf("Capturing from DPDK (port 0)...\n");
#else
printf("Capturing live traffic from device %s...\n", pcap_file);
#endif
}
}
configurePcapHandle(pcap_handle);
#endif /* !DPDK */
if(capture_for > 0) {
if((!quiet_mode))
printf("Capturing traffic up to %u seconds\n", (unsigned int)capture_for);
#ifndef WIN32
alarm(capture_for);
signal(SIGALRM, sigproc);
#endif
}
return pcap_handle;
}
/**
* @brief Check pcap packet
*/
static void ndpi_process_packet(u_char *args,
const struct pcap_pkthdr *header,
const u_char *packet) {
struct ndpi_proto p;
u_int16_t thread_id = *((u_int16_t*)args);
/* allocate an exact size buffer to check overflows */
uint8_t *packet_checked = malloc(header->caplen);
memcpy(packet_checked, packet, header->caplen);
p = ndpi_workflow_process_packet(ndpi_thread_info[thread_id].workflow, header, packet_checked);
if(!pcap_start.tv_sec) pcap_start.tv_sec = header->ts.tv_sec, pcap_start.tv_usec = header->ts.tv_usec;
pcap_end.tv_sec = header->ts.tv_sec, pcap_end.tv_usec = header->ts.tv_usec;
/* Idle flows cleanup */
if(live_capture) {
if(ndpi_thread_info[thread_id].last_idle_scan_time + IDLE_SCAN_PERIOD < ndpi_thread_info[thread_id].workflow->last_time) {
/* scan for idle flows */
ndpi_twalk(ndpi_thread_info[thread_id].workflow->ndpi_flows_root[ndpi_thread_info[thread_id].idle_scan_idx],
node_idle_scan_walker, &thread_id);
/* remove idle flows (unfortunately we cannot do this inline) */
while(ndpi_thread_info[thread_id].num_idle_flows > 0) {
/* search and delete the idle flow from the "ndpi_flow_root" (see struct reader thread) - here flows are the node of a b-tree */
ndpi_tdelete(ndpi_thread_info[thread_id].idle_flows[--ndpi_thread_info[thread_id].num_idle_flows],
&ndpi_thread_info[thread_id].workflow->ndpi_flows_root[ndpi_thread_info[thread_id].idle_scan_idx],
ndpi_workflow_node_cmp);
/* free the memory associated to idle flow in "idle_flows" - (see struct reader thread)*/
ndpi_free_flow_info_half(ndpi_thread_info[thread_id].idle_flows[ndpi_thread_info[thread_id].num_idle_flows]);
ndpi_free(ndpi_thread_info[thread_id].idle_flows[ndpi_thread_info[thread_id].num_idle_flows]);
}
if(++ndpi_thread_info[thread_id].idle_scan_idx == ndpi_thread_info[thread_id].workflow->prefs.num_roots)
ndpi_thread_info[thread_id].idle_scan_idx = 0;
ndpi_thread_info[thread_id].last_idle_scan_time = ndpi_thread_info[thread_id].workflow->last_time;
}
}
#ifdef DEBUG_TRACE
if(trace) fprintf(trace, "Found %u bytes packet %u.%u\n", header->caplen, p.app_protocol, p.master_protocol);
#endif
if(extcap_dumper
&& ((extcap_packet_filter == (u_int16_t)-1)
|| (p.app_protocol == extcap_packet_filter)
|| (p.master_protocol == extcap_packet_filter)
)
) {
struct pcap_pkthdr h;
uint32_t *crc, delta = sizeof(struct ndpi_packet_trailer) + 4 /* ethernet trailer */;
struct ndpi_packet_trailer *trailer;
memcpy(&h, header, sizeof(h));
if(h.caplen > (sizeof(extcap_buf)-sizeof(struct ndpi_packet_trailer) - 4)) {
printf("INTERNAL ERROR: caplen=%u\n", h.caplen);
h.caplen = sizeof(extcap_buf)-sizeof(struct ndpi_packet_trailer) - 4;
}
trailer = (struct ndpi_packet_trailer*)&extcap_buf[h.caplen];
memcpy(extcap_buf, packet, h.caplen);
memset(trailer, 0, sizeof(struct ndpi_packet_trailer));
trailer->magic = htonl(0x19680924);
trailer->master_protocol = htons(p.master_protocol), trailer->app_protocol = htons(p.app_protocol);
ndpi_protocol2name(ndpi_thread_info[thread_id].workflow->ndpi_struct, p, trailer->name, sizeof(trailer->name));
crc = (uint32_t*)&extcap_buf[h.caplen+sizeof(struct ndpi_packet_trailer)];
*crc = ethernet_crc32((const void*)extcap_buf, h.caplen+sizeof(struct ndpi_packet_trailer));
h.caplen += delta, h.len += delta;
#ifdef DEBUG_TRACE
if(trace) fprintf(trace, "Dumping %u bytes packet\n", h.caplen);
#endif
pcap_dump((u_char*)extcap_dumper, &h, (const u_char *)extcap_buf);
pcap_dump_flush(extcap_dumper);
}
/* check for buffer changes */
if(memcmp(packet, packet_checked, header->caplen) != 0)
printf("INTERNAL ERROR: ingress packet was modified by nDPI: this should not happen [thread_id=%u, packetId=%lu, caplen=%u]\n",
thread_id, (unsigned long)ndpi_thread_info[thread_id].workflow->stats.raw_packet_count, header->caplen);
if((pcap_end.tv_sec-pcap_start.tv_sec) > pcap_analysis_duration) {
int i;
u_int64_t processing_time_usec, setup_time_usec;
gettimeofday(&end, NULL);
processing_time_usec = end.tv_sec*1000000 + end.tv_usec - (begin.tv_sec*1000000 + begin.tv_usec);
setup_time_usec = begin.tv_sec*1000000 + begin.tv_usec - (startup_time.tv_sec*1000000 + startup_time.tv_usec);
printResults(processing_time_usec, setup_time_usec);
for(i=0; i<ndpi_thread_info[thread_id].workflow->prefs.num_roots; i++) {
ndpi_tdestroy(ndpi_thread_info[thread_id].workflow->ndpi_flows_root[i], ndpi_flow_info_freer);
ndpi_thread_info[thread_id].workflow->ndpi_flows_root[i] = NULL;
memset(&ndpi_thread_info[thread_id].workflow->stats, 0, sizeof(struct ndpi_stats));
}
if(!quiet_mode)
printf("\n-------------------------------------------\n\n");
memcpy(&begin, &end, sizeof(begin));
memcpy(&pcap_start, &pcap_end, sizeof(pcap_start));
}
/*
Leave the free as last statement to avoid crashes when ndpi_detection_giveup()
is called above by printResults()
*/
free(packet_checked);
}
/**
* @brief Call pcap_loop() to process packets from a live capture or savefile
*/
static void runPcapLoop(u_int16_t thread_id) {
if((!shutdown_app) && (ndpi_thread_info[thread_id].workflow->pcap_handle != NULL))
if(pcap_loop(ndpi_thread_info[thread_id].workflow->pcap_handle, -1, &ndpi_process_packet, (u_char*)&thread_id) < 0)
printf("Error while reading pcap file: '%s'\n", pcap_geterr(ndpi_thread_info[thread_id].workflow->pcap_handle));
}
/**
* @brief Process a running thread
*/
void * processing_thread(void *_thread_id) {
long thread_id = (long) _thread_id;
char pcap_error_buffer[PCAP_ERRBUF_SIZE];
#if defined(linux) && defined(HAVE_PTHREAD_SETAFFINITY_NP)
if(core_affinity[thread_id] >= 0) {
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core_affinity[thread_id], &cpuset);
if(pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset) != 0)
fprintf(stderr, "Error while binding thread %ld to core %d\n", thread_id, core_affinity[thread_id]);
else {
if((!quiet_mode)) printf("Running thread %ld on core %d...\n", thread_id, core_affinity[thread_id]);
}
} else
#endif
if((!quiet_mode)) printf("Running thread %ld...\n", thread_id);
#ifdef USE_DPDK
while(dpdk_run_capture) {
struct rte_mbuf *bufs[BURST_SIZE];
u_int16_t num = rte_eth_rx_burst(dpdk_port_id, 0, bufs, BURST_SIZE);
u_int i;
if(num == 0) {
usleep(1);
continue;
}
for(i = 0; i < PREFETCH_OFFSET && i < num; i++)
rte_prefetch0(rte_pktmbuf_mtod(bufs[i], void *));
for(i = 0; i < num; i++) {
char *data = rte_pktmbuf_mtod(bufs[i], char *);
int len = rte_pktmbuf_pkt_len(bufs[i]);
struct pcap_pkthdr h;
h.len = h.caplen = len;
gettimeofday(&h.ts, NULL);
ndpi_process_packet((u_char*)&thread_id, &h, (const u_char *)data);
rte_pktmbuf_free(bufs[i]);
}
}
#else
pcap_loop:
runPcapLoop(thread_id);
if(playlist_fp[thread_id] != NULL) { /* playlist: read next file */
char filename[256];
if(getNextPcapFileFromPlaylist(thread_id, filename, sizeof(filename)) == 0 &&
(ndpi_thread_info[thread_id].workflow->pcap_handle = pcap_open_offline(filename, pcap_error_buffer)) != NULL) {
configurePcapHandle(ndpi_thread_info[thread_id].workflow->pcap_handle);
goto pcap_loop;
}
}
#endif
return NULL;
}
/**
* @brief Begin, process, end detection process
*/
void test_lib() {
u_int64_t processing_time_usec, setup_time_usec;
long thread_id;
#ifdef DEBUG_TRACE
if(trace) fprintf(trace, "Num threads: %d\n", num_threads);
#endif
for(thread_id = 0; thread_id < num_threads; thread_id++) {
pcap_t *cap;
#ifdef DEBUG_TRACE
if(trace) fprintf(trace, "Opening %s\n", (const u_char*)_pcap_file[thread_id]);
#endif
cap = openPcapFileOrDevice(thread_id, (const u_char*)_pcap_file[thread_id]);
setupDetection(thread_id, cap);
}
gettimeofday(&begin, NULL);
int status;
void * thd_res;
/* Running processing threads */
for(thread_id = 0; thread_id < num_threads; thread_id++) {
status = pthread_create(&ndpi_thread_info[thread_id].pthread, NULL, processing_thread, (void *) thread_id);
/* check pthreade_create return value */
if(status != 0) {
fprintf(stderr, "error on create %ld thread\n", thread_id);
exit(-1);
}
}
/* Waiting for completion */
for(thread_id = 0; thread_id < num_threads; thread_id++) {
status = pthread_join(ndpi_thread_info[thread_id].pthread, &thd_res);
/* check pthreade_join return value */
if(status != 0) {
fprintf(stderr, "error on join %ld thread\n", thread_id);
exit(-1);
}
if(thd_res != NULL) {
fprintf(stderr, "error on returned value of %ld joined thread\n", thread_id);
exit(-1);
}
}
gettimeofday(&end, NULL);
processing_time_usec = end.tv_sec*1000000 + end.tv_usec - (begin.tv_sec*1000000 + begin.tv_usec);
setup_time_usec = begin.tv_sec*1000000 + begin.tv_usec - (startup_time.tv_sec*1000000 + startup_time.tv_usec);
/* Printing cumulative results */
printResults(processing_time_usec, setup_time_usec);
for(thread_id = 0; thread_id < num_threads; thread_id++) {
if(ndpi_thread_info[thread_id].workflow->pcap_handle != NULL)
pcap_close(ndpi_thread_info[thread_id].workflow->pcap_handle);
terminateDetection(thread_id);
}
}
/* *********************************************** */
static void bitmapUnitTest() {
u_int32_t val, i, j;
for(i=0; i<32; i++) {
NDPI_ZERO_BIT(val);
NDPI_SET_BIT(val, i);
assert(NDPI_ISSET_BIT(val, i));
for(j=0; j<32; j++) {
if(j != i) {
assert(!NDPI_ISSET_BIT(val, j));
}
}
}
}
/* *********************************************** */
void automataUnitTest() {
void *automa = ndpi_init_automa();
assert(automa);
assert(ndpi_add_string_to_automa(automa, "hello") == 0);
assert(ndpi_add_string_to_automa(automa, "world") == 0);
ndpi_finalize_automa(automa);
assert(ndpi_match_string(automa, "This is the wonderful world of nDPI") == 1);
ndpi_free_automa(automa);
}
/* *********************************************** */
void serializerUnitTest() {
ndpi_serializer serializer, deserializer;
int i;
u_int8_t trace = 0;
assert(ndpi_init_serializer(&serializer, ndpi_serialization_format_tlv) != -1);
for(i=0; i<16; i++) {
char kbuf[32], vbuf[32];
assert(ndpi_serialize_uint32_uint32(&serializer, i, i*i) != -1);
snprintf(kbuf, sizeof(kbuf), "Hello %d", i);
snprintf(vbuf, sizeof(vbuf), "World %d", i);
assert(ndpi_serialize_uint32_string(&serializer, i, "Hello") != -1);
assert(ndpi_serialize_string_string(&serializer, kbuf, vbuf) != -1);
assert(ndpi_serialize_string_uint32(&serializer, kbuf, i*i) != -1);
assert(ndpi_serialize_string_float(&serializer, kbuf, (float)(i*i), "%f") != -1);
}
if(trace)
printf("Serialization size: %u\n", ndpi_serializer_get_buffer_len(&serializer));
assert(ndpi_init_deserializer(&deserializer, &serializer) != -1);
while(1) {
ndpi_serialization_type kt, et;
et = ndpi_deserialize_get_item_type(&deserializer, &kt);
if(et == ndpi_serialization_unknown)
break;
else {
u_int32_t k32, v32;
ndpi_string ks, vs;
float vf;
switch(kt) {
case ndpi_serialization_uint32:
ndpi_deserialize_key_uint32(&deserializer, &k32);
if(trace) printf("%u=", k32);
break;
case ndpi_serialization_string:
ndpi_deserialize_key_string(&deserializer, &ks);
if (trace) {
u_int8_t bkp = ks.str[ks.str_len];
ks.str[ks.str_len] = '\0';
printf("%s=", ks.str);
ks.str[ks.str_len] = bkp;
}
break;
default:
printf("Unsupported TLV key type %u\n", kt);
return;
}
switch(et) {
case ndpi_serialization_uint32:
assert(ndpi_deserialize_value_uint32(&deserializer, &v32) != -1);
if(trace) printf("%u\n", v32);
break;
case ndpi_serialization_string:
assert(ndpi_deserialize_value_string(&deserializer, &vs) != -1);
if(trace) {
u_int8_t bkp = vs.str[vs.str_len];
vs.str[vs.str_len] = '\0';
printf("%s\n", vs.str);
vs.str[vs.str_len] = bkp;
}
break;
case ndpi_serialization_float:
assert(ndpi_deserialize_value_float(&deserializer, &vf) != -1);
if(trace) printf("%f\n", vf);
break;
default:
if (trace) printf("\n");
printf("serializerUnitTest: unsupported type %u detected!\n", et);
return;
break;
}
}
ndpi_deserialize_next(&deserializer);
}
ndpi_term_serializer(&serializer);
}
/* *********************************************** */
// #define RUN_DATA_ANALYSIS_THEN_QUIT 1
void analyzeUnitTest() {
struct ndpi_analyze_struct *s = ndpi_alloc_data_analysis(32);
u_int32_t i;
for(i=0; i<256; i++) {
ndpi_data_add_value(s, rand()*i);
// ndpi_data_add_value(s, i+1);
}
// ndpi_data_print_window_values(s);
#ifdef RUN_DATA_ANALYSIS_THEN_QUIT
printf("Average: [all: %f][window: %f]\n",
ndpi_data_average(s), ndpi_data_window_average(s));
printf("Entropy: %f\n", ndpi_data_entropy(s));
printf("Min/Max: %u/%u\n",
ndpi_data_min(s), ndpi_data_max(s));
#endif
ndpi_free_data_analysis(s);
#ifdef RUN_DATA_ANALYSIS_THEN_QUIT
exit(0);
#endif
}
/* *********************************************** */
/**
* @brief Initialize port array
*/
void bpf_filter_port_array_init(int array[], int size) {
int i;
for(i=0; i<size; i++)
array[i] = INIT_VAL;
}
/* *********************************************** */
/**
* @brief Initialize host array
*/
void bpf_filter_host_array_init(const char *array[48], int size) {
int i;
for(i=0; i<size; i++)
array[i] = NULL;
}
/* *********************************************** */
/**
* @brief Add host to host filter array
*/
void bpf_filter_host_array_add(const char *filter_array[48], int size, const char *host) {
int i;
int r;
for(i=0; i<size; i++) {
if((filter_array[i] != NULL) && (r = strcmp(filter_array[i], host)) == 0)
return;
if(filter_array[i] == NULL) {
filter_array[i] = host;
return;
}
}
fprintf(stderr,"bpf_filter_host_array_add: max array size is reached!\n");
exit(-1);
}
/* *********************************************** */
/**
* @brief Add port to port filter array
*/
void bpf_filter_port_array_add(int filter_array[], int size, int port) {
int i;
for(i=0; i<size; i++) {
if(filter_array[i] == port)
return;
if(filter_array[i] == INIT_VAL) {
filter_array[i] = port;
return;
}
}
fprintf(stderr,"bpf_filter_port_array_add: max array size is reached!\n");
exit(-1);
}
/* *********************************************** */
/**
@brief MAIN FUNCTION
**/
#ifdef APP_HAS_OWN_MAIN
int orginal_main(int argc, char **argv) {
#else
int main(int argc, char **argv) {
#endif
int i;
if(ndpi_get_api_version() != NDPI_API_VERSION) {
printf("nDPI Library version mismatch: please make sure this code and the nDPI library are in sync\n");
return(-1);
}
/* Internal checks */
bitmapUnitTest();
automataUnitTest();
serializerUnitTest();
analyzeUnitTest();
ndpi_self_check_host_match();
gettimeofday(&startup_time, NULL);
ndpi_info_mod = ndpi_init_detection_module(ndpi_no_prefs);
if(ndpi_info_mod == NULL) return -1;
memset(ndpi_thread_info, 0, sizeof(ndpi_thread_info));
parseOptions(argc, argv);
if(!quiet_mode) {
printf("\n-----------------------------------------------------------\n"
"* NOTE: This is demo app to show *some* nDPI features.\n"
"* In this demo we have implemented only some basic features\n"
"* just to show you what you can do with the library. Feel \n"
"* free to extend it and send us the patches for inclusion\n"
"------------------------------------------------------------\n\n");
printf("Using nDPI (%s) [%d thread(s)]\n", ndpi_revision(), num_threads);
}
signal(SIGINT, sigproc);
for(i=0; i<num_loops; i++)
test_lib();
if(results_path) free(results_path);
if(results_file) fclose(results_file);
if(extcap_dumper) pcap_dump_close(extcap_dumper);
if(ndpi_info_mod) ndpi_exit_detection_module(ndpi_info_mod);
if(csv_fp) fclose(csv_fp);
return 0;
}
#ifdef WIN32
#ifndef __GNUC__
#define EPOCHFILETIME (116444736000000000i64)
#else
#define EPOCHFILETIME (116444736000000000LL)
#endif
/**
@brief Timezone
**/
struct timezone {
int tz_minuteswest; /* minutes W of Greenwich */
int tz_dsttime; /* type of dst correction */
};
/**
@brief Set time
**/
int gettimeofday(struct timeval *tv, struct timezone *tz) {
FILETIME ft;
LARGE_INTEGER li;
__int64 t;
static int tzflag;
if(tv) {
GetSystemTimeAsFileTime(&ft);
li.LowPart = ft.dwLowDateTime;
li.HighPart = ft.dwHighDateTime;
t = li.QuadPart; /* In 100-nanosecond intervals */
t -= EPOCHFILETIME; /* Offset to the Epoch time */
t /= 10; /* In microseconds */
tv->tv_sec = (long)(t / 1000000);
tv->tv_usec = (long)(t % 1000000);
}
if(tz) {
if(!tzflag) {
_tzset();
tzflag++;
}
tz->tz_minuteswest = _timezone / 60;
tz->tz_dsttime = _daylight;
}
return 0;
}
#endif /* WIN32 */
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4215_0 |
crossvul-cpp_data_good_5314_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% QQQ U U AAA N N TTTTT U U M M %
% Q Q U U A A NN N T U U MM MM %
% Q Q U U AAAAA N N N T U U M M M %
% Q QQ U U A A N NN T U U M M %
% QQQQ UUU A A N N T UUU M M %
% %
% IIIII M M PPPP OOO RRRR TTTTT %
% I MM MM P P O O R R T %
% I M M M PPPP O O RRRR T %
% I M M P O O R R T %
% IIIII M M P OOO R R T %
% %
% MagickCore Methods to Import Quantum Pixels %
% %
% Software Design %
% Cristy %
% October 1998 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/property.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/color-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/constitute.h"
#include "MagickCore/delegate.h"
#include "MagickCore/geometry.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/statistic.h"
#include "MagickCore/stream.h"
#include "MagickCore/string_.h"
#include "MagickCore/utility.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I m p o r t Q u a n t u m P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ImportQuantumPixels() transfers one or more pixel components from a user
% supplied buffer into the image pixel cache of an image. The pixels are
% expected in network byte order. It returns MagickTrue if the pixels are
% successfully transferred, otherwise MagickFalse.
%
% The format of the ImportQuantumPixels method is:
%
% size_t ImportQuantumPixels(const Image *image,CacheView *image_view,
% QuantumInfo *quantum_info,const QuantumType quantum_type,
% const unsigned char *magick_restrict pixels,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o image_view: the image cache view.
%
% o quantum_info: the quantum info.
%
% o quantum_type: Declare which pixel components to transfer (red, green,
% blue, opacity, RGB, or RGBA).
%
% o pixels: The pixel components are transferred from this buffer.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline Quantum PushColormapIndex(const Image *image,const size_t index,
MagickBooleanType *range_exception)
{
if (index < image->colors)
return((Quantum) index);
*range_exception=MagickTrue;
return((Quantum) 0);
}
static inline const unsigned char *PushDoublePixel(QuantumInfo *quantum_info,
const unsigned char *magick_restrict pixels,double *pixel)
{
double
*p;
unsigned char
quantum[8];
if (quantum_info->endian == LSBEndian)
{
quantum[0]=(*pixels++);
quantum[1]=(*pixels++);
quantum[2]=(*pixels++);
quantum[3]=(*pixels++);
quantum[4]=(*pixels++);
quantum[5]=(*pixels++);
quantum[6]=(*pixels++);
quantum[7]=(*pixels++);
p=(double *) quantum;
*pixel=(*p);
*pixel-=quantum_info->minimum;
*pixel*=quantum_info->scale;
return(pixels);
}
quantum[7]=(*pixels++);
quantum[6]=(*pixels++);
quantum[5]=(*pixels++);
quantum[4]=(*pixels++);
quantum[3]=(*pixels++);
quantum[2]=(*pixels++);
quantum[1]=(*pixels++);
quantum[0]=(*pixels++);
p=(double *) quantum;
*pixel=(*p);
*pixel-=quantum_info->minimum;
*pixel*=quantum_info->scale;
return(pixels);
}
static inline const unsigned char *PushFloatPixel(QuantumInfo *quantum_info,
const unsigned char *magick_restrict pixels,float *pixel)
{
float
*p;
unsigned char
quantum[4];
if (quantum_info->endian == LSBEndian)
{
quantum[0]=(*pixels++);
quantum[1]=(*pixels++);
quantum[2]=(*pixels++);
quantum[3]=(*pixels++);
p=(float *) quantum;
*pixel=(*p);
*pixel-=quantum_info->minimum;
*pixel*=quantum_info->scale;
return(pixels);
}
quantum[3]=(*pixels++);
quantum[2]=(*pixels++);
quantum[1]=(*pixels++);
quantum[0]=(*pixels++);
p=(float *) quantum;
*pixel=(*p);
*pixel-=quantum_info->minimum;
*pixel*=quantum_info->scale;
return(pixels);
}
static inline const unsigned char *PushQuantumPixel(QuantumInfo *quantum_info,
const unsigned char *magick_restrict pixels,unsigned int *quantum)
{
register ssize_t
i;
register size_t
quantum_bits;
*quantum=(QuantumAny) 0;
for (i=(ssize_t) quantum_info->depth; i > 0L; )
{
if (quantum_info->state.bits == 0UL)
{
quantum_info->state.pixel=(*pixels++);
quantum_info->state.bits=8UL;
}
quantum_bits=(size_t) i;
if (quantum_bits > quantum_info->state.bits)
quantum_bits=quantum_info->state.bits;
i-=(ssize_t) quantum_bits;
quantum_info->state.bits-=quantum_bits;
*quantum=(unsigned int) ((*quantum << quantum_bits) |
((quantum_info->state.pixel >> quantum_info->state.bits) &~ ((~0UL) <<
quantum_bits)));
}
return(pixels);
}
static inline const unsigned char *PushQuantumLongPixel(
QuantumInfo *quantum_info,const unsigned char *magick_restrict pixels,
unsigned int *quantum)
{
register ssize_t
i;
register size_t
quantum_bits;
*quantum=0UL;
for (i=(ssize_t) quantum_info->depth; i > 0; )
{
if (quantum_info->state.bits == 0)
{
pixels=PushLongPixel(quantum_info->endian,pixels,
&quantum_info->state.pixel);
quantum_info->state.bits=32U;
}
quantum_bits=(size_t) i;
if (quantum_bits > quantum_info->state.bits)
quantum_bits=quantum_info->state.bits;
*quantum|=(((quantum_info->state.pixel >> (32U-quantum_info->state.bits)) &
quantum_info->state.mask[quantum_bits]) << (quantum_info->depth-i));
i-=(ssize_t) quantum_bits;
quantum_info->state.bits-=quantum_bits;
}
return(pixels);
}
static void ImportAlphaQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelAlpha(image,ScaleCharToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportBGRQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
ssize_t
bit;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleCharToQuantum(pixel),q);
SetPixelAlpha(image,OpaqueAlpha,q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 10:
{
range=GetQuantumRange(quantum_info->depth);
if (quantum_info->pack == MagickFalse)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff,range),q);
SetPixelGreen(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff,range),
q);
SetPixelBlue(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff,range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
if (quantum_info->quantum == 32U)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumLongPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumLongPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumLongPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
case 12:
{
range=GetQuantumRange(quantum_info->depth);
if (quantum_info->pack == MagickFalse)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) (3*number_pixels-1); x+=2)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
switch (x % 3)
{
default:
case 0:
{
SetPixelRed(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
break;
}
case 1:
{
SetPixelGreen(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
break;
}
case 2:
{
SetPixelBlue(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
q+=GetPixelChannels(image);
break;
}
}
p=PushShortPixel(quantum_info->endian,p,&pixel);
switch ((x+1) % 3)
{
default:
case 0:
{
SetPixelRed(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
break;
}
case 1:
{
SetPixelGreen(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
break;
}
case 2:
{
SetPixelBlue(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
q+=GetPixelChannels(image);
break;
}
}
p+=quantum_info->pad;
}
for (bit=0; bit < (ssize_t) (3*number_pixels % 2); bit++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
switch ((x+bit) % 3)
{
default:
case 0:
{
SetPixelRed(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
break;
}
case 1:
{
SetPixelGreen(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
break;
}
case 2:
{
SetPixelBlue(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
q+=GetPixelChannels(image);
break;
}
}
p+=quantum_info->pad;
}
if (bit != 0)
p++;
break;
}
if (quantum_info->quantum == 32U)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumLongPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumLongPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumLongPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportBGRAQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelAlpha(image,ScaleCharToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 10:
{
pixel=0;
if (quantum_info->pack == MagickFalse)
{
register ssize_t
i;
size_t
quantum;
ssize_t
n;
n=0;
quantum=0;
for (x=0; x < (ssize_t) number_pixels; x++)
{
for (i=0; i < 4; i++)
{
switch (n % 3)
{
case 0:
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 22) & 0x3ff) << 6)));
break;
}
case 1:
{
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 12) & 0x3ff) << 6)));
break;
}
case 2:
{
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 2) & 0x3ff) << 6)));
break;
}
}
switch (i)
{
case 0: SetPixelRed(image,(Quantum) quantum,q); break;
case 1: SetPixelGreen(image,(Quantum) quantum,q); break;
case 2: SetPixelBlue(image,(Quantum) quantum,q); break;
case 3: SetPixelAlpha(image,(Quantum) quantum,q); break;
}
n++;
}
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),
q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),
q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),
q);
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportBGROQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelOpacity(image,ScaleCharToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 10:
{
pixel=0;
if (quantum_info->pack == MagickFalse)
{
register ssize_t
i;
size_t
quantum;
ssize_t
n;
n=0;
quantum=0;
for (x=0; x < (ssize_t) number_pixels; x++)
{
for (i=0; i < 4; i++)
{
switch (n % 3)
{
case 0:
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 22) & 0x3ff) << 6)));
break;
}
case 1:
{
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 12) & 0x3ff) << 6)));
break;
}
case 2:
{
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 2) & 0x3ff) << 6)));
break;
}
}
switch (i)
{
case 0: SetPixelRed(image,(Quantum) quantum,q); break;
case 1: SetPixelGreen(image,(Quantum) quantum,q); break;
case 2: SetPixelBlue(image,(Quantum) quantum,q); break;
case 3: SetPixelOpacity(image,(Quantum) quantum,q); break;
}
n++;
}
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),
q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),
q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelOpacity(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),
q);
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelOpacity(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelOpacity(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelOpacity(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelOpacity(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelOpacity(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelOpacity(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportBlackQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
if (image->colorspace != CMYKColorspace)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ColorSeparatedImageRequired","`%s'",image->filename);
return;
}
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelBlack(image,ScaleCharToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlack(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlack(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelBlack(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelBlack(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelBlack(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlack(image,ScaleAnyToQuantum(pixel,range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportBlueQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleCharToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportCbYCrYQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 10:
{
Quantum
cbcr[4];
pixel=0;
if (quantum_info->pack == MagickFalse)
{
register ssize_t
i;
size_t
quantum;
ssize_t
n;
n=0;
quantum=0;
for (x=0; x < (ssize_t) number_pixels; x+=4)
{
for (i=0; i < 4; i++)
{
switch (n % 3)
{
case 0:
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 22) & 0x3ff) << 6)));
break;
}
case 1:
{
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 12) & 0x3ff) << 6)));
break;
}
case 2:
{
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 2) & 0x3ff) << 6)));
break;
}
}
cbcr[i]=(Quantum) (quantum);
n++;
}
p+=quantum_info->pad;
SetPixelRed(image,cbcr[1],q);
SetPixelGreen(image,cbcr[0],q);
SetPixelBlue(image,cbcr[2],q);
q+=GetPixelChannels(image);
SetPixelRed(image,cbcr[3],q);
SetPixelGreen(image,cbcr[0],q);
SetPixelBlue(image,cbcr[2],q);
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportCMYKQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
if (image->colorspace != CMYKColorspace)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ColorSeparatedImageRequired","`%s'",image->filename);
return;
}
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelBlack(image,ScaleCharToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlack(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlack(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelBlack(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelBlack(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelBlack(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlack(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportCMYKAQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
if (image->colorspace != CMYKColorspace)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ColorSeparatedImageRequired","`%s'",image->filename);
return;
}
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelBlack(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelAlpha(image,ScaleCharToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlack(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlack(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelBlack(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelBlack(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelBlack(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlack(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportCMYKOQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
if (image->colorspace != CMYKColorspace)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ColorSeparatedImageRequired","`%s'",image->filename);
return;
}
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelBlack(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelOpacity(image,ScaleCharToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlack(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelOpacity(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlack(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelOpacity(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelBlack(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelOpacity(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelBlack(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelOpacity(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelBlack(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelOpacity(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlack(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelOpacity(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportGrayQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
ssize_t
bit;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 1:
{
register Quantum
black,
white;
black=0;
white=QuantumRange;
if (quantum_info->min_is_white != MagickFalse)
{
black=QuantumRange;
white=0;
}
for (x=0; x < ((ssize_t) number_pixels-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
SetPixelGray(image,((*p) & (1 << (7-bit))) == 0 ? black : white,q);
q+=GetPixelChannels(image);
}
p++;
}
for (bit=0; bit < (ssize_t) (number_pixels % 8); bit++)
{
SetPixelGray(image,((*p) & (0x01 << (7-bit))) == 0 ? black : white,q);
q+=GetPixelChannels(image);
}
if (bit != 0)
p++;
break;
}
case 4:
{
register unsigned char
pixel;
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < ((ssize_t) number_pixels-1); x+=2)
{
pixel=(unsigned char) ((*p >> 4) & 0xf);
SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
pixel=(unsigned char) ((*p) & 0xf);
SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q);
p++;
q+=GetPixelChannels(image);
}
for (bit=0; bit < (ssize_t) (number_pixels % 2); bit++)
{
pixel=(unsigned char) (*p++ >> 4);
SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
case 8:
{
unsigned char
pixel;
if (quantum_info->min_is_white != MagickFalse)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelGray(image,ScaleCharToQuantum(pixel),q);
SetPixelAlpha(image,OpaqueAlpha,q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelGray(image,ScaleCharToQuantum(pixel),q);
SetPixelAlpha(image,OpaqueAlpha,q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 10:
{
range=GetQuantumRange(quantum_info->depth);
if (quantum_info->pack == MagickFalse)
{
if (image->endian == LSBEndian)
{
for (x=0; x < (ssize_t) (number_pixels-2); x+=3)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff,
range),q);
q+=GetPixelChannels(image);
SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff,
range),q);
q+=GetPixelChannels(image);
SetPixelGray(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff,
range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
p=PushLongPixel(quantum_info->endian,p,&pixel);
if (x++ < (ssize_t) (number_pixels-1))
{
SetPixelGray(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff,
range),q);
q+=GetPixelChannels(image);
}
if (x++ < (ssize_t) number_pixels)
{
SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff,
range),q);
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) (number_pixels-2); x+=3)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff,range),
q);
q+=GetPixelChannels(image);
SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff,range),
q);
q+=GetPixelChannels(image);
SetPixelGray(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff,range),
q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
p=PushLongPixel(quantum_info->endian,p,&pixel);
if (x++ < (ssize_t) (number_pixels-1))
{
SetPixelGray(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff,
range),q);
q+=GetPixelChannels(image);
}
if (x++ < (ssize_t) number_pixels)
{
SetPixelGray(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff,
range),q);
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 12:
{
range=GetQuantumRange(quantum_info->depth);
if (quantum_info->pack == MagickFalse)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) (number_pixels-1); x+=2)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
q+=GetPixelChannels(image);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
for (bit=0; bit < (ssize_t) (number_pixels % 2); bit++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
if (bit != 0)
p++;
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->min_is_white != MagickFalse)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGray(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGray(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGray(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelGray(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelGray(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelGray(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportGrayAlphaQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
ssize_t
bit;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 1:
{
register unsigned char
pixel;
bit=0;
for (x=((ssize_t) number_pixels-3); x > 0; x-=4)
{
for (bit=0; bit < 8; bit+=2)
{
pixel=(unsigned char) (((*p) & (1 << (7-bit))) != 0 ? 0x00 : 0x01);
SetPixelGray(image,(Quantum) (pixel == 0 ? 0 : QuantumRange),q);
SetPixelAlpha(image,((*p) & (1UL << (unsigned char) (6-bit))) == 0 ?
TransparentAlpha : OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
p++;
}
if ((number_pixels % 4) != 0)
for (bit=3; bit >= (ssize_t) (4-(number_pixels % 4)); bit-=2)
{
pixel=(unsigned char) (((*p) & (1 << (7-bit))) != 0 ? 0x00 : 0x01);
SetPixelGray(image,(Quantum) (pixel != 0 ? 0 : QuantumRange),q);
SetPixelAlpha(image,((*p) & (1UL << (unsigned char) (6-bit))) == 0 ?
TransparentAlpha : OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
if (bit != 0)
p++;
break;
}
case 4:
{
register unsigned char
pixel;
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
pixel=(unsigned char) ((*p >> 4) & 0xf);
SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q);
pixel=(unsigned char) ((*p) & 0xf);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q);
p++;
q+=GetPixelChannels(image);
}
break;
}
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelGray(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelAlpha(image,ScaleCharToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 10:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 12:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGray(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGray(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelGray(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelGray(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelGray(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGray(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportGreenQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleCharToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportIndexQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
MagickBooleanType
range_exception;
register ssize_t
x;
ssize_t
bit;
unsigned int
pixel;
if (image->storage_class != PseudoClass)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ColormappedImageRequired","`%s'",image->filename);
return;
}
range_exception=MagickFalse;
switch (quantum_info->depth)
{
case 1:
{
register unsigned char
pixel;
for (x=0; x < ((ssize_t) number_pixels-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
if (quantum_info->min_is_white == MagickFalse)
pixel=(unsigned char) (((*p) & (1 << (7-bit))) == 0 ?
0x00 : 0x01);
else
pixel=(unsigned char) (((*p) & (1 << (7-bit))) != 0 ?
0x00 : 0x01);
SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),
q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
q+=GetPixelChannels(image);
}
p++;
}
for (bit=0; bit < (ssize_t) (number_pixels % 8); bit++)
{
if (quantum_info->min_is_white == MagickFalse)
pixel=(unsigned char) (((*p) & (1 << (7-bit))) == 0 ? 0x00 : 0x01);
else
pixel=(unsigned char) (((*p) & (1 << (7-bit))) != 0 ? 0x00 : 0x01);
SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
q+=GetPixelChannels(image);
}
break;
}
case 4:
{
register unsigned char
pixel;
for (x=0; x < ((ssize_t) number_pixels-1); x+=2)
{
pixel=(unsigned char) ((*p >> 4) & 0xf);
SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
q+=GetPixelChannels(image);
pixel=(unsigned char) ((*p) & 0xf);
SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
p++;
q+=GetPixelChannels(image);
}
for (bit=0; bit < (ssize_t) (number_pixels % 2); bit++)
{
pixel=(unsigned char) ((*p++ >> 4) & 0xf);
SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
q+=GetPixelChannels(image);
}
break;
}
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelIndex(image,PushColormapIndex(image,ClampToQuantum(
(double) QuantumRange*HalfToSinglePrecision(pixel)),
&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelIndex(image,PushColormapIndex(image,ClampToQuantum(pixel),
&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelIndex(image,PushColormapIndex(image,ClampToQuantum(pixel),
&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
if (range_exception != MagickFalse)
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"InvalidColormapIndex","`%s'",image->filename);
}
static void ImportIndexAlphaQuantum(const Image *image,
QuantumInfo *quantum_info,const MagickSizeType number_pixels,
const unsigned char *magick_restrict p,Quantum *magick_restrict q,
ExceptionInfo *exception)
{
MagickBooleanType
range_exception;
QuantumAny
range;
register ssize_t
x;
ssize_t
bit;
unsigned int
pixel;
if (image->storage_class != PseudoClass)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ColormappedImageRequired","`%s'",image->filename);
return;
}
range_exception=MagickFalse;
switch (quantum_info->depth)
{
case 1:
{
register unsigned char
pixel;
for (x=((ssize_t) number_pixels-3); x > 0; x-=4)
{
for (bit=0; bit < 8; bit+=2)
{
if (quantum_info->min_is_white == MagickFalse)
pixel=(unsigned char) (((*p) & (1 << (7-bit))) == 0 ? 0x00 : 0x01);
else
pixel=(unsigned char) (((*p) & (1 << (7-bit))) != 0 ? 0x00 : 0x01);
SetPixelGray(image,(Quantum) (pixel == 0 ? 0 : QuantumRange),q);
SetPixelAlpha(image,((*p) & (1UL << (unsigned char) (6-bit))) == 0 ?
TransparentAlpha : OpaqueAlpha,q);
SetPixelIndex(image,(Quantum) (pixel == 0 ? 0 : 1),q);
q+=GetPixelChannels(image);
}
}
if ((number_pixels % 4) != 0)
for (bit=3; bit >= (ssize_t) (4-(number_pixels % 4)); bit-=2)
{
if (quantum_info->min_is_white == MagickFalse)
pixel=(unsigned char) (((*p) & (1 << (7-bit))) == 0 ? 0x00 : 0x01);
else
pixel=(unsigned char) (((*p) & (1 << (7-bit))) != 0 ? 0x00 : 0x01);
SetPixelIndex(image,(Quantum) (pixel == 0 ? 0 : 1),q);
SetPixelGray(image,(Quantum) (pixel == 0 ? 0 : QuantumRange),q);
SetPixelAlpha(image,((*p) & (1UL << (unsigned char) (6-bit))) == 0 ?
TransparentAlpha : OpaqueAlpha,q);
q+=GetPixelChannels(image);
}
break;
}
case 4:
{
register unsigned char
pixel;
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
pixel=(unsigned char) ((*p >> 4) & 0xf);
SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
pixel=(unsigned char) ((*p) & 0xf);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q);
p++;
q+=GetPixelChannels(image);
}
break;
}
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
p=PushCharPixel(p,&pixel);
SetPixelAlpha(image,ScaleCharToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelIndex(image,PushColormapIndex(image,ClampToQuantum(
(double) QuantumRange*HalfToSinglePrecision(pixel)),
&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelIndex(image,PushColormapIndex(image,
ClampToQuantum(pixel),&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelIndex(image,PushColormapIndex(image,ClampToQuantum(pixel),
&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelIndex(image,PushColormapIndex(image,pixel,&range_exception),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
GetPixelIndex(image,q),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
if (range_exception != MagickFalse)
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"InvalidColormapIndex","`%s'",image->filename);
}
static void ImportOpacityQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelOpacity(image,ScaleCharToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelOpacity(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelOpacity(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelOpacity(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelOpacity(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelOpacity(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelOpacity(image,ScaleAnyToQuantum(pixel,range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportRedQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleCharToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportRGBQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
ssize_t
bit;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleCharToQuantum(pixel),q);
SetPixelAlpha(image,OpaqueAlpha,q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 10:
{
range=GetQuantumRange(quantum_info->depth);
if (quantum_info->pack == MagickFalse)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum((pixel >> 22) & 0x3ff,range),q);
SetPixelGreen(image,ScaleAnyToQuantum((pixel >> 12) & 0x3ff,range),
q);
SetPixelBlue(image,ScaleAnyToQuantum((pixel >> 2) & 0x3ff,range),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
if (quantum_info->quantum == 32U)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumLongPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumLongPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumLongPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
case 12:
{
range=GetQuantumRange(quantum_info->depth);
if (quantum_info->pack == MagickFalse)
{
unsigned short
pixel;
for (x=0; x < (ssize_t) (3*number_pixels-1); x+=2)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
switch (x % 3)
{
default:
case 0:
{
SetPixelRed(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
break;
}
case 1:
{
SetPixelGreen(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
break;
}
case 2:
{
SetPixelBlue(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
q+=GetPixelChannels(image);
break;
}
}
p=PushShortPixel(quantum_info->endian,p,&pixel);
switch ((x+1) % 3)
{
default:
case 0:
{
SetPixelRed(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
break;
}
case 1:
{
SetPixelGreen(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
break;
}
case 2:
{
SetPixelBlue(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
q+=GetPixelChannels(image);
break;
}
}
p+=quantum_info->pad;
}
for (bit=0; bit < (ssize_t) (3*number_pixels % 2); bit++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
switch ((x+bit) % 3)
{
default:
case 0:
{
SetPixelRed(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
break;
}
case 1:
{
SetPixelGreen(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
break;
}
case 2:
{
SetPixelBlue(image,ScaleAnyToQuantum((QuantumAny) (pixel >> 4),
range),q);
q+=GetPixelChannels(image);
break;
}
}
p+=quantum_info->pad;
}
if (bit != 0)
p++;
break;
}
if (quantum_info->quantum == 32U)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumLongPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumLongPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumLongPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportRGBAQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelAlpha(image,ScaleCharToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 10:
{
pixel=0;
if (quantum_info->pack == MagickFalse)
{
register ssize_t
i;
size_t
quantum;
ssize_t
n;
n=0;
quantum=0;
for (x=0; x < (ssize_t) number_pixels; x++)
{
for (i=0; i < 4; i++)
{
switch (n % 3)
{
case 0:
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 22) & 0x3ff) << 6)));
break;
}
case 1:
{
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 12) & 0x3ff) << 6)));
break;
}
case 2:
{
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 2) & 0x3ff) << 6)));
break;
}
}
switch (i)
{
case 0: SetPixelRed(image,(Quantum) quantum,q); break;
case 1: SetPixelGreen(image,(Quantum) quantum,q); break;
case 2: SetPixelBlue(image,(Quantum) quantum,q); break;
case 3: SetPixelAlpha(image,(Quantum) quantum,q); break;
}
n++;
}
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),
q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),
q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),
q);
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelAlpha(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelAlpha(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
}
}
static void ImportRGBOQuantum(const Image *image,QuantumInfo *quantum_info,
const MagickSizeType number_pixels,const unsigned char *magick_restrict p,
Quantum *magick_restrict q,ExceptionInfo *exception)
{
QuantumAny
range;
register ssize_t
x;
unsigned int
pixel;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
switch (quantum_info->depth)
{
case 8:
{
unsigned char
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushCharPixel(p,&pixel);
SetPixelRed(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelGreen(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelBlue(image,ScaleCharToQuantum(pixel),q);
p=PushCharPixel(p,&pixel);
SetPixelOpacity(image,ScaleCharToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 10:
{
pixel=0;
if (quantum_info->pack == MagickFalse)
{
register ssize_t
i;
size_t
quantum;
ssize_t
n;
n=0;
quantum=0;
for (x=0; x < (ssize_t) number_pixels; x++)
{
for (i=0; i < 4; i++)
{
switch (n % 3)
{
case 0:
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 22) & 0x3ff) << 6)));
break;
}
case 1:
{
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 12) & 0x3ff) << 6)));
break;
}
case 2:
{
quantum=(size_t) (ScaleShortToQuantum((unsigned short)
(((pixel >> 2) & 0x3ff) << 6)));
break;
}
}
switch (i)
{
case 0: SetPixelRed(image,(Quantum) quantum,q); break;
case 1: SetPixelGreen(image,(Quantum) quantum,q); break;
case 2: SetPixelBlue(image,(Quantum) quantum,q); break;
case 3: SetPixelOpacity(image,(Quantum) quantum,q); break;
}
n++;
}
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),
q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),
q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelOpacity(image,ScaleShortToQuantum((unsigned short) (pixel << 6)),
q);
q+=GetPixelChannels(image);
}
break;
}
case 16:
{
unsigned short
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelOpacity(image,ClampToQuantum(QuantumRange*
HalfToSinglePrecision(pixel)),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleShortToQuantum(pixel),q);
p=PushShortPixel(quantum_info->endian,p,&pixel);
SetPixelOpacity(image,ScaleShortToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 32:
{
unsigned int
pixel;
if (quantum_info->format == FloatingPointQuantumFormat)
{
float
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p=PushFloatPixel(quantum_info,p,&pixel);
SetPixelOpacity(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelRed(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelGreen(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelBlue(image,ScaleLongToQuantum(pixel),q);
p=PushLongPixel(quantum_info->endian,p,&pixel);
SetPixelOpacity(image,ScaleLongToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
case 64:
{
if (quantum_info->format == FloatingPointQuantumFormat)
{
double
pixel;
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelRed(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelGreen(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelBlue(image,ClampToQuantum(pixel),q);
p=PushDoublePixel(quantum_info,p,&pixel);
SetPixelOpacity(image,ClampToQuantum(pixel),q);
p+=quantum_info->pad;
q+=GetPixelChannels(image);
}
break;
}
}
default:
{
range=GetQuantumRange(quantum_info->depth);
for (x=0; x < (ssize_t) number_pixels; x++)
{
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelRed(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelGreen(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelBlue(image,ScaleAnyToQuantum(pixel,range),q);
p=PushQuantumPixel(quantum_info,p,&pixel);
SetPixelOpacity(image,ScaleAnyToQuantum(pixel,range),q);
q+=GetPixelChannels(image);
}
break;
}
}
}
MagickExport size_t ImportQuantumPixels(const Image *image,
CacheView *image_view,QuantumInfo *quantum_info,
const QuantumType quantum_type,const unsigned char *magick_restrict pixels,
ExceptionInfo *exception)
{
MagickSizeType
number_pixels;
register const unsigned char
*magick_restrict p;
register ssize_t
x;
register Quantum
*magick_restrict q;
size_t
extent;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickCoreSignature);
if (pixels == (const unsigned char *) NULL)
pixels=(const unsigned char *) GetQuantumPixels(quantum_info);
x=0;
p=pixels;
if (image_view == (CacheView *) NULL)
{
number_pixels=GetImageExtent(image);
q=GetAuthenticPixelQueue(image);
}
else
{
number_pixels=GetCacheViewExtent(image_view);
q=GetCacheViewAuthenticPixelQueue(image_view);
}
ResetQuantumState(quantum_info);
extent=GetQuantumExtent(image,quantum_info,quantum_type);
switch (quantum_type)
{
case AlphaQuantum:
{
ImportAlphaQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case BGRQuantum:
{
ImportBGRQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case BGRAQuantum:
{
ImportBGRAQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case BGROQuantum:
{
ImportBGROQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case BlackQuantum:
{
ImportBlackQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case BlueQuantum:
case YellowQuantum:
{
ImportBlueQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case CMYKQuantum:
{
ImportCMYKQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case CMYKAQuantum:
{
ImportCMYKAQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case CMYKOQuantum:
{
ImportCMYKOQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case CbYCrYQuantum:
{
ImportCbYCrYQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case GrayQuantum:
{
ImportGrayQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case GrayAlphaQuantum:
{
ImportGrayAlphaQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case GreenQuantum:
case MagentaQuantum:
{
ImportGreenQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case IndexQuantum:
{
ImportIndexQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case IndexAlphaQuantum:
{
ImportIndexAlphaQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case OpacityQuantum:
{
ImportOpacityQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case RedQuantum:
case CyanQuantum:
{
ImportRedQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case RGBQuantum:
case CbYCrQuantum:
{
ImportRGBQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case RGBAQuantum:
case CbYCrAQuantum:
{
ImportRGBAQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
case RGBOQuantum:
{
ImportRGBOQuantum(image,quantum_info,number_pixels,p,q,exception);
break;
}
default:
break;
}
if ((quantum_type == CbYCrQuantum) || (quantum_type == CbYCrAQuantum))
{
Quantum
quantum;
register Quantum
*magick_restrict q;
q=GetAuthenticPixelQueue(image);
if (image_view != (CacheView *) NULL)
q=GetCacheViewAuthenticPixelQueue(image_view);
for (x=0; x < (ssize_t) number_pixels; x++)
{
quantum=GetPixelRed(image,q);
SetPixelRed(image,GetPixelGreen(image,q),q);
SetPixelGreen(image,quantum,q);
q+=GetPixelChannels(image);
}
}
if (quantum_info->alpha_type == DisassociatedQuantumAlpha)
{
double
gamma,
Sa;
register Quantum
*magick_restrict q;
/*
Disassociate alpha.
*/
q=GetAuthenticPixelQueue(image);
if (image_view != (CacheView *) NULL)
q=GetCacheViewAuthenticPixelQueue(image_view);
for (x=0; x < (ssize_t) number_pixels; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
Sa=QuantumScale*GetPixelAlpha(image,q);
gamma=PerceptibleReciprocal(Sa);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
if ((channel == AlphaPixelChannel) ||
((traits & UpdatePixelTrait) == 0))
continue;
q[i]=ClampToQuantum(gamma*q[i]);
}
q+=GetPixelChannels(image);
}
}
return(extent);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5314_0 |
crossvul-cpp_data_good_4686_0 |
#include <config.h>
#include "ftpd.h"
#include "utils.h"
#ifdef WITH_DMALLOC
# include <dmalloc.h>
#endif
#ifdef HAVE_LIBSODIUM
# if !defined(pure_memzero) || !defined(pure_memcmp)
# error pure_memzero/pure_memcmp not defined
# endif
#else
void pure_memzero(void * const pnt, const size_t len)
{
# ifdef HAVE_EXPLICIT_BZERO
explicit_bzero(pnt, len);
# else
volatile unsigned char *pnt_ = (volatile unsigned char *) pnt;
size_t i = (size_t) 0U;
while (i < len) {
pnt_[i++] = 0U;
}
# endif
}
int pure_memcmp(const void * const b1_, const void * const b2_, size_t len)
{
const unsigned char *b1 = (const unsigned char *) b1_;
const unsigned char *b2 = (const unsigned char *) b2_;
size_t i;
unsigned char d = (unsigned char) 0U;
for (i = 0U; i < len; i++) {
d |= b1[i] ^ b2[i];
}
return (int) ((1 & ((d - 1) >> 8)) - 1);
}
#endif
int pure_strcmp(const char * const s1, const char * const s2)
{
const size_t s1_len = strlen(s1);
const size_t s2_len = strlen(s2);
if (s1_len != s2_len) {
return -1;
}
return pure_memcmp(s1, s2, s1_len);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4686_0 |
crossvul-cpp_data_good_2644_2 | /*
* Copyright (c) 1990, 1991, 1993, 1994, 1995, 1996, 1997
* 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: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: Cisco HDLC printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "ethertype.h"
#include "extract.h"
#include "chdlc.h"
static void chdlc_slarp_print(netdissect_options *, const u_char *, u_int);
static const struct tok chdlc_cast_values[] = {
{ CHDLC_UNICAST, "unicast" },
{ CHDLC_BCAST, "bcast" },
{ 0, NULL}
};
/* Standard CHDLC printer */
u_int
chdlc_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p)
{
return chdlc_print(ndo, p, h->len);
}
u_int
chdlc_print(netdissect_options *ndo, register const u_char *p, u_int length)
{
u_int proto;
const u_char *bp = p;
if (length < CHDLC_HDRLEN)
goto trunc;
ND_TCHECK2(*p, CHDLC_HDRLEN);
proto = EXTRACT_16BITS(&p[2]);
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "%s, ethertype %s (0x%04x), length %u: ",
tok2str(chdlc_cast_values, "0x%02x", p[0]),
tok2str(ethertype_values, "Unknown", proto),
proto,
length));
}
length -= CHDLC_HDRLEN;
p += CHDLC_HDRLEN;
switch (proto) {
case ETHERTYPE_IP:
ip_print(ndo, p, length);
break;
case ETHERTYPE_IPV6:
ip6_print(ndo, p, length);
break;
case CHDLC_TYPE_SLARP:
chdlc_slarp_print(ndo, p, length);
break;
#if 0
case CHDLC_TYPE_CDP:
chdlc_cdp_print(p, length);
break;
#endif
case ETHERTYPE_MPLS:
case ETHERTYPE_MPLS_MULTI:
mpls_print(ndo, p, length);
break;
case ETHERTYPE_ISO:
/* is the fudge byte set ? lets verify by spotting ISO headers */
if (length < 2)
goto trunc;
ND_TCHECK_16BITS(p);
if (*(p+1) == 0x81 ||
*(p+1) == 0x82 ||
*(p+1) == 0x83)
isoclns_print(ndo, p + 1, length - 1);
else
isoclns_print(ndo, p, length);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "unknown CHDLC protocol (0x%04x)", proto));
break;
}
return (CHDLC_HDRLEN);
trunc:
ND_PRINT((ndo, "[|chdlc]"));
return ndo->ndo_snapend - bp;
}
/*
* The fixed-length portion of a SLARP packet.
*/
struct cisco_slarp {
uint8_t code[4];
#define SLARP_REQUEST 0
#define SLARP_REPLY 1
#define SLARP_KEEPALIVE 2
union {
struct {
uint8_t addr[4];
uint8_t mask[4];
} addr;
struct {
uint8_t myseq[4];
uint8_t yourseq[4];
uint8_t rel[2];
} keep;
} un;
};
#define SLARP_MIN_LEN 14
#define SLARP_MAX_LEN 18
static void
chdlc_slarp_print(netdissect_options *ndo, const u_char *cp, u_int length)
{
const struct cisco_slarp *slarp;
u_int sec,min,hrs,days;
ND_PRINT((ndo, "SLARP (length: %u), ",length));
if (length < SLARP_MIN_LEN)
goto trunc;
slarp = (const struct cisco_slarp *)cp;
ND_TCHECK2(*slarp, SLARP_MIN_LEN);
switch (EXTRACT_32BITS(&slarp->code)) {
case SLARP_REQUEST:
ND_PRINT((ndo, "request"));
/*
* At least according to William "Chops" Westfield's
* message in
*
* http://www.nethelp.no/net/cisco-hdlc.txt
*
* the address and mask aren't used in requests -
* they're just zero.
*/
break;
case SLARP_REPLY:
ND_PRINT((ndo, "reply %s/%s",
ipaddr_string(ndo, &slarp->un.addr.addr),
ipaddr_string(ndo, &slarp->un.addr.mask)));
break;
case SLARP_KEEPALIVE:
ND_PRINT((ndo, "keepalive: mineseen=0x%08x, yourseen=0x%08x, reliability=0x%04x",
EXTRACT_32BITS(&slarp->un.keep.myseq),
EXTRACT_32BITS(&slarp->un.keep.yourseq),
EXTRACT_16BITS(&slarp->un.keep.rel)));
if (length >= SLARP_MAX_LEN) { /* uptime-stamp is optional */
cp += SLARP_MIN_LEN;
ND_TCHECK2(*cp, 4);
sec = EXTRACT_32BITS(cp) / 1000;
min = sec / 60; sec -= min * 60;
hrs = min / 60; min -= hrs * 60;
days = hrs / 24; hrs -= days * 24;
ND_PRINT((ndo, ", link uptime=%ud%uh%um%us",days,hrs,min,sec));
}
break;
default:
ND_PRINT((ndo, "0x%02x unknown", EXTRACT_32BITS(&slarp->code)));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,cp+4,"\n\t",length-4);
break;
}
if (SLARP_MAX_LEN < length && ndo->ndo_vflag)
ND_PRINT((ndo, ", (trailing junk: %d bytes)", length - SLARP_MAX_LEN));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo,cp+4,"\n\t",length-4);
return;
trunc:
ND_PRINT((ndo, "[|slarp]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2644_2 |
crossvul-cpp_data_good_2685_0 | /*
* Copyright (C) 2000, Richard Sharpe
*
* This software may be distributed either under the terms of the
* BSD-style license that accompanies tcpdump or under the GNU GPL
* version 2 or later.
*
* print-beep.c
*
*/
/* \summary: Blocks Extensible Exchange Protocol (BEEP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
/* Check for a string but not go beyond length
* Return TRUE on match, FALSE otherwise
*
* Looks at the first few chars up to tl1 ...
*/
static int
l_strnstart(netdissect_options *ndo, const char *tstr1, u_int tl1,
const char *str2, u_int l2)
{
if (!ND_TTEST2(*str2, tl1)) {
/*
* We don't have tl1 bytes worth of captured data
* for the string, so we can't check for this
* string.
*/
return 0;
}
if (tl1 > l2)
return 0;
return (strncmp(tstr1, str2, tl1) == 0 ? 1 : 0);
}
void
beep_print(netdissect_options *ndo, const u_char *bp, u_int length)
{
if (l_strnstart(ndo, "MSG", 4, (const char *)bp, length)) /* A REQuest */
ND_PRINT((ndo, " BEEP MSG"));
else if (l_strnstart(ndo, "RPY ", 4, (const char *)bp, length))
ND_PRINT((ndo, " BEEP RPY"));
else if (l_strnstart(ndo, "ERR ", 4, (const char *)bp, length))
ND_PRINT((ndo, " BEEP ERR"));
else if (l_strnstart(ndo, "ANS ", 4, (const char *)bp, length))
ND_PRINT((ndo, " BEEP ANS"));
else if (l_strnstart(ndo, "NUL ", 4, (const char *)bp, length))
ND_PRINT((ndo, " BEEP NUL"));
else if (l_strnstart(ndo, "SEQ ", 4, (const char *)bp, length))
ND_PRINT((ndo, " BEEP SEQ"));
else if (l_strnstart(ndo, "END", 4, (const char *)bp, length))
ND_PRINT((ndo, " BEEP END"));
else
ND_PRINT((ndo, " BEEP (payload or undecoded)"));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2685_0 |
crossvul-cpp_data_good_3946_4 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Remote Desktop Gateway (RDG)
*
* Copyright 2015 Denis Vincent <dvincent@devolutions.net>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <assert.h>
#include <winpr/crt.h>
#include <winpr/synch.h>
#include <winpr/print.h>
#include <winpr/stream.h>
#include <winpr/winsock.h>
#include <freerdp/log.h>
#include <freerdp/error.h>
#include <freerdp/utils/ringbuffer.h>
#include "rdg.h"
#include "../proxy.h"
#include "../rdp.h"
#include "../../crypto/opensslcompat.h"
#include "rpc_fault.h"
#define TAG FREERDP_TAG("core.gateway.rdg")
/* HTTP channel response fields present flags. */
#define HTTP_CHANNEL_RESPONSE_FIELD_CHANNELID 0x1
#define HTTP_CHANNEL_RESPONSE_OPTIONAL 0x2
#define HTTP_CHANNEL_RESPONSE_FIELD_UDPPORT 0x4
/* HTTP extended auth. */
#define HTTP_EXTENDED_AUTH_NONE 0x0
#define HTTP_EXTENDED_AUTH_SC 0x1 /* Smart card authentication. */
#define HTTP_EXTENDED_AUTH_PAA 0x02 /* Pluggable authentication. */
#define HTTP_EXTENDED_AUTH_SSPI_NTLM 0x04 /* NTLM extended authentication. */
/* HTTP packet types. */
#define PKT_TYPE_HANDSHAKE_REQUEST 0x1
#define PKT_TYPE_HANDSHAKE_RESPONSE 0x2
#define PKT_TYPE_EXTENDED_AUTH_MSG 0x3
#define PKT_TYPE_TUNNEL_CREATE 0x4
#define PKT_TYPE_TUNNEL_RESPONSE 0x5
#define PKT_TYPE_TUNNEL_AUTH 0x6
#define PKT_TYPE_TUNNEL_AUTH_RESPONSE 0x7
#define PKT_TYPE_CHANNEL_CREATE 0x8
#define PKT_TYPE_CHANNEL_RESPONSE 0x9
#define PKT_TYPE_DATA 0xA
#define PKT_TYPE_SERVICE_MESSAGE 0xB
#define PKT_TYPE_REAUTH_MESSAGE 0xC
#define PKT_TYPE_KEEPALIVE 0xD
#define PKT_TYPE_CLOSE_CHANNEL 0x10
#define PKT_TYPE_CLOSE_CHANNEL_RESPONSE 0x11
/* HTTP tunnel auth fields present flags. */
#define HTTP_TUNNEL_AUTH_FIELD_SOH 0x1
/* HTTP tunnel auth response fields present flags. */
#define HTTP_TUNNEL_AUTH_RESPONSE_FIELD_REDIR_FLAGS 0x1
#define HTTP_TUNNEL_AUTH_RESPONSE_FIELD_IDLE_TIMEOUT 0x2
#define HTTP_TUNNEL_AUTH_RESPONSE_FIELD_SOH_RESPONSE 0x4
/* HTTP tunnel packet fields present flags. */
#define HTTP_TUNNEL_PACKET_FIELD_PAA_COOKIE 0x1
#define HTTP_TUNNEL_PACKET_FIELD_REAUTH 0x2
/* HTTP tunnel redir flags. */
#define HTTP_TUNNEL_REDIR_ENABLE_ALL 0x80000000
#define HTTP_TUNNEL_REDIR_DISABLE_ALL 0x40000000
#define HTTP_TUNNEL_REDIR_DISABLE_DRIVE 0x1
#define HTTP_TUNNEL_REDIR_DISABLE_PRINTER 0x2
#define HTTP_TUNNEL_REDIR_DISABLE_PORT 0x4
#define HTTP_TUNNEL_REDIR_DISABLE_CLIPBOARD 0x8
#define HTTP_TUNNEL_REDIR_DISABLE_PNP 0x10
/* HTTP tunnel response fields present flags. */
#define HTTP_TUNNEL_RESPONSE_FIELD_TUNNEL_ID 0x1
#define HTTP_TUNNEL_RESPONSE_FIELD_CAPS 0x2
#define HTTP_TUNNEL_RESPONSE_FIELD_SOH_REQ 0x4
#define HTTP_TUNNEL_RESPONSE_FIELD_CONSENT_MSG 0x10
/* HTTP capability type enumeration. */
#define HTTP_CAPABILITY_TYPE_QUAR_SOH 0x1
#define HTTP_CAPABILITY_IDLE_TIMEOUT 0x2
#define HTTP_CAPABILITY_MESSAGING_CONSENT_SIGN 0x4
#define HTTP_CAPABILITY_MESSAGING_SERVICE_MSG 0x8
#define HTTP_CAPABILITY_REAUTH 0x10
#define HTTP_CAPABILITY_UDP_TRANSPORT 0x20
struct rdp_rdg
{
rdpContext* context;
rdpSettings* settings;
BOOL attached;
BIO* frontBio;
rdpTls* tlsIn;
rdpTls* tlsOut;
rdpNtlm* ntlm;
HttpContext* http;
CRITICAL_SECTION writeSection;
UUID guid;
int state;
UINT16 packetRemainingCount;
UINT16 reserved1;
int timeout;
UINT16 extAuth;
UINT16 reserved2;
};
enum
{
RDG_CLIENT_STATE_INITIAL,
RDG_CLIENT_STATE_HANDSHAKE,
RDG_CLIENT_STATE_TUNNEL_CREATE,
RDG_CLIENT_STATE_TUNNEL_AUTHORIZE,
RDG_CLIENT_STATE_CHANNEL_CREATE,
RDG_CLIENT_STATE_OPENED,
};
#pragma pack(push, 1)
typedef struct rdg_packet_header
{
UINT16 type;
UINT16 reserved;
UINT32 packetLength;
} RdgPacketHeader;
#pragma pack(pop)
typedef struct
{
UINT32 code;
const char* name;
} t_err_mapping;
static const t_err_mapping tunnel_response_fields_present[] = {
{ HTTP_TUNNEL_RESPONSE_FIELD_TUNNEL_ID, "HTTP_TUNNEL_RESPONSE_FIELD_TUNNEL_ID" },
{ HTTP_TUNNEL_RESPONSE_FIELD_CAPS, "HTTP_TUNNEL_RESPONSE_FIELD_CAPS" },
{ HTTP_TUNNEL_RESPONSE_FIELD_SOH_REQ, "HTTP_TUNNEL_RESPONSE_FIELD_SOH_REQ" },
{ HTTP_TUNNEL_RESPONSE_FIELD_CONSENT_MSG, "HTTP_TUNNEL_RESPONSE_FIELD_CONSENT_MSG" }
};
static const t_err_mapping channel_response_fields_present[] = {
{ HTTP_CHANNEL_RESPONSE_FIELD_CHANNELID, "HTTP_CHANNEL_RESPONSE_FIELD_CHANNELID" },
{ HTTP_CHANNEL_RESPONSE_OPTIONAL, "HTTP_CHANNEL_RESPONSE_OPTIONAL" },
{ HTTP_CHANNEL_RESPONSE_FIELD_UDPPORT, "HTTP_CHANNEL_RESPONSE_FIELD_UDPPORT" }
};
static const t_err_mapping tunnel_authorization_response_fields_present[] = {
{ HTTP_TUNNEL_AUTH_RESPONSE_FIELD_REDIR_FLAGS, "HTTP_TUNNEL_AUTH_RESPONSE_FIELD_REDIR_FLAGS" },
{ HTTP_TUNNEL_AUTH_RESPONSE_FIELD_IDLE_TIMEOUT,
"HTTP_TUNNEL_AUTH_RESPONSE_FIELD_IDLE_TIMEOUT" },
{ HTTP_TUNNEL_AUTH_RESPONSE_FIELD_SOH_RESPONSE,
"HTTP_TUNNEL_AUTH_RESPONSE_FIELD_SOH_RESPONSE" }
};
static const t_err_mapping extended_auth[] = {
{ HTTP_EXTENDED_AUTH_NONE, "HTTP_EXTENDED_AUTH_NONE" },
{ HTTP_EXTENDED_AUTH_SC, "HTTP_EXTENDED_AUTH_SC" },
{ HTTP_EXTENDED_AUTH_PAA, "HTTP_EXTENDED_AUTH_PAA" },
{ HTTP_EXTENDED_AUTH_SSPI_NTLM, "HTTP_EXTENDED_AUTH_SSPI_NTLM" }
};
static const char* fields_present_to_string(UINT16 fieldsPresent, const t_err_mapping* map,
size_t elements)
{
size_t x = 0;
static char buffer[1024] = { 0 };
char fields[12];
memset(buffer, 0, sizeof(buffer));
for (x = 0; x < elements; x++)
{
if (buffer[0] != '\0')
strcat(buffer, "|");
if ((map[x].code & fieldsPresent) != 0)
strcat(buffer, map[x].name);
}
sprintf_s(fields, ARRAYSIZE(fields), " [%04" PRIx16 "]", fieldsPresent);
strcat(buffer, fields);
return buffer;
}
static const char* channel_response_fields_present_to_string(UINT16 fieldsPresent)
{
return fields_present_to_string(fieldsPresent, channel_response_fields_present,
ARRAYSIZE(channel_response_fields_present));
}
static const char* tunnel_response_fields_present_to_string(UINT16 fieldsPresent)
{
return fields_present_to_string(fieldsPresent, tunnel_response_fields_present,
ARRAYSIZE(tunnel_response_fields_present));
}
static const char* tunnel_authorization_response_fields_present_to_string(UINT16 fieldsPresent)
{
return fields_present_to_string(fieldsPresent, tunnel_authorization_response_fields_present,
ARRAYSIZE(tunnel_authorization_response_fields_present));
}
static const char* extended_auth_to_string(UINT16 auth)
{
if (auth == HTTP_EXTENDED_AUTH_NONE)
return "HTTP_EXTENDED_AUTH_NONE [0x0000]";
return fields_present_to_string(auth, extended_auth, ARRAYSIZE(extended_auth));
}
static BOOL rdg_write_packet(rdpRdg* rdg, wStream* sPacket)
{
size_t s;
int status;
wStream* sChunk;
char chunkSize[11];
sprintf_s(chunkSize, sizeof(chunkSize), "%" PRIXz "\r\n", Stream_Length(sPacket));
sChunk = Stream_New(NULL, strnlen(chunkSize, sizeof(chunkSize)) + Stream_Length(sPacket) + 2);
if (!sChunk)
return FALSE;
Stream_Write(sChunk, chunkSize, strnlen(chunkSize, sizeof(chunkSize)));
Stream_Write(sChunk, Stream_Buffer(sPacket), Stream_Length(sPacket));
Stream_Write(sChunk, "\r\n", 2);
Stream_SealLength(sChunk);
s = Stream_Length(sChunk);
if (s > INT_MAX)
return FALSE;
status = tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), (int)s);
Stream_Free(sChunk, TRUE);
if (status < 0)
return FALSE;
return TRUE;
}
static BOOL rdg_read_all(rdpTls* tls, BYTE* buffer, int size)
{
int status;
int readCount = 0;
BYTE* pBuffer = buffer;
while (readCount < size)
{
status = BIO_read(tls->bio, pBuffer, size - readCount);
if (status <= 0)
{
if (!BIO_should_retry(tls->bio))
return FALSE;
continue;
}
readCount += status;
pBuffer += status;
}
return TRUE;
}
static wStream* rdg_receive_packet(rdpRdg* rdg)
{
wStream* s;
const size_t header = sizeof(RdgPacketHeader);
size_t packetLength;
assert(header <= INT_MAX);
s = Stream_New(NULL, 1024);
if (!s)
return NULL;
if (!rdg_read_all(rdg->tlsOut, Stream_Buffer(s), header))
{
Stream_Free(s, TRUE);
return NULL;
}
Stream_Seek(s, 4);
Stream_Read_UINT32(s, packetLength);
if ((packetLength > INT_MAX) || !Stream_EnsureCapacity(s, packetLength) ||
(packetLength < header))
{
Stream_Free(s, TRUE);
return NULL;
}
if (!rdg_read_all(rdg->tlsOut, Stream_Buffer(s) + header, (int)packetLength - (int)header))
{
Stream_Free(s, TRUE);
return NULL;
}
Stream_SetLength(s, packetLength);
return s;
}
static BOOL rdg_send_handshake(rdpRdg* rdg)
{
wStream* s;
BOOL status;
s = Stream_New(NULL, 14);
if (!s)
return FALSE;
Stream_Write_UINT16(s, PKT_TYPE_HANDSHAKE_REQUEST); /* Type (2 bytes) */
Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */
Stream_Write_UINT32(s, 14); /* PacketLength (4 bytes) */
Stream_Write_UINT8(s, 1); /* VersionMajor (1 byte) */
Stream_Write_UINT8(s, 0); /* VersionMinor (1 byte) */
Stream_Write_UINT16(s, 0); /* ClientVersion (2 bytes), must be 0 */
Stream_Write_UINT16(s, rdg->extAuth); /* ExtendedAuthentication (2 bytes) */
Stream_SealLength(s);
status = rdg_write_packet(rdg, s);
Stream_Free(s, TRUE);
if (status)
{
rdg->state = RDG_CLIENT_STATE_HANDSHAKE;
}
return status;
}
static BOOL rdg_send_tunnel_request(rdpRdg* rdg)
{
wStream* s;
BOOL status;
UINT32 packetSize = 16;
UINT16 fieldsPresent = 0;
WCHAR* PAACookie = NULL;
int PAACookieLen = 0;
if (rdg->extAuth == HTTP_EXTENDED_AUTH_PAA)
{
PAACookieLen =
ConvertToUnicode(CP_UTF8, 0, rdg->settings->GatewayAccessToken, -1, &PAACookie, 0);
if (!PAACookie || (PAACookieLen < 0) || (PAACookieLen > UINT16_MAX / 2))
{
free(PAACookie);
return FALSE;
}
packetSize += 2 + (UINT32)PAACookieLen * sizeof(WCHAR);
fieldsPresent = HTTP_TUNNEL_PACKET_FIELD_PAA_COOKIE;
}
s = Stream_New(NULL, packetSize);
if (!s)
{
free(PAACookie);
return FALSE;
}
Stream_Write_UINT16(s, PKT_TYPE_TUNNEL_CREATE); /* Type (2 bytes) */
Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */
Stream_Write_UINT32(s, packetSize); /* PacketLength (4 bytes) */
Stream_Write_UINT32(s, HTTP_CAPABILITY_TYPE_QUAR_SOH); /* CapabilityFlags (4 bytes) */
Stream_Write_UINT16(s, fieldsPresent); /* FieldsPresent (2 bytes) */
Stream_Write_UINT16(s, 0); /* Reserved (2 bytes), must be 0 */
if (PAACookie)
{
Stream_Write_UINT16(s, (UINT16)PAACookieLen * 2); /* PAA cookie string length */
Stream_Write_UTF16_String(s, PAACookie, (size_t)PAACookieLen);
}
Stream_SealLength(s);
status = rdg_write_packet(rdg, s);
Stream_Free(s, TRUE);
free(PAACookie);
if (status)
{
rdg->state = RDG_CLIENT_STATE_TUNNEL_CREATE;
}
return status;
}
static BOOL rdg_send_tunnel_authorization(rdpRdg* rdg)
{
wStream* s;
BOOL status;
WCHAR* clientName = NULL;
UINT32 packetSize;
int clientNameLen =
ConvertToUnicode(CP_UTF8, 0, rdg->settings->ClientHostname, -1, &clientName, 0);
if (!clientName || (clientNameLen < 0) || (clientNameLen > UINT16_MAX / 2))
{
free(clientName);
return FALSE;
}
packetSize = 12 + (UINT32)clientNameLen * sizeof(WCHAR);
s = Stream_New(NULL, packetSize);
if (!s)
{
free(clientName);
return FALSE;
}
Stream_Write_UINT16(s, PKT_TYPE_TUNNEL_AUTH); /* Type (2 bytes) */
Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */
Stream_Write_UINT32(s, packetSize); /* PacketLength (4 bytes) */
Stream_Write_UINT16(s, 0); /* FieldsPresent (2 bytes) */
Stream_Write_UINT16(s, (UINT16)clientNameLen * 2); /* Client name string length */
Stream_Write_UTF16_String(s, clientName, (size_t)clientNameLen);
Stream_SealLength(s);
status = rdg_write_packet(rdg, s);
Stream_Free(s, TRUE);
free(clientName);
if (status)
{
rdg->state = RDG_CLIENT_STATE_TUNNEL_AUTHORIZE;
}
return status;
}
static BOOL rdg_send_channel_create(rdpRdg* rdg)
{
wStream* s = NULL;
BOOL status = FALSE;
WCHAR* serverName = NULL;
int serverNameLen =
ConvertToUnicode(CP_UTF8, 0, rdg->settings->ServerHostname, -1, &serverName, 0);
UINT32 packetSize = 16 + ((UINT32)serverNameLen) * 2;
if ((serverNameLen < 0) || (serverNameLen > UINT16_MAX / 2))
goto fail;
s = Stream_New(NULL, packetSize);
if (!s)
goto fail;
Stream_Write_UINT16(s, PKT_TYPE_CHANNEL_CREATE); /* Type (2 bytes) */
Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */
Stream_Write_UINT32(s, packetSize); /* PacketLength (4 bytes) */
Stream_Write_UINT8(s, 1); /* Number of resources. (1 byte) */
Stream_Write_UINT8(s, 0); /* Number of alternative resources (1 byte) */
Stream_Write_UINT16(s, (UINT16)rdg->settings->ServerPort); /* Resource port (2 bytes) */
Stream_Write_UINT16(s, 3); /* Protocol number (2 bytes) */
Stream_Write_UINT16(s, (UINT16)serverNameLen * 2);
Stream_Write_UTF16_String(s, serverName, (size_t)serverNameLen);
Stream_SealLength(s);
status = rdg_write_packet(rdg, s);
fail:
free(serverName);
Stream_Free(s, TRUE);
if (status)
rdg->state = RDG_CLIENT_STATE_CHANNEL_CREATE;
return status;
}
static BOOL rdg_set_ntlm_auth_header(rdpNtlm* ntlm, HttpRequest* request)
{
const SecBuffer* ntlmToken = ntlm_client_get_output_buffer(ntlm);
char* base64NtlmToken = NULL;
if (ntlmToken)
{
if (ntlmToken->cbBuffer > INT_MAX)
return FALSE;
base64NtlmToken = crypto_base64_encode(ntlmToken->pvBuffer, (int)ntlmToken->cbBuffer);
}
if (base64NtlmToken)
{
BOOL rc = http_request_set_auth_scheme(request, "NTLM") &&
http_request_set_auth_param(request, base64NtlmToken);
free(base64NtlmToken);
if (!rc)
return FALSE;
}
return TRUE;
}
static wStream* rdg_build_http_request(rdpRdg* rdg, const char* method,
const char* transferEncoding)
{
wStream* s = NULL;
HttpRequest* request = NULL;
const char* uri;
if (!rdg || !method)
return NULL;
uri = http_context_get_uri(rdg->http);
request = http_request_new();
if (!request)
return NULL;
if (!http_request_set_method(request, method) || !http_request_set_uri(request, uri))
goto out;
if (rdg->ntlm)
{
if (!rdg_set_ntlm_auth_header(rdg->ntlm, request))
goto out;
}
if (transferEncoding)
{
http_request_set_transfer_encoding(request, transferEncoding);
}
s = http_request_write(rdg->http, request);
out:
http_request_free(request);
if (s)
Stream_SealLength(s);
return s;
}
static BOOL rdg_handle_ntlm_challenge(rdpNtlm* ntlm, HttpResponse* response)
{
BOOL continueNeeded = FALSE;
size_t len;
const char* token64 = NULL;
int ntlmTokenLength = 0;
BYTE* ntlmTokenData = NULL;
long StatusCode;
if (!ntlm || !response)
return FALSE;
StatusCode = http_response_get_status_code(response);
if (StatusCode != HTTP_STATUS_DENIED)
{
WLog_DBG(TAG, "Unexpected NTLM challenge HTTP status: %ld", StatusCode);
return FALSE;
}
token64 = http_response_get_auth_token(response, "NTLM");
if (!token64)
return FALSE;
len = strlen(token64);
if (len > INT_MAX)
return FALSE;
crypto_base64_decode(token64, (int)len, &ntlmTokenData, &ntlmTokenLength);
if (ntlmTokenLength < 0)
{
free(ntlmTokenData);
return FALSE;
}
if (ntlmTokenData && ntlmTokenLength)
{
if (!ntlm_client_set_input_buffer(ntlm, FALSE, ntlmTokenData, (size_t)ntlmTokenLength))
return FALSE;
}
if (!ntlm_authenticate(ntlm, &continueNeeded))
return FALSE;
if (continueNeeded)
return FALSE;
return TRUE;
}
static BOOL rdg_skip_seed_payload(rdpTls* tls, SSIZE_T lastResponseLength)
{
BYTE seed_payload[10];
const size_t size = sizeof(seed_payload);
assert(size < SSIZE_MAX);
/* Per [MS-TSGU] 3.3.5.1 step 4, after final OK response RDG server sends
* random "seed" payload of limited size. In practice it's 10 bytes.
*/
if (lastResponseLength < (SSIZE_T)size)
{
if (!rdg_read_all(tls, seed_payload, size - lastResponseLength))
{
return FALSE;
}
}
return TRUE;
}
static BOOL rdg_process_handshake_response(rdpRdg* rdg, wStream* s)
{
UINT32 errorCode;
UINT16 serverVersion, extendedAuth;
BYTE verMajor, verMinor;
const char* error;
WLog_DBG(TAG, "Handshake response received");
if (rdg->state != RDG_CLIENT_STATE_HANDSHAKE)
{
return FALSE;
}
if (Stream_GetRemainingLength(s) < 10)
{
WLog_ERR(TAG, "[%s] Short packet %" PRIuz ", expected 10", __FUNCTION__,
Stream_GetRemainingLength(s));
return FALSE;
}
Stream_Read_UINT32(s, errorCode);
Stream_Read_UINT8(s, verMajor);
Stream_Read_UINT8(s, verMinor);
Stream_Read_UINT16(s, serverVersion);
Stream_Read_UINT16(s, extendedAuth);
error = rpc_error_to_string(errorCode);
WLog_DBG(TAG,
"errorCode=%s, verMajor=%" PRId8 ", verMinor=%" PRId8 ", serverVersion=%" PRId16
", extendedAuth=%s",
error, verMajor, verMinor, serverVersion, extended_auth_to_string(extendedAuth));
if (FAILED(errorCode))
{
WLog_ERR(TAG, "Handshake error %s", error);
freerdp_set_last_error_log(rdg->context, errorCode);
return FALSE;
}
return rdg_send_tunnel_request(rdg);
}
static BOOL rdg_process_tunnel_response(rdpRdg* rdg, wStream* s)
{
UINT16 serverVersion, fieldsPresent;
UINT32 errorCode;
const char* error;
WLog_DBG(TAG, "Tunnel response received");
if (rdg->state != RDG_CLIENT_STATE_TUNNEL_CREATE)
{
return FALSE;
}
if (Stream_GetRemainingLength(s) < 10)
{
WLog_ERR(TAG, "[%s] Short packet %" PRIuz ", expected 10", __FUNCTION__,
Stream_GetRemainingLength(s));
return FALSE;
}
Stream_Read_UINT16(s, serverVersion);
Stream_Read_UINT32(s, errorCode);
Stream_Read_UINT16(s, fieldsPresent);
Stream_Seek_UINT16(s); /* reserved */
error = rpc_error_to_string(errorCode);
WLog_DBG(TAG, "serverVersion=%" PRId16 ", errorCode=%s, fieldsPresent=%s", serverVersion, error,
tunnel_response_fields_present_to_string(fieldsPresent));
if (FAILED(errorCode))
{
WLog_ERR(TAG, "Tunnel creation error %s", error);
freerdp_set_last_error_log(rdg->context, errorCode);
return FALSE;
}
return rdg_send_tunnel_authorization(rdg);
}
static BOOL rdg_process_tunnel_authorization_response(rdpRdg* rdg, wStream* s)
{
UINT32 errorCode;
UINT16 fieldsPresent;
const char* error;
WLog_DBG(TAG, "Tunnel authorization received");
if (rdg->state != RDG_CLIENT_STATE_TUNNEL_AUTHORIZE)
{
return FALSE;
}
if (Stream_GetRemainingLength(s) < 8)
{
WLog_ERR(TAG, "[%s] Short packet %" PRIuz ", expected 8", __FUNCTION__,
Stream_GetRemainingLength(s));
return FALSE;
}
Stream_Read_UINT32(s, errorCode);
Stream_Read_UINT16(s, fieldsPresent);
Stream_Seek_UINT16(s); /* reserved */
error = rpc_error_to_string(errorCode);
WLog_DBG(TAG, "errorCode=%s, fieldsPresent=%s", error,
tunnel_authorization_response_fields_present_to_string(fieldsPresent));
if (FAILED(errorCode))
{
WLog_ERR(TAG, "Tunnel authorization error %s", error);
freerdp_set_last_error_log(rdg->context, errorCode);
return FALSE;
}
return rdg_send_channel_create(rdg);
}
static BOOL rdg_process_channel_response(rdpRdg* rdg, wStream* s)
{
UINT16 fieldsPresent;
UINT32 errorCode;
const char* error;
WLog_DBG(TAG, "Channel response received");
if (rdg->state != RDG_CLIENT_STATE_CHANNEL_CREATE)
{
return FALSE;
}
if (Stream_GetRemainingLength(s) < 8)
{
WLog_ERR(TAG, "[%s] Short packet %" PRIuz ", expected 8", __FUNCTION__,
Stream_GetRemainingLength(s));
return FALSE;
}
Stream_Read_UINT32(s, errorCode);
Stream_Read_UINT16(s, fieldsPresent);
Stream_Seek_UINT16(s); /* reserved */
error = rpc_error_to_string(errorCode);
WLog_DBG(TAG, "channel response errorCode=%s, fieldsPresent=%s", error,
channel_response_fields_present_to_string(fieldsPresent));
if (FAILED(errorCode))
{
WLog_ERR(TAG, "channel response errorCode=%s, fieldsPresent=%s", error,
channel_response_fields_present_to_string(fieldsPresent));
freerdp_set_last_error_log(rdg->context, errorCode);
return FALSE;
}
rdg->state = RDG_CLIENT_STATE_OPENED;
return TRUE;
}
static BOOL rdg_process_packet(rdpRdg* rdg, wStream* s)
{
BOOL status = TRUE;
UINT16 type;
UINT32 packetLength;
Stream_SetPosition(s, 0);
if (Stream_GetRemainingLength(s) < 8)
{
WLog_ERR(TAG, "[%s] Short packet %" PRIuz ", expected 8", __FUNCTION__,
Stream_GetRemainingLength(s));
return FALSE;
}
Stream_Read_UINT16(s, type);
Stream_Seek_UINT16(s); /* reserved */
Stream_Read_UINT32(s, packetLength);
if (Stream_Length(s) < packetLength)
{
WLog_ERR(TAG, "[%s] Short packet %" PRIuz ", expected %" PRIuz, __FUNCTION__,
Stream_Length(s), packetLength);
return FALSE;
}
switch (type)
{
case PKT_TYPE_HANDSHAKE_RESPONSE:
status = rdg_process_handshake_response(rdg, s);
break;
case PKT_TYPE_TUNNEL_RESPONSE:
status = rdg_process_tunnel_response(rdg, s);
break;
case PKT_TYPE_TUNNEL_AUTH_RESPONSE:
status = rdg_process_tunnel_authorization_response(rdg, s);
break;
case PKT_TYPE_CHANNEL_RESPONSE:
status = rdg_process_channel_response(rdg, s);
break;
case PKT_TYPE_DATA:
WLog_ERR(TAG, "[%s] Unexpected packet type DATA", __FUNCTION__);
return FALSE;
}
return status;
}
DWORD rdg_get_event_handles(rdpRdg* rdg, HANDLE* events, DWORD count)
{
DWORD nCount = 0;
assert(rdg != NULL);
if (rdg->tlsOut && rdg->tlsOut->bio)
{
if (events && (nCount < count))
{
BIO_get_event(rdg->tlsOut->bio, &events[nCount]);
nCount++;
}
else
return 0;
}
if (rdg->tlsIn && rdg->tlsIn->bio)
{
if (events && (nCount < count))
{
BIO_get_event(rdg->tlsIn->bio, &events[nCount]);
nCount++;
}
else
return 0;
}
return nCount;
}
static BOOL rdg_get_gateway_credentials(rdpContext* context)
{
rdpSettings* settings = context->settings;
freerdp* instance = context->instance;
if (!settings->GatewayPassword || !settings->GatewayUsername ||
!strlen(settings->GatewayPassword) || !strlen(settings->GatewayUsername))
{
if (freerdp_shall_disconnect(instance))
return FALSE;
if (!instance->GatewayAuthenticate)
{
freerdp_set_last_error_log(context, FREERDP_ERROR_CONNECT_NO_OR_MISSING_CREDENTIALS);
return FALSE;
}
else
{
BOOL proceed =
instance->GatewayAuthenticate(instance, &settings->GatewayUsername,
&settings->GatewayPassword, &settings->GatewayDomain);
if (!proceed)
{
freerdp_set_last_error_log(context,
FREERDP_ERROR_CONNECT_NO_OR_MISSING_CREDENTIALS);
return FALSE;
}
if (settings->GatewayUseSameCredentials)
{
if (settings->GatewayUsername)
{
free(settings->Username);
if (!(settings->Username = _strdup(settings->GatewayUsername)))
return FALSE;
}
if (settings->GatewayDomain)
{
free(settings->Domain);
if (!(settings->Domain = _strdup(settings->GatewayDomain)))
return FALSE;
}
if (settings->GatewayPassword)
{
free(settings->Password);
if (!(settings->Password = _strdup(settings->GatewayPassword)))
return FALSE;
}
}
}
}
return TRUE;
}
static BOOL rdg_ntlm_init(rdpRdg* rdg, rdpTls* tls)
{
BOOL continueNeeded = FALSE;
rdpContext* context = rdg->context;
rdpSettings* settings = context->settings;
rdg->ntlm = ntlm_new();
if (!rdg->ntlm)
return FALSE;
if (!rdg_get_gateway_credentials(context))
return FALSE;
if (!ntlm_client_init(rdg->ntlm, TRUE, settings->GatewayUsername, settings->GatewayDomain,
settings->GatewayPassword, tls->Bindings))
return FALSE;
if (!ntlm_client_make_spn(rdg->ntlm, _T("HTTP"), settings->GatewayHostname))
return FALSE;
if (!ntlm_authenticate(rdg->ntlm, &continueNeeded))
return FALSE;
return continueNeeded;
}
static BOOL rdg_send_http_request(rdpRdg* rdg, rdpTls* tls, const char* method,
const char* transferEncoding)
{
size_t sz;
wStream* s = NULL;
int status = -1;
s = rdg_build_http_request(rdg, method, transferEncoding);
if (!s)
return FALSE;
sz = Stream_Length(s);
if (sz <= INT_MAX)
status = tls_write_all(tls, Stream_Buffer(s), (int)sz);
Stream_Free(s, TRUE);
return (status >= 0);
}
static BOOL rdg_tls_connect(rdpRdg* rdg, rdpTls* tls, const char* peerAddress, int timeout)
{
int sockfd = 0;
long status = 0;
BIO* socketBio = NULL;
BIO* bufferedBio = NULL;
rdpSettings* settings = rdg->settings;
const char* peerHostname = settings->GatewayHostname;
UINT16 peerPort = (UINT16)settings->GatewayPort;
const char *proxyUsername, *proxyPassword;
BOOL isProxyConnection =
proxy_prepare(settings, &peerHostname, &peerPort, &proxyUsername, &proxyPassword);
if (settings->GatewayPort > UINT16_MAX)
return FALSE;
sockfd = freerdp_tcp_connect(rdg->context, settings, peerAddress ? peerAddress : peerHostname,
peerPort, timeout);
if (sockfd < 0)
{
return FALSE;
}
socketBio = BIO_new(BIO_s_simple_socket());
if (!socketBio)
{
closesocket((SOCKET)sockfd);
return FALSE;
}
BIO_set_fd(socketBio, sockfd, BIO_CLOSE);
bufferedBio = BIO_new(BIO_s_buffered_socket());
if (!bufferedBio)
{
BIO_free_all(socketBio);
return FALSE;
}
bufferedBio = BIO_push(bufferedBio, socketBio);
status = BIO_set_nonblock(bufferedBio, TRUE);
if (isProxyConnection)
{
if (!proxy_connect(settings, bufferedBio, proxyUsername, proxyPassword,
settings->GatewayHostname, (UINT16)settings->GatewayPort))
{
BIO_free_all(bufferedBio);
return FALSE;
}
}
if (!status)
{
BIO_free_all(bufferedBio);
return FALSE;
}
tls->hostname = settings->GatewayHostname;
tls->port = (int)settings->GatewayPort;
tls->isGatewayTransport = TRUE;
status = tls_connect(tls, bufferedBio);
if (status < 1)
{
rdpContext* context = rdg->context;
if (status < 0)
{
freerdp_set_last_error_if_not(context, FREERDP_ERROR_TLS_CONNECT_FAILED);
}
else
{
freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_CANCELLED);
}
return FALSE;
}
return (status >= 1);
}
static BOOL rdg_establish_data_connection(rdpRdg* rdg, rdpTls* tls, const char* method,
const char* peerAddress, int timeout, BOOL* rpcFallback)
{
HttpResponse* response = NULL;
long statusCode;
SSIZE_T bodyLength;
long StatusCode;
if (!rdg_tls_connect(rdg, tls, peerAddress, timeout))
return FALSE;
if (rdg->extAuth == HTTP_EXTENDED_AUTH_NONE)
{
if (!rdg_ntlm_init(rdg, tls))
return FALSE;
if (!rdg_send_http_request(rdg, tls, method, NULL))
return FALSE;
response = http_response_recv(tls, TRUE);
if (!response)
return FALSE;
StatusCode = http_response_get_status_code(response);
switch (StatusCode)
{
case HTTP_STATUS_NOT_FOUND:
{
WLog_INFO(TAG, "RD Gateway does not support HTTP transport.");
if (rpcFallback)
*rpcFallback = TRUE;
http_response_free(response);
return FALSE;
}
default:
break;
}
if (!rdg_handle_ntlm_challenge(rdg->ntlm, response))
{
http_response_free(response);
return FALSE;
}
http_response_free(response);
}
if (!rdg_send_http_request(rdg, tls, method, NULL))
return FALSE;
ntlm_free(rdg->ntlm);
rdg->ntlm = NULL;
response = http_response_recv(tls, TRUE);
if (!response)
return FALSE;
statusCode = http_response_get_status_code(response);
bodyLength = http_response_get_body_length(response);
http_response_free(response);
WLog_DBG(TAG, "%s authorization result: %d", method, statusCode);
switch (statusCode)
{
case HTTP_STATUS_OK:
break;
case HTTP_STATUS_DENIED:
freerdp_set_last_error_log(rdg->context, FREERDP_ERROR_CONNECT_ACCESS_DENIED);
return FALSE;
default:
return FALSE;
}
if (strcmp(method, "RDG_OUT_DATA") == 0)
{
if (!rdg_skip_seed_payload(tls, bodyLength))
return FALSE;
}
else
{
if (!rdg_send_http_request(rdg, tls, method, "chunked"))
return FALSE;
}
return TRUE;
}
static BOOL rdg_tunnel_connect(rdpRdg* rdg)
{
BOOL status;
wStream* s;
rdg_send_handshake(rdg);
while (rdg->state < RDG_CLIENT_STATE_OPENED)
{
status = FALSE;
s = rdg_receive_packet(rdg);
if (s)
{
status = rdg_process_packet(rdg, s);
Stream_Free(s, TRUE);
}
if (!status)
{
rdg->context->rdp->transport->layer = TRANSPORT_LAYER_CLOSED;
return FALSE;
}
}
return TRUE;
}
BOOL rdg_connect(rdpRdg* rdg, int timeout, BOOL* rpcFallback)
{
BOOL status;
SOCKET outConnSocket = 0;
char* peerAddress = NULL;
assert(rdg != NULL);
status =
rdg_establish_data_connection(rdg, rdg->tlsOut, "RDG_OUT_DATA", NULL, timeout, rpcFallback);
if (status)
{
/* Establish IN connection with the same peer/server as OUT connection,
* even when server hostname resolves to different IP addresses.
*/
BIO_get_socket(rdg->tlsOut->underlying, &outConnSocket);
peerAddress = freerdp_tcp_get_peer_address(outConnSocket);
status = rdg_establish_data_connection(rdg, rdg->tlsIn, "RDG_IN_DATA", peerAddress, timeout,
NULL);
free(peerAddress);
}
if (!status)
{
rdg->context->rdp->transport->layer = TRANSPORT_LAYER_CLOSED;
return FALSE;
}
status = rdg_tunnel_connect(rdg);
if (!status)
return FALSE;
return TRUE;
}
static int rdg_write_data_packet(rdpRdg* rdg, const BYTE* buf, int isize)
{
int status;
size_t s;
wStream* sChunk;
size_t size = (size_t)isize;
size_t packetSize = size + 10;
char chunkSize[11];
if ((isize < 0) || (isize > UINT16_MAX))
return -1;
if (size < 1)
return 0;
sprintf_s(chunkSize, sizeof(chunkSize), "%" PRIxz "\r\n", packetSize);
sChunk = Stream_New(NULL, strnlen(chunkSize, sizeof(chunkSize)) + packetSize + 2);
if (!sChunk)
return -1;
Stream_Write(sChunk, chunkSize, strnlen(chunkSize, sizeof(chunkSize)));
Stream_Write_UINT16(sChunk, PKT_TYPE_DATA); /* Type */
Stream_Write_UINT16(sChunk, 0); /* Reserved */
Stream_Write_UINT32(sChunk, (UINT32)packetSize); /* Packet length */
Stream_Write_UINT16(sChunk, (UINT16)size); /* Data size */
Stream_Write(sChunk, buf, size); /* Data */
Stream_Write(sChunk, "\r\n", 2);
Stream_SealLength(sChunk);
s = Stream_Length(sChunk);
if (s > INT_MAX)
return -1;
status = tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), (int)s);
Stream_Free(sChunk, TRUE);
if (status < 0)
return -1;
return (int)size;
}
static BOOL rdg_process_close_packet(rdpRdg* rdg)
{
int status = -1;
size_t s;
wStream* sChunk;
UINT32 packetSize = 12;
char chunkSize[11];
int chunkLen = sprintf_s(chunkSize, sizeof(chunkSize), "%" PRIx32 "\r\n", packetSize);
if (chunkLen < 0)
return FALSE;
sChunk = Stream_New(NULL, (size_t)chunkLen + packetSize + 2);
if (!sChunk)
return FALSE;
Stream_Write(sChunk, chunkSize, (size_t)chunkLen);
Stream_Write_UINT16(sChunk, PKT_TYPE_CLOSE_CHANNEL_RESPONSE); /* Type */
Stream_Write_UINT16(sChunk, 0); /* Reserved */
Stream_Write_UINT32(sChunk, packetSize); /* Packet length */
Stream_Write_UINT32(sChunk, 0); /* Status code */
Stream_Write(sChunk, "\r\n", 2);
Stream_SealLength(sChunk);
s = Stream_Length(sChunk);
if (s <= INT_MAX)
status = tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), (int)s);
Stream_Free(sChunk, TRUE);
return (status < 0 ? FALSE : TRUE);
}
static BOOL rdg_process_keep_alive_packet(rdpRdg* rdg)
{
int status = -1;
size_t s;
wStream* sChunk;
size_t packetSize = 8;
char chunkSize[11];
int chunkLen = sprintf_s(chunkSize, sizeof(chunkSize), "%" PRIxz "\r\n", packetSize);
if ((chunkLen < 0) || (packetSize > UINT32_MAX))
return FALSE;
sChunk = Stream_New(NULL, (size_t)chunkLen + packetSize + 2);
if (!sChunk)
return FALSE;
Stream_Write(sChunk, chunkSize, (size_t)chunkLen);
Stream_Write_UINT16(sChunk, PKT_TYPE_KEEPALIVE); /* Type */
Stream_Write_UINT16(sChunk, 0); /* Reserved */
Stream_Write_UINT32(sChunk, (UINT32)packetSize); /* Packet length */
Stream_Write(sChunk, "\r\n", 2);
Stream_SealLength(sChunk);
s = Stream_Length(sChunk);
if (s <= INT_MAX)
status = tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), (int)s);
Stream_Free(sChunk, TRUE);
return (status < 0 ? FALSE : TRUE);
}
static BOOL rdg_process_unknown_packet(rdpRdg* rdg, int type)
{
WINPR_UNUSED(rdg);
WINPR_UNUSED(type);
WLog_WARN(TAG, "Unknown Control Packet received: %X", type);
return TRUE;
}
static BOOL rdg_process_control_packet(rdpRdg* rdg, int type, size_t packetLength)
{
wStream* s = NULL;
size_t readCount = 0;
int status;
size_t payloadSize = packetLength - sizeof(RdgPacketHeader);
if (packetLength < sizeof(RdgPacketHeader))
return FALSE;
assert(sizeof(RdgPacketHeader) < INT_MAX);
if (payloadSize)
{
s = Stream_New(NULL, payloadSize);
if (!s)
return FALSE;
while (readCount < payloadSize)
{
status =
BIO_read(rdg->tlsOut->bio, Stream_Pointer(s), (int)payloadSize - (int)readCount);
if (status <= 0)
{
if (!BIO_should_retry(rdg->tlsOut->bio))
{
Stream_Free(s, TRUE);
return FALSE;
}
continue;
}
Stream_Seek(s, (size_t)status);
readCount += (size_t)status;
if (readCount > INT_MAX)
{
Stream_Free(s, TRUE);
return FALSE;
}
}
}
switch (type)
{
case PKT_TYPE_CLOSE_CHANNEL:
EnterCriticalSection(&rdg->writeSection);
status = rdg_process_close_packet(rdg);
LeaveCriticalSection(&rdg->writeSection);
break;
case PKT_TYPE_KEEPALIVE:
EnterCriticalSection(&rdg->writeSection);
status = rdg_process_keep_alive_packet(rdg);
LeaveCriticalSection(&rdg->writeSection);
break;
default:
status = rdg_process_unknown_packet(rdg, type);
break;
}
Stream_Free(s, TRUE);
return status;
}
static int rdg_read_data_packet(rdpRdg* rdg, BYTE* buffer, int size)
{
RdgPacketHeader header;
size_t readCount = 0;
int readSize;
int status;
if (!rdg->packetRemainingCount)
{
assert(sizeof(RdgPacketHeader) < INT_MAX);
while (readCount < sizeof(RdgPacketHeader))
{
status = BIO_read(rdg->tlsOut->bio, (BYTE*)(&header) + readCount,
(int)sizeof(RdgPacketHeader) - (int)readCount);
if (status <= 0)
{
if (!BIO_should_retry(rdg->tlsOut->bio))
return -1;
if (!readCount)
return 0;
BIO_wait_read(rdg->tlsOut->bio, 50);
continue;
}
readCount += (size_t)status;
if (readCount > INT_MAX)
return -1;
}
if (header.type != PKT_TYPE_DATA)
{
status = rdg_process_control_packet(rdg, header.type, header.packetLength);
if (!status)
return -1;
return 0;
}
readCount = 0;
while (readCount < 2)
{
status = BIO_read(rdg->tlsOut->bio, (BYTE*)(&rdg->packetRemainingCount) + readCount,
2 - (int)readCount);
if (status < 0)
{
if (!BIO_should_retry(rdg->tlsOut->bio))
return -1;
BIO_wait_read(rdg->tlsOut->bio, 50);
continue;
}
readCount += (size_t)status;
}
}
readSize = (rdg->packetRemainingCount < size ? rdg->packetRemainingCount : size);
status = BIO_read(rdg->tlsOut->bio, buffer, readSize);
if (status <= 0)
{
if (!BIO_should_retry(rdg->tlsOut->bio))
{
return -1;
}
return 0;
}
rdg->packetRemainingCount -= status;
return status;
}
static int rdg_bio_write(BIO* bio, const char* buf, int num)
{
int status;
rdpRdg* rdg = (rdpRdg*)BIO_get_data(bio);
BIO_clear_flags(bio, BIO_FLAGS_WRITE);
EnterCriticalSection(&rdg->writeSection);
status = rdg_write_data_packet(rdg, (const BYTE*)buf, num);
LeaveCriticalSection(&rdg->writeSection);
if (status < 0)
{
BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
return -1;
}
else if (status < num)
{
BIO_set_flags(bio, BIO_FLAGS_WRITE);
WSASetLastError(WSAEWOULDBLOCK);
}
else
{
BIO_set_flags(bio, BIO_FLAGS_WRITE);
}
return status;
}
static int rdg_bio_read(BIO* bio, char* buf, int size)
{
int status;
rdpRdg* rdg = (rdpRdg*)BIO_get_data(bio);
status = rdg_read_data_packet(rdg, (BYTE*)buf, size);
if (status < 0)
{
BIO_clear_retry_flags(bio);
return -1;
}
else if (status == 0)
{
BIO_set_retry_read(bio);
WSASetLastError(WSAEWOULDBLOCK);
return -1;
}
else
{
BIO_set_flags(bio, BIO_FLAGS_READ);
}
return status;
}
static int rdg_bio_puts(BIO* bio, const char* str)
{
WINPR_UNUSED(bio);
WINPR_UNUSED(str);
return -2;
}
static int rdg_bio_gets(BIO* bio, char* str, int size)
{
WINPR_UNUSED(bio);
WINPR_UNUSED(str);
WINPR_UNUSED(size);
return -2;
}
static long rdg_bio_ctrl(BIO* bio, int cmd, long arg1, void* arg2)
{
long status = -1;
rdpRdg* rdg = (rdpRdg*)BIO_get_data(bio);
rdpTls* tlsOut = rdg->tlsOut;
rdpTls* tlsIn = rdg->tlsIn;
if (cmd == BIO_CTRL_FLUSH)
{
(void)BIO_flush(tlsOut->bio);
(void)BIO_flush(tlsIn->bio);
status = 1;
}
else if (cmd == BIO_C_SET_NONBLOCK)
{
status = 1;
}
else if (cmd == BIO_C_READ_BLOCKED)
{
BIO* bio = tlsOut->bio;
status = BIO_read_blocked(bio);
}
else if (cmd == BIO_C_WRITE_BLOCKED)
{
BIO* bio = tlsIn->bio;
status = BIO_write_blocked(bio);
}
else if (cmd == BIO_C_WAIT_READ)
{
int timeout = (int)arg1;
BIO* bio = tlsOut->bio;
if (BIO_read_blocked(bio))
return BIO_wait_read(bio, timeout);
else if (BIO_write_blocked(bio))
return BIO_wait_write(bio, timeout);
else
status = 1;
}
else if (cmd == BIO_C_WAIT_WRITE)
{
int timeout = (int)arg1;
BIO* bio = tlsIn->bio;
if (BIO_write_blocked(bio))
status = BIO_wait_write(bio, timeout);
else if (BIO_read_blocked(bio))
status = BIO_wait_read(bio, timeout);
else
status = 1;
}
else if (cmd == BIO_C_GET_EVENT || cmd == BIO_C_GET_FD)
{
/*
* A note about BIO_C_GET_FD:
* Even if two FDs are part of RDG, only one FD can be returned here.
*
* In FreeRDP, BIO FDs are only used for polling, so it is safe to use the outgoing FD only
*
* See issue #3602
*/
status = BIO_ctrl(tlsOut->bio, cmd, arg1, arg2);
}
return status;
}
static int rdg_bio_new(BIO* bio)
{
BIO_set_init(bio, 1);
BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
return 1;
}
static int rdg_bio_free(BIO* bio)
{
WINPR_UNUSED(bio);
return 1;
}
static BIO_METHOD* BIO_s_rdg(void)
{
static BIO_METHOD* bio_methods = NULL;
if (bio_methods == NULL)
{
if (!(bio_methods = BIO_meth_new(BIO_TYPE_TSG, "RDGateway")))
return NULL;
BIO_meth_set_write(bio_methods, rdg_bio_write);
BIO_meth_set_read(bio_methods, rdg_bio_read);
BIO_meth_set_puts(bio_methods, rdg_bio_puts);
BIO_meth_set_gets(bio_methods, rdg_bio_gets);
BIO_meth_set_ctrl(bio_methods, rdg_bio_ctrl);
BIO_meth_set_create(bio_methods, rdg_bio_new);
BIO_meth_set_destroy(bio_methods, rdg_bio_free);
}
return bio_methods;
}
rdpRdg* rdg_new(rdpContext* context)
{
rdpRdg* rdg;
RPC_CSTR stringUuid;
char bracedUuid[40];
RPC_STATUS rpcStatus;
if (!context)
return NULL;
rdg = (rdpRdg*)calloc(1, sizeof(rdpRdg));
if (rdg)
{
rdg->state = RDG_CLIENT_STATE_INITIAL;
rdg->context = context;
rdg->settings = rdg->context->settings;
rdg->extAuth = HTTP_EXTENDED_AUTH_NONE;
if (rdg->settings->GatewayAccessToken)
rdg->extAuth = HTTP_EXTENDED_AUTH_PAA;
UuidCreate(&rdg->guid);
rpcStatus = UuidToStringA(&rdg->guid, &stringUuid);
if (rpcStatus == RPC_S_OUT_OF_MEMORY)
goto rdg_alloc_error;
sprintf_s(bracedUuid, sizeof(bracedUuid), "{%s}", stringUuid);
RpcStringFreeA(&stringUuid);
rdg->tlsOut = tls_new(rdg->settings);
if (!rdg->tlsOut)
goto rdg_alloc_error;
rdg->tlsIn = tls_new(rdg->settings);
if (!rdg->tlsIn)
goto rdg_alloc_error;
rdg->http = http_context_new();
if (!rdg->http)
goto rdg_alloc_error;
if (!http_context_set_uri(rdg->http, "/remoteDesktopGateway/") ||
!http_context_set_accept(rdg->http, "*/*") ||
!http_context_set_cache_control(rdg->http, "no-cache") ||
!http_context_set_pragma(rdg->http, "no-cache") ||
!http_context_set_connection(rdg->http, "Keep-Alive") ||
!http_context_set_user_agent(rdg->http, "MS-RDGateway/1.0") ||
!http_context_set_host(rdg->http, rdg->settings->GatewayHostname) ||
!http_context_set_rdg_connection_id(rdg->http, bracedUuid))
{
goto rdg_alloc_error;
}
if (rdg->extAuth != HTTP_EXTENDED_AUTH_NONE)
{
switch (rdg->extAuth)
{
case HTTP_EXTENDED_AUTH_PAA:
if (!http_context_set_rdg_auth_scheme(rdg->http, "PAA"))
goto rdg_alloc_error;
break;
default:
WLog_DBG(TAG, "RDG extended authentication method %d not supported",
rdg->extAuth);
}
}
rdg->frontBio = BIO_new(BIO_s_rdg());
if (!rdg->frontBio)
goto rdg_alloc_error;
BIO_set_data(rdg->frontBio, rdg);
InitializeCriticalSection(&rdg->writeSection);
}
return rdg;
rdg_alloc_error:
rdg_free(rdg);
return NULL;
}
void rdg_free(rdpRdg* rdg)
{
if (!rdg)
return;
tls_free(rdg->tlsOut);
tls_free(rdg->tlsIn);
http_context_free(rdg->http);
ntlm_free(rdg->ntlm);
if (!rdg->attached)
BIO_free_all(rdg->frontBio);
DeleteCriticalSection(&rdg->writeSection);
free(rdg);
}
BIO* rdg_get_front_bio_and_take_ownership(rdpRdg* rdg)
{
if (!rdg)
return NULL;
rdg->attached = TRUE;
return rdg->frontBio;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3946_4 |
crossvul-cpp_data_good_2694_0 | /*
* Copyright (c) 1998-2007 The TCPDUMP project
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Reference documentation:
* http://www.cisco.com/en/US/tech/tk389/tk689/technologies_tech_note09186a0080094c52.shtml
* http://www.cisco.com/warp/public/473/21.html
* http://www.cisco.com/univercd/cc/td/doc/product/lan/trsrb/frames.htm
*
* Original code ode by Carles Kishimoto <carles.kishimoto@gmail.com>
*/
/* \summary: Cisco VLAN Trunking Protocol (VTP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#define VTP_HEADER_LEN 36
#define VTP_DOMAIN_NAME_LEN 32
#define VTP_MD5_DIGEST_LEN 16
#define VTP_UPDATE_TIMESTAMP_LEN 12
#define VTP_VLAN_INFO_OFFSET 12
#define VTP_SUMMARY_ADV 0x01
#define VTP_SUBSET_ADV 0x02
#define VTP_ADV_REQUEST 0x03
#define VTP_JOIN_MESSAGE 0x04
struct vtp_vlan_ {
uint8_t len;
uint8_t status;
uint8_t type;
uint8_t name_len;
uint16_t vlanid;
uint16_t mtu;
uint32_t index;
};
static const struct tok vtp_message_type_values[] = {
{ VTP_SUMMARY_ADV, "Summary advertisement"},
{ VTP_SUBSET_ADV, "Subset advertisement"},
{ VTP_ADV_REQUEST, "Advertisement request"},
{ VTP_JOIN_MESSAGE, "Join message"},
{ 0, NULL }
};
static const struct tok vtp_header_values[] = {
{ 0x01, "Followers"}, /* On Summary advertisement, 3rd byte is Followers */
{ 0x02, "Seq number"}, /* On Subset advertisement, 3rd byte is Sequence number */
{ 0x03, "Rsvd"}, /* On Adver. requests 3rd byte is Rsvd */
{ 0x04, "Rsvd"}, /* On Adver. requests 3rd byte is Rsvd */
{ 0, NULL }
};
static const struct tok vtp_vlan_type_values[] = {
{ 0x01, "Ethernet"},
{ 0x02, "FDDI"},
{ 0x03, "TrCRF"},
{ 0x04, "FDDI-net"},
{ 0x05, "TrBRF"},
{ 0, NULL }
};
static const struct tok vtp_vlan_status[] = {
{ 0x00, "Operational"},
{ 0x01, "Suspended"},
{ 0, NULL }
};
#define VTP_VLAN_SOURCE_ROUTING_RING_NUMBER 0x01
#define VTP_VLAN_SOURCE_ROUTING_BRIDGE_NUMBER 0x02
#define VTP_VLAN_STP_TYPE 0x03
#define VTP_VLAN_PARENT_VLAN 0x04
#define VTP_VLAN_TRANS_BRIDGED_VLAN 0x05
#define VTP_VLAN_PRUNING 0x06
#define VTP_VLAN_BRIDGE_TYPE 0x07
#define VTP_VLAN_ARP_HOP_COUNT 0x08
#define VTP_VLAN_STE_HOP_COUNT 0x09
#define VTP_VLAN_BACKUP_CRF_MODE 0x0A
static const struct tok vtp_vlan_tlv_values[] = {
{ VTP_VLAN_SOURCE_ROUTING_RING_NUMBER, "Source-Routing Ring Number TLV"},
{ VTP_VLAN_SOURCE_ROUTING_BRIDGE_NUMBER, "Source-Routing Bridge Number TLV"},
{ VTP_VLAN_STP_TYPE, "STP type TLV"},
{ VTP_VLAN_PARENT_VLAN, "Parent VLAN TLV"},
{ VTP_VLAN_TRANS_BRIDGED_VLAN, "Translationally bridged VLANs TLV"},
{ VTP_VLAN_PRUNING, "Pruning TLV"},
{ VTP_VLAN_BRIDGE_TYPE, "Bridge Type TLV"},
{ VTP_VLAN_ARP_HOP_COUNT, "Max ARP Hop Count TLV"},
{ VTP_VLAN_STE_HOP_COUNT, "Max STE Hop Count TLV"},
{ VTP_VLAN_BACKUP_CRF_MODE, "Backup CRF Mode TLV"},
{ 0, NULL }
};
static const struct tok vtp_stp_type_values[] = {
{ 1, "SRT"},
{ 2, "SRB"},
{ 3, "Auto"},
{ 0, NULL }
};
void
vtp_print (netdissect_options *ndo,
const u_char *pptr, u_int length)
{
int type, len, tlv_len, tlv_value, mgmtd_len;
const u_char *tptr;
const struct vtp_vlan_ *vtp_vlan;
if (length < VTP_HEADER_LEN)
goto trunc;
tptr = pptr;
ND_TCHECK2(*tptr, VTP_HEADER_LEN);
type = *(tptr+1);
ND_PRINT((ndo, "VTPv%u, Message %s (0x%02x), length %u",
*tptr,
tok2str(vtp_message_type_values,"Unknown message type", type),
type,
length));
/* In non-verbose mode, just print version and message type */
if (ndo->ndo_vflag < 1) {
return;
}
/* verbose mode print all fields */
ND_PRINT((ndo, "\n\tDomain name: "));
mgmtd_len = *(tptr + 3);
if (mgmtd_len < 1 || mgmtd_len > 32) {
ND_PRINT((ndo, " [invalid MgmtD Len %d]", mgmtd_len));
return;
}
fn_printzp(ndo, tptr + 4, mgmtd_len, NULL);
ND_PRINT((ndo, ", %s: %u",
tok2str(vtp_header_values, "Unknown", type),
*(tptr+2)));
tptr += VTP_HEADER_LEN;
switch (type) {
case VTP_SUMMARY_ADV:
/*
* SUMMARY ADVERTISEMENT
*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Version | Code | Followers | MgmtD Len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Management Domain Name (zero-padded to 32 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Configuration revision number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Updater Identity IP address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Update Timestamp (12 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | MD5 digest (16 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
ND_TCHECK2(*tptr, 8);
ND_PRINT((ndo, "\n\t Config Rev %x, Updater %s",
EXTRACT_32BITS(tptr),
ipaddr_string(ndo, tptr+4)));
tptr += 8;
ND_TCHECK2(*tptr, VTP_UPDATE_TIMESTAMP_LEN);
ND_PRINT((ndo, ", Timestamp 0x%08x 0x%08x 0x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8)));
tptr += VTP_UPDATE_TIMESTAMP_LEN;
ND_TCHECK2(*tptr, VTP_MD5_DIGEST_LEN);
ND_PRINT((ndo, ", MD5 digest: %08x%08x%08x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
EXTRACT_32BITS(tptr + 12)));
tptr += VTP_MD5_DIGEST_LEN;
break;
case VTP_SUBSET_ADV:
/*
* SUBSET ADVERTISEMENT
*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Version | Code | Seq number | MgmtD Len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Management Domain Name (zero-padded to 32 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Configuration revision number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | VLAN info field 1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ................ |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | VLAN info field N |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
ND_TCHECK_32BITS(tptr);
ND_PRINT((ndo, ", Config Rev %x", EXTRACT_32BITS(tptr)));
/*
* VLAN INFORMATION
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | V info len | Status | VLAN type | VLAN name len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ISL vlan id | MTU size |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 802.10 index (SAID) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | VLAN name |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
tptr += 4;
while (tptr < (pptr+length)) {
ND_TCHECK_8BITS(tptr);
len = *tptr;
if (len == 0)
break;
ND_TCHECK2(*tptr, len);
vtp_vlan = (const struct vtp_vlan_*)tptr;
ND_TCHECK(*vtp_vlan);
ND_PRINT((ndo, "\n\tVLAN info status %s, type %s, VLAN-id %u, MTU %u, SAID 0x%08x, Name ",
tok2str(vtp_vlan_status,"Unknown",vtp_vlan->status),
tok2str(vtp_vlan_type_values,"Unknown",vtp_vlan->type),
EXTRACT_16BITS(&vtp_vlan->vlanid),
EXTRACT_16BITS(&vtp_vlan->mtu),
EXTRACT_32BITS(&vtp_vlan->index)));
fn_printzp(ndo, tptr + VTP_VLAN_INFO_OFFSET, vtp_vlan->name_len, NULL);
/*
* Vlan names are aligned to 32-bit boundaries.
*/
len -= VTP_VLAN_INFO_OFFSET + 4*((vtp_vlan->name_len + 3)/4);
tptr += VTP_VLAN_INFO_OFFSET + 4*((vtp_vlan->name_len + 3)/4);
/* TLV information follows */
while (len > 0) {
/*
* Cisco specs says 2 bytes for type + 2 bytes for length, take only 1
* See: http://www.cisco.com/univercd/cc/td/doc/product/lan/trsrb/frames.htm
*/
type = *tptr;
tlv_len = *(tptr+1);
ND_PRINT((ndo, "\n\t\t%s (0x%04x) TLV",
tok2str(vtp_vlan_tlv_values, "Unknown", type),
type));
/*
* infinite loop check
*/
if (type == 0 || tlv_len == 0) {
return;
}
ND_TCHECK2(*tptr, tlv_len * 2 +2);
tlv_value = EXTRACT_16BITS(tptr+2);
switch (type) {
case VTP_VLAN_STE_HOP_COUNT:
ND_PRINT((ndo, ", %u", tlv_value));
break;
case VTP_VLAN_PRUNING:
ND_PRINT((ndo, ", %s (%u)",
tlv_value == 1 ? "Enabled" : "Disabled",
tlv_value));
break;
case VTP_VLAN_STP_TYPE:
ND_PRINT((ndo, ", %s (%u)",
tok2str(vtp_stp_type_values, "Unknown", tlv_value),
tlv_value));
break;
case VTP_VLAN_BRIDGE_TYPE:
ND_PRINT((ndo, ", %s (%u)",
tlv_value == 1 ? "SRB" : "SRT",
tlv_value));
break;
case VTP_VLAN_BACKUP_CRF_MODE:
ND_PRINT((ndo, ", %s (%u)",
tlv_value == 1 ? "Backup" : "Not backup",
tlv_value));
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case VTP_VLAN_SOURCE_ROUTING_RING_NUMBER:
case VTP_VLAN_SOURCE_ROUTING_BRIDGE_NUMBER:
case VTP_VLAN_PARENT_VLAN:
case VTP_VLAN_TRANS_BRIDGED_VLAN:
case VTP_VLAN_ARP_HOP_COUNT:
default:
print_unknown_data(ndo, tptr, "\n\t\t ", 2 + tlv_len*2);
break;
}
len -= 2 + tlv_len*2;
tptr += 2 + tlv_len*2;
}
}
break;
case VTP_ADV_REQUEST:
/*
* ADVERTISEMENT REQUEST
*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Version | Code | Reserved | MgmtD Len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Management Domain Name (zero-padded to 32 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Start value |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\tStart value: %u", EXTRACT_32BITS(tptr)));
break;
case VTP_JOIN_MESSAGE:
/* FIXME - Could not find message format */
break;
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "[|vtp]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 4
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2694_0 |
crossvul-cpp_data_bad_138_0 | /**
* Simple engine for creating PDF files.
* It supports text, shapes, images etc...
* Capable of handling millions of objects without too much performance
* penalty.
* Public domain license - no warrenty implied; use at your own risk.
*/
/**
* PDF HINTS & TIPS
* The following sites have various bits & pieces about PDF document
* generation
* http://www.mactech.com/articles/mactech/Vol.15/15.09/PDFIntro/index.html
* http://gnupdf.org/Introduction_to_PDF
* http://www.planetpdf.com/mainpage.asp?WebPageID=63
* http://archive.vector.org.uk/art10008970
* http://www.adobe.com/devnet/acrobat/pdfs/pdf_reference_1-7.pdf
* https://blog.idrsolutions.com/2013/01/understanding-the-pdf-file-format-overview/
*
* To validate the PDF output, there are several online validators:
* http://www.validatepdfa.com/online.htm
* http://www.datalogics.com/products/callas/callaspdfA-onlinedemo.asp
* http://www.pdf-tools.com/pdf/validate-pdfa-online.aspx
*
* In addition the 'pdftk' server can be used to analyse the output:
* https://www.pdflabs.com/docs/pdftk-cli-examples/
*
* PDF page markup operators:
* b closepath, fill,and stroke path.
* B fill and stroke path.
* b* closepath, eofill,and stroke path.
* B* eofill and stroke path.
* BI begin image.
* BMC begin marked content.
* BT begin text object.
* BX begin section allowing undefined operators.
* c curveto.
* cm concat. Concatenates the matrix to the current transform.
* cs setcolorspace for fill.
* CS setcolorspace for stroke.
* d setdash.
* Do execute the named XObject.
* DP mark a place in the content stream, with a dictionary.
* EI end image.
* EMC end marked content.
* ET end text object.
* EX end section that allows undefined operators.
* f fill path.
* f* eofill Even/odd fill path.
* g setgray (fill).
* G setgray (stroke).
* gs set parameters in the extended graphics state.
* h closepath.
* i setflat.
* ID begin image data.
* j setlinejoin.
* J setlinecap.
* k setcmykcolor (fill).
* K setcmykcolor (stroke).
* l lineto.
* m moveto.
* M setmiterlimit.
* n end path without fill or stroke.
* q save graphics state.
* Q restore graphics state.
* re rectangle.
* rg setrgbcolor (fill).
* RG setrgbcolor (stroke).
* s closepath and stroke path.
* S stroke path.
* sc setcolor (fill).
* SC setcolor (stroke).
* sh shfill (shaded fill).
* Tc set character spacing.
* Td move text current point.
* TD move text current point and set leading.
* Tf set font name and size.
* Tj show text.
* TJ show text, allowing individual character positioning.
* TL set leading.
* Tm set text matrix.
* Tr set text rendering mode.
* Ts set super/subscripting text rise.
* Tw set word spacing.
* Tz set horizontal scaling.
* T* move to start of next line.
* v curveto.
* w setlinewidth.
* W clip.
* y curveto.
*/
#define _POSIX_SOURCE /* For localtime_r */
#include <sys/types.h>
#include <ctype.h>
#include <sys/stat.h>
#include <errno.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "pdfgen.h"
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
#define PDF_RGB_R(c) ((((c) >> 16) & 0xff) / 255.0)
#define PDF_RGB_G(c) ((((c) >> 8) & 0xff) / 255.0)
#define PDF_RGB_B(c) ((((c) >> 0) & 0xff) / 255.0)
#if defined(_MSC_VER)
/*
* As stated here: http://stackoverflow.com/questions/70013/how-to-detect-if-im-compiling-code-with-visual-studio-2008
* Visual Studio 2015 has better support for C99
* We need to use __inline for older version.
*/
#if _MSC_VER < 1900
#define inline __inline
#endif
#endif // _MSC_VER
typedef struct pdf_object pdf_object;
enum {
OBJ_none, /* skipped */
OBJ_info,
OBJ_stream,
OBJ_font,
OBJ_page,
OBJ_bookmark,
OBJ_outline,
OBJ_catalog,
OBJ_pages,
OBJ_image,
OBJ_count,
};
struct flexarray {
void ***bins;
int item_count;
int bin_count;
};
struct pdf_object {
int type; /* See OBJ_xxxx */
int index; /* PDF output index */
int offset; /* Byte position within the output file */
struct pdf_object *prev; /* Previous of this type */
struct pdf_object *next; /* Next of this type */
union {
struct {
struct pdf_object *page;
char name[64];
struct pdf_object *parent;
struct flexarray children;
} bookmark;
struct {
char *text;
int len;
} stream;
struct {
int width;
int height;
struct flexarray children;
} page;
struct pdf_info info;
struct {
char name[64];
int index;
} font;
};
};
struct pdf_doc {
char errstr[128];
int errval;
struct flexarray objects;
int width;
int height;
struct pdf_object *current_font;
struct pdf_object *last_objects[OBJ_count];
struct pdf_object *first_objects[OBJ_count];
};
/**
* Simple flexible resizing array implementation
* The bins get larger in powers of two
* bin 0 = 1024 items
* 1 = 2048 items
* 2 = 4096 items
* etc...
*/
/* What is the first index that will be in the given bin? */
#define MIN_SHIFT 10
#define MIN_OFFSET ((1 << MIN_SHIFT) - 1)
static int bin_offset[] = {
(1 << (MIN_SHIFT + 0)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 1)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 2)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 3)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 4)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 5)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 6)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 7)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 8)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 9)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 10)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 11)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 12)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 13)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 14)) - 1 - MIN_OFFSET,
(1 << (MIN_SHIFT + 15)) - 1 - MIN_OFFSET,
};
static inline int flexarray_get_bin(struct flexarray *flex, int index)
{
int i;
(void)flex;
for (i = 0; i < ARRAY_SIZE(bin_offset); i++)
if (index < bin_offset[i])
return i - 1;
return -1;
}
static inline int flexarray_get_bin_size(struct flexarray *flex, int bin)
{
(void)flex;
if (bin >= ARRAY_SIZE(bin_offset))
return -1;
int next = bin_offset[bin + 1];
return next - bin_offset[bin];
}
static inline int flexarray_get_bin_offset(struct flexarray *flex, int bin, int index)
{
(void)flex;
return index - bin_offset[bin];
}
static void flexarray_clear(struct flexarray *flex)
{
int i;
for (i = 0; i < flex->bin_count; i++)
free(flex->bins[i]);
free(flex->bins);
flex->bin_count = 0;
flex->item_count = 0;
}
static inline int flexarray_size(struct flexarray *flex)
{
return flex->item_count;
}
static int flexarray_set(struct flexarray *flex, int index, void *data)
{
int bin = flexarray_get_bin(flex, index);
if (bin < 0)
return -EINVAL;
if (bin >= flex->bin_count) {
void *bins = realloc(flex->bins, (flex->bin_count + 1) *
sizeof(flex->bins));
if (!bins)
return -ENOMEM;
flex->bin_count++;
flex->bins = bins;
flex->bins[flex->bin_count - 1] =
calloc(flexarray_get_bin_size(flex, flex->bin_count - 1),
sizeof(void *));
if (!flex->bins[flex->bin_count - 1]) {
flex->bin_count--;
return -ENOMEM;
}
}
flex->item_count++;
flex->bins[bin][flexarray_get_bin_offset(flex, bin, index)] = data;
return flex->item_count - 1;
}
static inline int flexarray_append(struct flexarray *flex, void *data)
{
return flexarray_set(flex, flexarray_size(flex), data);
}
static inline void *flexarray_get(struct flexarray *flex, int index)
{
int bin;
if (index >= flex->item_count)
return NULL;
bin = flexarray_get_bin(flex, index);
if (bin < 0 || bin >= flex->bin_count)
return NULL;
return flex->bins[bin][flexarray_get_bin_offset(flex, bin, index)];
}
/**
* PDF Implementation
*/
static int pdf_set_err(struct pdf_doc *doc, int errval,
const char *buffer, ...)
__attribute__ ((format(printf, 3, 4)));
static int pdf_set_err(struct pdf_doc *doc, int errval,
const char *buffer, ...)
{
va_list ap;
int len;
va_start(ap, buffer);
len = vsnprintf(doc->errstr, sizeof(doc->errstr) - 2, buffer, ap);
va_end(ap);
/* Make sure we're properly terminated */
if (doc->errstr[len] != '\n')
doc->errstr[len] = '\n';
doc->errstr[len] = '\0';
doc->errval = errval;
return errval;
}
const char *pdf_get_err(struct pdf_doc *pdf, int *errval)
{
if (!pdf)
return NULL;
if (pdf->errstr[0] == '\0')
return NULL;
if (errval) *errval = pdf->errval;
return pdf->errstr;
}
void pdf_clear_err(struct pdf_doc *pdf)
{
if (!pdf)
return;
pdf->errstr[0] = '\0';
pdf->errval = 0;
}
static struct pdf_object *pdf_get_object(struct pdf_doc *pdf, int index)
{
return flexarray_get(&pdf->objects, index);
}
static int pdf_append_object(struct pdf_doc *pdf, struct pdf_object *obj)
{
int index = flexarray_append(&pdf->objects, obj);
if (index < 0)
return index;
obj->index = index;
if (pdf->last_objects[obj->type]) {
obj->prev = pdf->last_objects[obj->type];
pdf->last_objects[obj->type]->next = obj;
}
pdf->last_objects[obj->type] = obj;
if (!pdf->first_objects[obj->type])
pdf->first_objects[obj->type] = obj;
return 0;
}
static struct pdf_object *pdf_add_object(struct pdf_doc *pdf, int type)
{
struct pdf_object *obj;
obj = calloc(1, sizeof(struct pdf_object));
if (!obj) {
pdf_set_err(pdf, -errno, "Unable to allocate object %d: %s",
flexarray_size(&pdf->objects) + 1, strerror(errno));
return NULL;
}
obj->type = type;
if (pdf_append_object(pdf, obj) < 0) {
free(obj);
return NULL;
}
return obj;
}
struct pdf_doc *pdf_create(int width, int height, struct pdf_info *info)
{
struct pdf_doc *pdf;
struct pdf_object *obj;
pdf = calloc(1, sizeof(struct pdf_doc));
pdf->width = width;
pdf->height = height;
/* We don't want to use ID 0 */
pdf_add_object(pdf, OBJ_none);
/* Create the 'info' object */
obj = pdf_add_object(pdf, OBJ_info);
if (info)
obj->info = *info;
/* FIXME: Should be quoting PDF strings? */
if (!obj->info.date[0]) {
time_t now = time(NULL);
struct tm tm;
#ifdef _WIN32
struct tm *tmp;
tmp = localtime(&now);
tm = *tmp;
#else
localtime_r(&now, &tm);
#endif
strftime(obj->info.date, sizeof(obj->info.date),
"%Y%m%d%H%M%SZ", &tm);
}
if (!obj->info.creator[0])
strcpy(obj->info.creator, "pdfgen");
if (!obj->info.producer[0])
strcpy(obj->info.producer, "pdfgen");
if (!obj->info.title[0])
strcpy(obj->info.title, "pdfgen");
if (!obj->info.author[0])
strcpy(obj->info.author, "pdfgen");
if (!obj->info.subject[0])
strcpy(obj->info.subject, "pdfgen");
pdf_add_object(pdf, OBJ_pages);
pdf_add_object(pdf, OBJ_catalog);
pdf_set_font(pdf, "Times-Roman");
return pdf;
}
int pdf_width(struct pdf_doc *pdf)
{
return pdf->width;
}
int pdf_height(struct pdf_doc *pdf)
{
return pdf->height;
}
static void pdf_object_destroy(struct pdf_object *object)
{
switch (object->type) {
case OBJ_stream:
case OBJ_image:
free(object->stream.text);
break;
case OBJ_page:
flexarray_clear(&object->page.children);
break;
case OBJ_bookmark:
flexarray_clear(&object->bookmark.children);
break;
}
free(object);
}
void pdf_destroy(struct pdf_doc *pdf)
{
if (pdf) {
int i;
for (i = 0; i < flexarray_size(&pdf->objects); i++)
pdf_object_destroy(pdf_get_object(pdf, i));
flexarray_clear(&pdf->objects);
free(pdf);
}
}
static struct pdf_object *pdf_find_first_object(struct pdf_doc *pdf,
int type)
{
return pdf->first_objects[type];
}
static struct pdf_object *pdf_find_last_object(struct pdf_doc *pdf,
int type)
{
return pdf->last_objects[type];
}
int pdf_set_font(struct pdf_doc *pdf, const char *font)
{
struct pdf_object *obj;
int last_index = 0;
/* See if we've used this font before */
for (obj = pdf_find_first_object(pdf, OBJ_font); obj; obj = obj->next) {
if (strcmp(obj->font.name, font) == 0)
break;
last_index = obj->font.index;
}
/* Create a new font object if we need it */
if (!obj) {
obj = pdf_add_object(pdf, OBJ_font);
if (!obj)
return pdf->errval;
strncpy(obj->font.name, font, sizeof(obj->font.name));
obj->font.name[sizeof(obj->font.name) - 1] = '\0';
obj->font.index = last_index + 1;
}
pdf->current_font = obj;
return 0;
}
struct pdf_object *pdf_append_page(struct pdf_doc *pdf)
{
struct pdf_object *page;
page = pdf_add_object(pdf, OBJ_page);
if (!page)
return NULL;
page->page.width = pdf->width;
page->page.height = pdf->height;
return page;
}
int pdf_page_set_size(struct pdf_doc *pdf, struct pdf_object *page, int width, int height)
{
if (!page)
page = pdf_find_last_object(pdf, OBJ_page);
if (!page || page->type != OBJ_page)
return pdf_set_err(pdf, -EINVAL, "Invalid PDF page");
page->page.width = width;
page->page.height = height;
return 0;
}
static int pdf_save_object(struct pdf_doc *pdf, FILE *fp, int index)
{
struct pdf_object *object = pdf_get_object(pdf, index);
if (object->type == OBJ_none)
return -ENOENT;
object->offset = ftell(fp);
fprintf(fp, "%d 0 obj\r\n", index);
switch (object->type) {
case OBJ_stream:
case OBJ_image: {
int len = object->stream.len ? object->stream.len :
strlen(object->stream.text);
fwrite(object->stream.text, len, 1, fp);
break;
}
case OBJ_info: {
struct pdf_info *info = &object->info;
fprintf(fp, "<<\r\n"
" /Creator (%s)\r\n"
" /Producer (%s)\r\n"
" /Title (%s)\r\n"
" /Author (%s)\r\n"
" /Subject (%s)\r\n"
" /CreationDate (D:%s)\r\n"
">>\r\n",
info->creator, info->producer, info->title,
info->author, info->subject, info->date);
break;
}
case OBJ_page: {
int i;
struct pdf_object *font;
struct pdf_object *pages = pdf_find_first_object(pdf, OBJ_pages);
struct pdf_object *image = pdf_find_first_object(pdf, OBJ_image);
fprintf(fp, "<<\r\n"
"/Type /Page\r\n"
"/Parent %d 0 R\r\n", pages->index);
fprintf(fp, "/MediaBox [0 0 %d %d]\r\n",
object->page.width, object->page.height);
fprintf(fp, "/Resources <<\r\n");
fprintf(fp, " /Font <<\r\n");
for (font = pdf_find_first_object(pdf, OBJ_font); font; font = font->next)
fprintf(fp, " /F%d %d 0 R\r\n",
font->font.index, font->index);
fprintf(fp, " >>\r\n");
if (image) {
fprintf(fp, " /XObject <<");
for (; image; image = image->next)
fprintf(fp, "/Image%d %d 0 R ", image->index, image->index);
fprintf(fp, ">>\r\n");
}
fprintf(fp, ">>\r\n");
fprintf(fp, "/Contents [\r\n");
for (i = 0; i < flexarray_size(&object->page.children); i++) {
struct pdf_object *child = flexarray_get(&object->page.children, i);
fprintf(fp, "%d 0 R\r\n", child->index);
}
fprintf(fp, "]\r\n");
fprintf(fp, ">>\r\n");
break;
}
case OBJ_bookmark: {
struct pdf_object *parent, *other;
parent = object->bookmark.parent;
if (!parent)
parent = pdf_find_first_object(pdf, OBJ_outline);
if (!object->bookmark.page)
break;
fprintf(fp, "<<\r\n"
"/A << /Type /Action\r\n"
" /S /GoTo\r\n"
" /D [%d 0 R /XYZ 0 %d null]\r\n"
" >>\r\n"
"/Parent %d 0 R\r\n"
"/Title (%s)\r\n",
object->bookmark.page->index,
pdf->height,
parent->index,
object->bookmark.name);
int nchildren = flexarray_size(&object->bookmark.children);
if (nchildren > 0) {
struct pdf_object *f, *l;
f = flexarray_get(&object->bookmark.children, 0);
l = flexarray_get(&object->bookmark.children, nchildren - 1);
fprintf(fp, "/First %d 0 R\r\n", f->index);
fprintf(fp, "/Last %d 0 R\r\n", l->index);
}
// Find the previous bookmark with the same parent
for (other = object->prev;
other && other->bookmark.parent != object->bookmark.parent;
other = other->prev)
;
if (other)
fprintf(fp, "/Prev %d 0 R\r\n", other->index);
// Find the next bookmark with the same parent
for (other = object->next;
other && other->bookmark.parent != object->bookmark.parent;
other = other->next)
;
if (other)
fprintf(fp, "/Next %d 0 R\r\n", other->index);
fprintf(fp, ">>\r\n");
break;
}
case OBJ_outline: {
struct pdf_object *first, *last, *cur;
first = pdf_find_first_object(pdf, OBJ_bookmark);
last = pdf_find_last_object(pdf, OBJ_bookmark);
if (first && last) {
int count = 0;
cur = first;
while (cur) {
if (!cur->bookmark.parent)
count++;
cur = cur->next;
}
/* Bookmark outline */
fprintf(fp, "<<\r\n"
"/Count %d\r\n"
"/Type /Outlines\r\n"
"/First %d 0 R\r\n"
"/Last %d 0 R\r\n"
">>\r\n",
count, first->index, last->index);
}
break;
}
case OBJ_font:
fprintf(fp, "<<\r\n"
" /Type /Font\r\n"
" /Subtype /Type1\r\n"
" /BaseFont /%s\r\n"
" /Encoding /WinAnsiEncoding\r\n"
">>\r\n", object->font.name);
break;
case OBJ_pages: {
struct pdf_object *page;
int npages = 0;
fprintf(fp, "<<\r\n"
"/Type /Pages\r\n"
"/Kids [ ");
for (page = pdf_find_first_object(pdf, OBJ_page);
page;
page = page->next) {
npages++;
fprintf(fp, "%d 0 R ", page->index);
}
fprintf(fp, "]\r\n");
fprintf(fp, "/Count %d\r\n", npages);
fprintf(fp, ">>\r\n");
break;
}
case OBJ_catalog: {
struct pdf_object *outline = pdf_find_first_object(pdf, OBJ_outline);
struct pdf_object *pages = pdf_find_first_object(pdf, OBJ_pages);
fprintf(fp, "<<\r\n"
"/Type /Catalog\r\n");
if (outline)
fprintf(fp,
"/Outlines %d 0 R\r\n"
"/PageMode /UseOutlines\r\n", outline->index);
fprintf(fp, "/Pages %d 0 R\r\n"
">>\r\n",
pages->index);
break;
}
default:
return pdf_set_err(pdf, -EINVAL, "Invalid PDF object type %d",
object->type);
}
fprintf(fp, "endobj\r\n");
return 0;
}
int pdf_save(struct pdf_doc *pdf, const char *filename)
{
FILE *fp;
int i;
struct pdf_object *obj;
int xref_offset;
int xref_count = 0;
if (filename == NULL)
fp = stdout;
else if ((fp = fopen(filename, "wb")) == NULL)
return pdf_set_err(pdf, -errno, "Unable to open '%s': %s",
filename, strerror(errno));
fprintf(fp, "%%PDF-1.2\r\n");
/* Hibit bytes */
fprintf(fp, "%c%c%c%c%c\r\n", 0x25, 0xc7, 0xec, 0x8f, 0xa2);
/* Dump all the objects & get their file offsets */
for (i = 0; i < flexarray_size(&pdf->objects); i++)
if (pdf_save_object(pdf, fp, i) >= 0)
xref_count++;
/* xref */
xref_offset = ftell(fp);
fprintf(fp, "xref\r\n");
fprintf(fp, "0 %d\r\n", xref_count + 1);
fprintf(fp, "0000000000 65535 f\r\n");
for (i = 0; i < flexarray_size(&pdf->objects); i++) {
obj = pdf_get_object(pdf, i);
if (obj->type != OBJ_none)
fprintf(fp, "%10.10d 00000 n\r\n",
obj->offset);
}
fprintf(fp, "trailer\r\n"
"<<\r\n"
"/Size %d\r\n", xref_count + 1);
obj = pdf_find_first_object(pdf, OBJ_catalog);
fprintf(fp, "/Root %d 0 R\r\n", obj->index);
obj = pdf_find_first_object(pdf, OBJ_info);
fprintf(fp, "/Info %d 0 R\r\n", obj->index);
/* FIXME: Not actually generating a unique ID */
fprintf(fp, "/ID [<%16.16x> <%16.16x>]\r\n", 0x123, 0x123);
fprintf(fp, ">>\r\n"
"startxref\r\n");
fprintf(fp, "%d\r\n", xref_offset);
fprintf(fp, "%%%%EOF\r\n");
fclose(fp);
return 0;
}
static int pdf_add_stream(struct pdf_doc *pdf, struct pdf_object *page,
char *buffer)
{
struct pdf_object *obj;
int len;
char prefix[128];
char suffix[128];
if (!page)
page = pdf_find_last_object(pdf, OBJ_page);
if (!page)
return pdf_set_err(pdf, -EINVAL, "Invalid pdf page");
len = strlen(buffer);
/* We don't want any trailing whitespace in the stream */
while (len >= 1 && (buffer[len - 1] == '\r' ||
buffer[len - 1] == '\n')) {
buffer[len - 1] = '\0';
len--;
}
sprintf(prefix, "<< /Length %d >>stream\r\n", len);
sprintf(suffix, "\r\nendstream\r\n");
len += strlen(prefix) + strlen(suffix);
obj = pdf_add_object(pdf, OBJ_stream);
if (!obj)
return pdf->errval;
obj->stream.text = malloc(len + 1);
if (!obj->stream.text) {
obj->type = OBJ_none;
return pdf_set_err(pdf, -ENOMEM, "Insufficient memory for text (%d bytes)",
len + 1);
}
obj->stream.text[0] = '\0';
strcat(obj->stream.text, prefix);
strcat(obj->stream.text, buffer);
strcat(obj->stream.text, suffix);
obj->stream.len = 0;
return flexarray_append(&page->page.children, obj);
}
int pdf_add_bookmark(struct pdf_doc *pdf, struct pdf_object *page,
int parent, const char *name)
{
struct pdf_object *obj;
if (!page)
page = pdf_find_last_object(pdf, OBJ_page);
if (!page)
return pdf_set_err(pdf, -EINVAL,
"Unable to add bookmark, no pages available");
if (!pdf_find_first_object(pdf, OBJ_outline))
if (!pdf_add_object(pdf, OBJ_outline))
return pdf->errval;
obj = pdf_add_object(pdf, OBJ_bookmark);
if (!obj)
return pdf->errval;
strncpy(obj->bookmark.name, name, sizeof(obj->bookmark.name));
obj->bookmark.name[sizeof(obj->bookmark.name) - 1] = '\0';
obj->bookmark.page = page;
if (parent >= 0) {
struct pdf_object *parent_obj = pdf_get_object(pdf, parent);
if (!parent_obj)
return pdf_set_err(pdf, -EINVAL,
"Invalid parent ID %d supplied", parent);
obj->bookmark.parent = parent_obj;
flexarray_append(&parent_obj->bookmark.children, obj);
}
return obj->index;
}
struct dstr {
char *data;
int alloc_len;
int used_len;
};
static int dstr_ensure(struct dstr *str, int len)
{
if (str->alloc_len < len) {
int new_len = len + 4096;
char *new_data = realloc(str->data, new_len);
if (!new_data)
return -ENOMEM;
str->data = new_data;
str->alloc_len = new_len;
}
return 0;
}
static int dstr_printf(struct dstr *str, const char *fmt, ...)
__attribute__((format(printf,2,3)));
static int dstr_printf(struct dstr *str, const char *fmt, ...)
{
va_list ap, aq;
int len;
va_start(ap, fmt);
va_copy(aq, ap);
len = vsnprintf(NULL, 0, fmt, ap);
if (dstr_ensure(str, str->used_len + len + 1) < 0) {
va_end(ap);
va_end(aq);
return -ENOMEM;
}
vsprintf(&str->data[str->used_len], fmt, aq);
str->used_len += len;
va_end(ap);
va_end(aq);
return len;
}
static int dstr_append(struct dstr *str, const char *extend)
{
int len = strlen(extend);
if (dstr_ensure(str, str->used_len + len + 1) < 0)
return -ENOMEM;
strcpy(&str->data[str->used_len], extend);
str->used_len += len;
return len;
}
static void dstr_free(struct dstr *str)
{
free(str->data);
}
static int utf8_to_utf32(const char *utf8, int len, uint32_t *utf32)
{
uint32_t ch = *utf8;
int i;
uint8_t mask;
if ((ch & 0x80) == 0) {
len = 1;
mask = 0x7f;
} else if ((ch & 0xe0) == 0xc0 && len >= 2) {
len = 2;
mask = 0x1f;
} else if ((ch & 0xf0) == 0xe0 && len >= 3) {
len = 3;
mask = 0xf;
} else if ((ch & 0xf8) == 0xf0 && len >= 4) {
len = 4;
mask = 0x7;
} else
return -EINVAL;
ch = 0;
for (i = 0; i < len; i++) {
int shift = (len - i - 1) * 6;
if (i == 0)
ch |= ((uint32_t)(*utf8++) & mask) << shift;
else
ch |= ((uint32_t)(*utf8++) & 0x3f) << shift;
}
*utf32 = ch;
return len;
}
int pdf_add_text(struct pdf_doc *pdf, struct pdf_object *page,
const char *text, int size, int xoff, int yoff,
uint32_t colour)
{
int i, ret;
int len = text ? strlen(text) : 0;
struct dstr str = {0, 0, 0};
/* Don't bother adding empty/null strings */
if (!len)
return 0;
dstr_append(&str, "BT ");
dstr_printf(&str, "%d %d TD ", xoff, yoff);
dstr_printf(&str, "/F%d %d Tf ",
pdf->current_font->font.index, size);
dstr_printf(&str, "%f %f %f rg ",
PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));
dstr_append(&str, "(");
/* Escape magic characters properly */
for (i = 0; i < len; ) {
uint32_t code;
int code_len;
code_len = utf8_to_utf32(&text[i], len - i, &code);
if (code_len < 0) {
dstr_free(&str);
return pdf_set_err(pdf, -EINVAL, "Invalid UTF-8 encoding");
}
if (code > 255) {
/* We support *some* minimal UTF-8 characters */
char buf[5] = {0};
switch (code) {
case 0x160:
buf[0] = (char)0x8a;
break;
case 0x161:
buf[0] = (char)0x9a;
break;
case 0x17d:
buf[0] = (char)0x8e;
break;
case 0x17e:
buf[0] = (char)0x9e;
break;
case 0x20ac:
strcpy(buf, "\\200");
break;
default:
dstr_free(&str);
return pdf_set_err(pdf, -EINVAL, "Unsupported UTF-8 character: 0x%x 0o%o", code, code);
}
dstr_append(&str, buf);
} else if (strchr("()\\", code)) {
char buf[3];
/* Escape some characters */
buf[0] = '\\';
buf[1] = code;
buf[2] = '\0';
dstr_append(&str, buf);
} else if (strrchr("\n\r\t\b\f", code)) {
/* Skip over these characters */
;
} else {
char buf[2];
buf[0] = code;
buf[1] = '\0';
dstr_append(&str, buf);
}
i += code_len;
}
dstr_append(&str, ") Tj ");
dstr_append(&str, "ET");
ret = pdf_add_stream(pdf, page, str.data);
dstr_free(&str);
return ret;
}
/* How wide is each character, in points, at size 14 */
static const uint16_t helvetica_widths[256] = {
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 355, 556, 556, 889, 667, 191,
333, 333, 389, 584, 278, 333, 278, 278,
556, 556, 556, 556, 556, 556, 556, 556,
556, 556, 278, 278, 584, 584, 584, 556,
1015, 667, 667, 722, 722, 667, 611, 778,
722, 278, 500, 667, 556, 833, 722, 778,
667, 778, 722, 667, 611, 722, 667, 944,
667, 667, 611, 278, 278, 278, 469, 556,
333, 556, 556, 500, 556, 556, 278, 556,
556, 222, 222, 500, 222, 833, 556, 556,
556, 556, 333, 500, 278, 556, 500, 722,
500, 500, 500, 334, 260, 334, 584, 350,
556, 350, 222, 556, 333, 1000, 556, 556,
333, 1000, 667, 333, 1000, 350, 611, 350,
350, 222, 222, 333, 333, 350, 556, 1000,
333, 1000, 500, 333, 944, 350, 500, 667,
278, 333, 556, 556, 556, 556, 260, 556,
333, 737, 370, 556, 584, 333, 737, 333,
400, 584, 333, 333, 333, 556, 537, 278,
333, 333, 365, 556, 834, 834, 834, 611,
667, 667, 667, 667, 667, 667, 1000, 722,
667, 667, 667, 667, 278, 278, 278, 278,
722, 722, 778, 778, 778, 778, 778, 584,
778, 722, 722, 722, 722, 667, 667, 611,
556, 556, 556, 556, 556, 556, 889, 500,
556, 556, 556, 556, 278, 278, 278, 278,
556, 556, 556, 556, 556, 556, 556, 584,
611, 556, 556, 556, 556, 500, 556, 500
};
static const uint16_t helvetica_bold_widths[256] = {
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 333, 474, 556, 556, 889, 722, 238,
333, 333, 389, 584, 278, 333, 278, 278,
556, 556, 556, 556, 556, 556, 556, 556,
556, 556, 333, 333, 584, 584, 584, 611,
975, 722, 722, 722, 722, 667, 611, 778,
722, 278, 556, 722, 611, 833, 722, 778,
667, 778, 722, 667, 611, 722, 667, 944,
667, 667, 611, 333, 278, 333, 584, 556,
333, 556, 611, 556, 611, 556, 333, 611,
611, 278, 278, 556, 278, 889, 611, 611,
611, 611, 389, 556, 333, 611, 556, 778,
556, 556, 500, 389, 280, 389, 584, 350,
556, 350, 278, 556, 500, 1000, 556, 556,
333, 1000, 667, 333, 1000, 350, 611, 350,
350, 278, 278, 500, 500, 350, 556, 1000,
333, 1000, 556, 333, 944, 350, 500, 667,
278, 333, 556, 556, 556, 556, 280, 556,
333, 737, 370, 556, 584, 333, 737, 333,
400, 584, 333, 333, 333, 611, 556, 278,
333, 333, 365, 556, 834, 834, 834, 611,
722, 722, 722, 722, 722, 722, 1000, 722,
667, 667, 667, 667, 278, 278, 278, 278,
722, 722, 778, 778, 778, 778, 778, 584,
778, 722, 722, 722, 722, 667, 667, 611,
556, 556, 556, 556, 556, 556, 889, 556,
556, 556, 556, 556, 278, 278, 278, 278,
611, 611, 611, 611, 611, 611, 611, 584,
611, 611, 611, 611, 611, 556, 611, 556
};
static uint16_t helvetica_bold_oblique_widths[256] = {
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 333, 474, 556, 556, 889, 722, 238,
333, 333, 389, 584, 278, 333, 278, 278,
556, 556, 556, 556, 556, 556, 556, 556,
556, 556, 333, 333, 584, 584, 584, 611,
975, 722, 722, 722, 722, 667, 611, 778,
722, 278, 556, 722, 611, 833, 722, 778,
667, 778, 722, 667, 611, 722, 667, 944,
667, 667, 611, 333, 278, 333, 584, 556,
333, 556, 611, 556, 611, 556, 333, 611,
611, 278, 278, 556, 278, 889, 611, 611,
611, 611, 389, 556, 333, 611, 556, 778,
556, 556, 500, 389, 280, 389, 584, 350,
556, 350, 278, 556, 500, 1000, 556, 556,
333, 1000, 667, 333, 1000, 350, 611, 350,
350, 278, 278, 500, 500, 350, 556, 1000,
333, 1000, 556, 333, 944, 350, 500, 667,
278, 333, 556, 556, 556, 556, 280, 556,
333, 737, 370, 556, 584, 333, 737, 333,
400, 584, 333, 333, 333, 611, 556, 278,
333, 333, 365, 556, 834, 834, 834, 611,
722, 722, 722, 722, 722, 722, 1000, 722,
667, 667, 667, 667, 278, 278, 278, 278,
722, 722, 778, 778, 778, 778, 778, 584,
778, 722, 722, 722, 722, 667, 667, 611,
556, 556, 556, 556, 556, 556, 889, 556,
556, 556, 556, 556, 278, 278, 278, 278,
611, 611, 611, 611, 611, 611, 611, 584,
611, 611, 611, 611, 611, 556, 611, 556
};
static uint16_t helvetica_oblique_widths[256] = {
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 355, 556, 556, 889, 667, 191,
333, 333, 389, 584, 278, 333, 278, 278,
556, 556, 556, 556, 556, 556, 556, 556,
556, 556, 278, 278, 584, 584, 584, 556,
1015, 667, 667, 722, 722, 667, 611, 778,
722, 278, 500, 667, 556, 833, 722, 778,
667, 778, 722, 667, 611, 722, 667, 944,
667, 667, 611, 278, 278, 278, 469, 556,
333, 556, 556, 500, 556, 556, 278, 556,
556, 222, 222, 500, 222, 833, 556, 556,
556, 556, 333, 500, 278, 556, 500, 722,
500, 500, 500, 334, 260, 334, 584, 350,
556, 350, 222, 556, 333, 1000, 556, 556,
333, 1000, 667, 333, 1000, 350, 611, 350,
350, 222, 222, 333, 333, 350, 556, 1000,
333, 1000, 500, 333, 944, 350, 500, 667,
278, 333, 556, 556, 556, 556, 260, 556,
333, 737, 370, 556, 584, 333, 737, 333,
400, 584, 333, 333, 333, 556, 537, 278,
333, 333, 365, 556, 834, 834, 834, 611,
667, 667, 667, 667, 667, 667, 1000, 722,
667, 667, 667, 667, 278, 278, 278, 278,
722, 722, 778, 778, 778, 778, 778, 584,
778, 722, 722, 722, 722, 667, 667, 611,
556, 556, 556, 556, 556, 556, 889, 500,
556, 556, 556, 556, 278, 278, 278, 278,
556, 556, 556, 556, 556, 556, 556, 584,
611, 556, 556, 556, 556, 500, 556, 500
};
static uint16_t symbol_widths[256] = {
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 333, 713, 500, 549, 833, 778, 439,
333, 333, 500, 549, 250, 549, 250, 278,
500, 500, 500, 500, 500, 500, 500, 500,
500, 500, 278, 278, 549, 549, 549, 444,
549, 722, 667, 722, 612, 611, 763, 603,
722, 333, 631, 722, 686, 889, 722, 722,
768, 741, 556, 592, 611, 690, 439, 768,
645, 795, 611, 333, 863, 333, 658, 500,
500, 631, 549, 549, 494, 439, 521, 411,
603, 329, 603, 549, 549, 576, 521, 549,
549, 521, 549, 603, 439, 576, 713, 686,
493, 686, 494, 480, 200, 480, 549, 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,
750, 620, 247, 549, 167, 713, 500, 753,
753, 753, 753, 1042, 987, 603, 987, 603,
400, 549, 411, 549, 549, 713, 494, 460,
549, 549, 549, 549, 1000, 603, 1000, 658,
823, 686, 795, 987, 768, 768, 823, 768,
768, 713, 713, 713, 713, 713, 713, 713,
768, 713, 790, 790, 890, 823, 549, 250,
713, 603, 603, 1042, 987, 603, 987, 603,
494, 329, 790, 790, 786, 713, 384, 384,
384, 384, 384, 384, 494, 494, 494, 494,
0, 329, 274, 686, 686, 686, 384, 384,
384, 384, 384, 384, 494, 494, 494, 0
};
static uint16_t times_widths[256] = {
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 333, 408, 500, 500, 833, 778, 180,
333, 333, 500, 564, 250, 333, 250, 278,
500, 500, 500, 500, 500, 500, 500, 500,
500, 500, 278, 278, 564, 564, 564, 444,
921, 722, 667, 667, 722, 611, 556, 722,
722, 333, 389, 722, 611, 889, 722, 722,
556, 722, 667, 556, 611, 722, 722, 944,
722, 722, 611, 333, 278, 333, 469, 500,
333, 444, 500, 444, 500, 444, 333, 500,
500, 278, 278, 500, 278, 778, 500, 500,
500, 500, 333, 389, 278, 500, 500, 722,
500, 500, 444, 480, 200, 480, 541, 350,
500, 350, 333, 500, 444, 1000, 500, 500,
333, 1000, 556, 333, 889, 350, 611, 350,
350, 333, 333, 444, 444, 350, 500, 1000,
333, 980, 389, 333, 722, 350, 444, 722,
250, 333, 500, 500, 500, 500, 200, 500,
333, 760, 276, 500, 564, 333, 760, 333,
400, 564, 300, 300, 333, 500, 453, 250,
333, 300, 310, 500, 750, 750, 750, 444,
722, 722, 722, 722, 722, 722, 889, 667,
611, 611, 611, 611, 333, 333, 333, 333,
722, 722, 722, 722, 722, 722, 722, 564,
722, 722, 722, 722, 722, 722, 556, 500,
444, 444, 444, 444, 444, 444, 667, 444,
444, 444, 444, 444, 278, 278, 278, 278,
500, 500, 500, 500, 500, 500, 500, 564,
500, 500, 500, 500, 500, 500, 500, 500
};
static uint16_t times_bold_widths[256] = {
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 333, 555, 500, 500, 1000, 833, 278,
333, 333, 500, 570, 250, 333, 250, 278,
500, 500, 500, 500, 500, 500, 500, 500,
500, 500, 333, 333, 570, 570, 570, 500,
930, 722, 667, 722, 722, 667, 611, 778,
778, 389, 500, 778, 667, 944, 722, 778,
611, 778, 722, 556, 667, 722, 722, 1000,
722, 722, 667, 333, 278, 333, 581, 500,
333, 500, 556, 444, 556, 444, 333, 500,
556, 278, 333, 556, 278, 833, 556, 500,
556, 556, 444, 389, 333, 556, 500, 722,
500, 500, 444, 394, 220, 394, 520, 350,
500, 350, 333, 500, 500, 1000, 500, 500,
333, 1000, 556, 333, 1000, 350, 667, 350,
350, 333, 333, 500, 500, 350, 500, 1000,
333, 1000, 389, 333, 722, 350, 444, 722,
250, 333, 500, 500, 500, 500, 220, 500,
333, 747, 300, 500, 570, 333, 747, 333,
400, 570, 300, 300, 333, 556, 540, 250,
333, 300, 330, 500, 750, 750, 750, 500,
722, 722, 722, 722, 722, 722, 1000, 722,
667, 667, 667, 667, 389, 389, 389, 389,
722, 722, 778, 778, 778, 778, 778, 570,
778, 722, 722, 722, 722, 722, 611, 556,
500, 500, 500, 500, 500, 500, 722, 444,
444, 444, 444, 444, 278, 278, 278, 278,
500, 556, 500, 500, 500, 500, 500, 570,
500, 556, 556, 556, 556, 500, 556, 500
} ;
static uint16_t times_bold_italic_widths[256] = {
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 389, 555, 500, 500, 833, 778, 278,
333, 333, 500, 570, 250, 333, 250, 278,
500, 500, 500, 500, 500, 500, 500, 500,
500, 500, 333, 333, 570, 570, 570, 500,
832, 667, 667, 667, 722, 667, 667, 722,
778, 389, 500, 667, 611, 889, 722, 722,
611, 722, 667, 556, 611, 722, 667, 889,
667, 611, 611, 333, 278, 333, 570, 500,
333, 500, 500, 444, 500, 444, 333, 500,
556, 278, 278, 500, 278, 778, 556, 500,
500, 500, 389, 389, 278, 556, 444, 667,
500, 444, 389, 348, 220, 348, 570, 350,
500, 350, 333, 500, 500, 1000, 500, 500,
333, 1000, 556, 333, 944, 350, 611, 350,
350, 333, 333, 500, 500, 350, 500, 1000,
333, 1000, 389, 333, 722, 350, 389, 611,
250, 389, 500, 500, 500, 500, 220, 500,
333, 747, 266, 500, 606, 333, 747, 333,
400, 570, 300, 300, 333, 576, 500, 250,
333, 300, 300, 500, 750, 750, 750, 500,
667, 667, 667, 667, 667, 667, 944, 667,
667, 667, 667, 667, 389, 389, 389, 389,
722, 722, 722, 722, 722, 722, 722, 570,
722, 722, 722, 722, 722, 611, 611, 500,
500, 500, 500, 500, 500, 500, 722, 444,
444, 444, 444, 444, 278, 278, 278, 278,
500, 556, 500, 500, 500, 500, 500, 570,
500, 556, 556, 556, 556, 444, 500, 444
};
static uint16_t times_italic_widths[256] = {
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250,
250, 333, 420, 500, 500, 833, 778, 214,
333, 333, 500, 675, 250, 333, 250, 278,
500, 500, 500, 500, 500, 500, 500, 500,
500, 500, 333, 333, 675, 675, 675, 500,
920, 611, 611, 667, 722, 611, 611, 722,
722, 333, 444, 667, 556, 833, 667, 722,
611, 722, 611, 500, 556, 722, 611, 833,
611, 556, 556, 389, 278, 389, 422, 500,
333, 500, 500, 444, 500, 444, 278, 500,
500, 278, 278, 444, 278, 722, 500, 500,
500, 500, 389, 389, 278, 500, 444, 667,
444, 444, 389, 400, 275, 400, 541, 350,
500, 350, 333, 500, 556, 889, 500, 500,
333, 1000, 500, 333, 944, 350, 556, 350,
350, 333, 333, 556, 556, 350, 500, 889,
333, 980, 389, 333, 667, 350, 389, 556,
250, 389, 500, 500, 500, 500, 275, 500,
333, 760, 276, 500, 675, 333, 760, 333,
400, 675, 300, 300, 333, 500, 523, 250,
333, 300, 310, 500, 750, 750, 750, 500,
611, 611, 611, 611, 611, 611, 889, 667,
611, 611, 611, 611, 333, 333, 333, 333,
722, 667, 722, 722, 722, 722, 722, 675,
722, 722, 722, 722, 722, 556, 611, 500,
500, 500, 500, 500, 500, 500, 667, 444,
444, 444, 444, 444, 278, 278, 278, 278,
500, 500, 500, 500, 500, 500, 500, 675,
500, 500, 500, 500, 500, 444, 500, 444
};
static uint16_t zapfdingbats_widths[256] = {
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,
278, 974, 961, 974, 980, 719, 789, 790,
791, 690, 960, 939, 549, 855, 911, 933,
911, 945, 974, 755, 846, 762, 761, 571,
677, 763, 760, 759, 754, 494, 552, 537,
577, 692, 786, 788, 788, 790, 793, 794,
816, 823, 789, 841, 823, 833, 816, 831,
923, 744, 723, 749, 790, 792, 695, 776,
768, 792, 759, 707, 708, 682, 701, 826,
815, 789, 789, 707, 687, 696, 689, 786,
787, 713, 791, 785, 791, 873, 761, 762,
762, 759, 759, 892, 892, 788, 784, 438,
138, 277, 415, 392, 392, 668, 668, 0,
390, 390, 317, 317, 276, 276, 509, 509,
410, 410, 234, 234, 334, 334, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 732, 544, 544, 910, 667, 760, 760,
776, 595, 694, 626, 788, 788, 788, 788,
788, 788, 788, 788, 788, 788, 788, 788,
788, 788, 788, 788, 788, 788, 788, 788,
788, 788, 788, 788, 788, 788, 788, 788,
788, 788, 788, 788, 788, 788, 788, 788,
788, 788, 788, 788, 894, 838, 1016, 458,
748, 924, 748, 918, 927, 928, 928, 834,
873, 828, 924, 924, 917, 930, 931, 463,
883, 836, 836, 867, 867, 696, 696, 874,
0, 874, 760, 946, 771, 865, 771, 888,
967, 888, 831, 873, 927, 970, 918, 0
};
static uint16_t courier_widths[256] = {
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
600, 600, 600, 600, 600, 600, 600, 600,
};
static int pdf_text_pixel_width(const char *text, int text_len, int size,
const uint16_t *widths)
{
int i;
int len = 0;
if (text_len < 0)
text_len = strlen(text);
for (i = 0; i < text_len; i++)
len += widths[(uint8_t)text[i]];
/* Our widths arrays are for 14pt fonts */
return len * size / (14 * 72);
}
static const uint16_t *find_font_widths(const char *font_name)
{
if (strcmp(font_name, "Helvetica") == 0)
return helvetica_widths;
if (strcmp(font_name, "Helvetica-Bold") == 0)
return helvetica_bold_widths;
if (strcmp(font_name, "Helvetica-BoldOblique") == 0)
return helvetica_bold_oblique_widths;
if (strcmp(font_name, "Helvetica-Oblique") == 0)
return helvetica_oblique_widths;
if (strcmp(font_name, "Courier") == 0 ||
strcmp(font_name, "Courier-Bold") == 0 ||
strcmp(font_name, "Courier-BoldOblique") == 0 ||
strcmp(font_name, "Courier-Oblique") == 0)
return courier_widths;
if (strcmp(font_name, "Times-Roman") == 0)
return times_widths;
if (strcmp(font_name, "Times-Bold") == 0)
return times_bold_widths;
if (strcmp(font_name, "Times-Italic") == 0)
return times_italic_widths;
if (strcmp(font_name, "Times-BoldItalic") == 0)
return times_bold_italic_widths;
if (strcmp(font_name, "Symbol") == 0)
return symbol_widths;
if (strcmp(font_name, "ZapfDingbats") == 0)
return zapfdingbats_widths;
return NULL;
}
int pdf_get_font_text_width(struct pdf_doc *pdf, const char *font_name,
const char *text, int size)
{
const uint16_t *widths = find_font_widths(font_name);
if (!widths)
return pdf_set_err(pdf, -EINVAL, "Unable to determine width for font '%s'",
pdf->current_font->font.name);
return pdf_text_pixel_width(text, -1, size, widths);
}
static const char *find_word_break(const char *string)
{
/* Skip over the actual word */
while (string && *string && !isspace(*string))
string++;
return string;
}
int pdf_add_text_wrap(struct pdf_doc *pdf, struct pdf_object *page,
const char *text, int size, int xoff, int yoff,
uint32_t colour, int wrap_width)
{
/* Move through the text string, stopping at word boundaries,
* trying to find the longest text string we can fit in the given width
*/
const char *start = text;
const char *last_best = text;
const char *end = text;
char line[512];
const uint16_t *widths;
int orig_yoff = yoff;
widths = find_font_widths(pdf->current_font->font.name);
if (!widths)
return pdf_set_err(pdf, -EINVAL, "Unable to determine width for font '%s'",
pdf->current_font->font.name);
while (start && *start) {
const char *new_end = find_word_break(end + 1);
int line_width;
int output = 0;
end = new_end;
line_width = pdf_text_pixel_width(start, end - start, size, widths);
if (line_width >= wrap_width) {
if (last_best == start) {
/* There is a single word that is too long for the line */
int i;
/* Find the best character to chop it at */
for (i = end - start - 1; i > 0; i--)
if (pdf_text_pixel_width(start, i, size, widths) < wrap_width)
break;
end = start + i;
} else
end = last_best;
output = 1;
}
if (*end == '\0')
output = 1;
if (*end == '\n' || *end == '\r')
output = 1;
if (output) {
int len = end - start;
strncpy(line, start, len);
line[len] = '\0';
pdf_add_text(pdf, page, line, size, xoff, yoff, colour);
if (*end == ' ')
end++;
start = last_best = end;
yoff -= size;
} else
last_best = end;
}
return orig_yoff - yoff;
}
int pdf_add_line(struct pdf_doc *pdf, struct pdf_object *page,
int x1, int y1, int x2, int y2, int width, uint32_t colour)
{
int ret;
struct dstr str = {0, 0, 0};
dstr_append(&str, "BT\r\n");
dstr_printf(&str, "%d w\r\n", width);
dstr_printf(&str, "%d %d m\r\n", x1, y1);
dstr_printf(&str, "/DeviceRGB CS\r\n");
dstr_printf(&str, "%f %f %f RG\r\n",
PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));
dstr_printf(&str, "%d %d l S\r\n", x2, y2);
dstr_append(&str, "ET");
ret = pdf_add_stream(pdf, page, str.data);
dstr_free(&str);
return ret;
}
int pdf_add_circle(struct pdf_doc *pdf, struct pdf_object *page,
int x, int y, int radius, int width, uint32_t colour, bool filled)
{
int ret;
struct dstr str = {0, 0, 0};
dstr_append(&str, "BT ");
if (filled)
dstr_printf(&str, "%f %f %f rg ",
PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));
else
dstr_printf(&str, "%f %f %f RG ",
PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));
dstr_printf(&str, "%d w ", width);
/* This is a bit of a rough approximation of a circle based on bezier curves.
* It's not exact
*/
dstr_printf(&str, "%d %d m ", x + radius, y);
dstr_printf(&str, "%d %d %d %d v ", x + radius, y + radius, x, y + radius);
dstr_printf(&str, "%d %d %d %d v ", x - radius, y + radius, x - radius, y);
dstr_printf(&str, "%d %d %d %d v ", x - radius, y - radius, x, y - radius);
dstr_printf(&str, "%d %d %d %d v ", x + radius, y - radius, x + radius, y);
if (filled)
dstr_append(&str, "f ");
else
dstr_append(&str, "S ");
dstr_append(&str, "ET");
ret = pdf_add_stream(pdf, page, str.data);
dstr_free(&str);
return ret;
}
int pdf_add_rectangle(struct pdf_doc *pdf, struct pdf_object *page,
int x, int y, int width, int height, int border_width,
uint32_t colour)
{
int ret;
struct dstr str = {0, 0, 0};
dstr_append(&str, "BT ");
dstr_printf(&str, "%f %f %f RG ",
PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));
dstr_printf(&str, "%d w ", border_width);
dstr_printf(&str, "%d %d %d %d re S ", x, y, width, height);
dstr_append(&str, "ET");
ret = pdf_add_stream(pdf, page, str.data);
dstr_free(&str);
return ret;
}
int pdf_add_filled_rectangle(struct pdf_doc *pdf, struct pdf_object *page,
int x, int y, int width, int height,
int border_width, uint32_t colour)
{
int ret;
struct dstr str = {0, 0, 0};
dstr_append(&str, "BT ");
dstr_printf(&str, "%f %f %f rg ",
PDF_RGB_R(colour), PDF_RGB_G(colour), PDF_RGB_B(colour));
dstr_printf(&str, "%d w ", border_width);
dstr_printf(&str, "%d %d %d %d re f ", x, y, width, height);
dstr_append(&str, "ET");
ret = pdf_add_stream(pdf, page, str.data);
dstr_free(&str);
return ret;
}
static const struct {
uint32_t code;
char ch;
} code_128a_encoding[] = {
{0x212222, ' '},
{0x222122, '!'},
{0x222221, '"'},
{0x121223, '#'},
{0x121322, '$'},
{0x131222, '%'},
{0x122213, '&'},
{0x122312, '\''},
{0x132212, '('},
{0x221213, ')'},
{0x221312, '*'},
{0x231212, '+'},
{0x112232, ','},
{0x122132, '-'},
{0x122231, '.'},
{0x113222, '/'},
{0x123122, '0'},
{0x123221, '1'},
{0x223211, '2'},
{0x221132, '3'},
{0x221231, '4'},
{0x213212, '5'},
{0x223112, '6'},
{0x312131, '7'},
{0x311222, '8'},
{0x321122, '9'},
{0x321221, ':'},
{0x312212, ';'},
{0x322112, '<'},
{0x322211, '='},
{0x212123, '>'},
{0x212321, '?'},
{0x232121, '@'},
{0x111323, 'A'},
{0x131123, 'B'},
{0x131321, 'C'},
{0x112313, 'D'},
{0x132113, 'E'},
{0x132311, 'F'},
{0x211313, 'G'},
{0x231113, 'H'},
{0x231311, 'I'},
{0x112133, 'J'},
{0x112331, 'K'},
{0x132131, 'L'},
{0x113123, 'M'},
{0x113321, 'N'},
{0x133121, 'O'},
{0x313121, 'P'},
{0x211331, 'Q'},
{0x231131, 'R'},
{0x213113, 'S'},
{0x213311, 'T'},
{0x213131, 'U'},
{0x311123, 'V'},
{0x311321, 'W'},
{0x331121, 'X'},
{0x312113, 'Y'},
{0x312311, 'Z'},
{0x332111, '['},
{0x314111, '\\'},
{0x221411, ']'},
{0x431111, '^'},
{0x111224, '_'},
{0x111422, '`'},
{0x121124, 'a'},
{0x121421, 'b'},
{0x141122, 'c'},
{0x141221, 'd'},
{0x112214, 'e'},
{0x112412, 'f'},
{0x122114, 'g'},
{0x122411, 'h'},
{0x142112, 'i'},
{0x142211, 'j'},
{0x241211, 'k'},
{0x221114, 'l'},
{0x413111, 'm'},
{0x241112, 'n'},
{0x134111, 'o'},
{0x111242, 'p'},
{0x121142, 'q'},
{0x121241, 'r'},
{0x114212, 's'},
{0x124112, 't'},
{0x124211, 'u'},
{0x411212, 'v'},
{0x421112, 'w'},
{0x421211, 'x'},
{0x212141, 'y'},
{0x214121, 'z'},
{0x412121, '{'},
{0x111143, '|'},
{0x111341, '}'},
{0x131141, '~'},
{0x114113, '\0'},
{0x114311, '\0'},
{0x411113, '\0'},
{0x411311, '\0'},
{0x113141, '\0'},
{0x114131, '\0'},
{0x311141, '\0'},
{0x411131, '\0'},
{0x211412, '\0'},
{0x211214, '\0'},
{0x211232, '\0'},
{0x2331112, '\0'},
};
static int find_128_encoding(char ch)
{
int i;
for (i = 0; i < ARRAY_SIZE(code_128a_encoding); i++) {
if (code_128a_encoding[i].ch == ch)
return i;
}
return -1;
}
static int pdf_barcode_128a_ch(struct pdf_doc *pdf, struct pdf_object *page,
int x, int y, int width, int height,
uint32_t colour, int index, int code_len)
{
uint32_t code = code_128a_encoding[index].code;
int i;
int line_width = width / 11;
for (i = 0; i < code_len; i++) {
uint8_t shift = (code_len - 1 - i) * 4;
uint8_t mask = (code >> shift) & 0xf;
if (!(i % 2)) {
int j;
for (j = 0; j < mask; j++) {
pdf_add_line(pdf, page, x, y, x, y + height, line_width, colour);
x += line_width;
}
} else
x += line_width * mask;
}
return x;
}
static int pdf_add_barcode_128a(struct pdf_doc *pdf, struct pdf_object *page,
int x, int y, int width, int height,
const char *string, uint32_t colour)
{
const char *s;
int len = strlen(string) + 3;
int char_width = width / len;
int checksum, i;
for (s = string; *s; s++)
if (find_128_encoding(*s) < 0)
return pdf_set_err(pdf, -EINVAL, "Invalid barcode character 0x%x", *s);
x = pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour, 104,
6);
checksum = 104;
for (i = 1, s = string; *s; s++, i++) {
int index = find_128_encoding(*s);
x = pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour, index,
6);
checksum += index * i;
}
x = pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour,
checksum % 103, 6);
pdf_barcode_128a_ch(pdf, page, x, y, char_width, height, colour, 106,
7);
return 0;
}
/* Code 39 character encoding. Each 4-bit value indicates:
* 0 => wide bar
* 1 => narrow bar
* 2 => wide space
*/
static const struct {
uint32_t code;
char ch;
} code_39_encoding[] = {
{0x012110, '1'},
{0x102110, '2'},
{0x002111, '3'},
{0x112010, '4'},
{0x012011, '5'},
{0x102011, '6'},
{0x112100, '7'},
{0x012101, '8'},
{0x102101, '9'},
{0x112001, '0'},
{0x011210, 'A'},
{0x101210, 'B'},
{0x001211, 'C'},
{0x110210, 'D'},
{0x010211, 'E'},
{0x100211, 'F'},
{0x111200, 'G'},
{0x011201, 'H'},
{0x101201, 'I'},
{0x110201, 'J'},
{0x011120, 'K'},
{0x101120, 'L'},
{0x001121, 'M'},
{0x110120, 'N'},
{0x010121, 'O'},
{0x100121, 'P'},
{0x111020, 'Q'},
{0x011021, 'R'},
{0x101021, 'S'},
{0x110021, 'T'},
{0x021110, 'U'},
{0x120110, 'V'},
{0x020111, 'W'},
{0x121010, 'X'},
{0x021011, 'Y'},
{0x120011, 'Z'},
{0x121100, '-'},
{0x021101, '.'},
{0x120101, ' '},
{0x121001, '*'}, // 'stop' character
};
static int pdf_barcode_39_ch(struct pdf_doc *pdf, struct pdf_object *page, int x, int y, int char_width, int height, uint32_t colour, char ch)
{
int nw = char_width / 12;
int ww = char_width / 4;
int i;
uint32_t code;
if (nw <= 1 || ww <= 1)
return pdf_set_err(pdf, -EINVAL, "Insufficient width for each character");
for (i = 0; i < ARRAY_SIZE(code_39_encoding); i++) {
if (code_39_encoding[i].ch == ch) {
code = code_39_encoding[i].code;
break;
}
}
if (i == ARRAY_SIZE(code_39_encoding))
return pdf_set_err(pdf, -EINVAL, "Invalid Code 39 character %c 0x%x", ch, ch);
for (i = 5; i >= 0; i--) {
int pattern = (code >> i * 4) & 0xf;
if (pattern == 0) { // wide
if (pdf_add_filled_rectangle(pdf, page, x, y, ww - 1, height, 0, colour) < 0)
return pdf->errval;
x += ww;
}
if (pattern == 1) { // narrow
if (pdf_add_filled_rectangle(pdf, page, x, y, nw - 1, height, 0, colour) < 0)
return pdf->errval;
x += nw;
}
if (pattern == 2) { // space
x += nw;
}
}
return x;
}
static int pdf_add_barcode_39(struct pdf_doc *pdf, struct pdf_object *page,
int x, int y, int width, int height,
const char *string, uint32_t colour)
{
int len = strlen(string);
int char_width = width / (len + 2);
x = pdf_barcode_39_ch(pdf, page, x, y, char_width, height, colour, '*');
if (x < 0)
return x;
while (string && *string) {
x = pdf_barcode_39_ch(pdf, page, x, y, char_width, height, colour, *string);
if (x < 0)
return x;
string++;
};
x = pdf_barcode_39_ch(pdf, page, x, y, char_width, height, colour, '*');
if (x < 0)
return x;
return 0;
}
int pdf_add_barcode(struct pdf_doc *pdf, struct pdf_object *page,
int code, int x, int y, int width, int height,
const char *string, uint32_t colour)
{
if (!string || !*string)
return 0;
switch (code) {
case PDF_BARCODE_128A:
return pdf_add_barcode_128a(pdf, page, x, y,
width, height, string, colour);
case PDF_BARCODE_39:
return pdf_add_barcode_39(pdf, page, x, y, width, height, string, colour);
default:
return pdf_set_err(pdf, -EINVAL, "Invalid barcode code %d", code);
}
}
static pdf_object *pdf_add_raw_rgb24(struct pdf_doc *pdf,
uint8_t *data, int width, int height)
{
struct pdf_object *obj;
char line[1024];
int len;
uint8_t *final_data;
const char *endstream = ">\r\nendstream\r\n";
int i;
sprintf(line,
"<<\r\n/Type /XObject\r\n/Name /Image%d\r\n/Subtype /Image\r\n"
"/ColorSpace /DeviceRGB\r\n/Height %d\r\n/Width %d\r\n"
"/BitsPerComponent 8\r\n/Filter /ASCIIHexDecode\r\n"
"/Length %d\r\n>>stream\r\n",
flexarray_size(&pdf->objects), height, width, width * height * 3 * 2 + 1);
len = strlen(line) + width * height * 3 * 2 + strlen(endstream) + 1;
final_data = malloc(len);
if (!final_data) {
pdf_set_err(pdf, -ENOMEM, "Unable to allocate %d bytes memory for image",
len);
return NULL;
}
strcpy((char *)final_data, line);
uint8_t *pos = &final_data[strlen(line)];
for (i = 0; i < width * height * 3; i++) {
*pos++ = "0123456789ABCDEF"[(data[i] >> 4) & 0xf];
*pos++ = "0123456789ABCDEF"[data[i] & 0xf];
}
strcpy((char *)pos, endstream);
pos += strlen(endstream);
obj = pdf_add_object(pdf, OBJ_image);
if (!obj) {
free(final_data);
return NULL;
}
obj->stream.text = (char *)final_data;
obj->stream.len = pos - final_data;
return obj;
}
/* See http://www.64lines.com/jpeg-width-height for details */
static int jpeg_size(unsigned char* data, unsigned int data_size,
int *width, int *height)
{
int i = 0;
if (i + 3 < data_size && data[i] == 0xFF && data[i+1] == 0xD8 &&
data[i+2] == 0xFF && data[i+3] == 0xE0) {
i += 4;
if(i + 6 < data_size &&
data[i+2] == 'J' && data[i+3] == 'F' && data[i+4] == 'I' &&
data[i+5] == 'F' && data[i+6] == 0x00) {
unsigned short block_length = data[i] * 256 + data[i+1];
while(i<data_size) {
i+=block_length;
if((i + 1) >= data_size)
return -1;
if(data[i] != 0xFF)
return -1;
if(data[i+1] == 0xC0) {
*height = data[i+5]*256 + data[i+6];
*width = data[i+7]*256 + data[i+8];
return 0;
}
i+=2;
block_length = data[i] * 256 + data[i+1];
}
}
}
return -1;
}
static pdf_object *pdf_add_raw_jpeg(struct pdf_doc *pdf,
const char *jpeg_file)
{
struct stat buf;
off_t len;
char *final_data;
uint8_t *jpeg_data;
int written = 0;
FILE *fp;
struct pdf_object *obj;
int width, height;
if (stat(jpeg_file, &buf) < 0) {
pdf_set_err(pdf, -errno, "Unable to access %s: %s", jpeg_file,
strerror(errno));
return NULL;
}
len = buf.st_size;
if ((fp = fopen(jpeg_file, "rb")) == NULL) {
pdf_set_err(pdf, -errno, "Unable to open %s: %s", jpeg_file,
strerror(errno));
return NULL;
}
jpeg_data = malloc(len);
if (!jpeg_data) {
pdf_set_err(pdf, -errno, "Unable to allocate: %zd", len);
fclose(fp);
return NULL;
}
if (fread(jpeg_data, len, 1, fp) != 1) {
pdf_set_err(pdf, -errno, "Unable to read full jpeg data");
free(jpeg_data);
fclose(fp);
return NULL;
}
fclose(fp);
if (jpeg_size(jpeg_data, len, &width, &height) < 0) {
free(jpeg_data);
pdf_set_err(pdf, -EINVAL, "Unable to determine jpeg width/height from %s",
jpeg_file);
return NULL;
}
final_data = malloc(len + 1024);
if (!final_data) {
pdf_set_err(pdf, -errno, "Unable to allocate jpeg data %zd", len + 1024);
free(jpeg_data);
return NULL;
}
written = sprintf(final_data,
"<<\r\n/Type /XObject\r\n/Name /Image%d\r\n"
"/Subtype /Image\r\n/ColorSpace /DeviceRGB\r\n"
"/Width %d\r\n/Height %d\r\n"
"/BitsPerComponent 8\r\n/Filter /DCTDecode\r\n"
"/Length %d\r\n>>stream\r\n",
flexarray_size(&pdf->objects), width, height, (int)len);
memcpy(&final_data[written], jpeg_data, len);
written += len;
written += sprintf(&final_data[written], "\r\nendstream\r\n");
free(jpeg_data);
obj = pdf_add_object(pdf, OBJ_image);
if (!obj) {
free(final_data);
return NULL;
}
obj->stream.text = final_data;
obj->stream.len = written;
return obj;
}
static int pdf_add_image(struct pdf_doc *pdf, struct pdf_object *page,
struct pdf_object *image, int x, int y, int width,
int height)
{
int ret;
struct dstr str = {0, 0, 0};
dstr_append(&str, "q ");
dstr_printf(&str, "%d 0 0 %d %d %d cm ", width, height, x, y);
dstr_printf(&str, "/Image%d Do ", image->index);
dstr_append(&str, "Q");
ret = pdf_add_stream(pdf, page, str.data);
dstr_free(&str);
return ret;
}
int pdf_add_ppm(struct pdf_doc *pdf, struct pdf_object *page,
int x, int y, int display_width, int display_height,
const char *ppm_file)
{
struct pdf_object *obj;
uint8_t *data;
FILE *fp;
char line[1024];
unsigned width, height, size;
/* Load the PPM file */
fp = fopen(ppm_file, "rb");
if (!fp)
return pdf_set_err(pdf, -errno, "Unable to open '%s'", ppm_file);
if (!fgets(line, sizeof(line) - 1, fp)) {
fclose(fp);
return pdf_set_err(pdf, -EINVAL, "Invalid PPM file");
}
/* We only support binary ppms */
if (strncmp(line, "P6", 2) != 0) {
fclose(fp);
return pdf_set_err(pdf, -EINVAL, "Only binary PPM files supported");
}
/* Find the width line */
do {
if (!fgets(line, sizeof(line) - 1, fp)) {
fclose(fp);
return pdf_set_err(pdf, -EINVAL, "Unable to find PPM size");
}
if (line[0] == '#')
continue;
if (sscanf(line, "%u %u\n", &width, &height) != 2) {
fclose(fp);
return pdf_set_err(pdf, -EINVAL, "Unable to find PPM size");
}
break;
} while (1);
/* Skip over the byte-size line */
if (!fgets(line, sizeof(line) - 1, fp)) {
fclose(fp);
return pdf_set_err(pdf, -EINVAL, "No byte-size line in PPM file");
}
if (width > INT_MAX || height > INT_MAX) {
fclose(fp);
return pdf_set_err(pdf, -EINVAL, "Invalid width/height in PPM file: %ux%u", width, height);
}
size = width * height * 3;
data = malloc(size);
if (!data) {
fclose(fp);
return pdf_set_err(pdf, -ENOMEM, "Unable to allocate memory for RGB data");
}
if (fread(data, 1, size, fp) != size) {
free(data);
fclose(fp);
return pdf_set_err(pdf, -EINVAL, "Insufficient RGB data available");
}
fclose(fp);
obj = pdf_add_raw_rgb24(pdf, data, width, height);
free(data);
if (!obj)
return pdf->errval;
return pdf_add_image(pdf, page, obj, x, y, display_width, display_height);
}
int pdf_add_jpeg(struct pdf_doc *pdf, struct pdf_object *page,
int x, int y, int display_width, int display_height,
const char *jpeg_file)
{
struct pdf_object *obj;
obj = pdf_add_raw_jpeg(pdf, jpeg_file);
if (!obj)
return pdf->errval;
return pdf_add_image(pdf, page, obj, x, y, display_width, display_height);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_138_0 |
crossvul-cpp_data_good_3946_3 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Serial Port Device Service Virtual Channel
*
* Copyright 2011 O.S. Systems Software Ltda.
* Copyright 2011 Eduardo Fiss Beloni <beloni@ossystems.com.br>
* Copyright 2014 Hewlett-Packard Development Company, L.P.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <winpr/collections.h>
#include <winpr/comm.h>
#include <winpr/crt.h>
#include <winpr/stream.h>
#include <winpr/synch.h>
#include <winpr/thread.h>
#include <winpr/wlog.h>
#include <freerdp/freerdp.h>
#include <freerdp/channels/rdpdr.h>
#include <freerdp/channels/log.h>
#define TAG CHANNELS_TAG("serial.client")
/* TODO: all #ifdef __linux__ could be removed once only some generic
* functions will be used. Replace CommReadFile by ReadFile,
* CommWriteFile by WriteFile etc.. */
#if defined __linux__ && !defined ANDROID
#define MAX_IRP_THREADS 5
typedef struct _SERIAL_DEVICE SERIAL_DEVICE;
struct _SERIAL_DEVICE
{
DEVICE device;
BOOL permissive;
SERIAL_DRIVER_ID ServerSerialDriverId;
HANDLE* hComm;
wLog* log;
HANDLE MainThread;
wMessageQueue* MainIrpQueue;
/* one thread per pending IRP and indexed according their CompletionId */
wListDictionary* IrpThreads;
UINT32 IrpThreadToBeTerminatedCount;
CRITICAL_SECTION TerminatingIrpThreadsLock;
rdpContext* rdpcontext;
};
typedef struct _IRP_THREAD_DATA IRP_THREAD_DATA;
struct _IRP_THREAD_DATA
{
SERIAL_DEVICE* serial;
IRP* irp;
};
static UINT32 _GetLastErrorToIoStatus(SERIAL_DEVICE* serial)
{
/* http://msdn.microsoft.com/en-us/library/ff547466%28v=vs.85%29.aspx#generic_status_values_for_serial_device_control_requests
*/
switch (GetLastError())
{
case ERROR_BAD_DEVICE:
return STATUS_INVALID_DEVICE_REQUEST;
case ERROR_CALL_NOT_IMPLEMENTED:
return STATUS_NOT_IMPLEMENTED;
case ERROR_CANCELLED:
return STATUS_CANCELLED;
case ERROR_INSUFFICIENT_BUFFER:
return STATUS_BUFFER_TOO_SMALL; /* NB: STATUS_BUFFER_SIZE_TOO_SMALL not defined */
case ERROR_INVALID_DEVICE_OBJECT_PARAMETER: /* eg: SerCx2.sys' _purge() */
return STATUS_INVALID_DEVICE_STATE;
case ERROR_INVALID_HANDLE:
return STATUS_INVALID_DEVICE_REQUEST;
case ERROR_INVALID_PARAMETER:
return STATUS_INVALID_PARAMETER;
case ERROR_IO_DEVICE:
return STATUS_IO_DEVICE_ERROR;
case ERROR_IO_PENDING:
return STATUS_PENDING;
case ERROR_NOT_SUPPORTED:
return STATUS_NOT_SUPPORTED;
case ERROR_TIMEOUT:
return STATUS_TIMEOUT;
/* no default */
}
WLog_Print(serial->log, WLOG_DEBUG, "unexpected last-error: 0x%08" PRIX32 "", GetLastError());
return STATUS_UNSUCCESSFUL;
}
static UINT serial_process_irp_create(SERIAL_DEVICE* serial, IRP* irp)
{
DWORD DesiredAccess;
DWORD SharedAccess;
DWORD CreateDisposition;
UINT32 PathLength;
if (Stream_GetRemainingLength(irp->input) < 32)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, DesiredAccess); /* DesiredAccess (4 bytes) */
Stream_Seek_UINT64(irp->input); /* AllocationSize (8 bytes) */
Stream_Seek_UINT32(irp->input); /* FileAttributes (4 bytes) */
Stream_Read_UINT32(irp->input, SharedAccess); /* SharedAccess (4 bytes) */
Stream_Read_UINT32(irp->input, CreateDisposition); /* CreateDisposition (4 bytes) */
Stream_Seek_UINT32(irp->input); /* CreateOptions (4 bytes) */
Stream_Read_UINT32(irp->input, PathLength); /* PathLength (4 bytes) */
if (!Stream_SafeSeek(irp->input, PathLength)) /* Path (variable) */
return ERROR_INVALID_DATA;
assert(PathLength == 0); /* MS-RDPESP 2.2.2.2 */
#ifndef _WIN32
/* Windows 2012 server sends on a first call :
* DesiredAccess = 0x00100080: SYNCHRONIZE | FILE_READ_ATTRIBUTES
* SharedAccess = 0x00000007: FILE_SHARE_DELETE | FILE_SHARE_WRITE | FILE_SHARE_READ
* CreateDisposition = 0x00000001: CREATE_NEW
*
* then Windows 2012 sends :
* DesiredAccess = 0x00120089: SYNCHRONIZE | READ_CONTROL | FILE_READ_ATTRIBUTES |
* FILE_READ_EA | FILE_READ_DATA SharedAccess = 0x00000007: FILE_SHARE_DELETE |
* FILE_SHARE_WRITE | FILE_SHARE_READ CreateDisposition = 0x00000001: CREATE_NEW
*
* assert(DesiredAccess == (GENERIC_READ | GENERIC_WRITE));
* assert(SharedAccess == 0);
* assert(CreateDisposition == OPEN_EXISTING);
*
*/
WLog_Print(serial->log, WLOG_DEBUG,
"DesiredAccess: 0x%" PRIX32 ", SharedAccess: 0x%" PRIX32
", CreateDisposition: 0x%" PRIX32 "",
DesiredAccess, SharedAccess, CreateDisposition);
/* FIXME: As of today only the flags below are supported by CommCreateFileA: */
DesiredAccess = GENERIC_READ | GENERIC_WRITE;
SharedAccess = 0;
CreateDisposition = OPEN_EXISTING;
#endif
serial->hComm =
CreateFile(serial->device.name, DesiredAccess, SharedAccess, NULL, /* SecurityAttributes */
CreateDisposition, 0, /* FlagsAndAttributes */
NULL); /* TemplateFile */
if (!serial->hComm || (serial->hComm == INVALID_HANDLE_VALUE))
{
WLog_Print(serial->log, WLOG_WARN, "CreateFile failure: %s last-error: 0x%08" PRIX32 "",
serial->device.name, GetLastError());
irp->IoStatus = STATUS_UNSUCCESSFUL;
goto error_handle;
}
_comm_setServerSerialDriver(serial->hComm, serial->ServerSerialDriverId);
_comm_set_permissive(serial->hComm, serial->permissive);
/* NOTE: binary mode/raw mode required for the redirection. On
* Linux, CommCreateFileA forces this setting.
*/
/* ZeroMemory(&dcb, sizeof(DCB)); */
/* dcb.DCBlength = sizeof(DCB); */
/* GetCommState(serial->hComm, &dcb); */
/* dcb.fBinary = TRUE; */
/* SetCommState(serial->hComm, &dcb); */
assert(irp->FileId == 0);
irp->FileId = irp->devman->id_sequence++; /* FIXME: why not ((WINPR_COMM*)hComm)->fd? */
irp->IoStatus = STATUS_SUCCESS;
WLog_Print(serial->log, WLOG_DEBUG, "%s (DeviceId: %" PRIu32 ", FileId: %" PRIu32 ") created.",
serial->device.name, irp->device->id, irp->FileId);
error_handle:
Stream_Write_UINT32(irp->output, irp->FileId); /* FileId (4 bytes) */
Stream_Write_UINT8(irp->output, 0); /* Information (1 byte) */
return CHANNEL_RC_OK;
}
static UINT serial_process_irp_close(SERIAL_DEVICE* serial, IRP* irp)
{
if (Stream_GetRemainingLength(irp->input) < 32)
return ERROR_INVALID_DATA;
Stream_Seek(irp->input, 32); /* Padding (32 bytes) */
if (!CloseHandle(serial->hComm))
{
WLog_Print(serial->log, WLOG_WARN, "CloseHandle failure: %s (%" PRIu32 ") closed.",
serial->device.name, irp->device->id);
irp->IoStatus = STATUS_UNSUCCESSFUL;
goto error_handle;
}
WLog_Print(serial->log, WLOG_DEBUG, "%s (DeviceId: %" PRIu32 ", FileId: %" PRIu32 ") closed.",
serial->device.name, irp->device->id, irp->FileId);
serial->hComm = NULL;
irp->IoStatus = STATUS_SUCCESS;
error_handle:
Stream_Zero(irp->output, 5); /* Padding (5 bytes) */
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT serial_process_irp_read(SERIAL_DEVICE* serial, IRP* irp)
{
UINT32 Length;
UINT64 Offset;
BYTE* buffer = NULL;
DWORD nbRead = 0;
if (Stream_GetRemainingLength(irp->input) < 32)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */
Stream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */
Stream_Seek(irp->input, 20); /* Padding (20 bytes) */
buffer = (BYTE*)calloc(Length, sizeof(BYTE));
if (buffer == NULL)
{
irp->IoStatus = STATUS_NO_MEMORY;
goto error_handle;
}
/* MS-RDPESP 3.2.5.1.4: If the Offset field is not set to 0, the value MUST be ignored
* assert(Offset == 0);
*/
WLog_Print(serial->log, WLOG_DEBUG, "reading %" PRIu32 " bytes from %s", Length,
serial->device.name);
/* FIXME: CommReadFile to be replaced by ReadFile */
if (CommReadFile(serial->hComm, buffer, Length, &nbRead, NULL))
{
irp->IoStatus = STATUS_SUCCESS;
}
else
{
WLog_Print(serial->log, WLOG_DEBUG,
"read failure to %s, nbRead=%" PRIu32 ", last-error: 0x%08" PRIX32 "",
serial->device.name, nbRead, GetLastError());
irp->IoStatus = _GetLastErrorToIoStatus(serial);
}
WLog_Print(serial->log, WLOG_DEBUG, "%" PRIu32 " bytes read from %s", nbRead,
serial->device.name);
error_handle:
Stream_Write_UINT32(irp->output, nbRead); /* Length (4 bytes) */
if (nbRead > 0)
{
if (!Stream_EnsureRemainingCapacity(irp->output, nbRead))
{
WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!");
free(buffer);
return CHANNEL_RC_NO_MEMORY;
}
Stream_Write(irp->output, buffer, nbRead); /* ReadData */
}
free(buffer);
return CHANNEL_RC_OK;
}
static UINT serial_process_irp_write(SERIAL_DEVICE* serial, IRP* irp)
{
UINT32 Length;
UINT64 Offset;
void* ptr;
DWORD nbWritten = 0;
if (Stream_GetRemainingLength(irp->input) < 32)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, Length); /* Length (4 bytes) */
Stream_Read_UINT64(irp->input, Offset); /* Offset (8 bytes) */
if (!Stream_SafeSeek(irp->input, 20)) /* Padding (20 bytes) */
return ERROR_INVALID_DATA;
/* MS-RDPESP 3.2.5.1.5: The Offset field is ignored
* assert(Offset == 0);
*
* Using a serial printer, noticed though this field could be
* set.
*/
WLog_Print(serial->log, WLOG_DEBUG, "writing %" PRIu32 " bytes to %s", Length,
serial->device.name);
ptr = Stream_Pointer(irp->input);
if (!Stream_SafeSeek(irp->input, Length))
return ERROR_INVALID_DATA;
/* FIXME: CommWriteFile to be replaced by WriteFile */
if (CommWriteFile(serial->hComm, ptr, Length, &nbWritten, NULL))
{
irp->IoStatus = STATUS_SUCCESS;
}
else
{
WLog_Print(serial->log, WLOG_DEBUG,
"write failure to %s, nbWritten=%" PRIu32 ", last-error: 0x%08" PRIX32 "",
serial->device.name, nbWritten, GetLastError());
irp->IoStatus = _GetLastErrorToIoStatus(serial);
}
WLog_Print(serial->log, WLOG_DEBUG, "%" PRIu32 " bytes written to %s", nbWritten,
serial->device.name);
Stream_Write_UINT32(irp->output, nbWritten); /* Length (4 bytes) */
Stream_Write_UINT8(irp->output, 0); /* Padding (1 byte) */
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT serial_process_irp_device_control(SERIAL_DEVICE* serial, IRP* irp)
{
UINT32 IoControlCode;
UINT32 InputBufferLength;
BYTE* InputBuffer = NULL;
UINT32 OutputBufferLength;
BYTE* OutputBuffer = NULL;
DWORD BytesReturned = 0;
if (Stream_GetRemainingLength(irp->input) < 32)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(irp->input, OutputBufferLength); /* OutputBufferLength (4 bytes) */
Stream_Read_UINT32(irp->input, InputBufferLength); /* InputBufferLength (4 bytes) */
Stream_Read_UINT32(irp->input, IoControlCode); /* IoControlCode (4 bytes) */
Stream_Seek(irp->input, 20); /* Padding (20 bytes) */
if (Stream_GetRemainingLength(irp->input) < InputBufferLength)
return ERROR_INVALID_DATA;
OutputBuffer = (BYTE*)calloc(OutputBufferLength, sizeof(BYTE));
if (OutputBuffer == NULL)
{
irp->IoStatus = STATUS_NO_MEMORY;
goto error_handle;
}
InputBuffer = (BYTE*)calloc(InputBufferLength, sizeof(BYTE));
if (InputBuffer == NULL)
{
irp->IoStatus = STATUS_NO_MEMORY;
goto error_handle;
}
Stream_Read(irp->input, InputBuffer, InputBufferLength);
WLog_Print(serial->log, WLOG_DEBUG,
"CommDeviceIoControl: CompletionId=%" PRIu32 ", IoControlCode=[0x%" PRIX32 "] %s",
irp->CompletionId, IoControlCode, _comm_serial_ioctl_name(IoControlCode));
/* FIXME: CommDeviceIoControl to be replaced by DeviceIoControl() */
if (CommDeviceIoControl(serial->hComm, IoControlCode, InputBuffer, InputBufferLength,
OutputBuffer, OutputBufferLength, &BytesReturned, NULL))
{
/* WLog_Print(serial->log, WLOG_DEBUG, "CommDeviceIoControl: CompletionId=%"PRIu32",
* IoControlCode=[0x%"PRIX32"] %s done", irp->CompletionId, IoControlCode,
* _comm_serial_ioctl_name(IoControlCode)); */
irp->IoStatus = STATUS_SUCCESS;
}
else
{
WLog_Print(serial->log, WLOG_DEBUG,
"CommDeviceIoControl failure: IoControlCode=[0x%" PRIX32
"] %s, last-error: 0x%08" PRIX32 "",
IoControlCode, _comm_serial_ioctl_name(IoControlCode), GetLastError());
irp->IoStatus = _GetLastErrorToIoStatus(serial);
}
error_handle:
/* FIXME: find out whether it's required or not to get
* BytesReturned == OutputBufferLength when
* CommDeviceIoControl returns FALSE */
assert(OutputBufferLength == BytesReturned);
Stream_Write_UINT32(irp->output, BytesReturned); /* OutputBufferLength (4 bytes) */
if (BytesReturned > 0)
{
if (!Stream_EnsureRemainingCapacity(irp->output, BytesReturned))
{
WLog_ERR(TAG, "Stream_EnsureRemainingCapacity failed!");
free(InputBuffer);
free(OutputBuffer);
return CHANNEL_RC_NO_MEMORY;
}
Stream_Write(irp->output, OutputBuffer, BytesReturned); /* OutputBuffer */
}
/* FIXME: Why at least Windows 2008R2 gets lost with this
* extra byte and likely on a IOCTL_SERIAL_SET_BAUD_RATE? The
* extra byte is well required according MS-RDPEFS
* 2.2.1.5.5 */
/* else */
/* { */
/* Stream_Write_UINT8(irp->output, 0); /\* Padding (1 byte) *\/ */
/* } */
free(InputBuffer);
free(OutputBuffer);
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT serial_process_irp(SERIAL_DEVICE* serial, IRP* irp)
{
UINT error = CHANNEL_RC_OK;
WLog_Print(serial->log, WLOG_DEBUG,
"IRP MajorFunction: 0x%08" PRIX32 " MinorFunction: 0x%08" PRIX32 "\n",
irp->MajorFunction, irp->MinorFunction);
switch (irp->MajorFunction)
{
case IRP_MJ_CREATE:
error = serial_process_irp_create(serial, irp);
break;
case IRP_MJ_CLOSE:
error = serial_process_irp_close(serial, irp);
break;
case IRP_MJ_READ:
if ((error = serial_process_irp_read(serial, irp)))
WLog_ERR(TAG, "serial_process_irp_read failed with error %" PRIu32 "!", error);
break;
case IRP_MJ_WRITE:
error = serial_process_irp_write(serial, irp);
break;
case IRP_MJ_DEVICE_CONTROL:
if ((error = serial_process_irp_device_control(serial, irp)))
WLog_ERR(TAG, "serial_process_irp_device_control failed with error %" PRIu32 "!",
error);
break;
default:
irp->IoStatus = STATUS_NOT_SUPPORTED;
break;
}
return error;
}
static DWORD WINAPI irp_thread_func(LPVOID arg)
{
IRP_THREAD_DATA* data = (IRP_THREAD_DATA*)arg;
UINT error;
/* blocks until the end of the request */
if ((error = serial_process_irp(data->serial, data->irp)))
{
WLog_ERR(TAG, "serial_process_irp failed with error %" PRIu32 "", error);
goto error_out;
}
EnterCriticalSection(&data->serial->TerminatingIrpThreadsLock);
data->serial->IrpThreadToBeTerminatedCount++;
error = data->irp->Complete(data->irp);
LeaveCriticalSection(&data->serial->TerminatingIrpThreadsLock);
error_out:
if (error && data->serial->rdpcontext)
setChannelError(data->serial->rdpcontext, error, "irp_thread_func reported an error");
/* NB: At this point, the server might already being reusing
* the CompletionId whereas the thread is not yet
* terminated */
free(data);
ExitThread(error);
return error;
}
static void create_irp_thread(SERIAL_DEVICE* serial, IRP* irp)
{
IRP_THREAD_DATA* data = NULL;
HANDLE irpThread;
HANDLE previousIrpThread;
uintptr_t key;
/* for a test/debug purpose, uncomment the code below to get a
* single thread for all IRPs. NB: two IRPs could not be
* processed at the same time, typically two concurent
* Read/Write operations could block each other. */
/* serial_process_irp(serial, irp); */
/* irp->Complete(irp); */
/* return; */
/* NOTE: for good or bad, this implementation relies on the
* server to avoid a flooding of requests. see also _purge().
*/
EnterCriticalSection(&serial->TerminatingIrpThreadsLock);
while (serial->IrpThreadToBeTerminatedCount > 0)
{
/* Cleaning up termitating and pending irp
* threads. See also: irp_thread_func() */
HANDLE irpThread;
ULONG_PTR* ids;
int i, nbIds;
nbIds = ListDictionary_GetKeys(serial->IrpThreads, &ids);
for (i = 0; i < nbIds; i++)
{
/* Checking if ids[i] is terminating or pending */
DWORD waitResult;
ULONG_PTR id = ids[i];
irpThread = ListDictionary_GetItemValue(serial->IrpThreads, (void*)id);
/* FIXME: not quite sure a zero timeout is a good thing to check whether a thread is
* stil alived or not */
waitResult = WaitForSingleObject(irpThread, 0);
if (waitResult == WAIT_OBJECT_0)
{
/* terminating thread */
/* WLog_Print(serial->log, WLOG_DEBUG, "IRP thread with CompletionId=%"PRIuz"
* naturally died", id); */
CloseHandle(irpThread);
ListDictionary_Remove(serial->IrpThreads, (void*)id);
serial->IrpThreadToBeTerminatedCount--;
}
else if (waitResult != WAIT_TIMEOUT)
{
/* unexpected thread state */
WLog_Print(serial->log, WLOG_WARN,
"WaitForSingleObject, got an unexpected result=0x%" PRIX32 "\n",
waitResult);
assert(FALSE);
}
/* pending thread (but not yet terminating thread) if waitResult == WAIT_TIMEOUT */
}
if (serial->IrpThreadToBeTerminatedCount > 0)
{
WLog_Print(serial->log, WLOG_DEBUG, "%" PRIu32 " IRP thread(s) not yet terminated",
serial->IrpThreadToBeTerminatedCount);
Sleep(1); /* 1 ms */
}
free(ids);
}
LeaveCriticalSection(&serial->TerminatingIrpThreadsLock);
/* NB: At this point and thanks to the synchronization we're
* sure that the incoming IRP uses well a recycled
* CompletionId or the server sent again an IRP already posted
* which didn't get yet a response (this later server behavior
* at least observed with IOCTL_SERIAL_WAIT_ON_MASK and
* mstsc.exe).
*
* FIXME: behavior documented somewhere? behavior not yet
* observed with FreeRDP).
*/
key = irp->CompletionId;
previousIrpThread = ListDictionary_GetItemValue(serial->IrpThreads, (void*)key);
if (previousIrpThread)
{
/* Thread still alived <=> Request still pending */
WLog_Print(serial->log, WLOG_DEBUG,
"IRP recall: IRP with the CompletionId=%" PRIu32 " not yet completed!",
irp->CompletionId);
assert(FALSE); /* unimplemented */
/* TODO: asserts that previousIrpThread handles well
* the same request by checking more details. Need an
* access to the IRP object used by previousIrpThread
*/
/* TODO: taking over the pending IRP or sending a kind
* of wake up signal to accelerate the pending
* request
*
* To be considered:
* if (IoControlCode == IOCTL_SERIAL_WAIT_ON_MASK) {
* pComm->PendingEvents |= SERIAL_EV_FREERDP_*;
* }
*/
irp->Discard(irp);
return;
}
if (ListDictionary_Count(serial->IrpThreads) >= MAX_IRP_THREADS)
{
WLog_Print(serial->log, WLOG_WARN,
"Number of IRP threads threshold reached: %d, keep on anyway",
ListDictionary_Count(serial->IrpThreads));
assert(FALSE); /* unimplemented */
/* TODO: MAX_IRP_THREADS has been thought to avoid a
* flooding of pending requests. Use
* WaitForMultipleObjects() when available in winpr
* for threads.
*/
}
/* error_handle to be used ... */
data = (IRP_THREAD_DATA*)calloc(1, sizeof(IRP_THREAD_DATA));
if (data == NULL)
{
WLog_Print(serial->log, WLOG_WARN, "Could not allocate a new IRP_THREAD_DATA.");
goto error_handle;
}
data->serial = serial;
data->irp = irp;
/* data freed by irp_thread_func */
irpThread = CreateThread(NULL, 0, irp_thread_func, (void*)data, 0, NULL);
if (irpThread == INVALID_HANDLE_VALUE)
{
WLog_Print(serial->log, WLOG_WARN, "Could not allocate a new IRP thread.");
goto error_handle;
}
key = irp->CompletionId;
if (!ListDictionary_Add(serial->IrpThreads, (void*)key, irpThread))
{
WLog_ERR(TAG, "ListDictionary_Add failed!");
goto error_handle;
}
return;
error_handle:
irp->IoStatus = STATUS_NO_MEMORY;
irp->Complete(irp);
free(data);
}
static void terminate_pending_irp_threads(SERIAL_DEVICE* serial)
{
ULONG_PTR* ids;
int i, nbIds;
nbIds = ListDictionary_GetKeys(serial->IrpThreads, &ids);
WLog_Print(serial->log, WLOG_DEBUG, "Terminating %d IRP thread(s)", nbIds);
for (i = 0; i < nbIds; i++)
{
HANDLE irpThread;
ULONG_PTR id = ids[i];
irpThread = ListDictionary_GetItemValue(serial->IrpThreads, (void*)id);
TerminateThread(irpThread, 0);
if (WaitForSingleObject(irpThread, INFINITE) == WAIT_FAILED)
{
WLog_ERR(TAG, "WaitForSingleObject failed!");
continue;
}
CloseHandle(irpThread);
WLog_Print(serial->log, WLOG_DEBUG, "IRP thread terminated, CompletionId %p", (void*)id);
}
ListDictionary_Clear(serial->IrpThreads);
free(ids);
}
static DWORD WINAPI serial_thread_func(LPVOID arg)
{
IRP* irp;
wMessage message;
SERIAL_DEVICE* serial = (SERIAL_DEVICE*)arg;
UINT error = CHANNEL_RC_OK;
while (1)
{
if (!MessageQueue_Wait(serial->MainIrpQueue))
{
WLog_ERR(TAG, "MessageQueue_Wait failed!");
error = ERROR_INTERNAL_ERROR;
break;
}
if (!MessageQueue_Peek(serial->MainIrpQueue, &message, TRUE))
{
WLog_ERR(TAG, "MessageQueue_Peek failed!");
error = ERROR_INTERNAL_ERROR;
break;
}
if (message.id == WMQ_QUIT)
{
terminate_pending_irp_threads(serial);
break;
}
irp = (IRP*)message.wParam;
if (irp)
create_irp_thread(serial, irp);
}
if (error && serial->rdpcontext)
setChannelError(serial->rdpcontext, error, "serial_thread_func reported an error");
ExitThread(error);
return error;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT serial_irp_request(DEVICE* device, IRP* irp)
{
SERIAL_DEVICE* serial = (SERIAL_DEVICE*)device;
assert(irp != NULL);
if (irp == NULL)
return CHANNEL_RC_OK;
/* NB: ENABLE_ASYNCIO is set, (MS-RDPEFS 2.2.2.7.2) this
* allows the server to send multiple simultaneous read or
* write requests.
*/
if (!MessageQueue_Post(serial->MainIrpQueue, NULL, 0, (void*)irp, NULL))
{
WLog_ERR(TAG, "MessageQueue_Post failed!");
return ERROR_INTERNAL_ERROR;
}
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT serial_free(DEVICE* device)
{
UINT error;
SERIAL_DEVICE* serial = (SERIAL_DEVICE*)device;
WLog_Print(serial->log, WLOG_DEBUG, "freeing");
MessageQueue_PostQuit(serial->MainIrpQueue, 0);
if (WaitForSingleObject(serial->MainThread, INFINITE) == WAIT_FAILED)
{
error = GetLastError();
WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "!", error);
return error;
}
CloseHandle(serial->MainThread);
if (serial->hComm)
CloseHandle(serial->hComm);
/* Clean up resources */
Stream_Free(serial->device.data, TRUE);
MessageQueue_Free(serial->MainIrpQueue);
ListDictionary_Free(serial->IrpThreads);
DeleteCriticalSection(&serial->TerminatingIrpThreadsLock);
free(serial);
return CHANNEL_RC_OK;
}
#endif /* __linux__ */
#ifdef BUILTIN_CHANNELS
#define DeviceServiceEntry serial_DeviceServiceEntry
#else
#define DeviceServiceEntry FREERDP_API DeviceServiceEntry
#endif
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
UINT DeviceServiceEntry(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints)
{
char* name;
char* path;
char* driver;
RDPDR_SERIAL* device;
#if defined __linux__ && !defined ANDROID
size_t i, len;
SERIAL_DEVICE* serial;
#endif /* __linux__ */
UINT error = CHANNEL_RC_OK;
device = (RDPDR_SERIAL*)pEntryPoints->device;
name = device->Name;
path = device->Path;
driver = device->Driver;
if (!name || (name[0] == '*'))
{
/* TODO: implement auto detection of serial ports */
return CHANNEL_RC_OK;
}
if ((name && name[0]) && (path && path[0]))
{
wLog* log;
log = WLog_Get("com.freerdp.channel.serial.client");
WLog_Print(log, WLOG_DEBUG, "initializing");
#ifndef __linux__ /* to be removed */
WLog_Print(log, WLOG_WARN, "Serial ports redirection not supported on this platform.");
return CHANNEL_RC_INITIALIZATION_ERROR;
#else /* __linux __ */
WLog_Print(log, WLOG_DEBUG, "Defining %s as %s", name, path);
if (!DefineCommDevice(name /* eg: COM1 */, path /* eg: /dev/ttyS0 */))
{
DWORD status = GetLastError();
WLog_ERR(TAG, "DefineCommDevice failed with %08" PRIx32, status);
return ERROR_INTERNAL_ERROR;
}
serial = (SERIAL_DEVICE*)calloc(1, sizeof(SERIAL_DEVICE));
if (!serial)
{
WLog_ERR(TAG, "calloc failed!");
return CHANNEL_RC_NO_MEMORY;
}
serial->log = log;
serial->device.type = RDPDR_DTYP_SERIAL;
serial->device.name = name;
serial->device.IRPRequest = serial_irp_request;
serial->device.Free = serial_free;
serial->rdpcontext = pEntryPoints->rdpcontext;
len = strlen(name);
serial->device.data = Stream_New(NULL, len + 1);
if (!serial->device.data)
{
WLog_ERR(TAG, "calloc failed!");
error = CHANNEL_RC_NO_MEMORY;
goto error_out;
}
for (i = 0; i <= len; i++)
Stream_Write_UINT8(serial->device.data, name[i] < 0 ? '_' : name[i]);
if (driver != NULL)
{
if (_stricmp(driver, "Serial") == 0)
serial->ServerSerialDriverId = SerialDriverSerialSys;
else if (_stricmp(driver, "SerCx") == 0)
serial->ServerSerialDriverId = SerialDriverSerCxSys;
else if (_stricmp(driver, "SerCx2") == 0)
serial->ServerSerialDriverId = SerialDriverSerCx2Sys;
else
{
assert(FALSE);
WLog_Print(serial->log, WLOG_DEBUG,
"Unknown server's serial driver: %s. SerCx2 will be used", driver);
serial->ServerSerialDriverId = SerialDriverSerialSys;
}
}
else
{
/* default driver */
serial->ServerSerialDriverId = SerialDriverSerialSys;
}
if (device->Permissive != NULL)
{
if (_stricmp(device->Permissive, "permissive") == 0)
{
serial->permissive = TRUE;
}
else
{
WLog_Print(serial->log, WLOG_DEBUG, "Unknown flag: %s", device->Permissive);
assert(FALSE);
}
}
WLog_Print(serial->log, WLOG_DEBUG, "Server's serial driver: %s (id: %d)", driver,
serial->ServerSerialDriverId);
/* TODO: implement auto detection of the server's serial driver */
serial->MainIrpQueue = MessageQueue_New(NULL);
if (!serial->MainIrpQueue)
{
WLog_ERR(TAG, "MessageQueue_New failed!");
error = CHANNEL_RC_NO_MEMORY;
goto error_out;
}
/* IrpThreads content only modified by create_irp_thread() */
serial->IrpThreads = ListDictionary_New(FALSE);
if (!serial->IrpThreads)
{
WLog_ERR(TAG, "ListDictionary_New failed!");
error = CHANNEL_RC_NO_MEMORY;
goto error_out;
}
serial->IrpThreadToBeTerminatedCount = 0;
InitializeCriticalSection(&serial->TerminatingIrpThreadsLock);
if ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*)serial)))
{
WLog_ERR(TAG, "EntryPoints->RegisterDevice failed with error %" PRIu32 "!", error);
goto error_out;
}
if (!(serial->MainThread =
CreateThread(NULL, 0, serial_thread_func, (void*)serial, 0, NULL)))
{
WLog_ERR(TAG, "CreateThread failed!");
error = ERROR_INTERNAL_ERROR;
goto error_out;
}
#endif /* __linux __ */
}
return error;
error_out:
#ifdef __linux__ /* to be removed */
ListDictionary_Free(serial->IrpThreads);
MessageQueue_Free(serial->MainIrpQueue);
Stream_Free(serial->device.data, TRUE);
free(serial);
#endif /* __linux __ */
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3946_3 |
crossvul-cpp_data_good_1329_0 | /*
* Copyright (c) Red Hat Inc.
* 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, sub license,
* 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 (including the
* next paragraph) 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 NON-INFRINGEMENT. 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.
*
* Authors: Dave Airlie <airlied@redhat.com>
* Jerome Glisse <jglisse@redhat.com>
* Pauli Nieminen <suokkos@gmail.com>
*/
/* simple list based uncached page pool
* - Pool collects resently freed pages for reuse
* - Use page->lru to keep a free list
* - doesn't track currently in use pages
*/
#define pr_fmt(fmt) "[TTM] " fmt
#include <linux/list.h>
#include <linux/spinlock.h>
#include <linux/highmem.h>
#include <linux/mm_types.h>
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/seq_file.h> /* for seq_printf */
#include <linux/slab.h>
#include <linux/dma-mapping.h>
#include <linux/atomic.h>
#include <drm/ttm/ttm_bo_driver.h>
#include <drm/ttm/ttm_page_alloc.h>
#include <drm/ttm/ttm_set_memory.h>
#define NUM_PAGES_TO_ALLOC (PAGE_SIZE/sizeof(struct page *))
#define SMALL_ALLOCATION 16
#define FREE_ALL_PAGES (~0U)
/* times are in msecs */
#define PAGE_FREE_INTERVAL 1000
/**
* struct ttm_page_pool - Pool to reuse recently allocated uc/wc pages.
*
* @lock: Protects the shared pool from concurrnet access. Must be used with
* irqsave/irqrestore variants because pool allocator maybe called from
* delayed work.
* @fill_lock: Prevent concurrent calls to fill.
* @list: Pool of free uc/wc pages for fast reuse.
* @gfp_flags: Flags to pass for alloc_page.
* @npages: Number of pages in pool.
*/
struct ttm_page_pool {
spinlock_t lock;
bool fill_lock;
struct list_head list;
gfp_t gfp_flags;
unsigned npages;
char *name;
unsigned long nfrees;
unsigned long nrefills;
unsigned int order;
};
/**
* Limits for the pool. They are handled without locks because only place where
* they may change is in sysfs store. They won't have immediate effect anyway
* so forcing serialization to access them is pointless.
*/
struct ttm_pool_opts {
unsigned alloc_size;
unsigned max_size;
unsigned small;
};
#define NUM_POOLS 6
/**
* struct ttm_pool_manager - Holds memory pools for fst allocation
*
* Manager is read only object for pool code so it doesn't need locking.
*
* @free_interval: minimum number of jiffies between freeing pages from pool.
* @page_alloc_inited: reference counting for pool allocation.
* @work: Work that is used to shrink the pool. Work is only run when there is
* some pages to free.
* @small_allocation: Limit in number of pages what is small allocation.
*
* @pools: All pool objects in use.
**/
struct ttm_pool_manager {
struct kobject kobj;
struct shrinker mm_shrink;
struct ttm_pool_opts options;
union {
struct ttm_page_pool pools[NUM_POOLS];
struct {
struct ttm_page_pool wc_pool;
struct ttm_page_pool uc_pool;
struct ttm_page_pool wc_pool_dma32;
struct ttm_page_pool uc_pool_dma32;
struct ttm_page_pool wc_pool_huge;
struct ttm_page_pool uc_pool_huge;
} ;
};
};
static struct attribute ttm_page_pool_max = {
.name = "pool_max_size",
.mode = S_IRUGO | S_IWUSR
};
static struct attribute ttm_page_pool_small = {
.name = "pool_small_allocation",
.mode = S_IRUGO | S_IWUSR
};
static struct attribute ttm_page_pool_alloc_size = {
.name = "pool_allocation_size",
.mode = S_IRUGO | S_IWUSR
};
static struct attribute *ttm_pool_attrs[] = {
&ttm_page_pool_max,
&ttm_page_pool_small,
&ttm_page_pool_alloc_size,
NULL
};
static void ttm_pool_kobj_release(struct kobject *kobj)
{
struct ttm_pool_manager *m =
container_of(kobj, struct ttm_pool_manager, kobj);
kfree(m);
}
static ssize_t ttm_pool_store(struct kobject *kobj,
struct attribute *attr, const char *buffer, size_t size)
{
struct ttm_pool_manager *m =
container_of(kobj, struct ttm_pool_manager, kobj);
int chars;
unsigned val;
chars = sscanf(buffer, "%u", &val);
if (chars == 0)
return size;
/* Convert kb to number of pages */
val = val / (PAGE_SIZE >> 10);
if (attr == &ttm_page_pool_max)
m->options.max_size = val;
else if (attr == &ttm_page_pool_small)
m->options.small = val;
else if (attr == &ttm_page_pool_alloc_size) {
if (val > NUM_PAGES_TO_ALLOC*8) {
pr_err("Setting allocation size to %lu is not allowed. Recommended size is %lu\n",
NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 7),
NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10));
return size;
} else if (val > NUM_PAGES_TO_ALLOC) {
pr_warn("Setting allocation size to larger than %lu is not recommended\n",
NUM_PAGES_TO_ALLOC*(PAGE_SIZE >> 10));
}
m->options.alloc_size = val;
}
return size;
}
static ssize_t ttm_pool_show(struct kobject *kobj,
struct attribute *attr, char *buffer)
{
struct ttm_pool_manager *m =
container_of(kobj, struct ttm_pool_manager, kobj);
unsigned val = 0;
if (attr == &ttm_page_pool_max)
val = m->options.max_size;
else if (attr == &ttm_page_pool_small)
val = m->options.small;
else if (attr == &ttm_page_pool_alloc_size)
val = m->options.alloc_size;
val = val * (PAGE_SIZE >> 10);
return snprintf(buffer, PAGE_SIZE, "%u\n", val);
}
static const struct sysfs_ops ttm_pool_sysfs_ops = {
.show = &ttm_pool_show,
.store = &ttm_pool_store,
};
static struct kobj_type ttm_pool_kobj_type = {
.release = &ttm_pool_kobj_release,
.sysfs_ops = &ttm_pool_sysfs_ops,
.default_attrs = ttm_pool_attrs,
};
static struct ttm_pool_manager *_manager;
/**
* Select the right pool or requested caching state and ttm flags. */
static struct ttm_page_pool *ttm_get_pool(int flags, bool huge,
enum ttm_caching_state cstate)
{
int pool_index;
if (cstate == tt_cached)
return NULL;
if (cstate == tt_wc)
pool_index = 0x0;
else
pool_index = 0x1;
if (flags & TTM_PAGE_FLAG_DMA32) {
if (huge)
return NULL;
pool_index |= 0x2;
} else if (huge) {
pool_index |= 0x4;
}
return &_manager->pools[pool_index];
}
/* set memory back to wb and free the pages. */
static void ttm_pages_put(struct page *pages[], unsigned npages,
unsigned int order)
{
unsigned int i, pages_nr = (1 << order);
if (order == 0) {
if (ttm_set_pages_array_wb(pages, npages))
pr_err("Failed to set %d pages to wb!\n", npages);
}
for (i = 0; i < npages; ++i) {
if (order > 0) {
if (ttm_set_pages_wb(pages[i], pages_nr))
pr_err("Failed to set %d pages to wb!\n", pages_nr);
}
__free_pages(pages[i], order);
}
}
static void ttm_pool_update_free_locked(struct ttm_page_pool *pool,
unsigned freed_pages)
{
pool->npages -= freed_pages;
pool->nfrees += freed_pages;
}
/**
* Free pages from pool.
*
* To prevent hogging the ttm_swap process we only free NUM_PAGES_TO_ALLOC
* number of pages in one go.
*
* @pool: to free the pages from
* @free_all: If set to true will free all pages in pool
* @use_static: Safe to use static buffer
**/
static int ttm_page_pool_free(struct ttm_page_pool *pool, unsigned nr_free,
bool use_static)
{
static struct page *static_buf[NUM_PAGES_TO_ALLOC];
unsigned long irq_flags;
struct page *p;
struct page **pages_to_free;
unsigned freed_pages = 0,
npages_to_free = nr_free;
if (NUM_PAGES_TO_ALLOC < nr_free)
npages_to_free = NUM_PAGES_TO_ALLOC;
if (use_static)
pages_to_free = static_buf;
else
pages_to_free = kmalloc_array(npages_to_free,
sizeof(struct page *),
GFP_KERNEL);
if (!pages_to_free) {
pr_debug("Failed to allocate memory for pool free operation\n");
return 0;
}
restart:
spin_lock_irqsave(&pool->lock, irq_flags);
list_for_each_entry_reverse(p, &pool->list, lru) {
if (freed_pages >= npages_to_free)
break;
pages_to_free[freed_pages++] = p;
/* We can only remove NUM_PAGES_TO_ALLOC at a time. */
if (freed_pages >= NUM_PAGES_TO_ALLOC) {
/* remove range of pages from the pool */
__list_del(p->lru.prev, &pool->list);
ttm_pool_update_free_locked(pool, freed_pages);
/**
* Because changing page caching is costly
* we unlock the pool to prevent stalling.
*/
spin_unlock_irqrestore(&pool->lock, irq_flags);
ttm_pages_put(pages_to_free, freed_pages, pool->order);
if (likely(nr_free != FREE_ALL_PAGES))
nr_free -= freed_pages;
if (NUM_PAGES_TO_ALLOC >= nr_free)
npages_to_free = nr_free;
else
npages_to_free = NUM_PAGES_TO_ALLOC;
freed_pages = 0;
/* free all so restart the processing */
if (nr_free)
goto restart;
/* Not allowed to fall through or break because
* following context is inside spinlock while we are
* outside here.
*/
goto out;
}
}
/* remove range of pages from the pool */
if (freed_pages) {
__list_del(&p->lru, &pool->list);
ttm_pool_update_free_locked(pool, freed_pages);
nr_free -= freed_pages;
}
spin_unlock_irqrestore(&pool->lock, irq_flags);
if (freed_pages)
ttm_pages_put(pages_to_free, freed_pages, pool->order);
out:
if (pages_to_free != static_buf)
kfree(pages_to_free);
return nr_free;
}
/**
* Callback for mm to request pool to reduce number of page held.
*
* XXX: (dchinner) Deadlock warning!
*
* This code is crying out for a shrinker per pool....
*/
static unsigned long
ttm_pool_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
{
static DEFINE_MUTEX(lock);
static unsigned start_pool;
unsigned i;
unsigned pool_offset;
struct ttm_page_pool *pool;
int shrink_pages = sc->nr_to_scan;
unsigned long freed = 0;
unsigned int nr_free_pool;
if (!mutex_trylock(&lock))
return SHRINK_STOP;
pool_offset = ++start_pool % NUM_POOLS;
/* select start pool in round robin fashion */
for (i = 0; i < NUM_POOLS; ++i) {
unsigned nr_free = shrink_pages;
unsigned page_nr;
if (shrink_pages == 0)
break;
pool = &_manager->pools[(i + pool_offset)%NUM_POOLS];
page_nr = (1 << pool->order);
/* OK to use static buffer since global mutex is held. */
nr_free_pool = roundup(nr_free, page_nr) >> pool->order;
shrink_pages = ttm_page_pool_free(pool, nr_free_pool, true);
freed += (nr_free_pool - shrink_pages) << pool->order;
if (freed >= sc->nr_to_scan)
break;
shrink_pages <<= pool->order;
}
mutex_unlock(&lock);
return freed;
}
static unsigned long
ttm_pool_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
{
unsigned i;
unsigned long count = 0;
struct ttm_page_pool *pool;
for (i = 0; i < NUM_POOLS; ++i) {
pool = &_manager->pools[i];
count += (pool->npages << pool->order);
}
return count;
}
static int ttm_pool_mm_shrink_init(struct ttm_pool_manager *manager)
{
manager->mm_shrink.count_objects = ttm_pool_shrink_count;
manager->mm_shrink.scan_objects = ttm_pool_shrink_scan;
manager->mm_shrink.seeks = 1;
return register_shrinker(&manager->mm_shrink);
}
static void ttm_pool_mm_shrink_fini(struct ttm_pool_manager *manager)
{
unregister_shrinker(&manager->mm_shrink);
}
static int ttm_set_pages_caching(struct page **pages,
enum ttm_caching_state cstate, unsigned cpages)
{
int r = 0;
/* Set page caching */
switch (cstate) {
case tt_uncached:
r = ttm_set_pages_array_uc(pages, cpages);
if (r)
pr_err("Failed to set %d pages to uc!\n", cpages);
break;
case tt_wc:
r = ttm_set_pages_array_wc(pages, cpages);
if (r)
pr_err("Failed to set %d pages to wc!\n", cpages);
break;
default:
break;
}
return r;
}
/**
* Free pages the pages that failed to change the caching state. If there is
* any pages that have changed their caching state already put them to the
* pool.
*/
static void ttm_handle_caching_state_failure(struct list_head *pages,
int ttm_flags, enum ttm_caching_state cstate,
struct page **failed_pages, unsigned cpages)
{
unsigned i;
/* Failed pages have to be freed */
for (i = 0; i < cpages; ++i) {
list_del(&failed_pages[i]->lru);
__free_page(failed_pages[i]);
}
}
/**
* Allocate new pages with correct caching.
*
* This function is reentrant if caller updates count depending on number of
* pages returned in pages array.
*/
static int ttm_alloc_new_pages(struct list_head *pages, gfp_t gfp_flags,
int ttm_flags, enum ttm_caching_state cstate,
unsigned count, unsigned order)
{
struct page **caching_array;
struct page *p;
int r = 0;
unsigned i, j, cpages;
unsigned npages = 1 << order;
unsigned max_cpages = min(count << order, (unsigned)NUM_PAGES_TO_ALLOC);
/* allocate array for page caching change */
caching_array = kmalloc_array(max_cpages, sizeof(struct page *),
GFP_KERNEL);
if (!caching_array) {
pr_debug("Unable to allocate table for new pages\n");
return -ENOMEM;
}
for (i = 0, cpages = 0; i < count; ++i) {
p = alloc_pages(gfp_flags, order);
if (!p) {
pr_debug("Unable to get page %u\n", i);
/* store already allocated pages in the pool after
* setting the caching state */
if (cpages) {
r = ttm_set_pages_caching(caching_array,
cstate, cpages);
if (r)
ttm_handle_caching_state_failure(pages,
ttm_flags, cstate,
caching_array, cpages);
}
r = -ENOMEM;
goto out;
}
list_add(&p->lru, pages);
#ifdef CONFIG_HIGHMEM
/* gfp flags of highmem page should never be dma32 so we
* we should be fine in such case
*/
if (PageHighMem(p))
continue;
#endif
for (j = 0; j < npages; ++j) {
caching_array[cpages++] = p++;
if (cpages == max_cpages) {
r = ttm_set_pages_caching(caching_array,
cstate, cpages);
if (r) {
ttm_handle_caching_state_failure(pages,
ttm_flags, cstate,
caching_array, cpages);
goto out;
}
cpages = 0;
}
}
}
if (cpages) {
r = ttm_set_pages_caching(caching_array, cstate, cpages);
if (r)
ttm_handle_caching_state_failure(pages,
ttm_flags, cstate,
caching_array, cpages);
}
out:
kfree(caching_array);
return r;
}
/**
* Fill the given pool if there aren't enough pages and the requested number of
* pages is small.
*/
static void ttm_page_pool_fill_locked(struct ttm_page_pool *pool, int ttm_flags,
enum ttm_caching_state cstate,
unsigned count, unsigned long *irq_flags)
{
struct page *p;
int r;
unsigned cpages = 0;
/**
* Only allow one pool fill operation at a time.
* If pool doesn't have enough pages for the allocation new pages are
* allocated from outside of pool.
*/
if (pool->fill_lock)
return;
pool->fill_lock = true;
/* If allocation request is small and there are not enough
* pages in a pool we fill the pool up first. */
if (count < _manager->options.small
&& count > pool->npages) {
struct list_head new_pages;
unsigned alloc_size = _manager->options.alloc_size;
/**
* Can't change page caching if in irqsave context. We have to
* drop the pool->lock.
*/
spin_unlock_irqrestore(&pool->lock, *irq_flags);
INIT_LIST_HEAD(&new_pages);
r = ttm_alloc_new_pages(&new_pages, pool->gfp_flags, ttm_flags,
cstate, alloc_size, 0);
spin_lock_irqsave(&pool->lock, *irq_flags);
if (!r) {
list_splice(&new_pages, &pool->list);
++pool->nrefills;
pool->npages += alloc_size;
} else {
pr_debug("Failed to fill pool (%p)\n", pool);
/* If we have any pages left put them to the pool. */
list_for_each_entry(p, &new_pages, lru) {
++cpages;
}
list_splice(&new_pages, &pool->list);
pool->npages += cpages;
}
}
pool->fill_lock = false;
}
/**
* Allocate pages from the pool and put them on the return list.
*
* @return zero for success or negative error code.
*/
static int ttm_page_pool_get_pages(struct ttm_page_pool *pool,
struct list_head *pages,
int ttm_flags,
enum ttm_caching_state cstate,
unsigned count, unsigned order)
{
unsigned long irq_flags;
struct list_head *p;
unsigned i;
int r = 0;
spin_lock_irqsave(&pool->lock, irq_flags);
if (!order)
ttm_page_pool_fill_locked(pool, ttm_flags, cstate, count,
&irq_flags);
if (count >= pool->npages) {
/* take all pages from the pool */
list_splice_init(&pool->list, pages);
count -= pool->npages;
pool->npages = 0;
goto out;
}
/* find the last pages to include for requested number of pages. Split
* pool to begin and halve it to reduce search space. */
if (count <= pool->npages/2) {
i = 0;
list_for_each(p, &pool->list) {
if (++i == count)
break;
}
} else {
i = pool->npages + 1;
list_for_each_prev(p, &pool->list) {
if (--i == count)
break;
}
}
/* Cut 'count' number of pages from the pool */
list_cut_position(pages, &pool->list, p);
pool->npages -= count;
count = 0;
out:
spin_unlock_irqrestore(&pool->lock, irq_flags);
/* clear the pages coming from the pool if requested */
if (ttm_flags & TTM_PAGE_FLAG_ZERO_ALLOC) {
struct page *page;
list_for_each_entry(page, pages, lru) {
if (PageHighMem(page))
clear_highpage(page);
else
clear_page(page_address(page));
}
}
/* If pool didn't have enough pages allocate new one. */
if (count) {
gfp_t gfp_flags = pool->gfp_flags;
/* set zero flag for page allocation if required */
if (ttm_flags & TTM_PAGE_FLAG_ZERO_ALLOC)
gfp_flags |= __GFP_ZERO;
if (ttm_flags & TTM_PAGE_FLAG_NO_RETRY)
gfp_flags |= __GFP_RETRY_MAYFAIL;
/* ttm_alloc_new_pages doesn't reference pool so we can run
* multiple requests in parallel.
**/
r = ttm_alloc_new_pages(pages, gfp_flags, ttm_flags, cstate,
count, order);
}
return r;
}
/* Put all pages in pages list to correct pool to wait for reuse */
static void ttm_put_pages(struct page **pages, unsigned npages, int flags,
enum ttm_caching_state cstate)
{
struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate);
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate);
#endif
unsigned long irq_flags;
unsigned i;
if (pool == NULL) {
/* No pool for this memory type so free the pages */
i = 0;
while (i < npages) {
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
struct page *p = pages[i];
#endif
unsigned order = 0, j;
if (!pages[i]) {
++i;
continue;
}
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
if (!(flags & TTM_PAGE_FLAG_DMA32) &&
(npages - i) >= HPAGE_PMD_NR) {
for (j = 0; j < HPAGE_PMD_NR; ++j)
if (p++ != pages[i + j])
break;
if (j == HPAGE_PMD_NR)
order = HPAGE_PMD_ORDER;
}
#endif
if (page_count(pages[i]) != 1)
pr_err("Erroneous page count. Leaking pages.\n");
__free_pages(pages[i], order);
j = 1 << order;
while (j) {
pages[i++] = NULL;
--j;
}
}
return;
}
i = 0;
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
if (huge) {
unsigned max_size, n2free;
spin_lock_irqsave(&huge->lock, irq_flags);
while ((npages - i) >= HPAGE_PMD_NR) {
struct page *p = pages[i];
unsigned j;
if (!p)
break;
for (j = 0; j < HPAGE_PMD_NR; ++j)
if (p++ != pages[i + j])
break;
if (j != HPAGE_PMD_NR)
break;
list_add_tail(&pages[i]->lru, &huge->list);
for (j = 0; j < HPAGE_PMD_NR; ++j)
pages[i++] = NULL;
huge->npages++;
}
/* Check that we don't go over the pool limit */
max_size = _manager->options.max_size;
max_size /= HPAGE_PMD_NR;
if (huge->npages > max_size)
n2free = huge->npages - max_size;
else
n2free = 0;
spin_unlock_irqrestore(&huge->lock, irq_flags);
if (n2free)
ttm_page_pool_free(huge, n2free, false);
}
#endif
spin_lock_irqsave(&pool->lock, irq_flags);
while (i < npages) {
if (pages[i]) {
if (page_count(pages[i]) != 1)
pr_err("Erroneous page count. Leaking pages.\n");
list_add_tail(&pages[i]->lru, &pool->list);
pages[i] = NULL;
pool->npages++;
}
++i;
}
/* Check that we don't go over the pool limit */
npages = 0;
if (pool->npages > _manager->options.max_size) {
npages = pool->npages - _manager->options.max_size;
/* free at least NUM_PAGES_TO_ALLOC number of pages
* to reduce calls to set_memory_wb */
if (npages < NUM_PAGES_TO_ALLOC)
npages = NUM_PAGES_TO_ALLOC;
}
spin_unlock_irqrestore(&pool->lock, irq_flags);
if (npages)
ttm_page_pool_free(pool, npages, false);
}
/*
* On success pages list will hold count number of correctly
* cached pages.
*/
static int ttm_get_pages(struct page **pages, unsigned npages, int flags,
enum ttm_caching_state cstate)
{
struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate);
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate);
#endif
struct list_head plist;
struct page *p = NULL;
unsigned count, first;
int r;
/* No pool for cached pages */
if (pool == NULL) {
gfp_t gfp_flags = GFP_USER;
unsigned i;
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
unsigned j;
#endif
/* set zero flag for page allocation if required */
if (flags & TTM_PAGE_FLAG_ZERO_ALLOC)
gfp_flags |= __GFP_ZERO;
if (flags & TTM_PAGE_FLAG_NO_RETRY)
gfp_flags |= __GFP_RETRY_MAYFAIL;
if (flags & TTM_PAGE_FLAG_DMA32)
gfp_flags |= GFP_DMA32;
else
gfp_flags |= GFP_HIGHUSER;
i = 0;
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
if (!(gfp_flags & GFP_DMA32)) {
while (npages >= HPAGE_PMD_NR) {
gfp_t huge_flags = gfp_flags;
huge_flags |= GFP_TRANSHUGE_LIGHT | __GFP_NORETRY |
__GFP_KSWAPD_RECLAIM;
huge_flags &= ~__GFP_MOVABLE;
huge_flags &= ~__GFP_COMP;
p = alloc_pages(huge_flags, HPAGE_PMD_ORDER);
if (!p)
break;
for (j = 0; j < HPAGE_PMD_NR; ++j)
pages[i++] = p++;
npages -= HPAGE_PMD_NR;
}
}
#endif
first = i;
while (npages) {
p = alloc_page(gfp_flags);
if (!p) {
pr_debug("Unable to allocate page\n");
return -ENOMEM;
}
/* Swap the pages if we detect consecutive order */
if (i > first && pages[i - 1] == p - 1)
swap(p, pages[i - 1]);
pages[i++] = p;
--npages;
}
return 0;
}
count = 0;
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
if (huge && npages >= HPAGE_PMD_NR) {
INIT_LIST_HEAD(&plist);
ttm_page_pool_get_pages(huge, &plist, flags, cstate,
npages / HPAGE_PMD_NR,
HPAGE_PMD_ORDER);
list_for_each_entry(p, &plist, lru) {
unsigned j;
for (j = 0; j < HPAGE_PMD_NR; ++j)
pages[count++] = &p[j];
}
}
#endif
INIT_LIST_HEAD(&plist);
r = ttm_page_pool_get_pages(pool, &plist, flags, cstate,
npages - count, 0);
first = count;
list_for_each_entry(p, &plist, lru) {
struct page *tmp = p;
/* Swap the pages if we detect consecutive order */
if (count > first && pages[count - 1] == tmp - 1)
swap(tmp, pages[count - 1]);
pages[count++] = tmp;
}
if (r) {
/* If there is any pages in the list put them back to
* the pool.
*/
pr_debug("Failed to allocate extra pages for large request\n");
ttm_put_pages(pages, count, flags, cstate);
return r;
}
return 0;
}
static void ttm_page_pool_init_locked(struct ttm_page_pool *pool, gfp_t flags,
char *name, unsigned int order)
{
spin_lock_init(&pool->lock);
pool->fill_lock = false;
INIT_LIST_HEAD(&pool->list);
pool->npages = pool->nfrees = 0;
pool->gfp_flags = flags;
pool->name = name;
pool->order = order;
}
int ttm_page_alloc_init(struct ttm_mem_global *glob, unsigned max_pages)
{
int ret;
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
unsigned order = HPAGE_PMD_ORDER;
#else
unsigned order = 0;
#endif
WARN_ON(_manager);
pr_info("Initializing pool allocator\n");
_manager = kzalloc(sizeof(*_manager), GFP_KERNEL);
if (!_manager)
return -ENOMEM;
ttm_page_pool_init_locked(&_manager->wc_pool, GFP_HIGHUSER, "wc", 0);
ttm_page_pool_init_locked(&_manager->uc_pool, GFP_HIGHUSER, "uc", 0);
ttm_page_pool_init_locked(&_manager->wc_pool_dma32,
GFP_USER | GFP_DMA32, "wc dma", 0);
ttm_page_pool_init_locked(&_manager->uc_pool_dma32,
GFP_USER | GFP_DMA32, "uc dma", 0);
ttm_page_pool_init_locked(&_manager->wc_pool_huge,
(GFP_TRANSHUGE_LIGHT | __GFP_NORETRY |
__GFP_KSWAPD_RECLAIM) &
~(__GFP_MOVABLE | __GFP_COMP),
"wc huge", order);
ttm_page_pool_init_locked(&_manager->uc_pool_huge,
(GFP_TRANSHUGE_LIGHT | __GFP_NORETRY |
__GFP_KSWAPD_RECLAIM) &
~(__GFP_MOVABLE | __GFP_COMP)
, "uc huge", order);
_manager->options.max_size = max_pages;
_manager->options.small = SMALL_ALLOCATION;
_manager->options.alloc_size = NUM_PAGES_TO_ALLOC;
ret = kobject_init_and_add(&_manager->kobj, &ttm_pool_kobj_type,
&glob->kobj, "pool");
if (unlikely(ret != 0))
goto error;
ret = ttm_pool_mm_shrink_init(_manager);
if (unlikely(ret != 0))
goto error;
return 0;
error:
kobject_put(&_manager->kobj);
_manager = NULL;
return ret;
}
void ttm_page_alloc_fini(void)
{
int i;
pr_info("Finalizing pool allocator\n");
ttm_pool_mm_shrink_fini(_manager);
/* OK to use static buffer since global mutex is no longer used. */
for (i = 0; i < NUM_POOLS; ++i)
ttm_page_pool_free(&_manager->pools[i], FREE_ALL_PAGES, true);
kobject_put(&_manager->kobj);
_manager = NULL;
}
static void
ttm_pool_unpopulate_helper(struct ttm_tt *ttm, unsigned mem_count_update)
{
struct ttm_mem_global *mem_glob = ttm->bdev->glob->mem_glob;
unsigned i;
if (mem_count_update == 0)
goto put_pages;
for (i = 0; i < mem_count_update; ++i) {
if (!ttm->pages[i])
continue;
ttm_mem_global_free_page(mem_glob, ttm->pages[i], PAGE_SIZE);
}
put_pages:
ttm_put_pages(ttm->pages, ttm->num_pages, ttm->page_flags,
ttm->caching_state);
ttm->state = tt_unpopulated;
}
int ttm_pool_populate(struct ttm_tt *ttm, struct ttm_operation_ctx *ctx)
{
struct ttm_mem_global *mem_glob = ttm->bdev->glob->mem_glob;
unsigned i;
int ret;
if (ttm->state != tt_unpopulated)
return 0;
if (ttm_check_under_lowerlimit(mem_glob, ttm->num_pages, ctx))
return -ENOMEM;
ret = ttm_get_pages(ttm->pages, ttm->num_pages, ttm->page_flags,
ttm->caching_state);
if (unlikely(ret != 0)) {
ttm_pool_unpopulate_helper(ttm, 0);
return ret;
}
for (i = 0; i < ttm->num_pages; ++i) {
ret = ttm_mem_global_alloc_page(mem_glob, ttm->pages[i],
PAGE_SIZE, ctx);
if (unlikely(ret != 0)) {
ttm_pool_unpopulate_helper(ttm, i);
return -ENOMEM;
}
}
if (unlikely(ttm->page_flags & TTM_PAGE_FLAG_SWAPPED)) {
ret = ttm_tt_swapin(ttm);
if (unlikely(ret != 0)) {
ttm_pool_unpopulate(ttm);
return ret;
}
}
ttm->state = tt_unbound;
return 0;
}
EXPORT_SYMBOL(ttm_pool_populate);
void ttm_pool_unpopulate(struct ttm_tt *ttm)
{
ttm_pool_unpopulate_helper(ttm, ttm->num_pages);
}
EXPORT_SYMBOL(ttm_pool_unpopulate);
int ttm_populate_and_map_pages(struct device *dev, struct ttm_dma_tt *tt,
struct ttm_operation_ctx *ctx)
{
unsigned i, j;
int r;
r = ttm_pool_populate(&tt->ttm, ctx);
if (r)
return r;
for (i = 0; i < tt->ttm.num_pages; ++i) {
struct page *p = tt->ttm.pages[i];
size_t num_pages = 1;
for (j = i + 1; j < tt->ttm.num_pages; ++j) {
if (++p != tt->ttm.pages[j])
break;
++num_pages;
}
tt->dma_address[i] = dma_map_page(dev, tt->ttm.pages[i],
0, num_pages * PAGE_SIZE,
DMA_BIDIRECTIONAL);
if (dma_mapping_error(dev, tt->dma_address[i])) {
while (i--) {
dma_unmap_page(dev, tt->dma_address[i],
PAGE_SIZE, DMA_BIDIRECTIONAL);
tt->dma_address[i] = 0;
}
ttm_pool_unpopulate(&tt->ttm);
return -EFAULT;
}
for (j = 1; j < num_pages; ++j) {
tt->dma_address[i + 1] = tt->dma_address[i] + PAGE_SIZE;
++i;
}
}
return 0;
}
EXPORT_SYMBOL(ttm_populate_and_map_pages);
void ttm_unmap_and_unpopulate_pages(struct device *dev, struct ttm_dma_tt *tt)
{
unsigned i, j;
for (i = 0; i < tt->ttm.num_pages;) {
struct page *p = tt->ttm.pages[i];
size_t num_pages = 1;
if (!tt->dma_address[i] || !tt->ttm.pages[i]) {
++i;
continue;
}
for (j = i + 1; j < tt->ttm.num_pages; ++j) {
if (++p != tt->ttm.pages[j])
break;
++num_pages;
}
dma_unmap_page(dev, tt->dma_address[i], num_pages * PAGE_SIZE,
DMA_BIDIRECTIONAL);
i += num_pages;
}
ttm_pool_unpopulate(&tt->ttm);
}
EXPORT_SYMBOL(ttm_unmap_and_unpopulate_pages);
int ttm_page_alloc_debugfs(struct seq_file *m, void *data)
{
struct ttm_page_pool *p;
unsigned i;
char *h[] = {"pool", "refills", "pages freed", "size"};
if (!_manager) {
seq_printf(m, "No pool allocator running.\n");
return 0;
}
seq_printf(m, "%7s %12s %13s %8s\n",
h[0], h[1], h[2], h[3]);
for (i = 0; i < NUM_POOLS; ++i) {
p = &_manager->pools[i];
seq_printf(m, "%7s %12ld %13ld %8d\n",
p->name, p->nrefills,
p->nfrees, p->npages);
}
return 0;
}
EXPORT_SYMBOL(ttm_page_alloc_debugfs);
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1329_0 |
crossvul-cpp_data_good_4019_1 | /* exif-mnote-data-fuji.c
*
* Copyright (c) 2002 Lutz Mueller <lutz@users.sourceforge.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*/
#include <stdlib.h>
#include <string.h>
#include <config.h>
#include <libexif/exif-byte-order.h>
#include <libexif/exif-utils.h>
#include "exif-mnote-data-fuji.h"
#define CHECKOVERFLOW(offset,datasize,structsize) (( offset >= datasize) || (structsize > datasize) || (offset > datasize - structsize ))
struct _MNoteFujiDataPrivate {
ExifByteOrder order;
};
static void
exif_mnote_data_fuji_clear (ExifMnoteDataFuji *n)
{
ExifMnoteData *d = (ExifMnoteData *) n;
unsigned int i;
if (!n) return;
if (n->entries) {
for (i = 0; i < n->count; i++)
if (n->entries[i].data) {
exif_mem_free (d->mem, n->entries[i].data);
n->entries[i].data = NULL;
}
exif_mem_free (d->mem, n->entries);
n->entries = NULL;
n->count = 0;
}
}
static void
exif_mnote_data_fuji_free (ExifMnoteData *n)
{
if (!n) return;
exif_mnote_data_fuji_clear ((ExifMnoteDataFuji *) n);
}
static char *
exif_mnote_data_fuji_get_value (ExifMnoteData *d, unsigned int i, char *val, unsigned int maxlen)
{
ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) d;
if (!d || !val) return NULL;
if (i > n->count -1) return NULL;
/*
exif_log (d->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataFuji",
"Querying value for tag '%s'...",
mnote_fuji_tag_get_name (n->entries[i].tag));
*/
return mnote_fuji_entry_get_value (&n->entries[i], val, maxlen);
}
static void
exif_mnote_data_fuji_save (ExifMnoteData *ne, unsigned char **buf,
unsigned int *buf_size)
{
ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) ne;
size_t i, o, s, doff;
unsigned char *t;
size_t ts;
if (!n || !buf || !buf_size) return;
/*
* Allocate enough memory for all entries and the number
* of entries.
*/
*buf_size = 8 + 4 + 2 + n->count * 12 + 4;
*buf = exif_mem_alloc (ne->mem, *buf_size);
if (!*buf) {
*buf_size = 0;
return;
}
/*
* Header: "FUJIFILM" and 4 bytes offset to the first entry.
* As the first entry will start right thereafter, the offset is 12.
*/
memcpy (*buf, "FUJIFILM", 8);
exif_set_long (*buf + 8, n->order, 12);
/* Save the number of entries */
exif_set_short (*buf + 8 + 4, n->order, (ExifShort) n->count);
/* Save each entry */
for (i = 0; i < n->count; i++) {
o = 8 + 4 + 2 + i * 12;
exif_set_short (*buf + o + 0, n->order, (ExifShort) n->entries[i].tag);
exif_set_short (*buf + o + 2, n->order, (ExifShort) n->entries[i].format);
exif_set_long (*buf + o + 4, n->order, n->entries[i].components);
o += 8;
s = exif_format_get_size (n->entries[i].format) *
n->entries[i].components;
if (s > 65536) {
/* Corrupt data: EXIF data size is limited to the
* maximum size of a JPEG segment (64 kb).
*/
continue;
}
if (s > 4) {
ts = *buf_size + s;
/* Ensure even offsets. Set padding bytes to 0. */
if (s & 1) ts += 1;
t = exif_mem_realloc (ne->mem, *buf, ts);
if (!t) {
return;
}
*buf = t;
*buf_size = ts;
doff = *buf_size - s;
if (s & 1) { doff--; *(*buf + *buf_size - 1) = '\0'; }
exif_set_long (*buf + o, n->order, doff);
} else
doff = o;
/*
* Write the data. Fill unneeded bytes with 0. Do not
* crash if data is NULL.
*/
if (!n->entries[i].data) memset (*buf + doff, 0, s);
else memcpy (*buf + doff, n->entries[i].data, s);
}
}
static void
exif_mnote_data_fuji_load (ExifMnoteData *en,
const unsigned char *buf, unsigned int buf_size)
{
ExifMnoteDataFuji *n = (ExifMnoteDataFuji*) en;
ExifLong c;
size_t i, tcount, o, datao;
if (!n || !buf || !buf_size) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataFuji", "Short MakerNote");
return;
}
datao = 6 + n->offset;
if (CHECKOVERFLOW(datao, buf_size, 12)) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataFuji", "Short MakerNote");
return;
}
n->order = EXIF_BYTE_ORDER_INTEL;
datao += exif_get_long (buf + datao + 8, EXIF_BYTE_ORDER_INTEL);
if (CHECKOVERFLOW(datao, buf_size, 2)) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataFuji", "Short MakerNote");
return;
}
/* Read the number of tags */
c = exif_get_short (buf + datao, EXIF_BYTE_ORDER_INTEL);
datao += 2;
/* Remove any old entries */
exif_mnote_data_fuji_clear (n);
/* Reserve enough space for all the possible MakerNote tags */
n->entries = exif_mem_alloc (en->mem, sizeof (MnoteFujiEntry) * c);
if (!n->entries) {
EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteDataFuji", sizeof (MnoteFujiEntry) * c);
return;
}
/* Parse all c entries, storing ones that are successfully parsed */
tcount = 0;
for (i = c, o = datao; i; --i, o += 12) {
size_t s;
if (CHECKOVERFLOW(o, buf_size, 12)) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataFuji", "Short MakerNote");
break;
}
n->entries[tcount].tag = exif_get_short (buf + o, n->order);
n->entries[tcount].format = exif_get_short (buf + o + 2, n->order);
n->entries[tcount].components = exif_get_long (buf + o + 4, n->order);
n->entries[tcount].order = n->order;
exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataFuji",
"Loading entry 0x%x ('%s')...", n->entries[tcount].tag,
mnote_fuji_tag_get_name (n->entries[tcount].tag));
/* Check if we overflow the multiplication. Use buf_size as the max size for integer overflow detection,
* we will check the buffer sizes closer later. */
if ( exif_format_get_size (n->entries[tcount].format) &&
buf_size / exif_format_get_size (n->entries[tcount].format) < n->entries[tcount].components
) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataFuji", "Tag size overflow detected (%u * %lu)", exif_format_get_size (n->entries[tcount].format), n->entries[tcount].components);
continue;
}
/*
* Size? If bigger than 4 bytes, the actual data is not
* in the entry but somewhere else (offset).
*/
s = exif_format_get_size (n->entries[tcount].format) * n->entries[tcount].components;
n->entries[tcount].size = s;
if (s) {
size_t dataofs = o + 8;
if (s > 4)
/* The data in this case is merely a pointer */
dataofs = exif_get_long (buf + dataofs, n->order) + 6 + n->offset;
if (CHECKOVERFLOW(dataofs, buf_size, s)) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataFuji", "Tag data past end of "
"buffer (%u >= %u)", (unsigned)(dataofs + s), buf_size);
continue;
}
n->entries[tcount].data = exif_mem_alloc (en->mem, s);
if (!n->entries[tcount].data) {
EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteDataFuji", s);
continue;
}
memcpy (n->entries[tcount].data, buf + dataofs, s);
}
/* Tag was successfully parsed */
++tcount;
}
/* Store the count of successfully parsed tags */
n->count = tcount;
}
static unsigned int
exif_mnote_data_fuji_count (ExifMnoteData *n)
{
return n ? ((ExifMnoteDataFuji *) n)->count : 0;
}
static unsigned int
exif_mnote_data_fuji_get_id (ExifMnoteData *d, unsigned int n)
{
ExifMnoteDataFuji *note = (ExifMnoteDataFuji *) d;
if (!note) return 0;
if (note->count <= n) return 0;
return note->entries[n].tag;
}
static const char *
exif_mnote_data_fuji_get_name (ExifMnoteData *d, unsigned int i)
{
ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) d;
if (!n) return NULL;
if (i >= n->count) return NULL;
return mnote_fuji_tag_get_name (n->entries[i].tag);
}
static const char *
exif_mnote_data_fuji_get_title (ExifMnoteData *d, unsigned int i)
{
ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) d;
if (!n) return NULL;
if (i >= n->count) return NULL;
return mnote_fuji_tag_get_title (n->entries[i].tag);
}
static const char *
exif_mnote_data_fuji_get_description (ExifMnoteData *d, unsigned int i)
{
ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) d;
if (!n) return NULL;
if (i >= n->count) return NULL;
return mnote_fuji_tag_get_description (n->entries[i].tag);
}
static void
exif_mnote_data_fuji_set_byte_order (ExifMnoteData *d, ExifByteOrder o)
{
ExifByteOrder o_orig;
ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) d;
unsigned int i;
if (!n) return;
o_orig = n->order;
n->order = o;
for (i = 0; i < n->count; i++) {
if (n->entries[i].components && (n->entries[i].size/n->entries[i].components < exif_format_get_size (n->entries[i].format)))
continue;
n->entries[i].order = o;
exif_array_set_byte_order (n->entries[i].format, n->entries[i].data,
n->entries[i].components, o_orig, o);
}
}
static void
exif_mnote_data_fuji_set_offset (ExifMnoteData *n, unsigned int o)
{
if (n) ((ExifMnoteDataFuji *) n)->offset = o;
}
int
exif_mnote_data_fuji_identify (const ExifData *ed, const ExifEntry *e)
{
(void) ed; /* unused */
return ((e->size >= 12) && !memcmp (e->data, "FUJIFILM", 8));
}
ExifMnoteData *
exif_mnote_data_fuji_new (ExifMem *mem)
{
ExifMnoteData *d;
if (!mem) return NULL;
d = exif_mem_alloc (mem, sizeof (ExifMnoteDataFuji));
if (!d) return NULL;
exif_mnote_data_construct (d, mem);
/* Set up function pointers */
d->methods.free = exif_mnote_data_fuji_free;
d->methods.set_byte_order = exif_mnote_data_fuji_set_byte_order;
d->methods.set_offset = exif_mnote_data_fuji_set_offset;
d->methods.load = exif_mnote_data_fuji_load;
d->methods.save = exif_mnote_data_fuji_save;
d->methods.count = exif_mnote_data_fuji_count;
d->methods.get_id = exif_mnote_data_fuji_get_id;
d->methods.get_name = exif_mnote_data_fuji_get_name;
d->methods.get_title = exif_mnote_data_fuji_get_title;
d->methods.get_description = exif_mnote_data_fuji_get_description;
d->methods.get_value = exif_mnote_data_fuji_get_value;
return d;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4019_1 |
crossvul-cpp_data_bad_669_3 | /*
* Record values functions
*
* Copyright (C) 2011-2018, Joachim Metz <joachim.metz@gmail.com>
*
* Refer to AUTHORS for acknowledgements.
*
* This software is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see <http://www.gnu.org/licenses/>.
*/
#include <common.h>
#include <byte_stream.h>
#include <memory.h>
#include <system_string.h>
#include <types.h>
#include "libevt_debug.h"
#include "libevt_io_handle.h"
#include "libevt_libbfio.h"
#include "libevt_libcerror.h"
#include "libevt_libcnotify.h"
#include "libevt_libfdatetime.h"
#include "libevt_libfvalue.h"
#include "libevt_libfwnt.h"
#include "libevt_record_values.h"
#include "libevt_unused.h"
#include "evt_file_header.h"
#include "evt_record.h"
const uint8_t evt_end_of_file_record_signature1[ 4 ] = { 0x11, 0x11, 0x11, 0x11 };
const uint8_t evt_end_of_file_record_signature2[ 4 ] = { 0x22, 0x22, 0x22, 0x22 };
const uint8_t evt_end_of_file_record_signature3[ 4 ] = { 0x33, 0x33, 0x33, 0x33 };
const uint8_t evt_end_of_file_record_signature4[ 4 ] = { 0x44, 0x44, 0x44, 0x44 };
/* Creates record values
* Make sure the value record_values is referencing, is set to NULL
* Returns 1 if successful or -1 on error
*/
int libevt_record_values_initialize(
libevt_record_values_t **record_values,
libcerror_error_t **error )
{
static char *function = "libevt_record_values_initialize";
if( record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record values.",
function );
return( -1 );
}
if( *record_values != NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_ALREADY_SET,
"%s: invalid record values value already set.",
function );
return( -1 );
}
*record_values = memory_allocate_structure(
libevt_record_values_t );
if( *record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_MEMORY,
LIBCERROR_MEMORY_ERROR_INSUFFICIENT,
"%s: unable to create record values.",
function );
goto on_error;
}
if( memory_set(
*record_values,
0,
sizeof( libevt_record_values_t ) ) == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_MEMORY,
LIBCERROR_MEMORY_ERROR_SET_FAILED,
"%s: unable to clear record values.",
function );
goto on_error;
}
return( 1 );
on_error:
if( *record_values != NULL )
{
memory_free(
*record_values );
*record_values = NULL;
}
return( -1 );
}
/* Frees record values
* Returns 1 if successful or -1 on error
*/
int libevt_record_values_free(
libevt_record_values_t **record_values,
libcerror_error_t **error )
{
static char *function = "libevt_record_values_free";
int result = 1;
if( record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record values.",
function );
return( -1 );
}
if( *record_values != NULL )
{
if( ( *record_values )->source_name != NULL )
{
if( libfvalue_value_free(
&( ( *record_values )->source_name ),
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED,
"%s: unable to free source name value.",
function );
result = -1;
}
}
if( ( *record_values )->computer_name != NULL )
{
if( libfvalue_value_free(
&( ( *record_values )->computer_name ),
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED,
"%s: unable to free computer name value.",
function );
result = -1;
}
}
if( ( *record_values )->user_security_identifier != NULL )
{
if( libfvalue_value_free(
&( ( *record_values )->user_security_identifier ),
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED,
"%s: unable to free user security identifier (SID).",
function );
result = -1;
}
}
if( ( *record_values )->strings != NULL )
{
if( libfvalue_value_free(
&( ( *record_values )->strings ),
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED,
"%s: unable to free strings.",
function );
result = -1;
}
}
if( ( *record_values )->data != NULL )
{
if( libfvalue_value_free(
&( ( *record_values )->data ),
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED,
"%s: unable to free data.",
function );
result = -1;
}
}
memory_free(
*record_values );
*record_values = NULL;
}
return( result );
}
/* Clones the record values
* Returns 1 if successful or -1 on error
*/
int libevt_record_values_clone(
libevt_record_values_t **destination_record_values,
libevt_record_values_t *source_record_values,
libcerror_error_t **error )
{
static char *function = "libevt_record_values_clone";
if( destination_record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid destination record values.",
function );
return( -1 );
}
if( *destination_record_values != NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_ALREADY_SET,
"%s: invalid destination record values value already set.",
function );
return( -1 );
}
if( source_record_values == NULL )
{
*destination_record_values = NULL;
return( 1 );
}
*destination_record_values = memory_allocate_structure(
libevt_record_values_t );
if( *destination_record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_MEMORY,
LIBCERROR_MEMORY_ERROR_INSUFFICIENT,
"%s: unable to create destination record values.",
function );
goto on_error;
}
if( memory_copy(
*destination_record_values,
source_record_values,
sizeof( libevt_record_values_t ) ) == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_MEMORY,
LIBCERROR_MEMORY_ERROR_COPY_FAILED,
"%s: unable to copy source to destination record values.",
function );
goto on_error;
}
return( 1 );
on_error:
if( *destination_record_values != NULL )
{
memory_free(
*destination_record_values );
*destination_record_values = NULL;
}
return( -1 );
}
/* Reads a record_values
* Returns the number of bytes read if successful or -1 on error
*/
ssize_t libevt_record_values_read(
libevt_record_values_t *record_values,
libbfio_handle_t *file_io_handle,
libevt_io_handle_t *io_handle,
off64_t *file_offset,
uint8_t strict_mode,
libcerror_error_t **error )
{
uint8_t record_size_data[ 4 ];
uint8_t *record_data = NULL;
static char *function = "libevt_record_values_read";
size_t read_size = 0;
size_t record_data_offset = 0;
ssize_t read_count = 0;
ssize_t total_read_count = 0;
uint32_t record_data_size = 0;
if( record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record values.",
function );
return( -1 );
}
if( io_handle == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid IO handle.",
function );
return( -1 );
}
if( file_offset == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid file offset.",
function );
return( -1 );
}
record_values->offset = *file_offset;
read_count = libbfio_handle_read_buffer(
file_io_handle,
record_size_data,
sizeof( uint32_t ),
error );
if( read_count != (ssize_t) sizeof( uint32_t ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_READ_FAILED,
"%s: unable to read record size data.",
function );
goto on_error;
}
*file_offset += read_count;
total_read_count = read_count;
byte_stream_copy_to_uint32_little_endian(
record_size_data,
record_data_size );
if( record_data_size < 4 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: record data size value out of bounds.",
function );
goto on_error;
}
#if SIZEOF_SIZE_T <= 4
if( (size_t) record_data_size > (size_t) SSIZE_MAX )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_EXCEEDS_MAXIMUM,
"%s: invalid record data size value exceeds maximum.",
function );
goto on_error;
}
#endif
/* Allocating record data as 4 bytes and then using realloc here
* corrupts the memory
*/
record_data = (uint8_t *) memory_allocate(
sizeof( uint8_t ) * record_data_size );
if( record_data == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_MEMORY,
LIBCERROR_MEMORY_ERROR_INSUFFICIENT,
"%s: unable to create record data.",
function );
goto on_error;
}
byte_stream_copy_from_uint32_little_endian(
record_data,
record_data_size );
record_data_offset = 4;
read_size = record_data_size - record_data_offset;
if( ( (size64_t) *file_offset + read_size ) > io_handle->file_size )
{
read_size = (size_t) ( io_handle->file_size - *file_offset );
}
read_count = libbfio_handle_read_buffer(
file_io_handle,
&( record_data[ record_data_offset ] ),
read_size,
error );
if( read_count != (ssize_t) read_size )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_READ_FAILED,
"%s: unable to read record data.",
function );
goto on_error;
}
*file_offset += read_count;
record_data_offset += read_count;
total_read_count += read_count;
if( record_data_offset < (size_t) record_data_size )
{
if( libbfio_handle_seek_offset(
file_io_handle,
(off64_t) sizeof( evt_file_header_t ),
SEEK_SET,
error ) == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_SEEK_FAILED,
"%s: unable to seek file header offset: %" PRIzd ".",
function,
sizeof( evt_file_header_t ) );
goto on_error;
}
*file_offset = (off64_t) sizeof( evt_file_header_t );
read_size = (size_t) record_data_size - record_data_offset;
read_count = libbfio_handle_read_buffer(
file_io_handle,
&( record_data[ record_data_offset ] ),
read_size,
error );
if( read_count != (ssize_t) read_size )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_READ_FAILED,
"%s: unable to read record data.",
function );
goto on_error;
}
*file_offset += read_count;
total_read_count += read_count;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: record data:\n",
function );
libcnotify_print_data(
record_data,
(size_t) record_data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( memory_compare(
&( record_data[ 4 ] ),
evt_file_signature,
4 ) == 0 )
{
record_values->type = LIBEVT_RECORD_TYPE_EVENT;
}
else if( memory_compare(
&( record_data[ 4 ] ),
evt_end_of_file_record_signature1,
4 ) == 0 )
{
record_values->type = LIBEVT_RECORD_TYPE_END_OF_FILE;
}
else
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_UNSUPPORTED_VALUE,
"%s: unsupported record values signature.",
function );
goto on_error;
}
if( record_values->type == LIBEVT_RECORD_TYPE_EVENT )
{
if( libevt_record_values_read_event(
record_values,
record_data,
(size_t) record_data_size,
strict_mode,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_READ_FAILED,
"%s: unable to read event record values.",
function );
goto on_error;
}
}
else if( record_values->type == LIBEVT_RECORD_TYPE_END_OF_FILE )
{
if( libevt_record_values_read_end_of_file(
record_values,
record_data,
(size_t) record_data_size,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_READ_FAILED,
"%s: unable to read end of file record values.",
function );
goto on_error;
}
}
memory_free(
record_data );
return( total_read_count );
on_error:
if( record_data != NULL )
{
memory_free(
record_data );
}
return( -1 );
}
/* Reads the event record values
* Returns 1 if successful or -1 on error
*/
int libevt_record_values_read_event(
libevt_record_values_t *record_values,
uint8_t *record_data,
size_t record_data_size,
uint8_t strict_mode,
libcerror_error_t **error )
{
static char *function = "libevt_record_values_read_event";
size_t record_data_offset = 0;
size_t strings_data_offset = 0;
ssize_t value_data_size = 0;
uint32_t data_offset = 0;
uint32_t data_size = 0;
uint32_t members_data_size = 0;
uint32_t size = 0;
uint32_t size_copy = 0;
uint32_t strings_offset = 0;
uint32_t strings_size = 0;
uint32_t user_sid_offset = 0;
uint32_t user_sid_size = 0;
#if defined( HAVE_DEBUG_OUTPUT )
uint32_t value_32bit = 0;
uint16_t value_16bit = 0;
#endif
if( record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record values.",
function );
return( -1 );
}
if( record_data == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record data.",
function );
return( -1 );
}
if( record_data_size > (size_t) SSIZE_MAX )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM,
"%s: invalid record data size value exceeds maximum.",
function );
return( -1 );
}
if( record_data_size < ( sizeof( evt_record_event_header_t ) + 4 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: record data size value out of bounds.",
function );
return( -1 );
}
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->size,
size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->record_number,
record_values->number );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->creation_time,
record_values->creation_time );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->written_time,
record_values->written_time );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->event_identifier,
record_values->event_identifier );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->event_type,
record_values->event_type );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->event_category,
record_values->event_category );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->strings_offset,
strings_offset );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->user_sid_size,
user_sid_size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->user_sid_offset,
user_sid_offset );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->data_size,
data_size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->data_offset,
data_offset );
byte_stream_copy_to_uint32_little_endian(
&( record_data[ record_data_size - 4 ] ),
size_copy );
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: size\t\t\t\t\t: %" PRIu32 "\n",
function,
size );
libcnotify_printf(
"%s: signature\t\t\t\t: %c%c%c%c\n",
function,
( (evt_record_event_header_t *) record_data )->signature[ 0 ],
( (evt_record_event_header_t *) record_data )->signature[ 1 ],
( (evt_record_event_header_t *) record_data )->signature[ 2 ],
( (evt_record_event_header_t *) record_data )->signature[ 3 ] );
libcnotify_printf(
"%s: record number\t\t\t\t: %" PRIu32 "\n",
function,
record_values->number );
if( libevt_debug_print_posix_time_value(
function,
"creation time\t\t\t\t",
( (evt_record_event_header_t *) record_data )->creation_time,
4,
LIBFDATETIME_ENDIAN_LITTLE,
LIBFDATETIME_POSIX_TIME_VALUE_TYPE_SECONDS_32BIT_SIGNED,
LIBFDATETIME_STRING_FORMAT_TYPE_CTIME | LIBFDATETIME_STRING_FORMAT_FLAG_DATE_TIME,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print POSIX time value.",
function );
goto on_error;
}
if( libevt_debug_print_posix_time_value(
function,
"written time\t\t\t\t",
( (evt_record_event_header_t *) record_data )->written_time,
4,
LIBFDATETIME_ENDIAN_LITTLE,
LIBFDATETIME_POSIX_TIME_VALUE_TYPE_SECONDS_32BIT_SIGNED,
LIBFDATETIME_STRING_FORMAT_TYPE_CTIME | LIBFDATETIME_STRING_FORMAT_FLAG_DATE_TIME,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print POSIX time value.",
function );
goto on_error;
}
libcnotify_printf(
"%s: event identifier\t\t\t: 0x%08" PRIx32 "\n",
function,
record_values->event_identifier );
libcnotify_printf(
"%s: event identifier: code\t\t\t: %" PRIu32 "\n",
function,
record_values->event_identifier & 0x0000ffffUL );
libcnotify_printf(
"%s: event identifier: facility\t\t: %" PRIu32 "\n",
function,
( record_values->event_identifier & 0x0fff0000UL ) >> 16 );
libcnotify_printf(
"%s: event identifier: reserved\t\t: %" PRIu32 "\n",
function,
( record_values->event_identifier & 0x10000000UL ) >> 28 );
libcnotify_printf(
"%s: event identifier: customer flags\t: %" PRIu32 "\n",
function,
( record_values->event_identifier & 0x20000000UL ) >> 29 );
libcnotify_printf(
"%s: event identifier: severity\t\t: %" PRIu32 " (",
function,
( record_values->event_identifier & 0xc0000000UL ) >> 30 );
libevt_debug_print_event_identifier_severity(
record_values->event_identifier );
libcnotify_printf(
")\n" );
libcnotify_printf(
"%s: event type\t\t\t\t: %" PRIu16 " (",
function,
record_values->event_type );
libevt_debug_print_event_type(
record_values->event_type );
libcnotify_printf(
")\n" );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->number_of_strings,
value_16bit );
libcnotify_printf(
"%s: number of strings\t\t\t: %" PRIu16 "\n",
function,
value_16bit );
libcnotify_printf(
"%s: event category\t\t\t\t: %" PRIu16 "\n",
function,
record_values->event_category );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->event_flags,
value_16bit );
libcnotify_printf(
"%s: event flags\t\t\t\t: 0x%04" PRIx16 "\n",
function,
value_16bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->closing_record_number,
value_32bit );
libcnotify_printf(
"%s: closing record values number\t\t: %" PRIu32 "\n",
function,
value_32bit );
libcnotify_printf(
"%s: strings offset\t\t\t\t: %" PRIu32 "\n",
function,
strings_offset );
libcnotify_printf(
"%s: user security identifier (SID) size\t: %" PRIu32 "\n",
function,
user_sid_size );
libcnotify_printf(
"%s: user security identifier (SID) offset\t: %" PRIu32 "\n",
function,
user_sid_offset );
libcnotify_printf(
"%s: data size\t\t\t\t: %" PRIu32 "\n",
function,
data_size );
libcnotify_printf(
"%s: data offset\t\t\t\t: %" PRIu32 "\n",
function,
data_offset );
}
#endif
record_data_offset = sizeof( evt_record_event_header_t );
if( ( user_sid_offset == 0 )
&& ( user_sid_size != 0 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID offset or size value out of bounds.",
function );
goto on_error;
}
if( user_sid_offset != 0 )
{
if( ( (size_t) user_sid_offset < record_data_offset )
|| ( (size_t) user_sid_offset >= ( record_data_size - 4 ) ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID offset value out of bounds.",
function );
goto on_error;
}
if( user_sid_size != 0 )
{
if( (size_t) ( user_sid_offset + user_sid_size ) > ( record_data_size - 4 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID size value out of bounds.",
function );
goto on_error;
}
}
}
/* If the strings offset is points at the offset at record data size - 4
* the strings are empty. For this to be sane the data offset should
* be the same as the strings offset or the data size 0.
*/
if( ( (size_t) strings_offset < user_sid_offset )
|| ( (size_t) strings_offset >= ( record_data_size - 4 ) ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings offset value out of bounds.",
function );
goto on_error;
}
if( ( (size_t) data_offset < strings_offset )
|| ( (size_t) data_offset >= ( record_data_size - 4 ) ) )
{
if( data_size != 0 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: data offset value out of bounds.",
function );
goto on_error;
}
data_offset = (uint32_t) record_data_size - 4;
}
if( ( (size_t) strings_offset >= ( record_data_size - 4 ) )
&& ( strings_offset != data_offset ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings offset value out of bounds.",
function );
goto on_error;
}
if( strings_offset != 0 )
{
if( strings_offset < record_data_offset )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings offset value out of bounds.",
function );
goto on_error;
}
}
if( user_sid_offset != 0 )
{
members_data_size = user_sid_offset - (uint32_t) record_data_offset;
}
else if( strings_offset != 0 )
{
members_data_size = strings_offset - (uint32_t) record_data_offset;
}
if( strings_offset != 0 )
{
strings_size = data_offset - strings_offset;
}
if( data_size != 0 )
{
if( (size_t) ( data_offset + data_size ) > ( record_data_size - 4 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: data size value out of bounds.",
function );
goto on_error;
}
}
if( members_data_size != 0 )
{
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: members data:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
members_data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( libfvalue_value_type_initialize(
&( record_values->source_name ),
LIBFVALUE_VALUE_TYPE_STRING_UTF16,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create source name value.",
function );
goto on_error;
}
value_data_size = libfvalue_value_type_set_data_string(
record_values->source_name,
&( record_data[ record_data_offset ] ),
members_data_size,
LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error );
if( value_data_size == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of source name value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: source name\t\t\t\t: ",
function );
if( libfvalue_value_print(
record_values->source_name,
0,
0,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print source name value.",
function );
goto on_error;
}
libcnotify_printf(
"\n" );
}
#endif
record_data_offset += value_data_size;
members_data_size -= (uint32_t) value_data_size;
if( libfvalue_value_type_initialize(
&( record_values->computer_name ),
LIBFVALUE_VALUE_TYPE_STRING_UTF16,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create computer name value.",
function );
goto on_error;
}
value_data_size = libfvalue_value_type_set_data_string(
record_values->computer_name,
&( record_data[ record_data_offset ] ),
members_data_size,
LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error );
if( value_data_size == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of computer name value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: computer name\t\t\t\t: ",
function );
if( libfvalue_value_print(
record_values->computer_name,
0,
0,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print computer name value.",
function );
goto on_error;
}
libcnotify_printf(
"\n" );
}
#endif
record_data_offset += value_data_size;
members_data_size -= (uint32_t) value_data_size;
if( members_data_size > 0 )
{
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: members trailing data:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
members_data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
record_data_offset += members_data_size;
}
}
if( user_sid_size != 0 )
{
if( libfvalue_value_type_initialize(
&( record_values->user_security_identifier ),
LIBFVALUE_VALUE_TYPE_NT_SECURITY_IDENTIFIER,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create user security identifier (SID) value.",
function );
goto on_error;
}
if( libfvalue_value_set_data(
record_values->user_security_identifier,
&( record_data[ user_sid_offset ] ),
(size_t) user_sid_size,
LIBFVALUE_ENDIAN_LITTLE,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of user security identifier (SID) value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: user security identifier (SID)\t\t: ",
function );
if( libfvalue_value_print(
record_values->user_security_identifier,
0,
0,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print user security identifier (SID) value.",
function );
goto on_error;
}
libcnotify_printf(
"\n" );
}
#endif
record_data_offset += user_sid_size;
}
if( strings_size != 0 )
{
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: strings data:\n",
function );
libcnotify_print_data(
&( record_data[ strings_offset ] ),
strings_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( size_copy == 0 )
{
/* If the strings data is truncated
*/
strings_data_offset = strings_offset + strings_size - 2;
while( strings_data_offset > strings_offset )
{
if( ( record_data[ strings_data_offset ] != 0 )
|| ( record_data[ strings_data_offset + 1 ] != 0 ) )
{
strings_size += 2;
break;
}
strings_data_offset -= 2;
strings_size -= 2;
}
}
if( libfvalue_value_type_initialize(
&( record_values->strings ),
LIBFVALUE_VALUE_TYPE_STRING_UTF16,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create strings value.",
function );
goto on_error;
}
value_data_size = libfvalue_value_type_set_data_strings_array(
record_values->strings,
&( record_data[ strings_offset ] ),
strings_size,
LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN,
error );
if( value_data_size == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of strings value.",
function );
goto on_error;
}
record_data_offset += strings_size;
}
if( data_size != 0 )
{
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: data:\n",
function );
libcnotify_print_data(
&( record_data[ data_offset ] ),
(size_t) data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( libfvalue_value_type_initialize(
&( record_values->data ),
LIBFVALUE_VALUE_TYPE_BINARY_DATA,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create data value.",
function );
goto on_error;
}
if( libfvalue_value_set_data(
record_values->data,
&( record_data[ record_data_offset ] ),
(size_t) data_size,
LIBFVALUE_ENDIAN_LITTLE,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of data value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
record_data_offset += data_size;
#endif
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
if( record_data_offset < ( record_data_size - 4 ) )
{
libcnotify_printf(
"%s: padding:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
(size_t) record_data_size - record_data_offset - 4,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
libcnotify_printf(
"%s: size copy\t\t\t\t: %" PRIu32 "\n",
function,
size_copy );
libcnotify_printf(
"\n" );
}
#endif
if( ( strict_mode == 0 )
&& ( size_copy == 0 ) )
{
size_copy = size;
}
if( size != size_copy )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_INPUT,
LIBCERROR_INPUT_ERROR_VALUE_MISMATCH,
"%s: value mismatch for size and size copy.",
function );
goto on_error;
}
if( record_data_size != (size_t) size )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_INPUT,
LIBCERROR_INPUT_ERROR_VALUE_MISMATCH,
"%s: value mismatch for record_values data size and size.",
function );
goto on_error;
}
return( 1 );
on_error:
if( record_values->data != NULL )
{
libfvalue_value_free(
&( record_values->data ),
NULL );
}
if( record_values->strings != NULL )
{
libfvalue_value_free(
&( record_values->strings ),
NULL );
}
if( record_values->user_security_identifier != NULL )
{
libfvalue_value_free(
&( record_values->user_security_identifier ),
NULL );
}
if( record_values->computer_name != NULL )
{
libfvalue_value_free(
&( record_values->computer_name ),
NULL );
}
if( record_values->source_name != NULL )
{
libfvalue_value_free(
&( record_values->source_name ),
NULL );
}
return( -1 );
}
/* Reads the end of file record values
* Returns 1 if successful or -1 on error
*/
int libevt_record_values_read_end_of_file(
libevt_record_values_t *record_values,
uint8_t *record_data,
size_t record_data_size,
libcerror_error_t **error )
{
static char *function = "libevt_record_values_read_end_of_file";
uint32_t size = 0;
uint32_t size_copy = 0;
#if defined( HAVE_DEBUG_OUTPUT )
uint32_t value_32bit = 0;
#endif
if( record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record values.",
function );
return( -1 );
}
if( record_data == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record data.",
function );
return( -1 );
}
if( record_data_size > (size_t) SSIZE_MAX )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM,
"%s: invalid record data size value exceeds maximum.",
function );
return( -1 );
}
if( record_data_size < sizeof( evt_record_end_of_file_t ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: record data size value out of bounds.",
function );
return( -1 );
}
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->size,
size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->size_copy,
size_copy );
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: size\t\t\t\t: %" PRIu32 "\n",
function,
size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->signature1,
value_32bit );
libcnotify_printf(
"%s: signature1\t\t\t: 0x%08" PRIx32 "\n",
function,
value_32bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->signature2,
value_32bit );
libcnotify_printf(
"%s: signature2\t\t\t: 0x%08" PRIx32 "\n",
function,
value_32bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->signature3,
value_32bit );
libcnotify_printf(
"%s: signature3\t\t\t: 0x%08" PRIx32 "\n",
function,
value_32bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->signature4,
value_32bit );
libcnotify_printf(
"%s: signature4\t\t\t: 0x%08" PRIx32 "\n",
function,
value_32bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->first_record_offset,
value_32bit );
libcnotify_printf(
"%s: first record offset\t\t: 0x%08" PRIx32 "\n",
function,
value_32bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->end_of_file_record_offset,
value_32bit );
libcnotify_printf(
"%s: end of file record offset\t: 0x%08" PRIx32 "\n",
function,
value_32bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->last_record_number,
value_32bit );
libcnotify_printf(
"%s: last record number\t\t: %" PRIu32 "\n",
function,
value_32bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->first_record_number,
value_32bit );
libcnotify_printf(
"%s: first record number\t\t: %" PRIu32 "\n",
function,
value_32bit );
libcnotify_printf(
"%s: size copy\t\t\t: %" PRIu32 "\n",
function,
size_copy );
libcnotify_printf(
"\n" );
}
#endif
if( size != size_copy )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_INPUT,
LIBCERROR_INPUT_ERROR_VALUE_MISMATCH,
"%s: value mismatch for size and size copy.",
function );
return( -1 );
}
if( record_data_size != (size_t) size )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_INPUT,
LIBCERROR_INPUT_ERROR_VALUE_MISMATCH,
"%s: value mismatch for record data size and size.",
function );
return( -1 );
}
/* TODO correct values in IO handle if necessary */
return( 1 );
}
/* Retrieves the type
* Returns 1 if successful or -1 on error
*/
int libevt_record_values_get_type(
libevt_record_values_t *record_values,
uint8_t *type,
libcerror_error_t **error )
{
static char *function = "libevt_record_values_get_type";
if( record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record values.",
function );
return( -1 );
}
if( type == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid type.",
function );
return( -1 );
}
*type = record_values->type;
return( 1 );
}
/* Reads record values
* Callback for the (recovered) records list
* Returns 1 if successful or -1 on error
*/
int libevt_record_values_read_element_data(
libevt_io_handle_t *io_handle,
libbfio_handle_t *file_io_handle,
libfdata_list_element_t *element,
libfcache_cache_t *cache,
int element_file_index LIBEVT_ATTRIBUTE_UNUSED,
off64_t element_offset,
size64_t element_size LIBEVT_ATTRIBUTE_UNUSED,
uint32_t element_flags LIBEVT_ATTRIBUTE_UNUSED,
uint8_t read_flags LIBEVT_ATTRIBUTE_UNUSED,
libcerror_error_t **error )
{
libevt_record_values_t *record_values = NULL;
static char *function = "libevt_record_values_read_element_data";
off64_t file_offset = 0;
ssize_t read_count = 0;
LIBEVT_UNREFERENCED_PARAMETER( element_size )
LIBEVT_UNREFERENCED_PARAMETER( element_file_index )
LIBEVT_UNREFERENCED_PARAMETER( element_flags )
LIBEVT_UNREFERENCED_PARAMETER( read_flags )
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: reading record at offset: %" PRIi64 " (0x%08" PRIx64 ")\n",
function,
element_offset,
element_offset );
}
#endif
if( libbfio_handle_seek_offset(
file_io_handle,
element_offset,
SEEK_SET,
error ) == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_SEEK_FAILED,
"%s: unable to seek record offset: %" PRIi64 ".",
function,
element_offset );
goto on_error;
}
if( libevt_record_values_initialize(
&record_values,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create record values.",
function );
goto on_error;
}
/* File offset must be before being passed to libevt_record_values_read
*/
file_offset = element_offset;
read_count = libevt_record_values_read(
record_values,
file_io_handle,
io_handle,
&file_offset,
0,
error );
if( read_count == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_READ_FAILED,
"%s: unable to read record at offset: %" PRIi64 ".",
function,
element_offset );
goto on_error;
}
if( libfdata_list_element_set_element_value(
element,
(intptr_t *) file_io_handle,
cache,
(intptr_t *) record_values,
(int (*)(intptr_t **, libcerror_error_t **)) &libevt_record_values_free,
LIBFDATA_LIST_ELEMENT_VALUE_FLAG_MANAGED,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set record values as element value.",
function );
goto on_error;
}
return( 1 );
on_error:
if( record_values != NULL )
{
libevt_record_values_free(
&record_values,
NULL );
}
return( -1 );
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_669_3 |
crossvul-cpp_data_bad_1019_2 | /*! @file GPMF_demo.c
*
* @brief Demo to extract GPMF from an MP4
*
* @version 1.0.1
*
* (C) Copyright 2017 GoPro Inc (http://gopro.com/).
*
* Licensed under either:
* - Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0
* - MIT license, http://opensource.org/licenses/MIT
* at your option.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include "../GPMF_parser.h"
#include "GPMF_mp4reader.h"
extern void PrintGPMF(GPMF_stream *ms);
int main(int argc, char *argv[])
{
int32_t ret = GPMF_OK;
GPMF_stream metadata_stream, *ms = &metadata_stream;
double metadatalength;
uint32_t *payload = NULL; //buffer to store GPMF samples from the MP4.
// get file return data
if (argc != 2)
{
printf("usage: %s <file_with_GPMF>\n", argv[0]);
return -1;
}
size_t mp4 = OpenMP4Source(argv[1], MOV_GPMF_TRAK_TYPE, MOV_GPMF_TRAK_SUBTYPE);
// size_t mp4 = OpenMP4SourceUDTA(argv[1]); //Search for GPMF payload with MP4's udta
metadatalength = GetDuration(mp4);
if (metadatalength > 0.0)
{
uint32_t index, payloads = GetNumberPayloads(mp4);
// printf("found %.2fs of metadata, from %d payloads, within %s\n", metadatalength, payloads, argv[1]);
#if 1
if (payloads == 1) // Printf the contents of the single payload
{
uint32_t payloadsize = GetPayloadSize(mp4,0);
payload = GetPayload(mp4, payload, 0);
if(payload == NULL)
goto cleanup;
ret = GPMF_Init(ms, payload, payloadsize);
if (ret != GPMF_OK)
goto cleanup;
// Output (printf) all the contained GPMF data within this payload
ret = GPMF_Validate(ms, GPMF_RECURSE_LEVELS); // optional
if (GPMF_OK != ret)
{
printf("Invalid Structure\n");
goto cleanup;
}
GPMF_ResetState(ms);
do
{
PrintGPMF(ms); // printf current GPMF KLV
} while (GPMF_OK == GPMF_Next(ms, GPMF_RECURSE_LEVELS));
GPMF_ResetState(ms);
printf("\n");
}
#endif
for (index = 0; index < payloads; index++)
{
uint32_t payloadsize = GetPayloadSize(mp4, index);
float in = 0.0, out = 0.0; //times
payload = GetPayload(mp4, payload, index);
if (payload == NULL)
goto cleanup;
ret = GetPayloadTime(mp4, index, &in, &out);
if (ret != GPMF_OK)
goto cleanup;
ret = GPMF_Init(ms, payload, payloadsize);
if (ret != GPMF_OK)
goto cleanup;
#if 1 // Find all the available Streams and the data carrying FourCC
if (index == 0) // show first payload
{
ret = GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS);
while (GPMF_OK == ret)
{
ret = GPMF_SeekToSamples(ms);
if (GPMF_OK == ret) //find the last FOURCC within the stream
{
uint32_t key = GPMF_Key(ms);
GPMF_SampleType type = GPMF_Type(ms);
uint32_t elements = GPMF_ElementsInStruct(ms);
//uint32_t samples = GPMF_Repeat(ms);
uint32_t samples = GPMF_PayloadSampleCount(ms);
if (samples)
{
printf(" STRM of %c%c%c%c ", PRINTF_4CC(key));
if (type == GPMF_TYPE_COMPLEX)
{
GPMF_stream find_stream;
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_CURRENT_LEVEL))
{
char tmp[64];
char *data = (char *)GPMF_RawData(&find_stream);
int size = GPMF_RawDataSize(&find_stream);
if (size < sizeof(tmp))
{
memcpy(tmp, data, size);
tmp[size] = 0;
printf("of type %s ", tmp);
}
}
}
else
{
printf("of type %c ", type);
}
printf("with %d sample%s ", samples, samples > 1 ? "s" : "");
if (elements > 1)
printf("-- %d elements per sample", elements);
printf("\n");
}
ret = GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS);
}
else
{
if (ret == GPMF_ERROR_BAD_STRUCTURE) // some payload element was corrupt, skip to the next valid GPMF KLV at the previous level.
{
ret = GPMF_Next(ms, GPMF_CURRENT_LEVEL); // this will be the next stream if any more are present.
}
}
}
GPMF_ResetState(ms);
printf("\n");
}
#endif
#if 1 // Find GPS values and return scaled doubles.
if (index == 0) // show first payload
{
if (GPMF_OK == GPMF_FindNext(ms, STR2FOURCC("GPS5"), GPMF_RECURSE_LEVELS) || //GoPro Hero5/6/7 GPS
GPMF_OK == GPMF_FindNext(ms, STR2FOURCC("GPRI"), GPMF_RECURSE_LEVELS)) //GoPro Karma GPS
{
uint32_t key = GPMF_Key(ms);
uint32_t samples = GPMF_Repeat(ms);
uint32_t elements = GPMF_ElementsInStruct(ms);
uint32_t buffersize = samples * elements * sizeof(double);
GPMF_stream find_stream;
double *ptr, *tmpbuffer = malloc(buffersize);
char units[10][6] = { "" };
uint32_t unit_samples = 1;
printf("MP4 Payload time %.3f to %.3f seconds\n", in, out);
if (tmpbuffer && samples)
{
uint32_t i, j;
//Search for any units to display
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_SI_UNITS, GPMF_CURRENT_LEVEL) ||
GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_UNITS, GPMF_CURRENT_LEVEL))
{
char *data = (char *)GPMF_RawData(&find_stream);
int ssize = GPMF_StructSize(&find_stream);
unit_samples = GPMF_Repeat(&find_stream);
for (i = 0; i < unit_samples; i++)
{
memcpy(units[i], data, ssize);
units[i][ssize] = 0;
data += ssize;
}
}
//GPMF_FormattedData(ms, tmpbuffer, buffersize, 0, samples); // Output data in LittleEnd, but no scale
GPMF_ScaledData(ms, tmpbuffer, buffersize, 0, samples, GPMF_TYPE_DOUBLE); //Output scaled data as floats
ptr = tmpbuffer;
for (i = 0; i < samples; i++)
{
printf("%c%c%c%c ", PRINTF_4CC(key));
for (j = 0; j < elements; j++)
printf("%.3f%s, ", *ptr++, units[j%unit_samples]);
printf("\n");
}
free(tmpbuffer);
}
}
GPMF_ResetState(ms);
printf("\n");
}
#endif
}
#if 1
// Find all the available Streams and compute they sample rates
while (GPMF_OK == GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS))
{
if (GPMF_OK == GPMF_SeekToSamples(ms)) //find the last FOURCC within the stream
{
uint32_t fourcc = GPMF_Key(ms);
double rate = GetGPMFSampleRate(mp4, fourcc, GPMF_SAMPLE_RATE_PRECISE);// GPMF_SAMPLE_RATE_FAST);
printf("%c%c%c%c sampling rate = %f Hz\n", PRINTF_4CC(fourcc), rate);
}
}
#endif
cleanup:
if (payload) FreePayload(payload); payload = NULL;
CloseSource(mp4);
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_1019_2 |
crossvul-cpp_data_good_2683_0 | /*
* Copyright (c) 2001
* Fortress Technologies, Inc. All rights reserved.
* Charlie Lenahan (clenahan@fortresstech.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IEEE 802.11 printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "cpack.h"
/* Lengths of 802.11 header components. */
#define IEEE802_11_FC_LEN 2
#define IEEE802_11_DUR_LEN 2
#define IEEE802_11_DA_LEN 6
#define IEEE802_11_SA_LEN 6
#define IEEE802_11_BSSID_LEN 6
#define IEEE802_11_RA_LEN 6
#define IEEE802_11_TA_LEN 6
#define IEEE802_11_ADDR1_LEN 6
#define IEEE802_11_SEQ_LEN 2
#define IEEE802_11_CTL_LEN 2
#define IEEE802_11_CARRIED_FC_LEN 2
#define IEEE802_11_HT_CONTROL_LEN 4
#define IEEE802_11_IV_LEN 3
#define IEEE802_11_KID_LEN 1
/* Frame check sequence length. */
#define IEEE802_11_FCS_LEN 4
/* Lengths of beacon components. */
#define IEEE802_11_TSTAMP_LEN 8
#define IEEE802_11_BCNINT_LEN 2
#define IEEE802_11_CAPINFO_LEN 2
#define IEEE802_11_LISTENINT_LEN 2
#define IEEE802_11_AID_LEN 2
#define IEEE802_11_STATUS_LEN 2
#define IEEE802_11_REASON_LEN 2
/* Length of previous AP in reassocation frame */
#define IEEE802_11_AP_LEN 6
#define T_MGMT 0x0 /* management */
#define T_CTRL 0x1 /* control */
#define T_DATA 0x2 /* data */
#define T_RESV 0x3 /* reserved */
#define ST_ASSOC_REQUEST 0x0
#define ST_ASSOC_RESPONSE 0x1
#define ST_REASSOC_REQUEST 0x2
#define ST_REASSOC_RESPONSE 0x3
#define ST_PROBE_REQUEST 0x4
#define ST_PROBE_RESPONSE 0x5
/* RESERVED 0x6 */
/* RESERVED 0x7 */
#define ST_BEACON 0x8
#define ST_ATIM 0x9
#define ST_DISASSOC 0xA
#define ST_AUTH 0xB
#define ST_DEAUTH 0xC
#define ST_ACTION 0xD
/* RESERVED 0xE */
/* RESERVED 0xF */
static const struct tok st_str[] = {
{ ST_ASSOC_REQUEST, "Assoc Request" },
{ ST_ASSOC_RESPONSE, "Assoc Response" },
{ ST_REASSOC_REQUEST, "ReAssoc Request" },
{ ST_REASSOC_RESPONSE, "ReAssoc Response" },
{ ST_PROBE_REQUEST, "Probe Request" },
{ ST_PROBE_RESPONSE, "Probe Response" },
{ ST_BEACON, "Beacon" },
{ ST_ATIM, "ATIM" },
{ ST_DISASSOC, "Disassociation" },
{ ST_AUTH, "Authentication" },
{ ST_DEAUTH, "DeAuthentication" },
{ ST_ACTION, "Action" },
{ 0, NULL }
};
#define CTRL_CONTROL_WRAPPER 0x7
#define CTRL_BAR 0x8
#define CTRL_BA 0x9
#define CTRL_PS_POLL 0xA
#define CTRL_RTS 0xB
#define CTRL_CTS 0xC
#define CTRL_ACK 0xD
#define CTRL_CF_END 0xE
#define CTRL_END_ACK 0xF
static const struct tok ctrl_str[] = {
{ CTRL_CONTROL_WRAPPER, "Control Wrapper" },
{ CTRL_BAR, "BAR" },
{ CTRL_BA, "BA" },
{ CTRL_PS_POLL, "Power Save-Poll" },
{ CTRL_RTS, "Request-To-Send" },
{ CTRL_CTS, "Clear-To-Send" },
{ CTRL_ACK, "Acknowledgment" },
{ CTRL_CF_END, "CF-End" },
{ CTRL_END_ACK, "CF-End+CF-Ack" },
{ 0, NULL }
};
#define DATA_DATA 0x0
#define DATA_DATA_CF_ACK 0x1
#define DATA_DATA_CF_POLL 0x2
#define DATA_DATA_CF_ACK_POLL 0x3
#define DATA_NODATA 0x4
#define DATA_NODATA_CF_ACK 0x5
#define DATA_NODATA_CF_POLL 0x6
#define DATA_NODATA_CF_ACK_POLL 0x7
#define DATA_QOS_DATA 0x8
#define DATA_QOS_DATA_CF_ACK 0x9
#define DATA_QOS_DATA_CF_POLL 0xA
#define DATA_QOS_DATA_CF_ACK_POLL 0xB
#define DATA_QOS_NODATA 0xC
#define DATA_QOS_CF_POLL_NODATA 0xE
#define DATA_QOS_CF_ACK_POLL_NODATA 0xF
/*
* The subtype field of a data frame is, in effect, composed of 4 flag
* bits - CF-Ack, CF-Poll, Null (means the frame doesn't actually have
* any data), and QoS.
*/
#define DATA_FRAME_IS_CF_ACK(x) ((x) & 0x01)
#define DATA_FRAME_IS_CF_POLL(x) ((x) & 0x02)
#define DATA_FRAME_IS_NULL(x) ((x) & 0x04)
#define DATA_FRAME_IS_QOS(x) ((x) & 0x08)
/*
* Bits in the frame control field.
*/
#define FC_VERSION(fc) ((fc) & 0x3)
#define FC_TYPE(fc) (((fc) >> 2) & 0x3)
#define FC_SUBTYPE(fc) (((fc) >> 4) & 0xF)
#define FC_TO_DS(fc) ((fc) & 0x0100)
#define FC_FROM_DS(fc) ((fc) & 0x0200)
#define FC_MORE_FLAG(fc) ((fc) & 0x0400)
#define FC_RETRY(fc) ((fc) & 0x0800)
#define FC_POWER_MGMT(fc) ((fc) & 0x1000)
#define FC_MORE_DATA(fc) ((fc) & 0x2000)
#define FC_PROTECTED(fc) ((fc) & 0x4000)
#define FC_ORDER(fc) ((fc) & 0x8000)
struct mgmt_header_t {
uint16_t fc;
uint16_t duration;
uint8_t da[IEEE802_11_DA_LEN];
uint8_t sa[IEEE802_11_SA_LEN];
uint8_t bssid[IEEE802_11_BSSID_LEN];
uint16_t seq_ctrl;
};
#define MGMT_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_DA_LEN+IEEE802_11_SA_LEN+\
IEEE802_11_BSSID_LEN+IEEE802_11_SEQ_LEN)
#define CAPABILITY_ESS(cap) ((cap) & 0x0001)
#define CAPABILITY_IBSS(cap) ((cap) & 0x0002)
#define CAPABILITY_CFP(cap) ((cap) & 0x0004)
#define CAPABILITY_CFP_REQ(cap) ((cap) & 0x0008)
#define CAPABILITY_PRIVACY(cap) ((cap) & 0x0010)
struct ssid_t {
uint8_t element_id;
uint8_t length;
u_char ssid[33]; /* 32 + 1 for null */
};
struct rates_t {
uint8_t element_id;
uint8_t length;
uint8_t rate[16];
};
struct challenge_t {
uint8_t element_id;
uint8_t length;
uint8_t text[254]; /* 1-253 + 1 for null */
};
struct fh_t {
uint8_t element_id;
uint8_t length;
uint16_t dwell_time;
uint8_t hop_set;
uint8_t hop_pattern;
uint8_t hop_index;
};
struct ds_t {
uint8_t element_id;
uint8_t length;
uint8_t channel;
};
struct cf_t {
uint8_t element_id;
uint8_t length;
uint8_t count;
uint8_t period;
uint16_t max_duration;
uint16_t dur_remaing;
};
struct tim_t {
uint8_t element_id;
uint8_t length;
uint8_t count;
uint8_t period;
uint8_t bitmap_control;
uint8_t bitmap[251];
};
#define E_SSID 0
#define E_RATES 1
#define E_FH 2
#define E_DS 3
#define E_CF 4
#define E_TIM 5
#define E_IBSS 6
/* reserved 7 */
/* reserved 8 */
/* reserved 9 */
/* reserved 10 */
/* reserved 11 */
/* reserved 12 */
/* reserved 13 */
/* reserved 14 */
/* reserved 15 */
/* reserved 16 */
#define E_CHALLENGE 16
/* reserved 17 */
/* reserved 18 */
/* reserved 19 */
/* reserved 16 */
/* reserved 16 */
struct mgmt_body_t {
uint8_t timestamp[IEEE802_11_TSTAMP_LEN];
uint16_t beacon_interval;
uint16_t listen_interval;
uint16_t status_code;
uint16_t aid;
u_char ap[IEEE802_11_AP_LEN];
uint16_t reason_code;
uint16_t auth_alg;
uint16_t auth_trans_seq_num;
int challenge_present;
struct challenge_t challenge;
uint16_t capability_info;
int ssid_present;
struct ssid_t ssid;
int rates_present;
struct rates_t rates;
int ds_present;
struct ds_t ds;
int cf_present;
struct cf_t cf;
int fh_present;
struct fh_t fh;
int tim_present;
struct tim_t tim;
};
struct ctrl_control_wrapper_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t addr1[IEEE802_11_ADDR1_LEN];
uint16_t carried_fc[IEEE802_11_CARRIED_FC_LEN];
uint16_t ht_control[IEEE802_11_HT_CONTROL_LEN];
};
#define CTRL_CONTROL_WRAPPER_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_ADDR1_LEN+\
IEEE802_11_CARRIED_FC_LEN+\
IEEE802_11_HT_CONTROL_LEN)
struct ctrl_rts_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
uint8_t ta[IEEE802_11_TA_LEN];
};
#define CTRL_RTS_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_RA_LEN+IEEE802_11_TA_LEN)
struct ctrl_cts_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
};
#define CTRL_CTS_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN)
struct ctrl_ack_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
};
#define CTRL_ACK_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN)
struct ctrl_ps_poll_hdr_t {
uint16_t fc;
uint16_t aid;
uint8_t bssid[IEEE802_11_BSSID_LEN];
uint8_t ta[IEEE802_11_TA_LEN];
};
#define CTRL_PS_POLL_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_AID_LEN+\
IEEE802_11_BSSID_LEN+IEEE802_11_TA_LEN)
struct ctrl_end_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
uint8_t bssid[IEEE802_11_BSSID_LEN];
};
#define CTRL_END_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_RA_LEN+IEEE802_11_BSSID_LEN)
struct ctrl_end_ack_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
uint8_t bssid[IEEE802_11_BSSID_LEN];
};
#define CTRL_END_ACK_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_RA_LEN+IEEE802_11_BSSID_LEN)
struct ctrl_ba_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
};
#define CTRL_BA_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN)
struct ctrl_bar_hdr_t {
uint16_t fc;
uint16_t dur;
uint8_t ra[IEEE802_11_RA_LEN];
uint8_t ta[IEEE802_11_TA_LEN];
uint16_t ctl;
uint16_t seq;
};
#define CTRL_BAR_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_RA_LEN+IEEE802_11_TA_LEN+\
IEEE802_11_CTL_LEN+IEEE802_11_SEQ_LEN)
struct meshcntl_t {
uint8_t flags;
uint8_t ttl;
uint8_t seq[4];
uint8_t addr4[6];
uint8_t addr5[6];
uint8_t addr6[6];
};
#define IV_IV(iv) ((iv) & 0xFFFFFF)
#define IV_PAD(iv) (((iv) >> 24) & 0x3F)
#define IV_KEYID(iv) (((iv) >> 30) & 0x03)
#define PRINT_SSID(p) \
if (p.ssid_present) { \
ND_PRINT((ndo, " (")); \
fn_print(ndo, p.ssid.ssid, NULL); \
ND_PRINT((ndo, ")")); \
}
#define PRINT_RATE(_sep, _r, _suf) \
ND_PRINT((ndo, "%s%2.1f%s", _sep, (.5 * ((_r) & 0x7f)), _suf))
#define PRINT_RATES(p) \
if (p.rates_present) { \
int z; \
const char *sep = " ["; \
for (z = 0; z < p.rates.length ; z++) { \
PRINT_RATE(sep, p.rates.rate[z], \
(p.rates.rate[z] & 0x80 ? "*" : "")); \
sep = " "; \
} \
if (p.rates.length != 0) \
ND_PRINT((ndo, " Mbit]")); \
}
#define PRINT_DS_CHANNEL(p) \
if (p.ds_present) \
ND_PRINT((ndo, " CH: %u", p.ds.channel)); \
ND_PRINT((ndo, "%s", \
CAPABILITY_PRIVACY(p.capability_info) ? ", PRIVACY" : ""));
#define MAX_MCS_INDEX 76
/*
* Indices are:
*
* the MCS index (0-76);
*
* 0 for 20 MHz, 1 for 40 MHz;
*
* 0 for a long guard interval, 1 for a short guard interval.
*/
static const float ieee80211_float_htrates[MAX_MCS_INDEX+1][2][2] = {
/* MCS 0 */
{ /* 20 Mhz */ { 6.5, /* SGI */ 7.2, },
/* 40 Mhz */ { 13.5, /* SGI */ 15.0, },
},
/* MCS 1 */
{ /* 20 Mhz */ { 13.0, /* SGI */ 14.4, },
/* 40 Mhz */ { 27.0, /* SGI */ 30.0, },
},
/* MCS 2 */
{ /* 20 Mhz */ { 19.5, /* SGI */ 21.7, },
/* 40 Mhz */ { 40.5, /* SGI */ 45.0, },
},
/* MCS 3 */
{ /* 20 Mhz */ { 26.0, /* SGI */ 28.9, },
/* 40 Mhz */ { 54.0, /* SGI */ 60.0, },
},
/* MCS 4 */
{ /* 20 Mhz */ { 39.0, /* SGI */ 43.3, },
/* 40 Mhz */ { 81.0, /* SGI */ 90.0, },
},
/* MCS 5 */
{ /* 20 Mhz */ { 52.0, /* SGI */ 57.8, },
/* 40 Mhz */ { 108.0, /* SGI */ 120.0, },
},
/* MCS 6 */
{ /* 20 Mhz */ { 58.5, /* SGI */ 65.0, },
/* 40 Mhz */ { 121.5, /* SGI */ 135.0, },
},
/* MCS 7 */
{ /* 20 Mhz */ { 65.0, /* SGI */ 72.2, },
/* 40 Mhz */ { 135.0, /* SGI */ 150.0, },
},
/* MCS 8 */
{ /* 20 Mhz */ { 13.0, /* SGI */ 14.4, },
/* 40 Mhz */ { 27.0, /* SGI */ 30.0, },
},
/* MCS 9 */
{ /* 20 Mhz */ { 26.0, /* SGI */ 28.9, },
/* 40 Mhz */ { 54.0, /* SGI */ 60.0, },
},
/* MCS 10 */
{ /* 20 Mhz */ { 39.0, /* SGI */ 43.3, },
/* 40 Mhz */ { 81.0, /* SGI */ 90.0, },
},
/* MCS 11 */
{ /* 20 Mhz */ { 52.0, /* SGI */ 57.8, },
/* 40 Mhz */ { 108.0, /* SGI */ 120.0, },
},
/* MCS 12 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 13 */
{ /* 20 Mhz */ { 104.0, /* SGI */ 115.6, },
/* 40 Mhz */ { 216.0, /* SGI */ 240.0, },
},
/* MCS 14 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 15 */
{ /* 20 Mhz */ { 130.0, /* SGI */ 144.4, },
/* 40 Mhz */ { 270.0, /* SGI */ 300.0, },
},
/* MCS 16 */
{ /* 20 Mhz */ { 19.5, /* SGI */ 21.7, },
/* 40 Mhz */ { 40.5, /* SGI */ 45.0, },
},
/* MCS 17 */
{ /* 20 Mhz */ { 39.0, /* SGI */ 43.3, },
/* 40 Mhz */ { 81.0, /* SGI */ 90.0, },
},
/* MCS 18 */
{ /* 20 Mhz */ { 58.5, /* SGI */ 65.0, },
/* 40 Mhz */ { 121.5, /* SGI */ 135.0, },
},
/* MCS 19 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 20 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 21 */
{ /* 20 Mhz */ { 156.0, /* SGI */ 173.3, },
/* 40 Mhz */ { 324.0, /* SGI */ 360.0, },
},
/* MCS 22 */
{ /* 20 Mhz */ { 175.5, /* SGI */ 195.0, },
/* 40 Mhz */ { 364.5, /* SGI */ 405.0, },
},
/* MCS 23 */
{ /* 20 Mhz */ { 195.0, /* SGI */ 216.7, },
/* 40 Mhz */ { 405.0, /* SGI */ 450.0, },
},
/* MCS 24 */
{ /* 20 Mhz */ { 26.0, /* SGI */ 28.9, },
/* 40 Mhz */ { 54.0, /* SGI */ 60.0, },
},
/* MCS 25 */
{ /* 20 Mhz */ { 52.0, /* SGI */ 57.8, },
/* 40 Mhz */ { 108.0, /* SGI */ 120.0, },
},
/* MCS 26 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 27 */
{ /* 20 Mhz */ { 104.0, /* SGI */ 115.6, },
/* 40 Mhz */ { 216.0, /* SGI */ 240.0, },
},
/* MCS 28 */
{ /* 20 Mhz */ { 156.0, /* SGI */ 173.3, },
/* 40 Mhz */ { 324.0, /* SGI */ 360.0, },
},
/* MCS 29 */
{ /* 20 Mhz */ { 208.0, /* SGI */ 231.1, },
/* 40 Mhz */ { 432.0, /* SGI */ 480.0, },
},
/* MCS 30 */
{ /* 20 Mhz */ { 234.0, /* SGI */ 260.0, },
/* 40 Mhz */ { 486.0, /* SGI */ 540.0, },
},
/* MCS 31 */
{ /* 20 Mhz */ { 260.0, /* SGI */ 288.9, },
/* 40 Mhz */ { 540.0, /* SGI */ 600.0, },
},
/* MCS 32 */
{ /* 20 Mhz */ { 0.0, /* SGI */ 0.0, }, /* not valid */
/* 40 Mhz */ { 6.0, /* SGI */ 6.7, },
},
/* MCS 33 */
{ /* 20 Mhz */ { 39.0, /* SGI */ 43.3, },
/* 40 Mhz */ { 81.0, /* SGI */ 90.0, },
},
/* MCS 34 */
{ /* 20 Mhz */ { 52.0, /* SGI */ 57.8, },
/* 40 Mhz */ { 108.0, /* SGI */ 120.0, },
},
/* MCS 35 */
{ /* 20 Mhz */ { 65.0, /* SGI */ 72.2, },
/* 40 Mhz */ { 135.0, /* SGI */ 150.0, },
},
/* MCS 36 */
{ /* 20 Mhz */ { 58.5, /* SGI */ 65.0, },
/* 40 Mhz */ { 121.5, /* SGI */ 135.0, },
},
/* MCS 37 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 38 */
{ /* 20 Mhz */ { 97.5, /* SGI */ 108.3, },
/* 40 Mhz */ { 202.5, /* SGI */ 225.0, },
},
/* MCS 39 */
{ /* 20 Mhz */ { 52.0, /* SGI */ 57.8, },
/* 40 Mhz */ { 108.0, /* SGI */ 120.0, },
},
/* MCS 40 */
{ /* 20 Mhz */ { 65.0, /* SGI */ 72.2, },
/* 40 Mhz */ { 135.0, /* SGI */ 150.0, },
},
/* MCS 41 */
{ /* 20 Mhz */ { 65.0, /* SGI */ 72.2, },
/* 40 Mhz */ { 135.0, /* SGI */ 150.0, },
},
/* MCS 42 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 43 */
{ /* 20 Mhz */ { 91.0, /* SGI */ 101.1, },
/* 40 Mhz */ { 189.0, /* SGI */ 210.0, },
},
/* MCS 44 */
{ /* 20 Mhz */ { 91.0, /* SGI */ 101.1, },
/* 40 Mhz */ { 189.0, /* SGI */ 210.0, },
},
/* MCS 45 */
{ /* 20 Mhz */ { 104.0, /* SGI */ 115.6, },
/* 40 Mhz */ { 216.0, /* SGI */ 240.0, },
},
/* MCS 46 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 47 */
{ /* 20 Mhz */ { 97.5, /* SGI */ 108.3, },
/* 40 Mhz */ { 202.5, /* SGI */ 225.0, },
},
/* MCS 48 */
{ /* 20 Mhz */ { 97.5, /* SGI */ 108.3, },
/* 40 Mhz */ { 202.5, /* SGI */ 225.0, },
},
/* MCS 49 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 50 */
{ /* 20 Mhz */ { 136.5, /* SGI */ 151.7, },
/* 40 Mhz */ { 283.5, /* SGI */ 315.0, },
},
/* MCS 51 */
{ /* 20 Mhz */ { 136.5, /* SGI */ 151.7, },
/* 40 Mhz */ { 283.5, /* SGI */ 315.0, },
},
/* MCS 52 */
{ /* 20 Mhz */ { 156.0, /* SGI */ 173.3, },
/* 40 Mhz */ { 324.0, /* SGI */ 360.0, },
},
/* MCS 53 */
{ /* 20 Mhz */ { 65.0, /* SGI */ 72.2, },
/* 40 Mhz */ { 135.0, /* SGI */ 150.0, },
},
/* MCS 54 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 55 */
{ /* 20 Mhz */ { 91.0, /* SGI */ 101.1, },
/* 40 Mhz */ { 189.0, /* SGI */ 210.0, },
},
/* MCS 56 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 57 */
{ /* 20 Mhz */ { 91.0, /* SGI */ 101.1, },
/* 40 Mhz */ { 189.0, /* SGI */ 210.0, },
},
/* MCS 58 */
{ /* 20 Mhz */ { 104.0, /* SGI */ 115.6, },
/* 40 Mhz */ { 216.0, /* SGI */ 240.0, },
},
/* MCS 59 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 60 */
{ /* 20 Mhz */ { 104.0, /* SGI */ 115.6, },
/* 40 Mhz */ { 216.0, /* SGI */ 240.0, },
},
/* MCS 61 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 62 */
{ /* 20 Mhz */ { 130.0, /* SGI */ 144.4, },
/* 40 Mhz */ { 270.0, /* SGI */ 300.0, },
},
/* MCS 63 */
{ /* 20 Mhz */ { 130.0, /* SGI */ 144.4, },
/* 40 Mhz */ { 270.0, /* SGI */ 300.0, },
},
/* MCS 64 */
{ /* 20 Mhz */ { 143.0, /* SGI */ 158.9, },
/* 40 Mhz */ { 297.0, /* SGI */ 330.0, },
},
/* MCS 65 */
{ /* 20 Mhz */ { 97.5, /* SGI */ 108.3, },
/* 40 Mhz */ { 202.5, /* SGI */ 225.0, },
},
/* MCS 66 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 67 */
{ /* 20 Mhz */ { 136.5, /* SGI */ 151.7, },
/* 40 Mhz */ { 283.5, /* SGI */ 315.0, },
},
/* MCS 68 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 69 */
{ /* 20 Mhz */ { 136.5, /* SGI */ 151.7, },
/* 40 Mhz */ { 283.5, /* SGI */ 315.0, },
},
/* MCS 70 */
{ /* 20 Mhz */ { 156.0, /* SGI */ 173.3, },
/* 40 Mhz */ { 324.0, /* SGI */ 360.0, },
},
/* MCS 71 */
{ /* 20 Mhz */ { 175.5, /* SGI */ 195.0, },
/* 40 Mhz */ { 364.5, /* SGI */ 405.0, },
},
/* MCS 72 */
{ /* 20 Mhz */ { 156.0, /* SGI */ 173.3, },
/* 40 Mhz */ { 324.0, /* SGI */ 360.0, },
},
/* MCS 73 */
{ /* 20 Mhz */ { 175.5, /* SGI */ 195.0, },
/* 40 Mhz */ { 364.5, /* SGI */ 405.0, },
},
/* MCS 74 */
{ /* 20 Mhz */ { 195.0, /* SGI */ 216.7, },
/* 40 Mhz */ { 405.0, /* SGI */ 450.0, },
},
/* MCS 75 */
{ /* 20 Mhz */ { 195.0, /* SGI */ 216.7, },
/* 40 Mhz */ { 405.0, /* SGI */ 450.0, },
},
/* MCS 76 */
{ /* 20 Mhz */ { 214.5, /* SGI */ 238.3, },
/* 40 Mhz */ { 445.5, /* SGI */ 495.0, },
},
};
static const char *auth_alg_text[]={"Open System","Shared Key","EAP"};
#define NUM_AUTH_ALGS (sizeof auth_alg_text / sizeof auth_alg_text[0])
static const char *status_text[] = {
"Successful", /* 0 */
"Unspecified failure", /* 1 */
"Reserved", /* 2 */
"Reserved", /* 3 */
"Reserved", /* 4 */
"Reserved", /* 5 */
"Reserved", /* 6 */
"Reserved", /* 7 */
"Reserved", /* 8 */
"Reserved", /* 9 */
"Cannot Support all requested capabilities in the Capability "
"Information field", /* 10 */
"Reassociation denied due to inability to confirm that association "
"exists", /* 11 */
"Association denied due to reason outside the scope of the "
"standard", /* 12 */
"Responding station does not support the specified authentication "
"algorithm ", /* 13 */
"Received an Authentication frame with authentication transaction "
"sequence number out of expected sequence", /* 14 */
"Authentication rejected because of challenge failure", /* 15 */
"Authentication rejected due to timeout waiting for next frame in "
"sequence", /* 16 */
"Association denied because AP is unable to handle additional"
"associated stations", /* 17 */
"Association denied due to requesting station not supporting all of "
"the data rates in BSSBasicRateSet parameter", /* 18 */
"Association denied due to requesting station not supporting "
"short preamble operation", /* 19 */
"Association denied due to requesting station not supporting "
"PBCC encoding", /* 20 */
"Association denied due to requesting station not supporting "
"channel agility", /* 21 */
"Association request rejected because Spectrum Management "
"capability is required", /* 22 */
"Association request rejected because the information in the "
"Power Capability element is unacceptable", /* 23 */
"Association request rejected because the information in the "
"Supported Channels element is unacceptable", /* 24 */
"Association denied due to requesting station not supporting "
"short slot operation", /* 25 */
"Association denied due to requesting station not supporting "
"DSSS-OFDM operation", /* 26 */
"Association denied because the requested STA does not support HT "
"features", /* 27 */
"Reserved", /* 28 */
"Association denied because the requested STA does not support "
"the PCO transition time required by the AP", /* 29 */
"Reserved", /* 30 */
"Reserved", /* 31 */
"Unspecified, QoS-related failure", /* 32 */
"Association denied due to QAP having insufficient bandwidth "
"to handle another QSTA", /* 33 */
"Association denied due to excessive frame loss rates and/or "
"poor conditions on current operating channel", /* 34 */
"Association (with QBSS) denied due to requesting station not "
"supporting the QoS facility", /* 35 */
"Association denied due to requesting station not supporting "
"Block Ack", /* 36 */
"The request has been declined", /* 37 */
"The request has not been successful as one or more parameters "
"have invalid values", /* 38 */
"The TS has not been created because the request cannot be honored. "
"Try again with the suggested changes to the TSPEC", /* 39 */
"Invalid Information Element", /* 40 */
"Group Cipher is not valid", /* 41 */
"Pairwise Cipher is not valid", /* 42 */
"AKMP is not valid", /* 43 */
"Unsupported RSN IE version", /* 44 */
"Invalid RSN IE Capabilities", /* 45 */
"Cipher suite is rejected per security policy", /* 46 */
"The TS has not been created. However, the HC may be capable of "
"creating a TS, in response to a request, after the time indicated "
"in the TS Delay element", /* 47 */
"Direct Link is not allowed in the BSS by policy", /* 48 */
"Destination STA is not present within this QBSS.", /* 49 */
"The Destination STA is not a QSTA.", /* 50 */
};
#define NUM_STATUSES (sizeof status_text / sizeof status_text[0])
static const char *reason_text[] = {
"Reserved", /* 0 */
"Unspecified reason", /* 1 */
"Previous authentication no longer valid", /* 2 */
"Deauthenticated because sending station is leaving (or has left) "
"IBSS or ESS", /* 3 */
"Disassociated due to inactivity", /* 4 */
"Disassociated because AP is unable to handle all currently "
" associated stations", /* 5 */
"Class 2 frame received from nonauthenticated station", /* 6 */
"Class 3 frame received from nonassociated station", /* 7 */
"Disassociated because sending station is leaving "
"(or has left) BSS", /* 8 */
"Station requesting (re)association is not authenticated with "
"responding station", /* 9 */
"Disassociated because the information in the Power Capability "
"element is unacceptable", /* 10 */
"Disassociated because the information in the SupportedChannels "
"element is unacceptable", /* 11 */
"Invalid Information Element", /* 12 */
"Reserved", /* 13 */
"Michael MIC failure", /* 14 */
"4-Way Handshake timeout", /* 15 */
"Group key update timeout", /* 16 */
"Information element in 4-Way Handshake different from (Re)Association"
"Request/Probe Response/Beacon", /* 17 */
"Group Cipher is not valid", /* 18 */
"AKMP is not valid", /* 20 */
"Unsupported RSN IE version", /* 21 */
"Invalid RSN IE Capabilities", /* 22 */
"IEEE 802.1X Authentication failed", /* 23 */
"Cipher suite is rejected per security policy", /* 24 */
"Reserved", /* 25 */
"Reserved", /* 26 */
"Reserved", /* 27 */
"Reserved", /* 28 */
"Reserved", /* 29 */
"Reserved", /* 30 */
"TS deleted because QoS AP lacks sufficient bandwidth for this "
"QoS STA due to a change in BSS service characteristics or "
"operational mode (e.g. an HT BSS change from 40 MHz channel "
"to 20 MHz channel)", /* 31 */
"Disassociated for unspecified, QoS-related reason", /* 32 */
"Disassociated because QoS AP lacks sufficient bandwidth for this "
"QoS STA", /* 33 */
"Disassociated because of excessive number of frames that need to be "
"acknowledged, but are not acknowledged for AP transmissions "
"and/or poor channel conditions", /* 34 */
"Disassociated because STA is transmitting outside the limits "
"of its TXOPs", /* 35 */
"Requested from peer STA as the STA is leaving the BSS "
"(or resetting)", /* 36 */
"Requested from peer STA as it does not want to use the "
"mechanism", /* 37 */
"Requested from peer STA as the STA received frames using the "
"mechanism for which a set up is required", /* 38 */
"Requested from peer STA due to time out", /* 39 */
"Reserved", /* 40 */
"Reserved", /* 41 */
"Reserved", /* 42 */
"Reserved", /* 43 */
"Reserved", /* 44 */
"Peer STA does not support the requested cipher suite", /* 45 */
"Association denied due to requesting STA not supporting HT "
"features", /* 46 */
};
#define NUM_REASONS (sizeof reason_text / sizeof reason_text[0])
static int
wep_print(netdissect_options *ndo,
const u_char *p)
{
uint32_t iv;
if (!ND_TTEST2(*p, IEEE802_11_IV_LEN + IEEE802_11_KID_LEN))
return 0;
iv = EXTRACT_LE_32BITS(p);
ND_PRINT((ndo, " IV:%3x Pad %x KeyID %x", IV_IV(iv), IV_PAD(iv),
IV_KEYID(iv)));
return 1;
}
static int
parse_elements(netdissect_options *ndo,
struct mgmt_body_t *pbody, const u_char *p, int offset,
u_int length)
{
u_int elementlen;
struct ssid_t ssid;
struct challenge_t challenge;
struct rates_t rates;
struct ds_t ds;
struct cf_t cf;
struct tim_t tim;
/*
* We haven't seen any elements yet.
*/
pbody->challenge_present = 0;
pbody->ssid_present = 0;
pbody->rates_present = 0;
pbody->ds_present = 0;
pbody->cf_present = 0;
pbody->tim_present = 0;
while (length != 0) {
/* Make sure we at least have the element ID and length. */
if (!ND_TTEST2(*(p + offset), 2))
return 0;
if (length < 2)
return 0;
elementlen = *(p + offset + 1);
/* Make sure we have the entire element. */
if (!ND_TTEST2(*(p + offset + 2), elementlen))
return 0;
if (length < elementlen + 2)
return 0;
switch (*(p + offset)) {
case E_SSID:
memcpy(&ssid, p + offset, 2);
offset += 2;
length -= 2;
if (ssid.length != 0) {
if (ssid.length > sizeof(ssid.ssid) - 1)
return 0;
memcpy(&ssid.ssid, p + offset, ssid.length);
offset += ssid.length;
length -= ssid.length;
}
ssid.ssid[ssid.length] = '\0';
/*
* Present and not truncated.
*
* If we haven't already seen an SSID IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->ssid_present) {
pbody->ssid = ssid;
pbody->ssid_present = 1;
}
break;
case E_CHALLENGE:
memcpy(&challenge, p + offset, 2);
offset += 2;
length -= 2;
if (challenge.length != 0) {
if (challenge.length >
sizeof(challenge.text) - 1)
return 0;
memcpy(&challenge.text, p + offset,
challenge.length);
offset += challenge.length;
length -= challenge.length;
}
challenge.text[challenge.length] = '\0';
/*
* Present and not truncated.
*
* If we haven't already seen a challenge IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->challenge_present) {
pbody->challenge = challenge;
pbody->challenge_present = 1;
}
break;
case E_RATES:
memcpy(&rates, p + offset, 2);
offset += 2;
length -= 2;
if (rates.length != 0) {
if (rates.length > sizeof rates.rate)
return 0;
memcpy(&rates.rate, p + offset, rates.length);
offset += rates.length;
length -= rates.length;
}
/*
* Present and not truncated.
*
* If we haven't already seen a rates IE,
* copy this one if it's not zero-length,
* otherwise ignore this one, so we later
* report the first one we saw.
*
* We ignore zero-length rates IEs as some
* devices seem to put a zero-length rates
* IE, followed by an SSID IE, followed by
* a non-zero-length rates IE into frames,
* even though IEEE Std 802.11-2007 doesn't
* seem to indicate that a zero-length rates
* IE is valid.
*/
if (!pbody->rates_present && rates.length != 0) {
pbody->rates = rates;
pbody->rates_present = 1;
}
break;
case E_DS:
memcpy(&ds, p + offset, 2);
offset += 2;
length -= 2;
if (ds.length != 1) {
offset += ds.length;
length -= ds.length;
break;
}
ds.channel = *(p + offset);
offset += 1;
length -= 1;
/*
* Present and not truncated.
*
* If we haven't already seen a DS IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->ds_present) {
pbody->ds = ds;
pbody->ds_present = 1;
}
break;
case E_CF:
memcpy(&cf, p + offset, 2);
offset += 2;
length -= 2;
if (cf.length != 6) {
offset += cf.length;
length -= cf.length;
break;
}
memcpy(&cf.count, p + offset, 6);
offset += 6;
length -= 6;
/*
* Present and not truncated.
*
* If we haven't already seen a CF IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->cf_present) {
pbody->cf = cf;
pbody->cf_present = 1;
}
break;
case E_TIM:
memcpy(&tim, p + offset, 2);
offset += 2;
length -= 2;
if (tim.length <= 3) {
offset += tim.length;
length -= tim.length;
break;
}
if (tim.length - 3 > (int)sizeof tim.bitmap)
return 0;
memcpy(&tim.count, p + offset, 3);
offset += 3;
length -= 3;
memcpy(tim.bitmap, p + offset, tim.length - 3);
offset += tim.length - 3;
length -= tim.length - 3;
/*
* Present and not truncated.
*
* If we haven't already seen a TIM IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->tim_present) {
pbody->tim = tim;
pbody->tim_present = 1;
}
break;
default:
#if 0
ND_PRINT((ndo, "(1) unhandled element_id (%d) ",
*(p + offset)));
#endif
offset += 2 + elementlen;
length -= 2 + elementlen;
break;
}
}
/* No problems found. */
return 1;
}
/*********************************************************************************
* Print Handle functions for the management frame types
*********************************************************************************/
static int
handle_beacon(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN +
IEEE802_11_CAPINFO_LEN))
return 0;
if (length < IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN +
IEEE802_11_CAPINFO_LEN)
return 0;
memcpy(&pbody.timestamp, p, IEEE802_11_TSTAMP_LEN);
offset += IEEE802_11_TSTAMP_LEN;
length -= IEEE802_11_TSTAMP_LEN;
pbody.beacon_interval = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_BCNINT_LEN;
length -= IEEE802_11_BCNINT_LEN;
pbody.capability_info = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_CAPINFO_LEN;
length -= IEEE802_11_CAPINFO_LEN;
ret = parse_elements(ndo, &pbody, p, offset, length);
PRINT_SSID(pbody);
PRINT_RATES(pbody);
ND_PRINT((ndo, " %s",
CAPABILITY_ESS(pbody.capability_info) ? "ESS" : "IBSS"));
PRINT_DS_CHANNEL(pbody);
return ret;
}
static int
handle_assoc_request(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN))
return 0;
if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN)
return 0;
pbody.capability_info = EXTRACT_LE_16BITS(p);
offset += IEEE802_11_CAPINFO_LEN;
length -= IEEE802_11_CAPINFO_LEN;
pbody.listen_interval = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_LISTENINT_LEN;
length -= IEEE802_11_LISTENINT_LEN;
ret = parse_elements(ndo, &pbody, p, offset, length);
PRINT_SSID(pbody);
PRINT_RATES(pbody);
return ret;
}
static int
handle_assoc_response(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_STATUS_LEN +
IEEE802_11_AID_LEN))
return 0;
if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_STATUS_LEN +
IEEE802_11_AID_LEN)
return 0;
pbody.capability_info = EXTRACT_LE_16BITS(p);
offset += IEEE802_11_CAPINFO_LEN;
length -= IEEE802_11_CAPINFO_LEN;
pbody.status_code = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_STATUS_LEN;
length -= IEEE802_11_STATUS_LEN;
pbody.aid = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_AID_LEN;
length -= IEEE802_11_AID_LEN;
ret = parse_elements(ndo, &pbody, p, offset, length);
ND_PRINT((ndo, " AID(%x) :%s: %s", ((uint16_t)(pbody.aid << 2 )) >> 2 ,
CAPABILITY_PRIVACY(pbody.capability_info) ? " PRIVACY " : "",
(pbody.status_code < NUM_STATUSES
? status_text[pbody.status_code]
: "n/a")));
return ret;
}
static int
handle_reassoc_request(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN +
IEEE802_11_AP_LEN))
return 0;
if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN +
IEEE802_11_AP_LEN)
return 0;
pbody.capability_info = EXTRACT_LE_16BITS(p);
offset += IEEE802_11_CAPINFO_LEN;
length -= IEEE802_11_CAPINFO_LEN;
pbody.listen_interval = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_LISTENINT_LEN;
length -= IEEE802_11_LISTENINT_LEN;
memcpy(&pbody.ap, p+offset, IEEE802_11_AP_LEN);
offset += IEEE802_11_AP_LEN;
length -= IEEE802_11_AP_LEN;
ret = parse_elements(ndo, &pbody, p, offset, length);
PRINT_SSID(pbody);
ND_PRINT((ndo, " AP : %s", etheraddr_string(ndo, pbody.ap )));
return ret;
}
static int
handle_reassoc_response(netdissect_options *ndo,
const u_char *p, u_int length)
{
/* Same as a Association Reponse */
return handle_assoc_response(ndo, p, length);
}
static int
handle_probe_request(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
ret = parse_elements(ndo, &pbody, p, offset, length);
PRINT_SSID(pbody);
PRINT_RATES(pbody);
return ret;
}
static int
handle_probe_response(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN +
IEEE802_11_CAPINFO_LEN))
return 0;
if (length < IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN +
IEEE802_11_CAPINFO_LEN)
return 0;
memcpy(&pbody.timestamp, p, IEEE802_11_TSTAMP_LEN);
offset += IEEE802_11_TSTAMP_LEN;
length -= IEEE802_11_TSTAMP_LEN;
pbody.beacon_interval = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_BCNINT_LEN;
length -= IEEE802_11_BCNINT_LEN;
pbody.capability_info = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_CAPINFO_LEN;
length -= IEEE802_11_CAPINFO_LEN;
ret = parse_elements(ndo, &pbody, p, offset, length);
PRINT_SSID(pbody);
PRINT_RATES(pbody);
PRINT_DS_CHANNEL(pbody);
return ret;
}
static int
handle_atim(void)
{
/* the frame body for ATIM is null. */
return 1;
}
static int
handle_disassoc(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_REASON_LEN))
return 0;
if (length < IEEE802_11_REASON_LEN)
return 0;
pbody.reason_code = EXTRACT_LE_16BITS(p);
ND_PRINT((ndo, ": %s",
(pbody.reason_code < NUM_REASONS)
? reason_text[pbody.reason_code]
: "Reserved"));
return 1;
}
static int
handle_auth(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, 6))
return 0;
if (length < 6)
return 0;
pbody.auth_alg = EXTRACT_LE_16BITS(p);
offset += 2;
length -= 2;
pbody.auth_trans_seq_num = EXTRACT_LE_16BITS(p + offset);
offset += 2;
length -= 2;
pbody.status_code = EXTRACT_LE_16BITS(p + offset);
offset += 2;
length -= 2;
ret = parse_elements(ndo, &pbody, p, offset, length);
if ((pbody.auth_alg == 1) &&
((pbody.auth_trans_seq_num == 2) ||
(pbody.auth_trans_seq_num == 3))) {
ND_PRINT((ndo, " (%s)-%x [Challenge Text] %s",
(pbody.auth_alg < NUM_AUTH_ALGS)
? auth_alg_text[pbody.auth_alg]
: "Reserved",
pbody.auth_trans_seq_num,
((pbody.auth_trans_seq_num % 2)
? ((pbody.status_code < NUM_STATUSES)
? status_text[pbody.status_code]
: "n/a") : "")));
return ret;
}
ND_PRINT((ndo, " (%s)-%x: %s",
(pbody.auth_alg < NUM_AUTH_ALGS)
? auth_alg_text[pbody.auth_alg]
: "Reserved",
pbody.auth_trans_seq_num,
(pbody.auth_trans_seq_num % 2)
? ((pbody.status_code < NUM_STATUSES)
? status_text[pbody.status_code]
: "n/a")
: ""));
return ret;
}
static int
handle_deauth(netdissect_options *ndo,
const uint8_t *src, const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
const char *reason = NULL;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_REASON_LEN))
return 0;
if (length < IEEE802_11_REASON_LEN)
return 0;
pbody.reason_code = EXTRACT_LE_16BITS(p);
reason = (pbody.reason_code < NUM_REASONS)
? reason_text[pbody.reason_code]
: "Reserved";
if (ndo->ndo_eflag) {
ND_PRINT((ndo, ": %s", reason));
} else {
ND_PRINT((ndo, " (%s): %s", etheraddr_string(ndo, src), reason));
}
return 1;
}
#define PRINT_HT_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "TxChWidth")) : \
(v) == 1 ? ND_PRINT((ndo, "MIMOPwrSave")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_BA_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "ADDBA Request")) : \
(v) == 1 ? ND_PRINT((ndo, "ADDBA Response")) : \
(v) == 2 ? ND_PRINT((ndo, "DELBA")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_MESHLINK_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "Request")) : \
(v) == 1 ? ND_PRINT((ndo, "Report")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_MESHPEERING_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "Open")) : \
(v) == 1 ? ND_PRINT((ndo, "Confirm")) : \
(v) == 2 ? ND_PRINT((ndo, "Close")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_MESHPATH_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "Request")) : \
(v) == 1 ? ND_PRINT((ndo, "Report")) : \
(v) == 2 ? ND_PRINT((ndo, "Error")) : \
(v) == 3 ? ND_PRINT((ndo, "RootAnnouncement")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_MESH_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "MeshLink")) : \
(v) == 1 ? ND_PRINT((ndo, "HWMP")) : \
(v) == 2 ? ND_PRINT((ndo, "Gate Announcement")) : \
(v) == 3 ? ND_PRINT((ndo, "Congestion Control")) : \
(v) == 4 ? ND_PRINT((ndo, "MCCA Setup Request")) : \
(v) == 5 ? ND_PRINT((ndo, "MCCA Setup Reply")) : \
(v) == 6 ? ND_PRINT((ndo, "MCCA Advertisement Request")) : \
(v) == 7 ? ND_PRINT((ndo, "MCCA Advertisement")) : \
(v) == 8 ? ND_PRINT((ndo, "MCCA Teardown")) : \
(v) == 9 ? ND_PRINT((ndo, "TBTT Adjustment Request")) : \
(v) == 10 ? ND_PRINT((ndo, "TBTT Adjustment Response")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_MULTIHOP_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "Proxy Update")) : \
(v) == 1 ? ND_PRINT((ndo, "Proxy Update Confirmation")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_SELFPROT_ACTION(v) (\
(v) == 1 ? ND_PRINT((ndo, "Peering Open")) : \
(v) == 2 ? ND_PRINT((ndo, "Peering Confirm")) : \
(v) == 3 ? ND_PRINT((ndo, "Peering Close")) : \
(v) == 4 ? ND_PRINT((ndo, "Group Key Inform")) : \
(v) == 5 ? ND_PRINT((ndo, "Group Key Acknowledge")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
static int
handle_action(netdissect_options *ndo,
const uint8_t *src, const u_char *p, u_int length)
{
if (!ND_TTEST2(*p, 2))
return 0;
if (length < 2)
return 0;
if (ndo->ndo_eflag) {
ND_PRINT((ndo, ": "));
} else {
ND_PRINT((ndo, " (%s): ", etheraddr_string(ndo, src)));
}
switch (p[0]) {
case 0: ND_PRINT((ndo, "Spectrum Management Act#%d", p[1])); break;
case 1: ND_PRINT((ndo, "QoS Act#%d", p[1])); break;
case 2: ND_PRINT((ndo, "DLS Act#%d", p[1])); break;
case 3: ND_PRINT((ndo, "BA ")); PRINT_BA_ACTION(p[1]); break;
case 7: ND_PRINT((ndo, "HT ")); PRINT_HT_ACTION(p[1]); break;
case 13: ND_PRINT((ndo, "MeshAction ")); PRINT_MESH_ACTION(p[1]); break;
case 14:
ND_PRINT((ndo, "MultiohopAction "));
PRINT_MULTIHOP_ACTION(p[1]); break;
case 15:
ND_PRINT((ndo, "SelfprotectAction "));
PRINT_SELFPROT_ACTION(p[1]); break;
case 127: ND_PRINT((ndo, "Vendor Act#%d", p[1])); break;
default:
ND_PRINT((ndo, "Reserved(%d) Act#%d", p[0], p[1]));
break;
}
return 1;
}
/*********************************************************************************
* Print Body funcs
*********************************************************************************/
static int
mgmt_body_print(netdissect_options *ndo,
uint16_t fc, const uint8_t *src, const u_char *p, u_int length)
{
ND_PRINT((ndo, "%s", tok2str(st_str, "Unhandled Management subtype(%x)", FC_SUBTYPE(fc))));
/* There may be a problem w/ AP not having this bit set */
if (FC_PROTECTED(fc))
return wep_print(ndo, p);
switch (FC_SUBTYPE(fc)) {
case ST_ASSOC_REQUEST:
return handle_assoc_request(ndo, p, length);
case ST_ASSOC_RESPONSE:
return handle_assoc_response(ndo, p, length);
case ST_REASSOC_REQUEST:
return handle_reassoc_request(ndo, p, length);
case ST_REASSOC_RESPONSE:
return handle_reassoc_response(ndo, p, length);
case ST_PROBE_REQUEST:
return handle_probe_request(ndo, p, length);
case ST_PROBE_RESPONSE:
return handle_probe_response(ndo, p, length);
case ST_BEACON:
return handle_beacon(ndo, p, length);
case ST_ATIM:
return handle_atim();
case ST_DISASSOC:
return handle_disassoc(ndo, p, length);
case ST_AUTH:
return handle_auth(ndo, p, length);
case ST_DEAUTH:
return handle_deauth(ndo, src, p, length);
case ST_ACTION:
return handle_action(ndo, src, p, length);
default:
return 1;
}
}
/*********************************************************************************
* Handles printing all the control frame types
*********************************************************************************/
static int
ctrl_body_print(netdissect_options *ndo,
uint16_t fc, const u_char *p)
{
ND_PRINT((ndo, "%s", tok2str(ctrl_str, "Unknown Ctrl Subtype", FC_SUBTYPE(fc))));
switch (FC_SUBTYPE(fc)) {
case CTRL_CONTROL_WRAPPER:
/* XXX - requires special handling */
break;
case CTRL_BAR:
if (!ND_TTEST2(*p, CTRL_BAR_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s TA:%s CTL(%x) SEQ(%u) ",
etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ra),
etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ta),
EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->ctl)),
EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->seq))));
break;
case CTRL_BA:
if (!ND_TTEST2(*p, CTRL_BA_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_ba_hdr_t *)p)->ra)));
break;
case CTRL_PS_POLL:
if (!ND_TTEST2(*p, CTRL_PS_POLL_HDRLEN))
return 0;
ND_PRINT((ndo, " AID(%x)",
EXTRACT_LE_16BITS(&(((const struct ctrl_ps_poll_hdr_t *)p)->aid))));
break;
case CTRL_RTS:
if (!ND_TTEST2(*p, CTRL_RTS_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " TA:%s ",
etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ta)));
break;
case CTRL_CTS:
if (!ND_TTEST2(*p, CTRL_CTS_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_cts_hdr_t *)p)->ra)));
break;
case CTRL_ACK:
if (!ND_TTEST2(*p, CTRL_ACK_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_ack_hdr_t *)p)->ra)));
break;
case CTRL_CF_END:
if (!ND_TTEST2(*p, CTRL_END_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->ra)));
break;
case CTRL_END_ACK:
if (!ND_TTEST2(*p, CTRL_END_ACK_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->ra)));
break;
}
return 1;
}
/*
* Data Frame - Address field contents
*
* To Ds | From DS | Addr 1 | Addr 2 | Addr 3 | Addr 4
* 0 | 0 | DA | SA | BSSID | n/a
* 0 | 1 | DA | BSSID | SA | n/a
* 1 | 0 | BSSID | SA | DA | n/a
* 1 | 1 | RA | TA | DA | SA
*/
/*
* Function to get source and destination MAC addresses for a data frame.
*/
static void
get_data_src_dst_mac(uint16_t fc, const u_char *p, const uint8_t **srcp,
const uint8_t **dstp)
{
#define ADDR1 (p + 4)
#define ADDR2 (p + 10)
#define ADDR3 (p + 16)
#define ADDR4 (p + 24)
if (!FC_TO_DS(fc)) {
if (!FC_FROM_DS(fc)) {
/* not To DS and not From DS */
*srcp = ADDR2;
*dstp = ADDR1;
} else {
/* not To DS and From DS */
*srcp = ADDR3;
*dstp = ADDR1;
}
} else {
if (!FC_FROM_DS(fc)) {
/* From DS and not To DS */
*srcp = ADDR2;
*dstp = ADDR3;
} else {
/* To DS and From DS */
*srcp = ADDR4;
*dstp = ADDR3;
}
}
#undef ADDR1
#undef ADDR2
#undef ADDR3
#undef ADDR4
}
static void
get_mgmt_src_dst_mac(const u_char *p, const uint8_t **srcp, const uint8_t **dstp)
{
const struct mgmt_header_t *hp = (const struct mgmt_header_t *) p;
if (srcp != NULL)
*srcp = hp->sa;
if (dstp != NULL)
*dstp = hp->da;
}
/*
* Print Header funcs
*/
static void
data_header_print(netdissect_options *ndo, uint16_t fc, const u_char *p)
{
u_int subtype = FC_SUBTYPE(fc);
if (DATA_FRAME_IS_CF_ACK(subtype) || DATA_FRAME_IS_CF_POLL(subtype) ||
DATA_FRAME_IS_QOS(subtype)) {
ND_PRINT((ndo, "CF "));
if (DATA_FRAME_IS_CF_ACK(subtype)) {
if (DATA_FRAME_IS_CF_POLL(subtype))
ND_PRINT((ndo, "Ack/Poll"));
else
ND_PRINT((ndo, "Ack"));
} else {
if (DATA_FRAME_IS_CF_POLL(subtype))
ND_PRINT((ndo, "Poll"));
}
if (DATA_FRAME_IS_QOS(subtype))
ND_PRINT((ndo, "+QoS"));
ND_PRINT((ndo, " "));
}
#define ADDR1 (p + 4)
#define ADDR2 (p + 10)
#define ADDR3 (p + 16)
#define ADDR4 (p + 24)
if (!FC_TO_DS(fc) && !FC_FROM_DS(fc)) {
ND_PRINT((ndo, "DA:%s SA:%s BSSID:%s ",
etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2),
etheraddr_string(ndo, ADDR3)));
} else if (!FC_TO_DS(fc) && FC_FROM_DS(fc)) {
ND_PRINT((ndo, "DA:%s BSSID:%s SA:%s ",
etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2),
etheraddr_string(ndo, ADDR3)));
} else if (FC_TO_DS(fc) && !FC_FROM_DS(fc)) {
ND_PRINT((ndo, "BSSID:%s SA:%s DA:%s ",
etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2),
etheraddr_string(ndo, ADDR3)));
} else if (FC_TO_DS(fc) && FC_FROM_DS(fc)) {
ND_PRINT((ndo, "RA:%s TA:%s DA:%s SA:%s ",
etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2),
etheraddr_string(ndo, ADDR3), etheraddr_string(ndo, ADDR4)));
}
#undef ADDR1
#undef ADDR2
#undef ADDR3
#undef ADDR4
}
static void
mgmt_header_print(netdissect_options *ndo, const u_char *p)
{
const struct mgmt_header_t *hp = (const struct mgmt_header_t *) p;
ND_PRINT((ndo, "BSSID:%s DA:%s SA:%s ",
etheraddr_string(ndo, (hp)->bssid), etheraddr_string(ndo, (hp)->da),
etheraddr_string(ndo, (hp)->sa)));
}
static void
ctrl_header_print(netdissect_options *ndo, uint16_t fc, const u_char *p)
{
switch (FC_SUBTYPE(fc)) {
case CTRL_BAR:
ND_PRINT((ndo, " RA:%s TA:%s CTL(%x) SEQ(%u) ",
etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ra),
etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ta),
EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->ctl)),
EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->seq))));
break;
case CTRL_BA:
ND_PRINT((ndo, "RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_ba_hdr_t *)p)->ra)));
break;
case CTRL_PS_POLL:
ND_PRINT((ndo, "BSSID:%s TA:%s ",
etheraddr_string(ndo, ((const struct ctrl_ps_poll_hdr_t *)p)->bssid),
etheraddr_string(ndo, ((const struct ctrl_ps_poll_hdr_t *)p)->ta)));
break;
case CTRL_RTS:
ND_PRINT((ndo, "RA:%s TA:%s ",
etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ra),
etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ta)));
break;
case CTRL_CTS:
ND_PRINT((ndo, "RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_cts_hdr_t *)p)->ra)));
break;
case CTRL_ACK:
ND_PRINT((ndo, "RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_ack_hdr_t *)p)->ra)));
break;
case CTRL_CF_END:
ND_PRINT((ndo, "RA:%s BSSID:%s ",
etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->ra),
etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->bssid)));
break;
case CTRL_END_ACK:
ND_PRINT((ndo, "RA:%s BSSID:%s ",
etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->ra),
etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->bssid)));
break;
default:
/* We shouldn't get here - we should already have quit */
break;
}
}
static int
extract_header_length(netdissect_options *ndo,
uint16_t fc)
{
int len;
switch (FC_TYPE(fc)) {
case T_MGMT:
return MGMT_HDRLEN;
case T_CTRL:
switch (FC_SUBTYPE(fc)) {
case CTRL_CONTROL_WRAPPER:
return CTRL_CONTROL_WRAPPER_HDRLEN;
case CTRL_BAR:
return CTRL_BAR_HDRLEN;
case CTRL_BA:
return CTRL_BA_HDRLEN;
case CTRL_PS_POLL:
return CTRL_PS_POLL_HDRLEN;
case CTRL_RTS:
return CTRL_RTS_HDRLEN;
case CTRL_CTS:
return CTRL_CTS_HDRLEN;
case CTRL_ACK:
return CTRL_ACK_HDRLEN;
case CTRL_CF_END:
return CTRL_END_HDRLEN;
case CTRL_END_ACK:
return CTRL_END_ACK_HDRLEN;
default:
ND_PRINT((ndo, "unknown 802.11 ctrl frame subtype (%d)", FC_SUBTYPE(fc)));
return 0;
}
case T_DATA:
len = (FC_TO_DS(fc) && FC_FROM_DS(fc)) ? 30 : 24;
if (DATA_FRAME_IS_QOS(FC_SUBTYPE(fc)))
len += 2;
return len;
default:
ND_PRINT((ndo, "unknown 802.11 frame type (%d)", FC_TYPE(fc)));
return 0;
}
}
static int
extract_mesh_header_length(const u_char *p)
{
return (p[0] &~ 3) ? 0 : 6*(1 + (p[0] & 3));
}
/*
* Print the 802.11 MAC header.
*/
static void
ieee_802_11_hdr_print(netdissect_options *ndo,
uint16_t fc, const u_char *p, u_int hdrlen,
u_int meshdrlen)
{
if (ndo->ndo_vflag) {
if (FC_MORE_DATA(fc))
ND_PRINT((ndo, "More Data "));
if (FC_MORE_FLAG(fc))
ND_PRINT((ndo, "More Fragments "));
if (FC_POWER_MGMT(fc))
ND_PRINT((ndo, "Pwr Mgmt "));
if (FC_RETRY(fc))
ND_PRINT((ndo, "Retry "));
if (FC_ORDER(fc))
ND_PRINT((ndo, "Strictly Ordered "));
if (FC_PROTECTED(fc))
ND_PRINT((ndo, "Protected "));
if (FC_TYPE(fc) != T_CTRL || FC_SUBTYPE(fc) != CTRL_PS_POLL)
ND_PRINT((ndo, "%dus ",
EXTRACT_LE_16BITS(
&((const struct mgmt_header_t *)p)->duration)));
}
if (meshdrlen != 0) {
const struct meshcntl_t *mc =
(const struct meshcntl_t *)&p[hdrlen - meshdrlen];
int ae = mc->flags & 3;
ND_PRINT((ndo, "MeshData (AE %d TTL %u seq %u", ae, mc->ttl,
EXTRACT_LE_32BITS(mc->seq)));
if (ae > 0)
ND_PRINT((ndo, " A4:%s", etheraddr_string(ndo, mc->addr4)));
if (ae > 1)
ND_PRINT((ndo, " A5:%s", etheraddr_string(ndo, mc->addr5)));
if (ae > 2)
ND_PRINT((ndo, " A6:%s", etheraddr_string(ndo, mc->addr6)));
ND_PRINT((ndo, ") "));
}
switch (FC_TYPE(fc)) {
case T_MGMT:
mgmt_header_print(ndo, p);
break;
case T_CTRL:
ctrl_header_print(ndo, fc, p);
break;
case T_DATA:
data_header_print(ndo, fc, p);
break;
default:
break;
}
}
#ifndef roundup2
#define roundup2(x, y) (((x)+((y)-1))&(~((y)-1))) /* if y is powers of two */
#endif
static const char tstr[] = "[|802.11]";
static u_int
ieee802_11_print(netdissect_options *ndo,
const u_char *p, u_int length, u_int orig_caplen, int pad,
u_int fcslen)
{
uint16_t fc;
u_int caplen, hdrlen, meshdrlen;
struct lladdr_info src, dst;
int llc_hdrlen;
caplen = orig_caplen;
/* Remove FCS, if present */
if (length < fcslen) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
length -= fcslen;
if (caplen > length) {
/* Amount of FCS in actual packet data, if any */
fcslen = caplen - length;
caplen -= fcslen;
ndo->ndo_snapend -= fcslen;
}
if (caplen < IEEE802_11_FC_LEN) {
ND_PRINT((ndo, "%s", tstr));
return orig_caplen;
}
fc = EXTRACT_LE_16BITS(p);
hdrlen = extract_header_length(ndo, fc);
if (hdrlen == 0) {
/* Unknown frame type or control frame subtype; quit. */
return (0);
}
if (pad)
hdrlen = roundup2(hdrlen, 4);
if (ndo->ndo_Hflag && FC_TYPE(fc) == T_DATA &&
DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) {
meshdrlen = extract_mesh_header_length(p+hdrlen);
hdrlen += meshdrlen;
} else
meshdrlen = 0;
if (caplen < hdrlen) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
if (ndo->ndo_eflag)
ieee_802_11_hdr_print(ndo, fc, p, hdrlen, meshdrlen);
/*
* Go past the 802.11 header.
*/
length -= hdrlen;
caplen -= hdrlen;
p += hdrlen;
src.addr_string = etheraddr_string;
dst.addr_string = etheraddr_string;
switch (FC_TYPE(fc)) {
case T_MGMT:
get_mgmt_src_dst_mac(p - hdrlen, &src.addr, &dst.addr);
if (!mgmt_body_print(ndo, fc, src.addr, p, length)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
break;
case T_CTRL:
if (!ctrl_body_print(ndo, fc, p - hdrlen)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
break;
case T_DATA:
if (DATA_FRAME_IS_NULL(FC_SUBTYPE(fc)))
return hdrlen; /* no-data frame */
/* There may be a problem w/ AP not having this bit set */
if (FC_PROTECTED(fc)) {
ND_PRINT((ndo, "Data"));
if (!wep_print(ndo, p)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
} else {
get_data_src_dst_mac(fc, p - hdrlen, &src.addr, &dst.addr);
llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst);
if (llc_hdrlen < 0) {
/*
* Some kinds of LLC packet we cannot
* handle intelligently
*/
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
llc_hdrlen = -llc_hdrlen;
}
hdrlen += llc_hdrlen;
}
break;
default:
/* We shouldn't get here - we should already have quit */
break;
}
return hdrlen;
}
/*
* This is the top level routine of the printer. 'p' points
* to the 802.11 header of the packet, 'h->ts' is the timestamp,
* 'h->len' is the length of the packet off the wire, and 'h->caplen'
* is the number of bytes actually captured.
*/
u_int
ieee802_11_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
return ieee802_11_print(ndo, p, h->len, h->caplen, 0, 0);
}
/* $FreeBSD: src/sys/net80211/ieee80211_radiotap.h,v 1.5 2005/01/22 20:12:05 sam Exp $ */
/* NetBSD: ieee802_11_radio.h,v 1.2 2006/02/26 03:04:03 dyoung Exp */
/*-
* Copyright (c) 2003, 2004 David Young. 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. The name of David Young may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY DAVID YOUNG ``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 DAVID
* YOUNG 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.
*/
/* A generic radio capture format is desirable. It must be
* rigidly defined (e.g., units for fields should be given),
* and easily extensible.
*
* The following is an extensible radio capture format. It is
* based on a bitmap indicating which fields are present.
*
* I am trying to describe precisely what the application programmer
* should expect in the following, and for that reason I tell the
* units and origin of each measurement (where it applies), or else I
* use sufficiently weaselly language ("is a monotonically nondecreasing
* function of...") that I cannot set false expectations for lawyerly
* readers.
*/
/*
* The radio capture header precedes the 802.11 header.
*
* Note well: all radiotap fields are little-endian.
*/
struct ieee80211_radiotap_header {
uint8_t it_version; /* Version 0. Only increases
* for drastic changes,
* introduction of compatible
* new fields does not count.
*/
uint8_t it_pad;
uint16_t it_len; /* length of the whole
* header in bytes, including
* it_version, it_pad,
* it_len, and data fields.
*/
uint32_t it_present; /* A bitmap telling which
* fields are present. Set bit 31
* (0x80000000) to extend the
* bitmap by another 32 bits.
* Additional extensions are made
* by setting bit 31.
*/
};
/* Name Data type Units
* ---- --------- -----
*
* IEEE80211_RADIOTAP_TSFT uint64_t microseconds
*
* Value in microseconds of the MAC's 64-bit 802.11 Time
* Synchronization Function timer when the first bit of the
* MPDU arrived at the MAC. For received frames, only.
*
* IEEE80211_RADIOTAP_CHANNEL 2 x uint16_t MHz, bitmap
*
* Tx/Rx frequency in MHz, followed by flags (see below).
* Note that IEEE80211_RADIOTAP_XCHANNEL must be used to
* represent an HT channel as there is not enough room in
* the flags word.
*
* IEEE80211_RADIOTAP_FHSS uint16_t see below
*
* For frequency-hopping radios, the hop set (first byte)
* and pattern (second byte).
*
* IEEE80211_RADIOTAP_RATE uint8_t 500kb/s or index
*
* Tx/Rx data rate. If bit 0x80 is set then it represents an
* an MCS index and not an IEEE rate.
*
* IEEE80211_RADIOTAP_DBM_ANTSIGNAL int8_t decibels from
* one milliwatt (dBm)
*
* RF signal power at the antenna, decibel difference from
* one milliwatt.
*
* IEEE80211_RADIOTAP_DBM_ANTNOISE int8_t decibels from
* one milliwatt (dBm)
*
* RF noise power at the antenna, decibel difference from one
* milliwatt.
*
* IEEE80211_RADIOTAP_DB_ANTSIGNAL uint8_t decibel (dB)
*
* RF signal power at the antenna, decibel difference from an
* arbitrary, fixed reference.
*
* IEEE80211_RADIOTAP_DB_ANTNOISE uint8_t decibel (dB)
*
* RF noise power at the antenna, decibel difference from an
* arbitrary, fixed reference point.
*
* IEEE80211_RADIOTAP_LOCK_QUALITY uint16_t unitless
*
* Quality of Barker code lock. Unitless. Monotonically
* nondecreasing with "better" lock strength. Called "Signal
* Quality" in datasheets. (Is there a standard way to measure
* this?)
*
* IEEE80211_RADIOTAP_TX_ATTENUATION uint16_t unitless
*
* Transmit power expressed as unitless distance from max
* power set at factory calibration. 0 is max power.
* Monotonically nondecreasing with lower power levels.
*
* IEEE80211_RADIOTAP_DB_TX_ATTENUATION uint16_t decibels (dB)
*
* Transmit power expressed as decibel distance from max power
* set at factory calibration. 0 is max power. Monotonically
* nondecreasing with lower power levels.
*
* IEEE80211_RADIOTAP_DBM_TX_POWER int8_t decibels from
* one milliwatt (dBm)
*
* Transmit power expressed as dBm (decibels from a 1 milliwatt
* reference). This is the absolute power level measured at
* the antenna port.
*
* IEEE80211_RADIOTAP_FLAGS uint8_t bitmap
*
* Properties of transmitted and received frames. See flags
* defined below.
*
* IEEE80211_RADIOTAP_ANTENNA uint8_t antenna index
*
* Unitless indication of the Rx/Tx antenna for this packet.
* The first antenna is antenna 0.
*
* IEEE80211_RADIOTAP_RX_FLAGS uint16_t bitmap
*
* Properties of received frames. See flags defined below.
*
* IEEE80211_RADIOTAP_XCHANNEL uint32_t bitmap
* uint16_t MHz
* uint8_t channel number
* uint8_t .5 dBm
*
* Extended channel specification: flags (see below) followed by
* frequency in MHz, the corresponding IEEE channel number, and
* finally the maximum regulatory transmit power cap in .5 dBm
* units. This property supersedes IEEE80211_RADIOTAP_CHANNEL
* and only one of the two should be present.
*
* IEEE80211_RADIOTAP_MCS uint8_t known
* uint8_t flags
* uint8_t mcs
*
* Bitset indicating which fields have known values, followed
* by bitset of flag values, followed by the MCS rate index as
* in IEEE 802.11n.
*
*
* IEEE80211_RADIOTAP_AMPDU_STATUS u32, u16, u8, u8 unitless
*
* Contains the AMPDU information for the subframe.
*
* IEEE80211_RADIOTAP_VHT u16, u8, u8, u8[4], u8, u8, u16
*
* Contains VHT information about this frame.
*
* IEEE80211_RADIOTAP_VENDOR_NAMESPACE
* uint8_t OUI[3]
* uint8_t subspace
* uint16_t length
*
* The Vendor Namespace Field contains three sub-fields. The first
* sub-field is 3 bytes long. It contains the vendor's IEEE 802
* Organizationally Unique Identifier (OUI). The fourth byte is a
* vendor-specific "namespace selector."
*
*/
enum ieee80211_radiotap_type {
IEEE80211_RADIOTAP_TSFT = 0,
IEEE80211_RADIOTAP_FLAGS = 1,
IEEE80211_RADIOTAP_RATE = 2,
IEEE80211_RADIOTAP_CHANNEL = 3,
IEEE80211_RADIOTAP_FHSS = 4,
IEEE80211_RADIOTAP_DBM_ANTSIGNAL = 5,
IEEE80211_RADIOTAP_DBM_ANTNOISE = 6,
IEEE80211_RADIOTAP_LOCK_QUALITY = 7,
IEEE80211_RADIOTAP_TX_ATTENUATION = 8,
IEEE80211_RADIOTAP_DB_TX_ATTENUATION = 9,
IEEE80211_RADIOTAP_DBM_TX_POWER = 10,
IEEE80211_RADIOTAP_ANTENNA = 11,
IEEE80211_RADIOTAP_DB_ANTSIGNAL = 12,
IEEE80211_RADIOTAP_DB_ANTNOISE = 13,
IEEE80211_RADIOTAP_RX_FLAGS = 14,
/* NB: gap for netbsd definitions */
IEEE80211_RADIOTAP_XCHANNEL = 18,
IEEE80211_RADIOTAP_MCS = 19,
IEEE80211_RADIOTAP_AMPDU_STATUS = 20,
IEEE80211_RADIOTAP_VHT = 21,
IEEE80211_RADIOTAP_NAMESPACE = 29,
IEEE80211_RADIOTAP_VENDOR_NAMESPACE = 30,
IEEE80211_RADIOTAP_EXT = 31
};
/* channel attributes */
#define IEEE80211_CHAN_TURBO 0x00010 /* Turbo channel */
#define IEEE80211_CHAN_CCK 0x00020 /* CCK channel */
#define IEEE80211_CHAN_OFDM 0x00040 /* OFDM channel */
#define IEEE80211_CHAN_2GHZ 0x00080 /* 2 GHz spectrum channel. */
#define IEEE80211_CHAN_5GHZ 0x00100 /* 5 GHz spectrum channel */
#define IEEE80211_CHAN_PASSIVE 0x00200 /* Only passive scan allowed */
#define IEEE80211_CHAN_DYN 0x00400 /* Dynamic CCK-OFDM channel */
#define IEEE80211_CHAN_GFSK 0x00800 /* GFSK channel (FHSS PHY) */
#define IEEE80211_CHAN_GSM 0x01000 /* 900 MHz spectrum channel */
#define IEEE80211_CHAN_STURBO 0x02000 /* 11a static turbo channel only */
#define IEEE80211_CHAN_HALF 0x04000 /* Half rate channel */
#define IEEE80211_CHAN_QUARTER 0x08000 /* Quarter rate channel */
#define IEEE80211_CHAN_HT20 0x10000 /* HT 20 channel */
#define IEEE80211_CHAN_HT40U 0x20000 /* HT 40 channel w/ ext above */
#define IEEE80211_CHAN_HT40D 0x40000 /* HT 40 channel w/ ext below */
/* Useful combinations of channel characteristics, borrowed from Ethereal */
#define IEEE80211_CHAN_A \
(IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM)
#define IEEE80211_CHAN_B \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_CCK)
#define IEEE80211_CHAN_G \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN)
#define IEEE80211_CHAN_TA \
(IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM | IEEE80211_CHAN_TURBO)
#define IEEE80211_CHAN_TG \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN | IEEE80211_CHAN_TURBO)
/* For IEEE80211_RADIOTAP_FLAGS */
#define IEEE80211_RADIOTAP_F_CFP 0x01 /* sent/received
* during CFP
*/
#define IEEE80211_RADIOTAP_F_SHORTPRE 0x02 /* sent/received
* with short
* preamble
*/
#define IEEE80211_RADIOTAP_F_WEP 0x04 /* sent/received
* with WEP encryption
*/
#define IEEE80211_RADIOTAP_F_FRAG 0x08 /* sent/received
* with fragmentation
*/
#define IEEE80211_RADIOTAP_F_FCS 0x10 /* frame includes FCS */
#define IEEE80211_RADIOTAP_F_DATAPAD 0x20 /* frame has padding between
* 802.11 header and payload
* (to 32-bit boundary)
*/
#define IEEE80211_RADIOTAP_F_BADFCS 0x40 /* does not pass FCS check */
/* For IEEE80211_RADIOTAP_RX_FLAGS */
#define IEEE80211_RADIOTAP_F_RX_BADFCS 0x0001 /* frame failed crc check */
#define IEEE80211_RADIOTAP_F_RX_PLCP_CRC 0x0002 /* frame failed PLCP CRC check */
/* For IEEE80211_RADIOTAP_MCS known */
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN 0x01
#define IEEE80211_RADIOTAP_MCS_MCS_INDEX_KNOWN 0x02 /* MCS index field */
#define IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN 0x04
#define IEEE80211_RADIOTAP_MCS_HT_FORMAT_KNOWN 0x08
#define IEEE80211_RADIOTAP_MCS_FEC_TYPE_KNOWN 0x10
#define IEEE80211_RADIOTAP_MCS_STBC_KNOWN 0x20
#define IEEE80211_RADIOTAP_MCS_NESS_KNOWN 0x40
#define IEEE80211_RADIOTAP_MCS_NESS_BIT_1 0x80
/* For IEEE80211_RADIOTAP_MCS flags */
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK 0x03
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20 0
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_40 1
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20L 2
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20U 3
#define IEEE80211_RADIOTAP_MCS_SHORT_GI 0x04 /* short guard interval */
#define IEEE80211_RADIOTAP_MCS_HT_GREENFIELD 0x08
#define IEEE80211_RADIOTAP_MCS_FEC_LDPC 0x10
#define IEEE80211_RADIOTAP_MCS_STBC_MASK 0x60
#define IEEE80211_RADIOTAP_MCS_STBC_1 1
#define IEEE80211_RADIOTAP_MCS_STBC_2 2
#define IEEE80211_RADIOTAP_MCS_STBC_3 3
#define IEEE80211_RADIOTAP_MCS_STBC_SHIFT 5
#define IEEE80211_RADIOTAP_MCS_NESS_BIT_0 0x80
/* For IEEE80211_RADIOTAP_AMPDU_STATUS */
#define IEEE80211_RADIOTAP_AMPDU_REPORT_ZEROLEN 0x0001
#define IEEE80211_RADIOTAP_AMPDU_IS_ZEROLEN 0x0002
#define IEEE80211_RADIOTAP_AMPDU_LAST_KNOWN 0x0004
#define IEEE80211_RADIOTAP_AMPDU_IS_LAST 0x0008
#define IEEE80211_RADIOTAP_AMPDU_DELIM_CRC_ERR 0x0010
#define IEEE80211_RADIOTAP_AMPDU_DELIM_CRC_KNOWN 0x0020
/* For IEEE80211_RADIOTAP_VHT known */
#define IEEE80211_RADIOTAP_VHT_STBC_KNOWN 0x0001
#define IEEE80211_RADIOTAP_VHT_TXOP_PS_NA_KNOWN 0x0002
#define IEEE80211_RADIOTAP_VHT_GUARD_INTERVAL_KNOWN 0x0004
#define IEEE80211_RADIOTAP_VHT_SGI_NSYM_DIS_KNOWN 0x0008
#define IEEE80211_RADIOTAP_VHT_LDPC_EXTRA_OFDM_SYM_KNOWN 0x0010
#define IEEE80211_RADIOTAP_VHT_BEAMFORMED_KNOWN 0x0020
#define IEEE80211_RADIOTAP_VHT_BANDWIDTH_KNOWN 0x0040
#define IEEE80211_RADIOTAP_VHT_GROUP_ID_KNOWN 0x0080
#define IEEE80211_RADIOTAP_VHT_PARTIAL_AID_KNOWN 0x0100
/* For IEEE80211_RADIOTAP_VHT flags */
#define IEEE80211_RADIOTAP_VHT_STBC 0x01
#define IEEE80211_RADIOTAP_VHT_TXOP_PS_NA 0x02
#define IEEE80211_RADIOTAP_VHT_SHORT_GI 0x04
#define IEEE80211_RADIOTAP_VHT_SGI_NSYM_M10_9 0x08
#define IEEE80211_RADIOTAP_VHT_LDPC_EXTRA_OFDM_SYM 0x10
#define IEEE80211_RADIOTAP_VHT_BEAMFORMED 0x20
#define IEEE80211_RADIOTAP_VHT_BANDWIDTH_MASK 0x1f
#define IEEE80211_RADIOTAP_VHT_NSS_MASK 0x0f
#define IEEE80211_RADIOTAP_VHT_MCS_MASK 0xf0
#define IEEE80211_RADIOTAP_VHT_MCS_SHIFT 4
#define IEEE80211_RADIOTAP_CODING_LDPC_USERn 0x01
#define IEEE80211_CHAN_FHSS \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_GFSK)
#define IEEE80211_CHAN_A \
(IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM)
#define IEEE80211_CHAN_B \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_CCK)
#define IEEE80211_CHAN_PUREG \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_OFDM)
#define IEEE80211_CHAN_G \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN)
#define IS_CHAN_FHSS(flags) \
((flags & IEEE80211_CHAN_FHSS) == IEEE80211_CHAN_FHSS)
#define IS_CHAN_A(flags) \
((flags & IEEE80211_CHAN_A) == IEEE80211_CHAN_A)
#define IS_CHAN_B(flags) \
((flags & IEEE80211_CHAN_B) == IEEE80211_CHAN_B)
#define IS_CHAN_PUREG(flags) \
((flags & IEEE80211_CHAN_PUREG) == IEEE80211_CHAN_PUREG)
#define IS_CHAN_G(flags) \
((flags & IEEE80211_CHAN_G) == IEEE80211_CHAN_G)
#define IS_CHAN_ANYG(flags) \
(IS_CHAN_PUREG(flags) || IS_CHAN_G(flags))
static void
print_chaninfo(netdissect_options *ndo,
uint16_t freq, int flags, int presentflags)
{
ND_PRINT((ndo, "%u MHz", freq));
if (presentflags & (1 << IEEE80211_RADIOTAP_MCS)) {
/*
* We have the MCS field, so this is 11n, regardless
* of what the channel flags say.
*/
ND_PRINT((ndo, " 11n"));
} else {
if (IS_CHAN_FHSS(flags))
ND_PRINT((ndo, " FHSS"));
if (IS_CHAN_A(flags)) {
if (flags & IEEE80211_CHAN_HALF)
ND_PRINT((ndo, " 11a/10Mhz"));
else if (flags & IEEE80211_CHAN_QUARTER)
ND_PRINT((ndo, " 11a/5Mhz"));
else
ND_PRINT((ndo, " 11a"));
}
if (IS_CHAN_ANYG(flags)) {
if (flags & IEEE80211_CHAN_HALF)
ND_PRINT((ndo, " 11g/10Mhz"));
else if (flags & IEEE80211_CHAN_QUARTER)
ND_PRINT((ndo, " 11g/5Mhz"));
else
ND_PRINT((ndo, " 11g"));
} else if (IS_CHAN_B(flags))
ND_PRINT((ndo, " 11b"));
if (flags & IEEE80211_CHAN_TURBO)
ND_PRINT((ndo, " Turbo"));
}
/*
* These apply to 11n.
*/
if (flags & IEEE80211_CHAN_HT20)
ND_PRINT((ndo, " ht/20"));
else if (flags & IEEE80211_CHAN_HT40D)
ND_PRINT((ndo, " ht/40-"));
else if (flags & IEEE80211_CHAN_HT40U)
ND_PRINT((ndo, " ht/40+"));
ND_PRINT((ndo, " "));
}
static int
print_radiotap_field(netdissect_options *ndo,
struct cpack_state *s, uint32_t bit, uint8_t *flagsp,
uint32_t presentflags)
{
u_int i;
int rc;
switch (bit) {
case IEEE80211_RADIOTAP_TSFT: {
uint64_t tsft;
rc = cpack_uint64(s, &tsft);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%" PRIu64 "us tsft ", tsft));
break;
}
case IEEE80211_RADIOTAP_FLAGS: {
uint8_t flagsval;
rc = cpack_uint8(s, &flagsval);
if (rc != 0)
goto trunc;
*flagsp = flagsval;
if (flagsval & IEEE80211_RADIOTAP_F_CFP)
ND_PRINT((ndo, "cfp "));
if (flagsval & IEEE80211_RADIOTAP_F_SHORTPRE)
ND_PRINT((ndo, "short preamble "));
if (flagsval & IEEE80211_RADIOTAP_F_WEP)
ND_PRINT((ndo, "wep "));
if (flagsval & IEEE80211_RADIOTAP_F_FRAG)
ND_PRINT((ndo, "fragmented "));
if (flagsval & IEEE80211_RADIOTAP_F_BADFCS)
ND_PRINT((ndo, "bad-fcs "));
break;
}
case IEEE80211_RADIOTAP_RATE: {
uint8_t rate;
rc = cpack_uint8(s, &rate);
if (rc != 0)
goto trunc;
/*
* XXX On FreeBSD rate & 0x80 means we have an MCS. On
* Linux and AirPcap it does not. (What about
* Mac OS X, NetBSD, OpenBSD, and DragonFly BSD?)
*
* This is an issue either for proprietary extensions
* to 11a or 11g, which do exist, or for 11n
* implementations that stuff a rate value into
* this field, which also appear to exist.
*
* We currently handle that by assuming that
* if the 0x80 bit is set *and* the remaining
* bits have a value between 0 and 15 it's
* an MCS value, otherwise it's a rate. If
* there are cases where systems that use
* "0x80 + MCS index" for MCS indices > 15,
* or stuff a rate value here between 64 and
* 71.5 Mb/s in here, we'll need a preference
* setting. Such rates do exist, e.g. 11n
* MCS 7 at 20 MHz with a long guard interval.
*/
if (rate >= 0x80 && rate <= 0x8f) {
/*
* XXX - we don't know the channel width
* or guard interval length, so we can't
* convert this to a data rate.
*
* If you want us to show a data rate,
* use the MCS field, not the Rate field;
* the MCS field includes not only the
* MCS index, it also includes bandwidth
* and guard interval information.
*
* XXX - can we get the channel width
* from XChannel and the guard interval
* information from Flags, at least on
* FreeBSD?
*/
ND_PRINT((ndo, "MCS %u ", rate & 0x7f));
} else
ND_PRINT((ndo, "%2.1f Mb/s ", .5 * rate));
break;
}
case IEEE80211_RADIOTAP_CHANNEL: {
uint16_t frequency;
uint16_t flags;
rc = cpack_uint16(s, &frequency);
if (rc != 0)
goto trunc;
rc = cpack_uint16(s, &flags);
if (rc != 0)
goto trunc;
/*
* If CHANNEL and XCHANNEL are both present, skip
* CHANNEL.
*/
if (presentflags & (1 << IEEE80211_RADIOTAP_XCHANNEL))
break;
print_chaninfo(ndo, frequency, flags, presentflags);
break;
}
case IEEE80211_RADIOTAP_FHSS: {
uint8_t hopset;
uint8_t hoppat;
rc = cpack_uint8(s, &hopset);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &hoppat);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "fhset %d fhpat %d ", hopset, hoppat));
break;
}
case IEEE80211_RADIOTAP_DBM_ANTSIGNAL: {
int8_t dbm_antsignal;
rc = cpack_int8(s, &dbm_antsignal);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddBm signal ", dbm_antsignal));
break;
}
case IEEE80211_RADIOTAP_DBM_ANTNOISE: {
int8_t dbm_antnoise;
rc = cpack_int8(s, &dbm_antnoise);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddBm noise ", dbm_antnoise));
break;
}
case IEEE80211_RADIOTAP_LOCK_QUALITY: {
uint16_t lock_quality;
rc = cpack_uint16(s, &lock_quality);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%u sq ", lock_quality));
break;
}
case IEEE80211_RADIOTAP_TX_ATTENUATION: {
uint16_t tx_attenuation;
rc = cpack_uint16(s, &tx_attenuation);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%d tx power ", -(int)tx_attenuation));
break;
}
case IEEE80211_RADIOTAP_DB_TX_ATTENUATION: {
uint8_t db_tx_attenuation;
rc = cpack_uint8(s, &db_tx_attenuation);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddB tx attenuation ", -(int)db_tx_attenuation));
break;
}
case IEEE80211_RADIOTAP_DBM_TX_POWER: {
int8_t dbm_tx_power;
rc = cpack_int8(s, &dbm_tx_power);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddBm tx power ", dbm_tx_power));
break;
}
case IEEE80211_RADIOTAP_ANTENNA: {
uint8_t antenna;
rc = cpack_uint8(s, &antenna);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "antenna %u ", antenna));
break;
}
case IEEE80211_RADIOTAP_DB_ANTSIGNAL: {
uint8_t db_antsignal;
rc = cpack_uint8(s, &db_antsignal);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddB signal ", db_antsignal));
break;
}
case IEEE80211_RADIOTAP_DB_ANTNOISE: {
uint8_t db_antnoise;
rc = cpack_uint8(s, &db_antnoise);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddB noise ", db_antnoise));
break;
}
case IEEE80211_RADIOTAP_RX_FLAGS: {
uint16_t rx_flags;
rc = cpack_uint16(s, &rx_flags);
if (rc != 0)
goto trunc;
/* Do nothing for now */
break;
}
case IEEE80211_RADIOTAP_XCHANNEL: {
uint32_t flags;
uint16_t frequency;
uint8_t channel;
uint8_t maxpower;
rc = cpack_uint32(s, &flags);
if (rc != 0)
goto trunc;
rc = cpack_uint16(s, &frequency);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &channel);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &maxpower);
if (rc != 0)
goto trunc;
print_chaninfo(ndo, frequency, flags, presentflags);
break;
}
case IEEE80211_RADIOTAP_MCS: {
uint8_t known;
uint8_t flags;
uint8_t mcs_index;
static const char *ht_bandwidth[4] = {
"20 MHz",
"40 MHz",
"20 MHz (L)",
"20 MHz (U)"
};
float htrate;
rc = cpack_uint8(s, &known);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &flags);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &mcs_index);
if (rc != 0)
goto trunc;
if (known & IEEE80211_RADIOTAP_MCS_MCS_INDEX_KNOWN) {
/*
* We know the MCS index.
*/
if (mcs_index <= MAX_MCS_INDEX) {
/*
* And it's in-range.
*/
if (known & (IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN|IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN)) {
/*
* And we know both the bandwidth and
* the guard interval, so we can look
* up the rate.
*/
htrate =
ieee80211_float_htrates \
[mcs_index] \
[((flags & IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK) == IEEE80211_RADIOTAP_MCS_BANDWIDTH_40 ? 1 : 0)] \
[((flags & IEEE80211_RADIOTAP_MCS_SHORT_GI) ? 1 : 0)];
} else {
/*
* We don't know both the bandwidth
* and the guard interval, so we can
* only report the MCS index.
*/
htrate = 0.0;
}
} else {
/*
* The MCS value is out of range.
*/
htrate = 0.0;
}
if (htrate != 0.0) {
/*
* We have the rate.
* Print it.
*/
ND_PRINT((ndo, "%.1f Mb/s MCS %u ", htrate, mcs_index));
} else {
/*
* We at least have the MCS index.
* Print it.
*/
ND_PRINT((ndo, "MCS %u ", mcs_index));
}
}
if (known & IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN) {
ND_PRINT((ndo, "%s ",
ht_bandwidth[flags & IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK]));
}
if (known & IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN) {
ND_PRINT((ndo, "%s GI ",
(flags & IEEE80211_RADIOTAP_MCS_SHORT_GI) ?
"short" : "long"));
}
if (known & IEEE80211_RADIOTAP_MCS_HT_FORMAT_KNOWN) {
ND_PRINT((ndo, "%s ",
(flags & IEEE80211_RADIOTAP_MCS_HT_GREENFIELD) ?
"greenfield" : "mixed"));
}
if (known & IEEE80211_RADIOTAP_MCS_FEC_TYPE_KNOWN) {
ND_PRINT((ndo, "%s FEC ",
(flags & IEEE80211_RADIOTAP_MCS_FEC_LDPC) ?
"LDPC" : "BCC"));
}
if (known & IEEE80211_RADIOTAP_MCS_STBC_KNOWN) {
ND_PRINT((ndo, "RX-STBC%u ",
(flags & IEEE80211_RADIOTAP_MCS_STBC_MASK) >> IEEE80211_RADIOTAP_MCS_STBC_SHIFT));
}
break;
}
case IEEE80211_RADIOTAP_AMPDU_STATUS: {
uint32_t reference_num;
uint16_t flags;
uint8_t delim_crc;
uint8_t reserved;
rc = cpack_uint32(s, &reference_num);
if (rc != 0)
goto trunc;
rc = cpack_uint16(s, &flags);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &delim_crc);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &reserved);
if (rc != 0)
goto trunc;
/* Do nothing for now */
break;
}
case IEEE80211_RADIOTAP_VHT: {
uint16_t known;
uint8_t flags;
uint8_t bandwidth;
uint8_t mcs_nss[4];
uint8_t coding;
uint8_t group_id;
uint16_t partial_aid;
static const char *vht_bandwidth[32] = {
"20 MHz",
"40 MHz",
"20 MHz (L)",
"20 MHz (U)",
"80 MHz",
"80 MHz (L)",
"80 MHz (U)",
"80 MHz (LL)",
"80 MHz (LU)",
"80 MHz (UL)",
"80 MHz (UU)",
"160 MHz",
"160 MHz (L)",
"160 MHz (U)",
"160 MHz (LL)",
"160 MHz (LU)",
"160 MHz (UL)",
"160 MHz (UU)",
"160 MHz (LLL)",
"160 MHz (LLU)",
"160 MHz (LUL)",
"160 MHz (UUU)",
"160 MHz (ULL)",
"160 MHz (ULU)",
"160 MHz (UUL)",
"160 MHz (UUU)",
"unknown (26)",
"unknown (27)",
"unknown (28)",
"unknown (29)",
"unknown (30)",
"unknown (31)"
};
rc = cpack_uint16(s, &known);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &flags);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &bandwidth);
if (rc != 0)
goto trunc;
for (i = 0; i < 4; i++) {
rc = cpack_uint8(s, &mcs_nss[i]);
if (rc != 0)
goto trunc;
}
rc = cpack_uint8(s, &coding);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &group_id);
if (rc != 0)
goto trunc;
rc = cpack_uint16(s, &partial_aid);
if (rc != 0)
goto trunc;
for (i = 0; i < 4; i++) {
u_int nss, mcs;
nss = mcs_nss[i] & IEEE80211_RADIOTAP_VHT_NSS_MASK;
mcs = (mcs_nss[i] & IEEE80211_RADIOTAP_VHT_MCS_MASK) >> IEEE80211_RADIOTAP_VHT_MCS_SHIFT;
if (nss == 0)
continue;
ND_PRINT((ndo, "User %u MCS %u ", i, mcs));
ND_PRINT((ndo, "%s FEC ",
(coding & (IEEE80211_RADIOTAP_CODING_LDPC_USERn << i)) ?
"LDPC" : "BCC"));
}
if (known & IEEE80211_RADIOTAP_VHT_BANDWIDTH_KNOWN) {
ND_PRINT((ndo, "%s ",
vht_bandwidth[bandwidth & IEEE80211_RADIOTAP_VHT_BANDWIDTH_MASK]));
}
if (known & IEEE80211_RADIOTAP_VHT_GUARD_INTERVAL_KNOWN) {
ND_PRINT((ndo, "%s GI ",
(flags & IEEE80211_RADIOTAP_VHT_SHORT_GI) ?
"short" : "long"));
}
break;
}
default:
/* this bit indicates a field whose
* size we do not know, so we cannot
* proceed. Just print the bit number.
*/
ND_PRINT((ndo, "[bit %u] ", bit));
return -1;
}
return 0;
trunc:
ND_PRINT((ndo, "%s", tstr));
return rc;
}
static int
print_in_radiotap_namespace(netdissect_options *ndo,
struct cpack_state *s, uint8_t *flags,
uint32_t presentflags, int bit0)
{
#define BITNO_32(x) (((x) >> 16) ? 16 + BITNO_16((x) >> 16) : BITNO_16((x)))
#define BITNO_16(x) (((x) >> 8) ? 8 + BITNO_8((x) >> 8) : BITNO_8((x)))
#define BITNO_8(x) (((x) >> 4) ? 4 + BITNO_4((x) >> 4) : BITNO_4((x)))
#define BITNO_4(x) (((x) >> 2) ? 2 + BITNO_2((x) >> 2) : BITNO_2((x)))
#define BITNO_2(x) (((x) & 2) ? 1 : 0)
uint32_t present, next_present;
int bitno;
enum ieee80211_radiotap_type bit;
int rc;
for (present = presentflags; present; present = next_present) {
/*
* Clear the least significant bit that is set.
*/
next_present = present & (present - 1);
/*
* Get the bit number, within this presence word,
* of the remaining least significant bit that
* is set.
*/
bitno = BITNO_32(present ^ next_present);
/*
* Stop if this is one of the "same meaning
* in all presence flags" bits.
*/
if (bitno >= IEEE80211_RADIOTAP_NAMESPACE)
break;
/*
* Get the radiotap bit number of that bit.
*/
bit = (enum ieee80211_radiotap_type)(bit0 + bitno);
rc = print_radiotap_field(ndo, s, bit, flags, presentflags);
if (rc != 0)
return rc;
}
return 0;
}
static u_int
ieee802_11_radio_print(netdissect_options *ndo,
const u_char *p, u_int length, u_int caplen)
{
#define BIT(n) (1U << n)
#define IS_EXTENDED(__p) \
(EXTRACT_LE_32BITS(__p) & BIT(IEEE80211_RADIOTAP_EXT)) != 0
struct cpack_state cpacker;
const struct ieee80211_radiotap_header *hdr;
uint32_t presentflags;
const uint32_t *presentp, *last_presentp;
int vendor_namespace;
uint8_t vendor_oui[3];
uint8_t vendor_subnamespace;
uint16_t skip_length;
int bit0;
u_int len;
uint8_t flags;
int pad;
u_int fcslen;
if (caplen < sizeof(*hdr)) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
hdr = (const struct ieee80211_radiotap_header *)p;
len = EXTRACT_LE_16BITS(&hdr->it_len);
/*
* If we don't have the entire radiotap header, just give up.
*/
if (caplen < len) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
cpack_init(&cpacker, (const uint8_t *)hdr, len); /* align against header start */
cpack_advance(&cpacker, sizeof(*hdr)); /* includes the 1st bitmap */
for (last_presentp = &hdr->it_present;
(const u_char*)(last_presentp + 1) <= p + len &&
IS_EXTENDED(last_presentp);
last_presentp++)
cpack_advance(&cpacker, sizeof(hdr->it_present)); /* more bitmaps */
/* are there more bitmap extensions than bytes in header? */
if ((const u_char*)(last_presentp + 1) > p + len) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
/*
* Start out at the beginning of the default radiotap namespace.
*/
bit0 = 0;
vendor_namespace = 0;
memset(vendor_oui, 0, 3);
vendor_subnamespace = 0;
skip_length = 0;
/* Assume no flags */
flags = 0;
/* Assume no Atheros padding between 802.11 header and body */
pad = 0;
/* Assume no FCS at end of frame */
fcslen = 0;
for (presentp = &hdr->it_present; presentp <= last_presentp;
presentp++) {
presentflags = EXTRACT_LE_32BITS(presentp);
/*
* If this is a vendor namespace, we don't handle it.
*/
if (vendor_namespace) {
/*
* Skip past the stuff we don't understand.
* If we add support for any vendor namespaces,
* it'd be added here; use vendor_oui and
* vendor_subnamespace to interpret the fields.
*/
if (cpack_advance(&cpacker, skip_length) != 0) {
/*
* Ran out of space in the packet.
*/
break;
}
/*
* We've skipped it all; nothing more to
* skip.
*/
skip_length = 0;
} else {
if (print_in_radiotap_namespace(ndo, &cpacker,
&flags, presentflags, bit0) != 0) {
/*
* Fatal error - can't process anything
* more in the radiotap header.
*/
break;
}
}
/*
* Handle the namespace switch bits; we've already handled
* the extension bit in all but the last word above.
*/
switch (presentflags &
(BIT(IEEE80211_RADIOTAP_NAMESPACE)|BIT(IEEE80211_RADIOTAP_VENDOR_NAMESPACE))) {
case 0:
/*
* We're not changing namespaces.
* advance to the next 32 bits in the current
* namespace.
*/
bit0 += 32;
break;
case BIT(IEEE80211_RADIOTAP_NAMESPACE):
/*
* We're switching to the radiotap namespace.
* Reset the presence-bitmap index to 0, and
* reset the namespace to the default radiotap
* namespace.
*/
bit0 = 0;
vendor_namespace = 0;
memset(vendor_oui, 0, 3);
vendor_subnamespace = 0;
skip_length = 0;
break;
case BIT(IEEE80211_RADIOTAP_VENDOR_NAMESPACE):
/*
* We're switching to a vendor namespace.
* Reset the presence-bitmap index to 0,
* note that we're in a vendor namespace,
* and fetch the fields of the Vendor Namespace
* item.
*/
bit0 = 0;
vendor_namespace = 1;
if ((cpack_align_and_reserve(&cpacker, 2)) == NULL) {
ND_PRINT((ndo, "%s", tstr));
break;
}
if (cpack_uint8(&cpacker, &vendor_oui[0]) != 0) {
ND_PRINT((ndo, "%s", tstr));
break;
}
if (cpack_uint8(&cpacker, &vendor_oui[1]) != 0) {
ND_PRINT((ndo, "%s", tstr));
break;
}
if (cpack_uint8(&cpacker, &vendor_oui[2]) != 0) {
ND_PRINT((ndo, "%s", tstr));
break;
}
if (cpack_uint8(&cpacker, &vendor_subnamespace) != 0) {
ND_PRINT((ndo, "%s", tstr));
break;
}
if (cpack_uint16(&cpacker, &skip_length) != 0) {
ND_PRINT((ndo, "%s", tstr));
break;
}
break;
default:
/*
* Illegal combination. The behavior in this
* case is undefined by the radiotap spec; we
* just ignore both bits.
*/
break;
}
}
if (flags & IEEE80211_RADIOTAP_F_DATAPAD)
pad = 1; /* Atheros padding */
if (flags & IEEE80211_RADIOTAP_F_FCS)
fcslen = 4; /* FCS at end of packet */
return len + ieee802_11_print(ndo, p + len, length - len, caplen - len, pad,
fcslen);
#undef BITNO_32
#undef BITNO_16
#undef BITNO_8
#undef BITNO_4
#undef BITNO_2
#undef BIT
}
static u_int
ieee802_11_avs_radio_print(netdissect_options *ndo,
const u_char *p, u_int length, u_int caplen)
{
uint32_t caphdr_len;
if (caplen < 8) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
caphdr_len = EXTRACT_32BITS(p + 4);
if (caphdr_len < 8) {
/*
* Yow! The capture header length is claimed not
* to be large enough to include even the version
* cookie or capture header length!
*/
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
if (caplen < caphdr_len) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
return caphdr_len + ieee802_11_print(ndo, p + caphdr_len,
length - caphdr_len, caplen - caphdr_len, 0, 0);
}
#define PRISM_HDR_LEN 144
#define WLANCAP_MAGIC_COOKIE_BASE 0x80211000
#define WLANCAP_MAGIC_COOKIE_V1 0x80211001
#define WLANCAP_MAGIC_COOKIE_V2 0x80211002
/*
* For DLT_PRISM_HEADER; like DLT_IEEE802_11, but with an extra header,
* containing information such as radio information, which we
* currently ignore.
*
* If, however, the packet begins with WLANCAP_MAGIC_COOKIE_V1 or
* WLANCAP_MAGIC_COOKIE_V2, it's really DLT_IEEE802_11_RADIO_AVS
* (currently, on Linux, there's no ARPHRD_ type for
* DLT_IEEE802_11_RADIO_AVS, as there is a ARPHRD_IEEE80211_PRISM
* for DLT_PRISM_HEADER, so ARPHRD_IEEE80211_PRISM is used for
* the AVS header, and the first 4 bytes of the header are used to
* indicate whether it's a Prism header or an AVS header).
*/
u_int
prism_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int length = h->len;
uint32_t msgcode;
if (caplen < 4) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
msgcode = EXTRACT_32BITS(p);
if (msgcode == WLANCAP_MAGIC_COOKIE_V1 ||
msgcode == WLANCAP_MAGIC_COOKIE_V2)
return ieee802_11_avs_radio_print(ndo, p, length, caplen);
if (caplen < PRISM_HDR_LEN) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
return PRISM_HDR_LEN + ieee802_11_print(ndo, p + PRISM_HDR_LEN,
length - PRISM_HDR_LEN, caplen - PRISM_HDR_LEN, 0, 0);
}
/*
* For DLT_IEEE802_11_RADIO; like DLT_IEEE802_11, but with an extra
* header, containing information such as radio information.
*/
u_int
ieee802_11_radio_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
return ieee802_11_radio_print(ndo, p, h->len, h->caplen);
}
/*
* For DLT_IEEE802_11_RADIO_AVS; like DLT_IEEE802_11, but with an
* extra header, containing information such as radio information,
* which we currently ignore.
*/
u_int
ieee802_11_radio_avs_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
return ieee802_11_avs_radio_print(ndo, p, h->len, h->caplen);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2683_0 |
crossvul-cpp_data_good_5249_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% SSSSS GGGG IIIII %
% SS G I %
% SSS G GG I %
% SS G G I %
% SSSSS GGG IIIII %
% %
% %
% Read/Write Irix RGB Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
/*
Typedef declaractions.
*/
typedef struct _SGIInfo
{
unsigned short
magic;
unsigned char
storage,
bytes_per_pixel;
unsigned short
dimension,
columns,
rows,
depth;
size_t
minimum_value,
maximum_value,
sans;
char
name[80];
size_t
pixel_format;
unsigned char
filler[404];
} SGIInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WriteSGIImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s S G I %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsSGI() returns MagickTrue if the image format type, identified by the
% magick string, is SGI.
%
% The format of the IsSGI method is:
%
% MagickBooleanType IsSGI(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsSGI(const unsigned char *magick,const size_t length)
{
if (length < 2)
return(MagickFalse);
if (memcmp(magick,"\001\332",2) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d S G I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadSGIImage() reads a SGI RGB image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadSGIImage method is:
%
% Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType SGIDecode(const size_t bytes_per_pixel,
ssize_t number_packets,unsigned char *packets,ssize_t number_pixels,
unsigned char *pixels)
{
register unsigned char
*p,
*q;
size_t
pixel;
ssize_t
count;
p=packets;
q=pixels;
if (bytes_per_pixel == 2)
{
for ( ; number_pixels > 0; )
{
if (number_packets-- == 0)
return(MagickFalse);
pixel=(size_t) (*p++) << 8;
pixel|=(*p++);
count=(ssize_t) (pixel & 0x7f);
if (count == 0)
break;
if (count > (ssize_t) number_pixels)
return(MagickFalse);
number_pixels-=count;
if ((pixel & 0x80) != 0)
for ( ; count != 0; count--)
{
if (number_packets-- == 0)
return(MagickFalse);
*q=(*p++);
*(q+1)=(*p++);
q+=8;
}
else
{
pixel=(size_t) (*p++) << 8;
pixel|=(*p++);
for ( ; count != 0; count--)
{
if (number_packets-- == 0)
return(MagickFalse);
*q=(unsigned char) (pixel >> 8);
*(q+1)=(unsigned char) pixel;
q+=8;
}
}
}
return(MagickTrue);
}
for ( ; number_pixels > 0; )
{
if (number_packets-- == 0)
return(MagickFalse);
pixel=(size_t) (*p++);
count=(ssize_t) (pixel & 0x7f);
if (count == 0)
break;
if (count > (ssize_t) number_pixels)
return(MagickFalse);
number_pixels-=count;
if ((pixel & 0x80) != 0)
for ( ; count != 0; count--)
{
if (number_packets-- == 0)
return(MagickFalse);
*q=(*p++);
q+=4;
}
else
{
if (number_packets-- == 0)
return(MagickFalse);
pixel=(size_t) (*p++);
for ( ; count != 0; count--)
{
*q=(unsigned char) pixel;
q+=4;
}
}
}
return(MagickTrue);
}
static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
SGIInfo
iris_info;
size_t
bytes_per_pixel,
quantum;
ssize_t
count,
y,
z;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SGI raster header.
*/
iris_info.magic=ReadBlobMSBShort(image);
do
{
/*
Verify SGI identifier.
*/
if (iris_info.magic != 0x01DA)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.storage=(unsigned char) ReadBlobByte(image);
switch (iris_info.storage)
{
case 0x00: image->compression=NoCompression; break;
case 0x01: image->compression=RLECompression; break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image);
if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.dimension=ReadBlobMSBShort(image);
iris_info.columns=ReadBlobMSBShort(image);
iris_info.rows=ReadBlobMSBShort(image);
iris_info.depth=ReadBlobMSBShort(image);
if ((iris_info.depth == 0) || (iris_info.depth > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.minimum_value=ReadBlobMSBLong(image);
iris_info.maximum_value=ReadBlobMSBLong(image);
iris_info.sans=ReadBlobMSBLong(image);
count=ReadBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
if (count != sizeof(iris_info.name))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.name[sizeof(iris_info.name)-1]='\0';
if (*iris_info.name != '\0')
(void) SetImageProperty(image,"label",iris_info.name,exception);
iris_info.pixel_format=ReadBlobMSBLong(image);
if (iris_info.pixel_format != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler);
if (count != sizeof(iris_info.filler))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=iris_info.columns;
image->rows=iris_info.rows;
image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.pixel_format == 0)
image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel,
MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.depth < 3)
{
image->storage_class=PseudoClass;
image->colors=iris_info.bytes_per_pixel > 1 ? 65535 : 256;
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Allocate SGI pixels.
*/
bytes_per_pixel=(size_t) iris_info.bytes_per_pixel;
number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows;
if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t)
(4*bytes_per_pixel*number_pixels)))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4*
bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((int) iris_info.storage != 0x01)
{
unsigned char
*scanline;
/*
Read standard image format.
*/
scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns,
bytes_per_pixel*sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels+bytes_per_pixel*z;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline);
if (EOFBlob(image) != MagickFalse)
break;
if (bytes_per_pixel == 2)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[2*x];
*(p+1)=scanline[2*x+1];
p+=8;
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[x];
p+=4;
}
}
}
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
}
else
{
MemoryInfo
*packet_info;
size_t
*runlength;
ssize_t
offset,
*offsets;
unsigned char
*packets;
unsigned int
data_order;
/*
Read runlength-encoded image format.
*/
offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL*
sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
if (offsets == (ssize_t *) NULL)
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
if (runlength == (size_t *) NULL)
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info == (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
offsets[i]=ReadBlobMSBSignedLong(image);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
{
runlength[i]=ReadBlobMSBLong(image);
if (runlength[i] > (4*(size_t) iris_info.columns+10))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Check data order.
*/
offset=0;
data_order=0;
for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++)
for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++)
{
if (offsets[y+z*iris_info.rows] < offset)
data_order=1;
offset=offsets[y+z*iris_info.rows];
}
offset=(ssize_t) TellBlob(image);
if (data_order == 1)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
1L*iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
p+=(iris_info.columns*4*bytes_per_pixel);
}
}
}
else
{
MagickOffsetType
position;
position=TellBlob(image);
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
1L*iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
p+=(iris_info.columns*4*bytes_per_pixel);
}
offset=(ssize_t) SeekBlob(image,position,SEEK_SET);
}
packet_info=RelinquishVirtualMemory(packet_info);
runlength=(size_t *) RelinquishMagickMemory(runlength);
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
}
/*
Initialize image structure.
*/
image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=iris_info.columns;
image->rows=iris_info.rows;
/*
Convert SGI raster image to pixel packets.
*/
if (image->storage_class == DirectClass)
{
/*
Convert SGI image to DirectClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleShortToQuantum((unsigned short)
((*(p+0) << 8) | (*(p+1)))),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short)
((*(p+2) << 8) | (*(p+3)))),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short)
((*(p+4) << 8) | (*(p+5)))),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleShortToQuantum((unsigned short)
((*(p+6) << 8) | (*(p+7)))),q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p),q);
SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q);
SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create grayscale map.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert SGI image to PseudoClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=(*p << 8);
quantum|=(*(p+1));
SetPixelIndex(image,(Quantum) quantum,q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p,q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
iris_info.magic=ReadBlobMSBShort(image);
if (iris_info.magic == 0x01DA)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (iris_info.magic == 0x01DA);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r S G I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterSGIImage() adds properties for the SGI image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterSGIImage method is:
%
% size_t RegisterSGIImage(void)
%
*/
ModuleExport size_t RegisterSGIImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("SGI","SGI","Irix RGB image");
entry->decoder=(DecodeImageHandler *) ReadSGIImage;
entry->encoder=(EncodeImageHandler *) WriteSGIImage;
entry->magick=(IsImageFormatHandler *) IsSGI;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r S G I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterSGIImage() removes format registrations made by the
% SGI module from the list of supported formats.
%
% The format of the UnregisterSGIImage method is:
%
% UnregisterSGIImage(void)
%
*/
ModuleExport void UnregisterSGIImage(void)
{
(void) UnregisterMagickInfo("SGI");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e S G I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteSGIImage() writes an image in SGI RGB encoded image format.
%
% The format of the WriteSGIImage method is:
%
% MagickBooleanType WriteSGIImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static size_t SGIEncode(unsigned char *pixels,size_t length,
unsigned char *packets)
{
short
runlength;
register unsigned char
*p,
*q;
unsigned char
*limit,
*mark;
p=pixels;
limit=p+length*4;
q=packets;
while (p < limit)
{
mark=p;
p+=8;
while ((p < limit) && ((*(p-8) != *(p-4)) || (*(p-4) != *p)))
p+=4;
p-=8;
length=(size_t) (p-mark) >> 2;
while (length != 0)
{
runlength=(short) (length > 126 ? 126 : length);
length-=runlength;
*q++=(unsigned char) (0x80 | runlength);
for ( ; runlength > 0; runlength--)
{
*q++=(*mark);
mark+=4;
}
}
mark=p;
p+=4;
while ((p < limit) && (*p == *mark))
p+=4;
length=(size_t) (p-mark) >> 2;
while (length != 0)
{
runlength=(short) (length > 126 ? 126 : length);
length-=runlength;
*q++=(unsigned char) runlength;
*q++=(*mark);
}
}
*q++='\0';
return((size_t) (q-packets));
}
static MagickBooleanType WriteSGIImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
CompressionType
compression;
const char
*value;
MagickBooleanType
status;
MagickOffsetType
scene;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
SGIInfo
iris_info;
register const Quantum
*p;
register ssize_t
i,
x;
register unsigned char
*q;
ssize_t
y,
z;
unsigned char
*pixels,
*packets;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->columns > 65535UL) || (image->rows > 65535UL))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
/*
Initialize SGI raster file header.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
(void) ResetMagickMemory(&iris_info,0,sizeof(iris_info));
iris_info.magic=0x01DA;
compression=image->compression;
if (image_info->compression != UndefinedCompression)
compression=image_info->compression;
if (image->depth > 8)
compression=NoCompression;
if (compression == NoCompression)
iris_info.storage=(unsigned char) 0x00;
else
iris_info.storage=(unsigned char) 0x01;
iris_info.bytes_per_pixel=(unsigned char) (image->depth > 8 ? 2 : 1);
iris_info.dimension=3;
iris_info.columns=(unsigned short) image->columns;
iris_info.rows=(unsigned short) image->rows;
if (image->alpha_trait != UndefinedPixelTrait)
iris_info.depth=4;
else
{
if ((image_info->type != TrueColorType) &&
(SetImageGray(image,exception) != MagickFalse))
{
iris_info.dimension=2;
iris_info.depth=1;
}
else
iris_info.depth=3;
}
iris_info.minimum_value=0;
iris_info.maximum_value=(size_t) (image->depth <= 8 ?
1UL*ScaleQuantumToChar(QuantumRange) :
1UL*ScaleQuantumToShort(QuantumRange));
/*
Write SGI header.
*/
(void) WriteBlobMSBShort(image,iris_info.magic);
(void) WriteBlobByte(image,iris_info.storage);
(void) WriteBlobByte(image,iris_info.bytes_per_pixel);
(void) WriteBlobMSBShort(image,iris_info.dimension);
(void) WriteBlobMSBShort(image,iris_info.columns);
(void) WriteBlobMSBShort(image,iris_info.rows);
(void) WriteBlobMSBShort(image,iris_info.depth);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.minimum_value);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.maximum_value);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.sans);
value=GetImageProperty(image,"label",exception);
if (value != (const char *) NULL)
(void) CopyMagickString(iris_info.name,value,sizeof(iris_info.name));
(void) WriteBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
(void) WriteBlobMSBLong(image,(unsigned int) iris_info.pixel_format);
(void) WriteBlob(image,sizeof(iris_info.filler),iris_info.filler);
/*
Allocate SGI pixels.
*/
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((4*iris_info.bytes_per_pixel*number_pixels) !=
((MagickSizeType) (size_t) (4*iris_info.bytes_per_pixel*number_pixels)))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory((size_t) number_pixels,4*
iris_info.bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Convert image pixels to uncompressed SGI pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (image->depth <= 8)
for (x=0; x < (ssize_t) image->columns; x++)
{
register unsigned char
*q;
q=(unsigned char *) pixels;
q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x;
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
else
for (x=0; x < (ssize_t) image->columns; x++)
{
register unsigned short
*q;
q=(unsigned short *) pixels;
q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x;
*q++=ScaleQuantumToShort(GetPixelRed(image,p));
*q++=ScaleQuantumToShort(GetPixelGreen(image,p));
*q++=ScaleQuantumToShort(GetPixelBlue(image,p));
*q++=ScaleQuantumToShort(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
switch (compression)
{
case NoCompression:
{
/*
Write uncompressed SGI pixels.
*/
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (image->depth <= 8)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
register unsigned char
*q;
q=(unsigned char *) pixels;
q+=y*(4*iris_info.columns)+4*x+z;
(void) WriteBlobByte(image,*q);
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
register unsigned short
*q;
q=(unsigned short *) pixels;
q+=y*(4*iris_info.columns)+4*x+z;
(void) WriteBlobMSBShort(image,*q);
}
}
}
break;
}
default:
{
MemoryInfo
*packet_info;
size_t
length,
number_packets,
*runlength;
ssize_t
offset,
*offsets;
/*
Convert SGI uncompressed pixels.
*/
offsets=(ssize_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((2*(size_t) iris_info.columns+10)*
image->rows,4*sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
if (offsets != (ssize_t *) NULL)
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
if (runlength != (size_t *) NULL)
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info != (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
offset=512+4*2*((ssize_t) iris_info.rows*iris_info.depth);
number_packets=0;
q=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
length=SGIEncode(q+z,(size_t) iris_info.columns,packets+
number_packets);
number_packets+=length;
offsets[y+z*iris_info.rows]=offset;
runlength[y+z*iris_info.rows]=(size_t) length;
offset+=(ssize_t) length;
}
q+=(iris_info.columns*4);
}
/*
Write out line start and length tables and runlength-encoded pixels.
*/
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
(void) WriteBlobMSBLong(image,(unsigned int) offsets[i]);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
(void) WriteBlobMSBLong(image,(unsigned int) runlength[i]);
(void) WriteBlob(image,number_packets,packets);
/*
Relinquish resources.
*/
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
runlength=(size_t *) RelinquishMagickMemory(runlength);
packet_info=RelinquishVirtualMemory(packet_info);
break;
}
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5249_0 |
crossvul-cpp_data_good_5082_0 | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Kirti Velankar <kirtig@yahoo-inc.com> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <unicode/ustring.h>
#include <unicode/udata.h>
#include <unicode/putil.h>
#include <unicode/ures.h>
#include "php_intl.h"
#include "locale.h"
#include "locale_class.h"
#include "locale_methods.h"
#include "intl_convert.h"
#include "intl_data.h"
#include <zend_API.h>
#include <zend.h>
#include <php.h>
#include "main/php_ini.h"
#include "ext/standard/php_smart_str.h"
ZEND_EXTERN_MODULE_GLOBALS( intl )
/* Sizes required for the strings "variant15" , "extlang11", "private12" etc. */
#define SEPARATOR "_"
#define SEPARATOR1 "-"
#define DELIMITER "-_"
#define EXTLANG_PREFIX "a"
#define PRIVATE_PREFIX "x"
#define DISP_NAME "name"
#define MAX_NO_VARIANT 15
#define MAX_NO_EXTLANG 3
#define MAX_NO_PRIVATE 15
#define MAX_NO_LOOKUP_LANG_TAG 100
#define LOC_NOT_FOUND 1
/* Sizes required for the strings "variant15" , "extlang3", "private12" etc. */
#define VARIANT_KEYNAME_LEN 11
#define EXTLANG_KEYNAME_LEN 10
#define PRIVATE_KEYNAME_LEN 11
/* Based on IANA registry at the time of writing this code
*
*/
static const char * const LOC_GRANDFATHERED[] = {
"art-lojban", "i-klingon", "i-lux", "i-navajo", "no-bok", "no-nyn",
"cel-gaulish", "en-GB-oed", "i-ami",
"i-bnn", "i-default", "i-enochian",
"i-mingo", "i-pwn", "i-tao",
"i-tay", "i-tsu", "sgn-BE-fr",
"sgn-BE-nl", "sgn-CH-de", "zh-cmn",
"zh-cmn-Hans", "zh-cmn-Hant", "zh-gan" ,
"zh-guoyu", "zh-hakka", "zh-min",
"zh-min-nan", "zh-wuu", "zh-xiang",
"zh-yue", NULL
};
/* Based on IANA registry at the time of writing this code
* This array lists the preferred values for the grandfathered tags if applicable
* This is in sync with the array LOC_GRANDFATHERED
* e.g. the offsets of the grandfathered tags match the offset of the preferred value
*/
static const int LOC_PREFERRED_GRANDFATHERED_LEN = 6;
static const char * const LOC_PREFERRED_GRANDFATHERED[] = {
"jbo", "tlh", "lb",
"nv", "nb", "nn",
NULL
};
/*returns TRUE if a is an ID separator FALSE otherwise*/
#define isIDSeparator(a) (a == '_' || a == '-')
#define isKeywordSeparator(a) (a == '@' )
#define isEndOfTag(a) (a == '\0' )
#define isPrefixLetter(a) ((a=='x')||(a=='X')||(a=='i')||(a=='I'))
/*returns TRUE if one of the special prefixes is here (s=string)
'x-' or 'i-' */
#define isIDPrefix(s) (isPrefixLetter(s[0])&&isIDSeparator(s[1]))
#define isKeywordPrefix(s) ( isKeywordSeparator(s[0]) )
/* Dot terminates it because of POSIX form where dot precedes the codepage
* except for variant */
#define isTerminator(a) ((a==0)||(a=='.')||(a=='@'))
/* {{{ return the offset of 'key' in the array 'list'.
* returns -1 if not present */
static int16_t findOffset(const char* const* list, const char* key)
{
const char* const* anchor = list;
while (*list != NULL) {
if (strcmp(key, *list) == 0) {
return (int16_t)(list - anchor);
}
list++;
}
return -1;
}
/*}}}*/
static char* getPreferredTag(const char* gf_tag)
{
char* result = NULL;
int grOffset = 0;
grOffset = findOffset( LOC_GRANDFATHERED ,gf_tag);
if(grOffset < 0) {
return NULL;
}
if( grOffset < LOC_PREFERRED_GRANDFATHERED_LEN ){
/* return preferred tag */
result = estrdup( LOC_PREFERRED_GRANDFATHERED[grOffset] );
} else {
/* Return correct grandfathered language tag */
result = estrdup( LOC_GRANDFATHERED[grOffset] );
}
return result;
}
/* {{{
* returns the position of next token for lookup
* or -1 if no token
* strtokr equivalent search for token in reverse direction
*/
static int getStrrtokenPos(char* str, int savedPos)
{
int result =-1;
int i;
for(i=savedPos-1; i>=0; i--) {
if(isIDSeparator(*(str+i)) ){
/* delimiter found; check for singleton */
if(i>=2 && isIDSeparator(*(str+i-2)) ){
/* a singleton; so send the position of token before the singleton */
result = i-2;
} else {
result = i;
}
break;
}
}
if(result < 1){
/* Just in case inavlid locale e.g. '-x-xyz' or '-sl_Latn' */
result =-1;
}
return result;
}
/* }}} */
/* {{{
* returns the position of a singleton if present
* returns -1 if no singleton
* strtok equivalent search for singleton
*/
static int getSingletonPos(const char* str)
{
int result =-1;
int i=0;
int len = 0;
if( str && ((len=strlen(str))>0) ){
for( i=0; i<len ; i++){
if( isIDSeparator(*(str+i)) ){
if( i==1){
/* string is of the form x-avy or a-prv1 */
result =0;
break;
} else {
/* delimiter found; check for singleton */
if( isIDSeparator(*(str+i+2)) ){
/* a singleton; so send the position of separator before singleton */
result = i+1;
break;
}
}
}
}/* end of for */
}
return result;
}
/* }}} */
/* {{{ proto static string Locale::getDefault( )
Get default locale */
/* }}} */
/* {{{ proto static string locale_get_default( )
Get default locale */
PHP_NAMED_FUNCTION(zif_locale_get_default)
{
RETURN_STRING( intl_locale_get_default( TSRMLS_C ), TRUE );
}
/* }}} */
/* {{{ proto static string Locale::setDefault( string $locale )
Set default locale */
/* }}} */
/* {{{ proto static string locale_set_default( string $locale )
Set default locale */
PHP_NAMED_FUNCTION(zif_locale_set_default)
{
char* locale_name = NULL;
int len=0;
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s",
&locale_name ,&len ) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_set_default: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
if(len == 0) {
locale_name = (char *)uloc_getDefault() ;
len = strlen(locale_name);
}
zend_alter_ini_entry(LOCALE_INI_NAME, sizeof(LOCALE_INI_NAME), locale_name, len, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
RETURN_TRUE;
}
/* }}} */
/* {{{
* Gets the value from ICU
* common code shared by get_primary_language,get_script or get_region or get_variant
* result = 0 if error, 1 if successful , -1 if no value
*/
static char* get_icu_value_internal( const char* loc_name , char* tag_name, int* result , int fromParseLocale)
{
char* tag_value = NULL;
int32_t tag_value_len = 512;
int singletonPos = 0;
char* mod_loc_name = NULL;
int grOffset = 0;
int32_t buflen = 512;
UErrorCode status = U_ZERO_ERROR;
if( strcmp(tag_name, LOC_CANONICALIZE_TAG) != 0 ){
/* Handle grandfathered languages */
grOffset = findOffset( LOC_GRANDFATHERED , loc_name );
if( grOffset >= 0 ){
if( strcmp(tag_name , LOC_LANG_TAG)==0 ){
return estrdup(loc_name);
} else {
/* Since Grandfathered , no value , do nothing , retutn NULL */
return NULL;
}
}
if( fromParseLocale==1 ){
/* Handle singletons */
if( strcmp(tag_name , LOC_LANG_TAG)==0 ){
if( strlen(loc_name)>1 && (isIDPrefix(loc_name) == 1) ){
return estrdup(loc_name);
}
}
singletonPos = getSingletonPos( loc_name );
if( singletonPos == 0){
/* singleton at start of script, region , variant etc.
* or invalid singleton at start of language */
return NULL;
} else if( singletonPos > 0 ){
/* singleton at some position except at start
* strip off the singleton and rest of the loc_name */
mod_loc_name = estrndup ( loc_name , singletonPos-1);
}
} /* end of if fromParse */
} /* end of if != LOC_CANONICAL_TAG */
if( mod_loc_name == NULL){
mod_loc_name = estrdup(loc_name );
}
/* Proceed to ICU */
do{
tag_value = erealloc( tag_value , buflen );
tag_value_len = buflen;
if( strcmp(tag_name , LOC_SCRIPT_TAG)==0 ){
buflen = uloc_getScript ( mod_loc_name ,tag_value , tag_value_len , &status);
}
if( strcmp(tag_name , LOC_LANG_TAG )==0 ){
buflen = uloc_getLanguage ( mod_loc_name ,tag_value , tag_value_len , &status);
}
if( strcmp(tag_name , LOC_REGION_TAG)==0 ){
buflen = uloc_getCountry ( mod_loc_name ,tag_value , tag_value_len , &status);
}
if( strcmp(tag_name , LOC_VARIANT_TAG)==0 ){
buflen = uloc_getVariant ( mod_loc_name ,tag_value , tag_value_len , &status);
}
if( strcmp(tag_name , LOC_CANONICALIZE_TAG)==0 ){
buflen = uloc_canonicalize ( mod_loc_name ,tag_value , tag_value_len , &status);
}
if( U_FAILURE( status ) ) {
if( status == U_BUFFER_OVERFLOW_ERROR ) {
status = U_ZERO_ERROR;
buflen++; /* add space for \0 */
continue;
}
/* Error in retriving data */
*result = 0;
if( tag_value ){
efree( tag_value );
}
if( mod_loc_name ){
efree( mod_loc_name);
}
return NULL;
}
} while( buflen > tag_value_len );
if( buflen ==0 ){
/* No value found */
*result = -1;
if( tag_value ){
efree( tag_value );
}
if( mod_loc_name ){
efree( mod_loc_name);
}
return NULL;
} else {
*result = 1;
}
if( mod_loc_name ){
efree( mod_loc_name);
}
return tag_value;
}
/* }}} */
/* {{{
* Gets the value from ICU , called when PHP userspace function is called
* common code shared by get_primary_language,get_script or get_region or get_variant
*/
static void get_icu_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAMETERS)
{
const char* loc_name = NULL;
int loc_name_len = 0;
char* tag_value = NULL;
char* empty_result = "";
int result = 0;
char* msg = NULL;
UErrorCode status = U_ZERO_ERROR;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s",
&loc_name ,&loc_name_len ) == FAILURE) {
spprintf(&msg , 0, "locale_get_%s : unable to parse input params", tag_name );
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, msg , 1 TSRMLS_CC );
efree(msg);
RETURN_FALSE;
}
if(loc_name_len == 0) {
loc_name = intl_locale_get_default(TSRMLS_C);
}
/* Call ICU get */
tag_value = get_icu_value_internal( loc_name , tag_name , &result ,0);
/* No value found */
if( result == -1 ) {
if( tag_value){
efree( tag_value);
}
RETURN_STRING( empty_result , TRUE);
}
/* value found */
if( tag_value){
RETURN_STRING( tag_value , FALSE);
}
/* Error encountered while fetching the value */
if( result ==0) {
spprintf(&msg , 0, "locale_get_%s : unable to get locale %s", tag_name , tag_name );
intl_error_set( NULL, status, msg , 1 TSRMLS_CC );
efree(msg);
RETURN_NULL();
}
}
/* }}} */
/* {{{ proto static string Locale::getScript($locale)
* gets the script for the $locale
}}} */
/* {{{ proto static string locale_get_script($locale)
* gets the script for the $locale
*/
PHP_FUNCTION( locale_get_script )
{
get_icu_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
/* }}} */
/* {{{ proto static string Locale::getRegion($locale)
* gets the region for the $locale
}}} */
/* {{{ proto static string locale_get_region($locale)
* gets the region for the $locale
*/
PHP_FUNCTION( locale_get_region )
{
get_icu_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
/* }}} */
/* {{{ proto static string Locale::getPrimaryLanguage($locale)
* gets the primary language for the $locale
}}} */
/* {{{ proto static string locale_get_primary_language($locale)
* gets the primary language for the $locale
*/
PHP_FUNCTION(locale_get_primary_language )
{
get_icu_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
/* }}} */
/* {{{
* common code shared by display_xyz functions to get the value from ICU
}}} */
static void get_icu_disp_value_src_php( char* tag_name, INTERNAL_FUNCTION_PARAMETERS)
{
const char* loc_name = NULL;
int loc_name_len = 0;
const char* disp_loc_name = NULL;
int disp_loc_name_len = 0;
int free_loc_name = 0;
UChar* disp_name = NULL;
int32_t disp_name_len = 0;
char* mod_loc_name = NULL;
int32_t buflen = 512;
UErrorCode status = U_ZERO_ERROR;
char* utf8value = NULL;
int utf8value_len = 0;
char* msg = NULL;
int grOffset = 0;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s|s",
&loc_name, &loc_name_len ,
&disp_loc_name ,&disp_loc_name_len ) == FAILURE)
{
spprintf(&msg , 0, "locale_get_display_%s : unable to parse input params", tag_name );
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, msg , 1 TSRMLS_CC );
efree(msg);
RETURN_FALSE;
}
if(loc_name_len > ULOC_FULLNAME_CAPACITY) {
/* See bug 67397: overlong locale names cause trouble in uloc_getDisplayName */
spprintf(&msg , 0, "locale_get_display_%s : name too long", tag_name );
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, msg , 1 TSRMLS_CC );
efree(msg);
RETURN_FALSE;
}
if(loc_name_len == 0) {
loc_name = intl_locale_get_default(TSRMLS_C);
}
if( strcmp(tag_name, DISP_NAME) != 0 ){
/* Handle grandfathered languages */
grOffset = findOffset( LOC_GRANDFATHERED , loc_name );
if( grOffset >= 0 ){
if( strcmp(tag_name , LOC_LANG_TAG)==0 ){
mod_loc_name = getPreferredTag( loc_name );
} else {
/* Since Grandfathered, no value, do nothing, retutn NULL */
RETURN_FALSE;
}
}
} /* end of if != LOC_CANONICAL_TAG */
if( mod_loc_name==NULL ){
mod_loc_name = estrdup( loc_name );
}
/* Check if disp_loc_name passed , if not use default locale */
if( !disp_loc_name){
disp_loc_name = estrdup(intl_locale_get_default(TSRMLS_C));
free_loc_name = 1;
}
/* Get the disp_value for the given locale */
do{
disp_name = erealloc( disp_name , buflen * sizeof(UChar) );
disp_name_len = buflen;
if( strcmp(tag_name , LOC_LANG_TAG)==0 ){
buflen = uloc_getDisplayLanguage ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status);
} else if( strcmp(tag_name , LOC_SCRIPT_TAG)==0 ){
buflen = uloc_getDisplayScript ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status);
} else if( strcmp(tag_name , LOC_REGION_TAG)==0 ){
buflen = uloc_getDisplayCountry ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status);
} else if( strcmp(tag_name , LOC_VARIANT_TAG)==0 ){
buflen = uloc_getDisplayVariant ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status);
} else if( strcmp(tag_name , DISP_NAME)==0 ){
buflen = uloc_getDisplayName ( mod_loc_name , disp_loc_name , disp_name , disp_name_len , &status);
}
/* U_STRING_NOT_TERMINATED_WARNING is admissible here; don't look for it */
if( U_FAILURE( status ) )
{
if( status == U_BUFFER_OVERFLOW_ERROR )
{
status = U_ZERO_ERROR;
continue;
}
spprintf(&msg, 0, "locale_get_display_%s : unable to get locale %s", tag_name , tag_name );
intl_error_set( NULL, status, msg , 1 TSRMLS_CC );
efree(msg);
if( disp_name){
efree( disp_name );
}
if( mod_loc_name){
efree( mod_loc_name );
}
if (free_loc_name) {
efree((void *)disp_loc_name);
disp_loc_name = NULL;
}
RETURN_FALSE;
}
} while( buflen > disp_name_len );
if( mod_loc_name){
efree( mod_loc_name );
}
if (free_loc_name) {
efree((void *)disp_loc_name);
disp_loc_name = NULL;
}
/* Convert display locale name from UTF-16 to UTF-8. */
intl_convert_utf16_to_utf8( &utf8value, &utf8value_len, disp_name, buflen, &status );
efree( disp_name );
if( U_FAILURE( status ) )
{
spprintf(&msg, 0, "locale_get_display_%s :error converting display name for %s to UTF-8", tag_name , tag_name );
intl_error_set( NULL, status, msg , 1 TSRMLS_CC );
efree(msg);
RETURN_FALSE;
}
RETVAL_STRINGL( utf8value, utf8value_len , FALSE);
}
/* }}} */
/* {{{ proto static string Locale::getDisplayName($locale[, $in_locale = null])
* gets the name for the $locale in $in_locale or default_locale
}}} */
/* {{{ proto static string get_display_name($locale[, $in_locale = null])
* gets the name for the $locale in $in_locale or default_locale
*/
PHP_FUNCTION(locale_get_display_name)
{
get_icu_disp_value_src_php( DISP_NAME , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
/* }}} */
/* {{{ proto static string Locale::getDisplayLanguage($locale[, $in_locale = null])
* gets the language for the $locale in $in_locale or default_locale
}}} */
/* {{{ proto static string get_display_language($locale[, $in_locale = null])
* gets the language for the $locale in $in_locale or default_locale
*/
PHP_FUNCTION(locale_get_display_language)
{
get_icu_disp_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
/* }}} */
/* {{{ proto static string Locale::getDisplayScript($locale, $in_locale = null)
* gets the script for the $locale in $in_locale or default_locale
}}} */
/* {{{ proto static string get_display_script($locale, $in_locale = null)
* gets the script for the $locale in $in_locale or default_locale
*/
PHP_FUNCTION(locale_get_display_script)
{
get_icu_disp_value_src_php( LOC_SCRIPT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
/* }}} */
/* {{{ proto static string Locale::getDisplayRegion($locale, $in_locale = null)
* gets the region for the $locale in $in_locale or default_locale
}}} */
/* {{{ proto static string get_display_region($locale, $in_locale = null)
* gets the region for the $locale in $in_locale or default_locale
*/
PHP_FUNCTION(locale_get_display_region)
{
get_icu_disp_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
/* }}} */
/* {{{
* proto static string Locale::getDisplayVariant($locale, $in_locale = null)
* gets the variant for the $locale in $in_locale or default_locale
}}} */
/* {{{
* proto static string get_display_variant($locale, $in_locale = null)
* gets the variant for the $locale in $in_locale or default_locale
*/
PHP_FUNCTION(locale_get_display_variant)
{
get_icu_disp_value_src_php( LOC_VARIANT_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
/* }}} */
/* {{{ proto static array getKeywords(string $locale) {
* return an associative array containing keyword-value
* pairs for this locale. The keys are keys to the array (doh!)
* }}}*/
/* {{{ proto static array locale_get_keywords(string $locale) {
* return an associative array containing keyword-value
* pairs for this locale. The keys are keys to the array (doh!)
*/
PHP_FUNCTION( locale_get_keywords )
{
UEnumeration* e = NULL;
UErrorCode status = U_ZERO_ERROR;
const char* kw_key = NULL;
int32_t kw_key_len = 0;
const char* loc_name = NULL;
int loc_name_len = 0;
/*
ICU expects the buffer to be allocated before calling the function
and so the buffer size has been explicitly specified
ICU uloc.h #define ULOC_KEYWORD_AND_VALUES_CAPACITY 100
hence the kw_value buffer size is 100
*/
char* kw_value = NULL;
int32_t kw_value_len = 100;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s",
&loc_name, &loc_name_len ) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_get_keywords: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
if(loc_name_len == 0) {
loc_name = intl_locale_get_default(TSRMLS_C);
}
/* Get the keywords */
e = uloc_openKeywords( loc_name, &status );
if( e != NULL )
{
/* Traverse it, filling the return array. */
array_init( return_value );
while( ( kw_key = uenum_next( e, &kw_key_len, &status ) ) != NULL ){
kw_value = ecalloc( 1 , kw_value_len );
/* Get the keyword value for each keyword */
kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len , &status );
if (status == U_BUFFER_OVERFLOW_ERROR) {
status = U_ZERO_ERROR;
kw_value = erealloc( kw_value , kw_value_len+1);
kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len+1 , &status );
} else if(!U_FAILURE(status)) {
kw_value = erealloc( kw_value , kw_value_len+1);
}
if (U_FAILURE(status)) {
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: Error encountered while getting the keyword value for the keyword", 0 TSRMLS_CC );
if( kw_value){
efree( kw_value );
}
zval_dtor(return_value);
RETURN_FALSE;
}
add_assoc_stringl( return_value, (char *)kw_key, kw_value , kw_value_len, 0);
} /* end of while */
} /* end of if e!=NULL */
uenum_close( e );
}
/* }}} */
/* {{{ proto static string Locale::canonicalize($locale)
* @return string the canonicalized locale
* }}} */
/* {{{ proto static string locale_canonicalize(Locale $loc, string $locale)
* @param string $locale The locale string to canonicalize
*/
PHP_FUNCTION(locale_canonicalize)
{
get_icu_value_src_php( LOC_CANONICALIZE_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
/* }}} */
/* {{{ append_key_value
* Internal function which is called from locale_compose
* gets the value for the key_name and appends to the loc_name
* returns 1 if successful , -1 if not found ,
* 0 if array element is not a string , -2 if buffer-overflow
*/
static int append_key_value(smart_str* loc_name, HashTable* hash_arr, char* key_name)
{
zval** ele_value = NULL;
if(zend_hash_find(hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) {
if(Z_TYPE_PP(ele_value)!= IS_STRING ){
/* element value is not a string */
return FAILURE;
}
if(strcmp(key_name, LOC_LANG_TAG) != 0 &&
strcmp(key_name, LOC_GRANDFATHERED_LANG_TAG)!=0 ) {
/* not lang or grandfathered tag */
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
}
smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));
return SUCCESS;
}
return LOC_NOT_FOUND;
}
/* }}} */
/* {{{ append_prefix , appends the prefix needed
* e.g. private adds 'x'
*/
static void add_prefix(smart_str* loc_name, char* key_name)
{
if( strncmp(key_name , LOC_PRIVATE_TAG , 7) == 0 ){
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
smart_str_appendl(loc_name, PRIVATE_PREFIX , sizeof(PRIVATE_PREFIX)-1);
}
}
/* }}} */
/* {{{ append_multiple_key_values
* Internal function which is called from locale_compose
* gets the multiple values for the key_name and appends to the loc_name
* used for 'variant','extlang','private'
* returns 1 if successful , -1 if not found ,
* 0 if array element is not a string , -2 if buffer-overflow
*/
static int append_multiple_key_values(smart_str* loc_name, HashTable* hash_arr, char* key_name TSRMLS_DC)
{
zval** ele_value = NULL;
int i = 0;
int isFirstSubtag = 0;
int max_value = 0;
/* Variant/ Extlang/Private etc. */
if( zend_hash_find( hash_arr , key_name , strlen(key_name) + 1 ,(void **)&ele_value ) == SUCCESS ) {
if( Z_TYPE_PP(ele_value) == IS_STRING ){
add_prefix( loc_name , key_name);
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));
return SUCCESS;
} else if(Z_TYPE_PP(ele_value) == IS_ARRAY ) {
HashPosition pos;
HashTable *arr = HASH_OF(*ele_value);
zval **data = NULL;
zend_hash_internal_pointer_reset_ex(arr, &pos);
while(zend_hash_get_current_data_ex(arr, (void **)&data, &pos) != FAILURE) {
if(Z_TYPE_PP(data) != IS_STRING) {
return FAILURE;
}
if (isFirstSubtag++ == 0){
add_prefix(loc_name , key_name);
}
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
smart_str_appendl(loc_name, Z_STRVAL_PP(data) , Z_STRLEN_PP(data));
zend_hash_move_forward_ex(arr, &pos);
}
return SUCCESS;
} else {
return FAILURE;
}
} else {
char cur_key_name[31];
/* Decide the max_value: the max. no. of elements allowed */
if( strcmp(key_name , LOC_VARIANT_TAG) ==0 ){
max_value = MAX_NO_VARIANT;
}
if( strcmp(key_name , LOC_EXTLANG_TAG) ==0 ){
max_value = MAX_NO_EXTLANG;
}
if( strcmp(key_name , LOC_PRIVATE_TAG) ==0 ){
max_value = MAX_NO_PRIVATE;
}
/* Multiple variant values as variant0, variant1 ,variant2 */
isFirstSubtag = 0;
for( i=0 ; i< max_value; i++ ){
snprintf( cur_key_name , 30, "%s%d", key_name , i);
if( zend_hash_find( hash_arr , cur_key_name , strlen(cur_key_name) + 1,(void **)&ele_value ) == SUCCESS ){
if( Z_TYPE_PP(ele_value)!= IS_STRING ){
/* variant is not a string */
return FAILURE;
}
/* Add the contents */
if (isFirstSubtag++ == 0){
add_prefix(loc_name , cur_key_name);
}
smart_str_appendl(loc_name, SEPARATOR , sizeof(SEPARATOR)-1);
smart_str_appendl(loc_name, Z_STRVAL_PP(ele_value) , Z_STRLEN_PP(ele_value));
}
} /* end of for */
} /* end of else */
return SUCCESS;
}
/* }}} */
/*{{{
* If applicable sets error message and aborts locale_compose gracefully
* returns 0 if locale_compose needs to be aborted
* otherwise returns 1
*/
static int handleAppendResult( int result, smart_str* loc_name TSRMLS_DC)
{
intl_error_reset( NULL TSRMLS_CC );
if( result == FAILURE) {
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_compose: parameter array element is not a string", 0 TSRMLS_CC );
smart_str_free(loc_name);
return 0;
}
return 1;
}
/* }}} */
#define RETURN_SMART_STR(s) smart_str_0((s)); RETURN_STRINGL((s)->c, (s)->len, 0)
/* {{{ proto static string Locale::composeLocale($array)
* Creates a locale by combining the parts of locale-ID passed
* }}} */
/* {{{ proto static string compose_locale($array)
* Creates a locale by combining the parts of locale-ID passed
* }}} */
PHP_FUNCTION(locale_compose)
{
smart_str loc_name_s = {0};
smart_str *loc_name = &loc_name_s;
zval* arr = NULL;
HashTable* hash_arr = NULL;
int result = 0;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "a",
&arr) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_compose: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
hash_arr = HASH_OF( arr );
if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 )
RETURN_FALSE;
/* Check for grandfathered first */
result = append_key_value(loc_name, hash_arr, LOC_GRANDFATHERED_LANG_TAG);
if( result == SUCCESS){
RETURN_SMART_STR(loc_name);
}
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Not grandfathered */
result = append_key_value(loc_name, hash_arr , LOC_LANG_TAG);
if( result == LOC_NOT_FOUND ){
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_compose: parameter array does not contain 'language' tag.", 0 TSRMLS_CC );
smart_str_free(loc_name);
RETURN_FALSE;
}
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Extlang */
result = append_multiple_key_values(loc_name, hash_arr , LOC_EXTLANG_TAG TSRMLS_CC);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Script */
result = append_key_value(loc_name, hash_arr , LOC_SCRIPT_TAG);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Region */
result = append_key_value( loc_name, hash_arr , LOC_REGION_TAG);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Variant */
result = append_multiple_key_values( loc_name, hash_arr , LOC_VARIANT_TAG TSRMLS_CC);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Private */
result = append_multiple_key_values( loc_name, hash_arr , LOC_PRIVATE_TAG TSRMLS_CC);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
RETURN_SMART_STR(loc_name);
}
/* }}} */
/*{{{
* Parses the locale and returns private subtags if existing
* else returns NULL
* e.g. for locale='en_US-x-prv1-prv2-prv3'
* returns a pointer to the string 'prv1-prv2-prv3'
*/
static char* get_private_subtags(const char* loc_name)
{
char* result =NULL;
int singletonPos = 0;
int len =0;
const char* mod_loc_name =NULL;
if( loc_name && (len = strlen(loc_name)>0 ) ){
mod_loc_name = loc_name ;
len = strlen(mod_loc_name);
while( (singletonPos = getSingletonPos(mod_loc_name))!= -1){
if( singletonPos!=-1){
if( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){
/* private subtag start found */
if( singletonPos + 2 == len){
/* loc_name ends with '-x-' ; return NULL */
}
else{
/* result = mod_loc_name + singletonPos +2; */
result = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) );
}
break;
}
else{
if( singletonPos + 1 >= len){
/* String end */
break;
} else {
/* singleton found but not a private subtag , hence check further in the string for the private subtag */
mod_loc_name = mod_loc_name + singletonPos +1;
len = strlen(mod_loc_name);
}
}
}
} /* end of while */
}
return result;
}
/* }}} */
/* {{{ code used by locale_parse
*/
static int add_array_entry(const char* loc_name, zval* hash_arr, char* key_name TSRMLS_DC)
{
char* key_value = NULL;
char* cur_key_name = NULL;
char* token = NULL;
char* last_ptr = NULL;
int result = 0;
int cur_result = 0;
int cnt = 0;
if( strcmp(key_name , LOC_PRIVATE_TAG)==0 ){
key_value = get_private_subtags( loc_name );
result = 1;
} else {
key_value = get_icu_value_internal( loc_name , key_name , &result,1 );
}
if( (strcmp(key_name , LOC_PRIVATE_TAG)==0) ||
( strcmp(key_name , LOC_VARIANT_TAG)==0) ){
if( result > 0 && key_value){
/* Tokenize on the "_" or "-" */
token = php_strtok_r( key_value , DELIMITER ,&last_ptr);
if( cur_key_name ){
efree( cur_key_name);
}
cur_key_name = (char*)ecalloc( 25, 25);
sprintf( cur_key_name , "%s%d", key_name , cnt++);
add_assoc_string( hash_arr, cur_key_name , token ,TRUE );
/* tokenize on the "_" or "-" and stop at singleton if any */
while( (token = php_strtok_r(NULL , DELIMITER , &last_ptr)) && (strlen(token)>1) ){
sprintf( cur_key_name , "%s%d", key_name , cnt++);
add_assoc_string( hash_arr, cur_key_name , token , TRUE );
}
/*
if( strcmp(key_name, LOC_PRIVATE_TAG) == 0 ){
}
*/
}
} else {
if( result == 1 ){
add_assoc_string( hash_arr, key_name , key_value , TRUE );
cur_result = 1;
}
}
if( cur_key_name ){
efree( cur_key_name);
}
/*if( key_name != LOC_PRIVATE_TAG && key_value){*/
if( key_value){
efree(key_value);
}
return cur_result;
}
/* }}} */
/* {{{ proto static array Locale::parseLocale($locale)
* parses a locale-id into an array the different parts of it
}}} */
/* {{{ proto static array parse_locale($locale)
* parses a locale-id into an array the different parts of it
*/
PHP_FUNCTION(locale_parse)
{
const char* loc_name = NULL;
int loc_name_len = 0;
int grOffset = 0;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s",
&loc_name, &loc_name_len ) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_parse: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
if(loc_name_len == 0) {
loc_name = intl_locale_get_default(TSRMLS_C);
}
array_init( return_value );
grOffset = findOffset( LOC_GRANDFATHERED , loc_name );
if( grOffset >= 0 ){
add_assoc_string( return_value , LOC_GRANDFATHERED_LANG_TAG , estrdup(loc_name) ,FALSE );
}
else{
/* Not grandfathered */
add_array_entry( loc_name , return_value , LOC_LANG_TAG TSRMLS_CC);
add_array_entry( loc_name , return_value , LOC_SCRIPT_TAG TSRMLS_CC);
add_array_entry( loc_name , return_value , LOC_REGION_TAG TSRMLS_CC);
add_array_entry( loc_name , return_value , LOC_VARIANT_TAG TSRMLS_CC);
add_array_entry( loc_name , return_value , LOC_PRIVATE_TAG TSRMLS_CC);
}
}
/* }}} */
/* {{{ proto static array Locale::getAllVariants($locale)
* gets an array containing the list of variants, or null
}}} */
/* {{{ proto static array locale_get_all_variants($locale)
* gets an array containing the list of variants, or null
*/
PHP_FUNCTION(locale_get_all_variants)
{
const char* loc_name = NULL;
int loc_name_len = 0;
int result = 0;
char* token = NULL;
char* variant = NULL;
char* saved_ptr = NULL;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s",
&loc_name, &loc_name_len ) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_parse: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
if(loc_name_len == 0) {
loc_name = intl_locale_get_default(TSRMLS_C);
}
array_init( return_value );
/* If the locale is grandfathered, stop, no variants */
if( findOffset( LOC_GRANDFATHERED , loc_name ) >= 0 ){
/* ("Grandfathered Tag. No variants."); */
}
else {
/* Call ICU variant */
variant = get_icu_value_internal( loc_name , LOC_VARIANT_TAG , &result ,0);
if( result > 0 && variant){
/* Tokenize on the "_" or "-" */
token = php_strtok_r( variant , DELIMITER , &saved_ptr);
add_next_index_stringl( return_value, token , strlen(token) ,TRUE );
/* tokenize on the "_" or "-" and stop at singleton if any */
while( (token = php_strtok_r(NULL , DELIMITER, &saved_ptr)) && (strlen(token)>1) ){
add_next_index_stringl( return_value, token , strlen(token) ,TRUE );
}
}
if( variant ){
efree( variant );
}
}
}
/* }}} */
/*{{{
* Converts to lower case and also replaces all hyphens with the underscore
*/
static int strToMatch(const char* str ,char *retstr)
{
char* anchor = NULL;
const char* anchor1 = NULL;
int result = 0;
if( (!str) || str[0] == '\0'){
return result;
} else {
anchor = retstr;
anchor1 = str;
while( (*str)!='\0' ){
if( *str == '-' ){
*retstr = '_';
} else {
*retstr = tolower(*str);
}
str++;
retstr++;
}
*retstr = '\0';
retstr= anchor;
str= anchor1;
result = 1;
}
return(result);
}
/* }}} */
/* {{{ proto static boolean Locale::filterMatches(string $langtag, string $locale[, bool $canonicalize])
* Checks if a $langtag filter matches with $locale according to RFC 4647's basic filtering algorithm
*/
/* }}} */
/* {{{ proto boolean locale_filter_matches(string $langtag, string $locale[, bool $canonicalize])
* Checks if a $langtag filter matches with $locale according to RFC 4647's basic filtering algorithm
*/
PHP_FUNCTION(locale_filter_matches)
{
char* lang_tag = NULL;
int lang_tag_len = 0;
const char* loc_range = NULL;
int loc_range_len = 0;
int result = 0;
char* token = 0;
char* chrcheck = NULL;
char* can_lang_tag = NULL;
char* can_loc_range = NULL;
char* cur_lang_tag = NULL;
char* cur_loc_range = NULL;
zend_bool boolCanonical = 0;
UErrorCode status = U_ZERO_ERROR;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "ss|b",
&lang_tag, &lang_tag_len , &loc_range , &loc_range_len ,
&boolCanonical) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_filter_matches: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
if(loc_range_len == 0) {
loc_range = intl_locale_get_default(TSRMLS_C);
}
if( strcmp(loc_range,"*")==0){
RETURN_TRUE;
}
if( boolCanonical ){
/* canonicalize loc_range */
can_loc_range=get_icu_value_internal( loc_range , LOC_CANONICALIZE_TAG , &result , 0);
if( result ==0) {
intl_error_set( NULL, status,
"locale_filter_matches : unable to canonicalize loc_range" , 0 TSRMLS_CC );
RETURN_FALSE;
}
/* canonicalize lang_tag */
can_lang_tag = get_icu_value_internal( lang_tag , LOC_CANONICALIZE_TAG , &result , 0);
if( result ==0) {
intl_error_set( NULL, status,
"locale_filter_matches : unable to canonicalize lang_tag" , 0 TSRMLS_CC );
RETURN_FALSE;
}
/* Convert to lower case for case-insensitive comparison */
cur_lang_tag = ecalloc( 1, strlen(can_lang_tag) + 1);
/* Convert to lower case for case-insensitive comparison */
result = strToMatch( can_lang_tag , cur_lang_tag);
if( result == 0) {
efree( cur_lang_tag );
efree( can_lang_tag );
RETURN_FALSE;
}
cur_loc_range = ecalloc( 1, strlen(can_loc_range) + 1);
result = strToMatch( can_loc_range , cur_loc_range );
if( result == 0) {
efree( cur_lang_tag );
efree( can_lang_tag );
efree( cur_loc_range );
efree( can_loc_range );
RETURN_FALSE;
}
/* check if prefix */
token = strstr( cur_lang_tag , cur_loc_range );
if( token && (token==cur_lang_tag) ){
/* check if the char. after match is SEPARATOR */
chrcheck = token + (strlen(cur_loc_range));
if( isIDSeparator(*chrcheck) || isEndOfTag(*chrcheck) ){
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
if( can_lang_tag){
efree( can_lang_tag );
}
if( can_loc_range){
efree( can_loc_range );
}
RETURN_TRUE;
}
}
/* No prefix as loc_range */
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
if( can_lang_tag){
efree( can_lang_tag );
}
if( can_loc_range){
efree( can_loc_range );
}
RETURN_FALSE;
} /* end of if isCanonical */
else{
/* Convert to lower case for case-insensitive comparison */
cur_lang_tag = ecalloc( 1, strlen(lang_tag ) + 1);
result = strToMatch( lang_tag , cur_lang_tag);
if( result == 0) {
efree( cur_lang_tag );
RETURN_FALSE;
}
cur_loc_range = ecalloc( 1, strlen(loc_range ) + 1);
result = strToMatch( loc_range , cur_loc_range );
if( result == 0) {
efree( cur_lang_tag );
efree( cur_loc_range );
RETURN_FALSE;
}
/* check if prefix */
token = strstr( cur_lang_tag , cur_loc_range );
if( token && (token==cur_lang_tag) ){
/* check if the char. after match is SEPARATOR */
chrcheck = token + (strlen(cur_loc_range));
if( isIDSeparator(*chrcheck) || isEndOfTag(*chrcheck) ){
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
RETURN_TRUE;
}
}
/* No prefix as loc_range */
if( cur_lang_tag){
efree( cur_lang_tag );
}
if( cur_loc_range){
efree( cur_loc_range );
}
RETURN_FALSE;
}
}
/* }}} */
static void array_cleanup( char* arr[] , int arr_size)
{
int i=0;
for( i=0; i< arr_size; i++ ){
if( arr[i*2] ){
efree( arr[i*2]);
}
}
efree(arr);
}
#define LOOKUP_CLEAN_RETURN(value) array_cleanup(cur_arr, cur_arr_len); return (value)
/* {{{
* returns the lookup result to lookup_loc_range_src_php
* internal function
*/
static char* lookup_loc_range(const char* loc_range, HashTable* hash_arr, int canonicalize TSRMLS_DC)
{
int i = 0;
int cur_arr_len = 0;
int result = 0;
char* lang_tag = NULL;
zval** ele_value = NULL;
char** cur_arr = NULL;
char* cur_loc_range = NULL;
char* can_loc_range = NULL;
int saved_pos = 0;
char* return_value = NULL;
cur_arr = ecalloc(zend_hash_num_elements(hash_arr)*2, sizeof(char *));
/* convert the array to lowercase , also replace hyphens with the underscore and store it in cur_arr */
for(zend_hash_internal_pointer_reset(hash_arr);
zend_hash_has_more_elements(hash_arr) == SUCCESS;
zend_hash_move_forward(hash_arr)) {
if (zend_hash_get_current_data(hash_arr, (void**)&ele_value) == FAILURE) {
/* Should never actually fail since the key is known to exist.*/
continue;
}
if(Z_TYPE_PP(ele_value)!= IS_STRING) {
/* element value is not a string */
intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: locale array element is not a string", 0 TSRMLS_CC);
LOOKUP_CLEAN_RETURN(NULL);
}
cur_arr[cur_arr_len*2] = estrndup(Z_STRVAL_PP(ele_value), Z_STRLEN_PP(ele_value));
result = strToMatch(Z_STRVAL_PP(ele_value), cur_arr[cur_arr_len*2]);
if(result == 0) {
intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag", 0 TSRMLS_CC);
LOOKUP_CLEAN_RETURN(NULL);
}
cur_arr[cur_arr_len*2+1] = Z_STRVAL_PP(ele_value);
cur_arr_len++ ;
} /* end of for */
/* Canonicalize array elements */
if(canonicalize) {
for(i=0; i<cur_arr_len; i++) {
lang_tag = get_icu_value_internal(cur_arr[i*2], LOC_CANONICALIZE_TAG, &result, 0);
if(result != 1 || lang_tag == NULL || !lang_tag[0]) {
if(lang_tag) {
efree(lang_tag);
}
intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC);
LOOKUP_CLEAN_RETURN(NULL);
}
cur_arr[i*2] = erealloc(cur_arr[i*2], strlen(lang_tag)+1);
result = strToMatch(lang_tag, cur_arr[i*2]);
efree(lang_tag);
if(result == 0) {
intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC);
LOOKUP_CLEAN_RETURN(NULL);
}
}
}
if(canonicalize) {
/* Canonicalize the loc_range */
can_loc_range = get_icu_value_internal(loc_range, LOC_CANONICALIZE_TAG, &result , 0);
if( result != 1 || can_loc_range == NULL || !can_loc_range[0]) {
/* Error */
intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize loc_range" , 0 TSRMLS_CC );
if(can_loc_range) {
efree(can_loc_range);
}
LOOKUP_CLEAN_RETURN(NULL);
} else {
loc_range = can_loc_range;
}
}
cur_loc_range = ecalloc(1, strlen(loc_range)+1);
/* convert to lower and replace hyphens */
result = strToMatch(loc_range, cur_loc_range);
if(can_loc_range) {
efree(can_loc_range);
}
if(result == 0) {
intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC);
LOOKUP_CLEAN_RETURN(NULL);
}
/* Lookup for the lang_tag match */
saved_pos = strlen(cur_loc_range);
while(saved_pos > 0) {
for(i=0; i< cur_arr_len; i++){
if(cur_arr[i*2] != NULL && strlen(cur_arr[i*2]) == saved_pos && strncmp(cur_loc_range, cur_arr[i*2], saved_pos) == 0) {
/* Match found */
return_value = estrdup(canonicalize?cur_arr[i*2]:cur_arr[i*2+1]);
efree(cur_loc_range);
LOOKUP_CLEAN_RETURN(return_value);
}
}
saved_pos = getStrrtokenPos(cur_loc_range, saved_pos);
}
/* Match not found */
efree(cur_loc_range);
LOOKUP_CLEAN_RETURN(NULL);
}
/* }}} */
/* {{{ proto string Locale::lookup(array $langtag, string $locale[, bool $canonicalize[, string $default = null]])
* Searchs the items in $langtag for the best match to the language
* range
*/
/* }}} */
/* {{{ proto string locale_lookup(array $langtag, string $locale[, bool $canonicalize[, string $default = null]])
* Searchs the items in $langtag for the best match to the language
* range
*/
PHP_FUNCTION(locale_lookup)
{
char* fallback_loc = NULL;
int fallback_loc_len = 0;
const char* loc_range = NULL;
int loc_range_len = 0;
zval* arr = NULL;
HashTable* hash_arr = NULL;
zend_bool boolCanonical = 0;
char* result =NULL;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "as|bs", &arr, &loc_range, &loc_range_len,
&boolCanonical, &fallback_loc, &fallback_loc_len) == FAILURE) {
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_lookup: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
if(loc_range_len == 0) {
loc_range = intl_locale_get_default(TSRMLS_C);
}
hash_arr = HASH_OF(arr);
if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 ) {
RETURN_EMPTY_STRING();
}
result = lookup_loc_range(loc_range, hash_arr, boolCanonical TSRMLS_CC);
if(result == NULL || result[0] == '\0') {
if( fallback_loc ) {
result = estrndup(fallback_loc, fallback_loc_len);
} else {
RETURN_EMPTY_STRING();
}
}
RETVAL_STRINGL(result, strlen(result), 0);
}
/* }}} */
/* {{{ proto string Locale::acceptFromHttp(string $http_accept)
* Tries to find out best available locale based on HTTP �Accept-Language� header
*/
/* }}} */
/* {{{ proto string locale_accept_from_http(string $http_accept)
* Tries to find out best available locale based on HTTP �Accept-Language� header
*/
PHP_FUNCTION(locale_accept_from_http)
{
UEnumeration *available;
char *http_accept = NULL;
int http_accept_len;
UErrorCode status = 0;
int len;
char resultLocale[INTL_MAX_LOCALE_LEN+1];
UAcceptResult outResult;
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &http_accept, &http_accept_len) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_accept_from_http: unable to parse input parameters", 0 TSRMLS_CC );
RETURN_FALSE;
}
available = ures_openAvailableLocales(NULL, &status);
INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to retrieve locale list");
len = uloc_acceptLanguageFromHTTP(resultLocale, INTL_MAX_LOCALE_LEN,
&outResult, http_accept, available, &status);
uenum_close(available);
INTL_CHECK_STATUS(status, "locale_accept_from_http: failed to find acceptable locale");
if (len < 0 || outResult == ULOC_ACCEPT_FAILED) {
RETURN_FALSE;
}
RETURN_STRINGL(resultLocale, len, 1);
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*can_loc_len
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5082_0 |
crossvul-cpp_data_good_417_0 | /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
* Copyright (c) 2016 Facebook
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/bpf.h>
#include <linux/bpf_verifier.h>
#include <linux/filter.h>
#include <net/netlink.h>
#include <linux/file.h>
#include <linux/vmalloc.h>
#include <linux/stringify.h>
#include <linux/bsearch.h>
#include <linux/sort.h>
#include <linux/perf_event.h>
#include "disasm.h"
static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
#define BPF_PROG_TYPE(_id, _name) \
[_id] = & _name ## _verifier_ops,
#define BPF_MAP_TYPE(_id, _ops)
#include <linux/bpf_types.h>
#undef BPF_PROG_TYPE
#undef BPF_MAP_TYPE
};
/* bpf_check() is a static code analyzer that walks eBPF program
* instruction by instruction and updates register/stack state.
* All paths of conditional branches are analyzed until 'bpf_exit' insn.
*
* The first pass is depth-first-search to check that the program is a DAG.
* It rejects the following programs:
* - larger than BPF_MAXINSNS insns
* - if loop is present (detected via back-edge)
* - unreachable insns exist (shouldn't be a forest. program = one function)
* - out of bounds or malformed jumps
* The second pass is all possible path descent from the 1st insn.
* Since it's analyzing all pathes through the program, the length of the
* analysis is limited to 64k insn, which may be hit even if total number of
* insn is less then 4K, but there are too many branches that change stack/regs.
* Number of 'branches to be analyzed' is limited to 1k
*
* On entry to each instruction, each register has a type, and the instruction
* changes the types of the registers depending on instruction semantics.
* If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
* copied to R1.
*
* All registers are 64-bit.
* R0 - return register
* R1-R5 argument passing registers
* R6-R9 callee saved registers
* R10 - frame pointer read-only
*
* At the start of BPF program the register R1 contains a pointer to bpf_context
* and has type PTR_TO_CTX.
*
* Verifier tracks arithmetic operations on pointers in case:
* BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
* BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
* 1st insn copies R10 (which has FRAME_PTR) type into R1
* and 2nd arithmetic instruction is pattern matched to recognize
* that it wants to construct a pointer to some element within stack.
* So after 2nd insn, the register R1 has type PTR_TO_STACK
* (and -20 constant is saved for further stack bounds checking).
* Meaning that this reg is a pointer to stack plus known immediate constant.
*
* Most of the time the registers have SCALAR_VALUE type, which
* means the register has some value, but it's not a valid pointer.
* (like pointer plus pointer becomes SCALAR_VALUE type)
*
* When verifier sees load or store instructions the type of base register
* can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
* types recognized by check_mem_access() function.
*
* PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
* and the range of [ptr, ptr + map's value_size) is accessible.
*
* registers used to pass values to function calls are checked against
* function argument constraints.
*
* ARG_PTR_TO_MAP_KEY is one of such argument constraints.
* It means that the register type passed to this function must be
* PTR_TO_STACK and it will be used inside the function as
* 'pointer to map element key'
*
* For example the argument constraints for bpf_map_lookup_elem():
* .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
* .arg1_type = ARG_CONST_MAP_PTR,
* .arg2_type = ARG_PTR_TO_MAP_KEY,
*
* ret_type says that this function returns 'pointer to map elem value or null'
* function expects 1st argument to be a const pointer to 'struct bpf_map' and
* 2nd argument should be a pointer to stack, which will be used inside
* the helper function as a pointer to map element key.
*
* On the kernel side the helper function looks like:
* u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
* {
* struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
* void *key = (void *) (unsigned long) r2;
* void *value;
*
* here kernel can access 'key' and 'map' pointers safely, knowing that
* [key, key + map->key_size) bytes are valid and were initialized on
* the stack of eBPF program.
* }
*
* Corresponding eBPF program may look like:
* BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
* BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
* BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
* BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
* here verifier looks at prototype of map_lookup_elem() and sees:
* .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
* Now verifier knows that this map has key of R1->map_ptr->key_size bytes
*
* Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
* Now verifier checks that [R2, R2 + map's key_size) are within stack limits
* and were initialized prior to this call.
* If it's ok, then verifier allows this BPF_CALL insn and looks at
* .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
* R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
* returns ether pointer to map value or NULL.
*
* When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
* insn, the register holding that pointer in the true branch changes state to
* PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
* branch. See check_cond_jmp_op().
*
* After the call R0 is set to return type of the function and registers R1-R5
* are set to NOT_INIT to indicate that they are no longer readable.
*/
/* verifier_state + insn_idx are pushed to stack when branch is encountered */
struct bpf_verifier_stack_elem {
/* verifer state is 'st'
* before processing instruction 'insn_idx'
* and after processing instruction 'prev_insn_idx'
*/
struct bpf_verifier_state st;
int insn_idx;
int prev_insn_idx;
struct bpf_verifier_stack_elem *next;
};
#define BPF_COMPLEXITY_LIMIT_INSNS 131072
#define BPF_COMPLEXITY_LIMIT_STACK 1024
#define BPF_MAP_PTR_UNPRIV 1UL
#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
POISON_POINTER_DELTA))
#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
{
return BPF_MAP_PTR(aux->map_state) == BPF_MAP_PTR_POISON;
}
static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
{
return aux->map_state & BPF_MAP_PTR_UNPRIV;
}
static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
const struct bpf_map *map, bool unpriv)
{
BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
unpriv |= bpf_map_ptr_unpriv(aux);
aux->map_state = (unsigned long)map |
(unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
}
struct bpf_call_arg_meta {
struct bpf_map *map_ptr;
bool raw_mode;
bool pkt_access;
int regno;
int access_size;
s64 msize_smax_value;
u64 msize_umax_value;
};
static DEFINE_MUTEX(bpf_verifier_lock);
void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
va_list args)
{
unsigned int n;
n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
"verifier log line truncated - local buffer too short\n");
n = min(log->len_total - log->len_used - 1, n);
log->kbuf[n] = '\0';
if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
log->len_used += n;
else
log->ubuf = NULL;
}
/* log_level controls verbosity level of eBPF verifier.
* bpf_verifier_log_write() is used to dump the verification trace to the log,
* so the user can figure out what's wrong with the program
*/
__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
const char *fmt, ...)
{
va_list args;
if (!bpf_verifier_log_needed(&env->log))
return;
va_start(args, fmt);
bpf_verifier_vlog(&env->log, fmt, args);
va_end(args);
}
EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
{
struct bpf_verifier_env *env = private_data;
va_list args;
if (!bpf_verifier_log_needed(&env->log))
return;
va_start(args, fmt);
bpf_verifier_vlog(&env->log, fmt, args);
va_end(args);
}
static bool type_is_pkt_pointer(enum bpf_reg_type type)
{
return type == PTR_TO_PACKET ||
type == PTR_TO_PACKET_META;
}
/* string representation of 'enum bpf_reg_type' */
static const char * const reg_type_str[] = {
[NOT_INIT] = "?",
[SCALAR_VALUE] = "inv",
[PTR_TO_CTX] = "ctx",
[CONST_PTR_TO_MAP] = "map_ptr",
[PTR_TO_MAP_VALUE] = "map_value",
[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
[PTR_TO_STACK] = "fp",
[PTR_TO_PACKET] = "pkt",
[PTR_TO_PACKET_META] = "pkt_meta",
[PTR_TO_PACKET_END] = "pkt_end",
};
static void print_liveness(struct bpf_verifier_env *env,
enum bpf_reg_liveness live)
{
if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN))
verbose(env, "_");
if (live & REG_LIVE_READ)
verbose(env, "r");
if (live & REG_LIVE_WRITTEN)
verbose(env, "w");
}
static struct bpf_func_state *func(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg)
{
struct bpf_verifier_state *cur = env->cur_state;
return cur->frame[reg->frameno];
}
static void print_verifier_state(struct bpf_verifier_env *env,
const struct bpf_func_state *state)
{
const struct bpf_reg_state *reg;
enum bpf_reg_type t;
int i;
if (state->frameno)
verbose(env, " frame%d:", state->frameno);
for (i = 0; i < MAX_BPF_REG; i++) {
reg = &state->regs[i];
t = reg->type;
if (t == NOT_INIT)
continue;
verbose(env, " R%d", i);
print_liveness(env, reg->live);
verbose(env, "=%s", reg_type_str[t]);
if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
tnum_is_const(reg->var_off)) {
/* reg->off should be 0 for SCALAR_VALUE */
verbose(env, "%lld", reg->var_off.value + reg->off);
if (t == PTR_TO_STACK)
verbose(env, ",call_%d", func(env, reg)->callsite);
} else {
verbose(env, "(id=%d", reg->id);
if (t != SCALAR_VALUE)
verbose(env, ",off=%d", reg->off);
if (type_is_pkt_pointer(t))
verbose(env, ",r=%d", reg->range);
else if (t == CONST_PTR_TO_MAP ||
t == PTR_TO_MAP_VALUE ||
t == PTR_TO_MAP_VALUE_OR_NULL)
verbose(env, ",ks=%d,vs=%d",
reg->map_ptr->key_size,
reg->map_ptr->value_size);
if (tnum_is_const(reg->var_off)) {
/* Typically an immediate SCALAR_VALUE, but
* could be a pointer whose offset is too big
* for reg->off
*/
verbose(env, ",imm=%llx", reg->var_off.value);
} else {
if (reg->smin_value != reg->umin_value &&
reg->smin_value != S64_MIN)
verbose(env, ",smin_value=%lld",
(long long)reg->smin_value);
if (reg->smax_value != reg->umax_value &&
reg->smax_value != S64_MAX)
verbose(env, ",smax_value=%lld",
(long long)reg->smax_value);
if (reg->umin_value != 0)
verbose(env, ",umin_value=%llu",
(unsigned long long)reg->umin_value);
if (reg->umax_value != U64_MAX)
verbose(env, ",umax_value=%llu",
(unsigned long long)reg->umax_value);
if (!tnum_is_unknown(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, ",var_off=%s", tn_buf);
}
}
verbose(env, ")");
}
}
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] == STACK_SPILL) {
verbose(env, " fp%d",
(-i - 1) * BPF_REG_SIZE);
print_liveness(env, state->stack[i].spilled_ptr.live);
verbose(env, "=%s",
reg_type_str[state->stack[i].spilled_ptr.type]);
}
if (state->stack[i].slot_type[0] == STACK_ZERO)
verbose(env, " fp%d=0", (-i - 1) * BPF_REG_SIZE);
}
verbose(env, "\n");
}
static int copy_stack_state(struct bpf_func_state *dst,
const struct bpf_func_state *src)
{
if (!src->stack)
return 0;
if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
/* internal bug, make state invalid to reject the program */
memset(dst, 0, sizeof(*dst));
return -EFAULT;
}
memcpy(dst->stack, src->stack,
sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
return 0;
}
/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
* make it consume minimal amount of memory. check_stack_write() access from
* the program calls into realloc_func_state() to grow the stack size.
* Note there is a non-zero 'parent' pointer inside bpf_verifier_state
* which this function copies over. It points to previous bpf_verifier_state
* which is never reallocated
*/
static int realloc_func_state(struct bpf_func_state *state, int size,
bool copy_old)
{
u32 old_size = state->allocated_stack;
struct bpf_stack_state *new_stack;
int slot = size / BPF_REG_SIZE;
if (size <= old_size || !size) {
if (copy_old)
return 0;
state->allocated_stack = slot * BPF_REG_SIZE;
if (!size && old_size) {
kfree(state->stack);
state->stack = NULL;
}
return 0;
}
new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
GFP_KERNEL);
if (!new_stack)
return -ENOMEM;
if (copy_old) {
if (state->stack)
memcpy(new_stack, state->stack,
sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
memset(new_stack + old_size / BPF_REG_SIZE, 0,
sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
}
state->allocated_stack = slot * BPF_REG_SIZE;
kfree(state->stack);
state->stack = new_stack;
return 0;
}
static void free_func_state(struct bpf_func_state *state)
{
if (!state)
return;
kfree(state->stack);
kfree(state);
}
static void free_verifier_state(struct bpf_verifier_state *state,
bool free_self)
{
int i;
for (i = 0; i <= state->curframe; i++) {
free_func_state(state->frame[i]);
state->frame[i] = NULL;
}
if (free_self)
kfree(state);
}
/* copy verifier state from src to dst growing dst stack space
* when necessary to accommodate larger src stack
*/
static int copy_func_state(struct bpf_func_state *dst,
const struct bpf_func_state *src)
{
int err;
err = realloc_func_state(dst, src->allocated_stack, false);
if (err)
return err;
memcpy(dst, src, offsetof(struct bpf_func_state, allocated_stack));
return copy_stack_state(dst, src);
}
static int copy_verifier_state(struct bpf_verifier_state *dst_state,
const struct bpf_verifier_state *src)
{
struct bpf_func_state *dst;
int i, err;
/* if dst has more stack frames then src frame, free them */
for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
free_func_state(dst_state->frame[i]);
dst_state->frame[i] = NULL;
}
dst_state->curframe = src->curframe;
dst_state->parent = src->parent;
for (i = 0; i <= src->curframe; i++) {
dst = dst_state->frame[i];
if (!dst) {
dst = kzalloc(sizeof(*dst), GFP_KERNEL);
if (!dst)
return -ENOMEM;
dst_state->frame[i] = dst;
}
err = copy_func_state(dst, src->frame[i]);
if (err)
return err;
}
return 0;
}
static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
int *insn_idx)
{
struct bpf_verifier_state *cur = env->cur_state;
struct bpf_verifier_stack_elem *elem, *head = env->head;
int err;
if (env->head == NULL)
return -ENOENT;
if (cur) {
err = copy_verifier_state(cur, &head->st);
if (err)
return err;
}
if (insn_idx)
*insn_idx = head->insn_idx;
if (prev_insn_idx)
*prev_insn_idx = head->prev_insn_idx;
elem = head->next;
free_verifier_state(&head->st, false);
kfree(head);
env->head = elem;
env->stack_size--;
return 0;
}
static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
int insn_idx, int prev_insn_idx)
{
struct bpf_verifier_state *cur = env->cur_state;
struct bpf_verifier_stack_elem *elem;
int err;
elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
if (!elem)
goto err;
elem->insn_idx = insn_idx;
elem->prev_insn_idx = prev_insn_idx;
elem->next = env->head;
env->head = elem;
env->stack_size++;
err = copy_verifier_state(&elem->st, cur);
if (err)
goto err;
if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
verbose(env, "BPF program is too complex\n");
goto err;
}
return &elem->st;
err:
free_verifier_state(env->cur_state, true);
env->cur_state = NULL;
/* pop all elements and return */
while (!pop_stack(env, NULL, NULL));
return NULL;
}
#define CALLER_SAVED_REGS 6
static const int caller_saved[CALLER_SAVED_REGS] = {
BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
};
static void __mark_reg_not_init(struct bpf_reg_state *reg);
/* Mark the unknown part of a register (variable offset or scalar value) as
* known to have the value @imm.
*/
static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
{
reg->id = 0;
reg->var_off = tnum_const(imm);
reg->smin_value = (s64)imm;
reg->smax_value = (s64)imm;
reg->umin_value = imm;
reg->umax_value = imm;
}
/* Mark the 'variable offset' part of a register as zero. This should be
* used only on registers holding a pointer type.
*/
static void __mark_reg_known_zero(struct bpf_reg_state *reg)
{
__mark_reg_known(reg, 0);
}
static void __mark_reg_const_zero(struct bpf_reg_state *reg)
{
__mark_reg_known(reg, 0);
reg->off = 0;
reg->type = SCALAR_VALUE;
}
static void mark_reg_known_zero(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs */
for (regno = 0; regno < MAX_BPF_REG; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_known_zero(regs + regno);
}
static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
{
return type_is_pkt_pointer(reg->type);
}
static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
{
return reg_is_pkt_pointer(reg) ||
reg->type == PTR_TO_PACKET_END;
}
/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
enum bpf_reg_type which)
{
/* The register can already have a range from prior markings.
* This is fine as long as it hasn't been advanced from its
* origin.
*/
return reg->type == which &&
reg->id == 0 &&
reg->off == 0 &&
tnum_equals_const(reg->var_off, 0);
}
/* Attempts to improve min/max values based on var_off information */
static void __update_reg_bounds(struct bpf_reg_state *reg)
{
/* min signed is max(sign bit) | min(other bits) */
reg->smin_value = max_t(s64, reg->smin_value,
reg->var_off.value | (reg->var_off.mask & S64_MIN));
/* max signed is min(sign bit) | max(other bits) */
reg->smax_value = min_t(s64, reg->smax_value,
reg->var_off.value | (reg->var_off.mask & S64_MAX));
reg->umin_value = max(reg->umin_value, reg->var_off.value);
reg->umax_value = min(reg->umax_value,
reg->var_off.value | reg->var_off.mask);
}
/* Uses signed min/max values to inform unsigned, and vice-versa */
static void __reg_deduce_bounds(struct bpf_reg_state *reg)
{
/* Learn sign from signed bounds.
* If we cannot cross the sign boundary, then signed and unsigned bounds
* are the same, so combine. This works even in the negative case, e.g.
* -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
*/
if (reg->smin_value >= 0 || reg->smax_value < 0) {
reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
reg->umin_value);
reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
reg->umax_value);
return;
}
/* Learn sign from unsigned bounds. Signed bounds cross the sign
* boundary, so we must be careful.
*/
if ((s64)reg->umax_value >= 0) {
/* Positive. We can't learn anything from the smin, but smax
* is positive, hence safe.
*/
reg->smin_value = reg->umin_value;
reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
reg->umax_value);
} else if ((s64)reg->umin_value < 0) {
/* Negative. We can't learn anything from the smax, but smin
* is negative, hence safe.
*/
reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
reg->umin_value);
reg->smax_value = reg->umax_value;
}
}
/* Attempts to improve var_off based on unsigned min/max information */
static void __reg_bound_offset(struct bpf_reg_state *reg)
{
reg->var_off = tnum_intersect(reg->var_off,
tnum_range(reg->umin_value,
reg->umax_value));
}
/* Reset the min/max bounds of a register */
static void __mark_reg_unbounded(struct bpf_reg_state *reg)
{
reg->smin_value = S64_MIN;
reg->smax_value = S64_MAX;
reg->umin_value = 0;
reg->umax_value = U64_MAX;
}
/* Mark a register as having a completely unknown (scalar) value. */
static void __mark_reg_unknown(struct bpf_reg_state *reg)
{
reg->type = SCALAR_VALUE;
reg->id = 0;
reg->off = 0;
reg->var_off = tnum_unknown;
reg->frameno = 0;
__mark_reg_unbounded(reg);
}
static void mark_reg_unknown(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs except FP */
for (regno = 0; regno < BPF_REG_FP; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_unknown(regs + regno);
}
static void __mark_reg_not_init(struct bpf_reg_state *reg)
{
__mark_reg_unknown(reg);
reg->type = NOT_INIT;
}
static void mark_reg_not_init(struct bpf_verifier_env *env,
struct bpf_reg_state *regs, u32 regno)
{
if (WARN_ON(regno >= MAX_BPF_REG)) {
verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
/* Something bad happened, let's kill all regs except FP */
for (regno = 0; regno < BPF_REG_FP; regno++)
__mark_reg_not_init(regs + regno);
return;
}
__mark_reg_not_init(regs + regno);
}
static void init_reg_state(struct bpf_verifier_env *env,
struct bpf_func_state *state)
{
struct bpf_reg_state *regs = state->regs;
int i;
for (i = 0; i < MAX_BPF_REG; i++) {
mark_reg_not_init(env, regs, i);
regs[i].live = REG_LIVE_NONE;
}
/* frame pointer */
regs[BPF_REG_FP].type = PTR_TO_STACK;
mark_reg_known_zero(env, regs, BPF_REG_FP);
regs[BPF_REG_FP].frameno = state->frameno;
/* 1st arg to a function */
regs[BPF_REG_1].type = PTR_TO_CTX;
mark_reg_known_zero(env, regs, BPF_REG_1);
}
#define BPF_MAIN_FUNC (-1)
static void init_func_state(struct bpf_verifier_env *env,
struct bpf_func_state *state,
int callsite, int frameno, int subprogno)
{
state->callsite = callsite;
state->frameno = frameno;
state->subprogno = subprogno;
init_reg_state(env, state);
}
enum reg_arg_type {
SRC_OP, /* register is used as source operand */
DST_OP, /* register is used as destination operand */
DST_OP_NO_MARK /* same as above, check only, don't mark */
};
static int cmp_subprogs(const void *a, const void *b)
{
return ((struct bpf_subprog_info *)a)->start -
((struct bpf_subprog_info *)b)->start;
}
static int find_subprog(struct bpf_verifier_env *env, int off)
{
struct bpf_subprog_info *p;
p = bsearch(&off, env->subprog_info, env->subprog_cnt,
sizeof(env->subprog_info[0]), cmp_subprogs);
if (!p)
return -ENOENT;
return p - env->subprog_info;
}
static int add_subprog(struct bpf_verifier_env *env, int off)
{
int insn_cnt = env->prog->len;
int ret;
if (off >= insn_cnt || off < 0) {
verbose(env, "call to invalid destination\n");
return -EINVAL;
}
ret = find_subprog(env, off);
if (ret >= 0)
return 0;
if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
verbose(env, "too many subprograms\n");
return -E2BIG;
}
env->subprog_info[env->subprog_cnt++].start = off;
sort(env->subprog_info, env->subprog_cnt,
sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
return 0;
}
static int check_subprogs(struct bpf_verifier_env *env)
{
int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
struct bpf_subprog_info *subprog = env->subprog_info;
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
/* Add entry function. */
ret = add_subprog(env, 0);
if (ret < 0)
return ret;
/* determine subprog starts. The end is one before the next starts */
for (i = 0; i < insn_cnt; i++) {
if (insn[i].code != (BPF_JMP | BPF_CALL))
continue;
if (insn[i].src_reg != BPF_PSEUDO_CALL)
continue;
if (!env->allow_ptr_leaks) {
verbose(env, "function calls to other bpf functions are allowed for root only\n");
return -EPERM;
}
if (bpf_prog_is_dev_bound(env->prog->aux)) {
verbose(env, "function calls in offloaded programs are not supported yet\n");
return -EINVAL;
}
ret = add_subprog(env, i + insn[i].imm + 1);
if (ret < 0)
return ret;
}
/* Add a fake 'exit' subprog which could simplify subprog iteration
* logic. 'subprog_cnt' should not be increased.
*/
subprog[env->subprog_cnt].start = insn_cnt;
if (env->log.level > 1)
for (i = 0; i < env->subprog_cnt; i++)
verbose(env, "func#%d @%d\n", i, subprog[i].start);
/* now check that all jumps are within the same subprog */
subprog_start = subprog[cur_subprog].start;
subprog_end = subprog[cur_subprog + 1].start;
for (i = 0; i < insn_cnt; i++) {
u8 code = insn[i].code;
if (BPF_CLASS(code) != BPF_JMP)
goto next;
if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
goto next;
off = i + insn[i].off + 1;
if (off < subprog_start || off >= subprog_end) {
verbose(env, "jump out of range from insn %d to %d\n", i, off);
return -EINVAL;
}
next:
if (i == subprog_end - 1) {
/* to avoid fall-through from one subprog into another
* the last insn of the subprog should be either exit
* or unconditional jump back
*/
if (code != (BPF_JMP | BPF_EXIT) &&
code != (BPF_JMP | BPF_JA)) {
verbose(env, "last insn is not an exit or jmp\n");
return -EINVAL;
}
subprog_start = subprog_end;
cur_subprog++;
if (cur_subprog < env->subprog_cnt)
subprog_end = subprog[cur_subprog + 1].start;
}
}
return 0;
}
static
struct bpf_verifier_state *skip_callee(struct bpf_verifier_env *env,
const struct bpf_verifier_state *state,
struct bpf_verifier_state *parent,
u32 regno)
{
struct bpf_verifier_state *tmp = NULL;
/* 'parent' could be a state of caller and
* 'state' could be a state of callee. In such case
* parent->curframe < state->curframe
* and it's ok for r1 - r5 registers
*
* 'parent' could be a callee's state after it bpf_exit-ed.
* In such case parent->curframe > state->curframe
* and it's ok for r0 only
*/
if (parent->curframe == state->curframe ||
(parent->curframe < state->curframe &&
regno >= BPF_REG_1 && regno <= BPF_REG_5) ||
(parent->curframe > state->curframe &&
regno == BPF_REG_0))
return parent;
if (parent->curframe > state->curframe &&
regno >= BPF_REG_6) {
/* for callee saved regs we have to skip the whole chain
* of states that belong to callee and mark as LIVE_READ
* the registers before the call
*/
tmp = parent;
while (tmp && tmp->curframe != state->curframe) {
tmp = tmp->parent;
}
if (!tmp)
goto bug;
parent = tmp;
} else {
goto bug;
}
return parent;
bug:
verbose(env, "verifier bug regno %d tmp %p\n", regno, tmp);
verbose(env, "regno %d parent frame %d current frame %d\n",
regno, parent->curframe, state->curframe);
return NULL;
}
static int mark_reg_read(struct bpf_verifier_env *env,
const struct bpf_verifier_state *state,
struct bpf_verifier_state *parent,
u32 regno)
{
bool writes = parent == state->parent; /* Observe write marks */
if (regno == BPF_REG_FP)
/* We don't need to worry about FP liveness because it's read-only */
return 0;
while (parent) {
/* if read wasn't screened by an earlier write ... */
if (writes && state->frame[state->curframe]->regs[regno].live & REG_LIVE_WRITTEN)
break;
parent = skip_callee(env, state, parent, regno);
if (!parent)
return -EFAULT;
/* ... then we depend on parent's value */
parent->frame[parent->curframe]->regs[regno].live |= REG_LIVE_READ;
state = parent;
parent = state->parent;
writes = true;
}
return 0;
}
static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
enum reg_arg_type t)
{
struct bpf_verifier_state *vstate = env->cur_state;
struct bpf_func_state *state = vstate->frame[vstate->curframe];
struct bpf_reg_state *regs = state->regs;
if (regno >= MAX_BPF_REG) {
verbose(env, "R%d is invalid\n", regno);
return -EINVAL;
}
if (t == SRC_OP) {
/* check whether register used as source operand can be read */
if (regs[regno].type == NOT_INIT) {
verbose(env, "R%d !read_ok\n", regno);
return -EACCES;
}
return mark_reg_read(env, vstate, vstate->parent, regno);
} else {
/* check whether register used as dest operand can be written to */
if (regno == BPF_REG_FP) {
verbose(env, "frame pointer is read only\n");
return -EACCES;
}
regs[regno].live |= REG_LIVE_WRITTEN;
if (t == DST_OP)
mark_reg_unknown(env, regs, regno);
}
return 0;
}
static bool is_spillable_regtype(enum bpf_reg_type type)
{
switch (type) {
case PTR_TO_MAP_VALUE:
case PTR_TO_MAP_VALUE_OR_NULL:
case PTR_TO_STACK:
case PTR_TO_CTX:
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
case PTR_TO_PACKET_END:
case CONST_PTR_TO_MAP:
return true;
default:
return false;
}
}
/* Does this register contain a constant zero? */
static bool register_is_null(struct bpf_reg_state *reg)
{
return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
}
/* check_stack_read/write functions track spill/fill of registers,
* stack boundary and alignment are checked in check_mem_access()
*/
static int check_stack_write(struct bpf_verifier_env *env,
struct bpf_func_state *state, /* func where register points to */
int off, int size, int value_regno, int insn_idx)
{
struct bpf_func_state *cur; /* state of the current function */
int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
enum bpf_reg_type type;
err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
true);
if (err)
return err;
/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
* so it's aligned access and [off, off + size) are within stack limits
*/
if (!env->allow_ptr_leaks &&
state->stack[spi].slot_type[0] == STACK_SPILL &&
size != BPF_REG_SIZE) {
verbose(env, "attempt to corrupt spilled pointer on stack\n");
return -EACCES;
}
cur = env->cur_state->frame[env->cur_state->curframe];
if (value_regno >= 0 &&
is_spillable_regtype((type = cur->regs[value_regno].type))) {
/* register containing pointer is being spilled into stack */
if (size != BPF_REG_SIZE) {
verbose(env, "invalid size of register spill\n");
return -EACCES;
}
if (state != cur && type == PTR_TO_STACK) {
verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
return -EINVAL;
}
/* save register state */
state->stack[spi].spilled_ptr = cur->regs[value_regno];
state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
for (i = 0; i < BPF_REG_SIZE; i++) {
if (state->stack[spi].slot_type[i] == STACK_MISC &&
!env->allow_ptr_leaks) {
int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
int soff = (-spi - 1) * BPF_REG_SIZE;
/* detected reuse of integer stack slot with a pointer
* which means either llvm is reusing stack slot or
* an attacker is trying to exploit CVE-2018-3639
* (speculative store bypass)
* Have to sanitize that slot with preemptive
* store of zero.
*/
if (*poff && *poff != soff) {
/* disallow programs where single insn stores
* into two different stack slots, since verifier
* cannot sanitize them
*/
verbose(env,
"insn %d cannot access two stack slots fp%d and fp%d",
insn_idx, *poff, soff);
return -EINVAL;
}
*poff = soff;
}
state->stack[spi].slot_type[i] = STACK_SPILL;
}
} else {
u8 type = STACK_MISC;
/* regular write of data into stack */
state->stack[spi].spilled_ptr = (struct bpf_reg_state) {};
/* only mark the slot as written if all 8 bytes were written
* otherwise read propagation may incorrectly stop too soon
* when stack slots are partially written.
* This heuristic means that read propagation will be
* conservative, since it will add reg_live_read marks
* to stack slots all the way to first state when programs
* writes+reads less than 8 bytes
*/
if (size == BPF_REG_SIZE)
state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
/* when we zero initialize stack slots mark them as such */
if (value_regno >= 0 &&
register_is_null(&cur->regs[value_regno]))
type = STACK_ZERO;
for (i = 0; i < size; i++)
state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
type;
}
return 0;
}
/* registers of every function are unique and mark_reg_read() propagates
* the liveness in the following cases:
* - from callee into caller for R1 - R5 that were used as arguments
* - from caller into callee for R0 that used as result of the call
* - from caller to the same caller skipping states of the callee for R6 - R9,
* since R6 - R9 are callee saved by implicit function prologue and
* caller's R6 != callee's R6, so when we propagate liveness up to
* parent states we need to skip callee states for R6 - R9.
*
* stack slot marking is different, since stacks of caller and callee are
* accessible in both (since caller can pass a pointer to caller's stack to
* callee which can pass it to another function), hence mark_stack_slot_read()
* has to propagate the stack liveness to all parent states at given frame number.
* Consider code:
* f1() {
* ptr = fp - 8;
* *ptr = ctx;
* call f2 {
* .. = *ptr;
* }
* .. = *ptr;
* }
* First *ptr is reading from f1's stack and mark_stack_slot_read() has
* to mark liveness at the f1's frame and not f2's frame.
* Second *ptr is also reading from f1's stack and mark_stack_slot_read() has
* to propagate liveness to f2 states at f1's frame level and further into
* f1 states at f1's frame level until write into that stack slot
*/
static void mark_stack_slot_read(struct bpf_verifier_env *env,
const struct bpf_verifier_state *state,
struct bpf_verifier_state *parent,
int slot, int frameno)
{
bool writes = parent == state->parent; /* Observe write marks */
while (parent) {
if (parent->frame[frameno]->allocated_stack <= slot * BPF_REG_SIZE)
/* since LIVE_WRITTEN mark is only done for full 8-byte
* write the read marks are conservative and parent
* state may not even have the stack allocated. In such case
* end the propagation, since the loop reached beginning
* of the function
*/
break;
/* if read wasn't screened by an earlier write ... */
if (writes && state->frame[frameno]->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN)
break;
/* ... then we depend on parent's value */
parent->frame[frameno]->stack[slot].spilled_ptr.live |= REG_LIVE_READ;
state = parent;
parent = state->parent;
writes = true;
}
}
static int check_stack_read(struct bpf_verifier_env *env,
struct bpf_func_state *reg_state /* func where register points to */,
int off, int size, int value_regno)
{
struct bpf_verifier_state *vstate = env->cur_state;
struct bpf_func_state *state = vstate->frame[vstate->curframe];
int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
u8 *stype;
if (reg_state->allocated_stack <= slot) {
verbose(env, "invalid read from stack off %d+0 size %d\n",
off, size);
return -EACCES;
}
stype = reg_state->stack[spi].slot_type;
if (stype[0] == STACK_SPILL) {
if (size != BPF_REG_SIZE) {
verbose(env, "invalid size of register spill\n");
return -EACCES;
}
for (i = 1; i < BPF_REG_SIZE; i++) {
if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
verbose(env, "corrupted spill memory\n");
return -EACCES;
}
}
if (value_regno >= 0) {
/* restore register state from stack */
state->regs[value_regno] = reg_state->stack[spi].spilled_ptr;
/* mark reg as written since spilled pointer state likely
* has its liveness marks cleared by is_state_visited()
* which resets stack/reg liveness for state transitions
*/
state->regs[value_regno].live |= REG_LIVE_WRITTEN;
}
mark_stack_slot_read(env, vstate, vstate->parent, spi,
reg_state->frameno);
return 0;
} else {
int zeros = 0;
for (i = 0; i < size; i++) {
if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
continue;
if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
zeros++;
continue;
}
verbose(env, "invalid read from stack off %d+%d size %d\n",
off, i, size);
return -EACCES;
}
mark_stack_slot_read(env, vstate, vstate->parent, spi,
reg_state->frameno);
if (value_regno >= 0) {
if (zeros == size) {
/* any size read into register is zero extended,
* so the whole register == const_zero
*/
__mark_reg_const_zero(&state->regs[value_regno]);
} else {
/* have read misc data from the stack */
mark_reg_unknown(env, state->regs, value_regno);
}
state->regs[value_regno].live |= REG_LIVE_WRITTEN;
}
return 0;
}
}
/* check read/write into map element returned by bpf_map_lookup_elem() */
static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_map *map = regs[regno].map_ptr;
if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
off + size > map->value_size) {
verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
map->value_size, off, size);
return -EACCES;
}
return 0;
}
/* check read/write into a map element with possible variable offset */
static int check_map_access(struct bpf_verifier_env *env, u32 regno,
int off, int size, bool zero_size_allowed)
{
struct bpf_verifier_state *vstate = env->cur_state;
struct bpf_func_state *state = vstate->frame[vstate->curframe];
struct bpf_reg_state *reg = &state->regs[regno];
int err;
/* We may have adjusted the register to this map value, so we
* need to try adding each of min_value and max_value to off
* to make sure our theoretical access will be safe.
*/
if (env->log.level)
print_verifier_state(env, state);
/* The minimum value is only important with signed
* comparisons where we can't assume the floor of a
* value is 0. If we are using signed variables for our
* index'es we need to make sure that whatever we use
* will have a set floor within our range.
*/
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
regno);
return -EACCES;
}
err = __check_map_access(env, regno, reg->smin_value + off, size,
zero_size_allowed);
if (err) {
verbose(env, "R%d min value is outside of the array range\n",
regno);
return err;
}
/* If we haven't set a max value then we need to bail since we can't be
* sure we won't do bad things.
* If reg->umax_value + off could overflow, treat that as unbounded too.
*/
if (reg->umax_value >= BPF_MAX_VAR_OFF) {
verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
regno);
return -EACCES;
}
err = __check_map_access(env, regno, reg->umax_value + off, size,
zero_size_allowed);
if (err)
verbose(env, "R%d max value is outside of the array range\n",
regno);
return err;
}
#define MAX_PACKET_OFF 0xffff
static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
const struct bpf_call_arg_meta *meta,
enum bpf_access_type t)
{
switch (env->prog->type) {
case BPF_PROG_TYPE_LWT_IN:
case BPF_PROG_TYPE_LWT_OUT:
case BPF_PROG_TYPE_LWT_SEG6LOCAL:
case BPF_PROG_TYPE_SK_REUSEPORT:
/* dst_input() and dst_output() can't write for now */
if (t == BPF_WRITE)
return false;
/* fallthrough */
case BPF_PROG_TYPE_SCHED_CLS:
case BPF_PROG_TYPE_SCHED_ACT:
case BPF_PROG_TYPE_XDP:
case BPF_PROG_TYPE_LWT_XMIT:
case BPF_PROG_TYPE_SK_SKB:
case BPF_PROG_TYPE_SK_MSG:
if (meta)
return meta->pkt_access;
env->seen_direct_write = true;
return true;
default:
return false;
}
}
static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
int off, int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = ®s[regno];
if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
(u64)off + size > reg->range) {
verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
off, size, regno, reg->id, reg->off, reg->range);
return -EACCES;
}
return 0;
}
static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
int size, bool zero_size_allowed)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = ®s[regno];
int err;
/* We may have added a variable offset to the packet pointer; but any
* reg->range we have comes after that. We are only checking the fixed
* offset.
*/
/* We don't allow negative numbers, because we aren't tracking enough
* detail to prove they're safe.
*/
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
regno);
return -EACCES;
}
err = __check_packet_access(env, regno, off, size, zero_size_allowed);
if (err) {
verbose(env, "R%d offset is outside of the packet\n", regno);
return err;
}
return err;
}
/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
enum bpf_access_type t, enum bpf_reg_type *reg_type)
{
struct bpf_insn_access_aux info = {
.reg_type = *reg_type,
};
if (env->ops->is_valid_access &&
env->ops->is_valid_access(off, size, t, env->prog, &info)) {
/* A non zero info.ctx_field_size indicates that this field is a
* candidate for later verifier transformation to load the whole
* field and then apply a mask when accessed with a narrower
* access than actual ctx access size. A zero info.ctx_field_size
* will only allow for whole field access and rejects any other
* type of narrower access.
*/
*reg_type = info.reg_type;
env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
/* remember the offset of last byte accessed in ctx */
if (env->prog->aux->max_ctx_offset < off + size)
env->prog->aux->max_ctx_offset = off + size;
return 0;
}
verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
return -EACCES;
}
static bool __is_pointer_value(bool allow_ptr_leaks,
const struct bpf_reg_state *reg)
{
if (allow_ptr_leaks)
return false;
return reg->type != SCALAR_VALUE;
}
static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
{
return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
}
static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
{
const struct bpf_reg_state *reg = cur_regs(env) + regno;
return reg->type == PTR_TO_CTX;
}
static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
{
const struct bpf_reg_state *reg = cur_regs(env) + regno;
return type_is_pkt_pointer(reg->type);
}
static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
int off, int size, bool strict)
{
struct tnum reg_off;
int ip_align;
/* Byte size accesses are always allowed. */
if (!strict || size == 1)
return 0;
/* For platforms that do not have a Kconfig enabling
* CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
* NET_IP_ALIGN is universally set to '2'. And on platforms
* that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
* to this code only in strict mode where we want to emulate
* the NET_IP_ALIGN==2 checking. Therefore use an
* unconditional IP align value of '2'.
*/
ip_align = 2;
reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
if (!tnum_is_aligned(reg_off, size)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env,
"misaligned packet access off %d+%s+%d+%d size %d\n",
ip_align, tn_buf, reg->off, off, size);
return -EACCES;
}
return 0;
}
static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
const char *pointer_desc,
int off, int size, bool strict)
{
struct tnum reg_off;
/* Byte size accesses are always allowed. */
if (!strict || size == 1)
return 0;
reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
if (!tnum_is_aligned(reg_off, size)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
pointer_desc, tn_buf, reg->off, off, size);
return -EACCES;
}
return 0;
}
static int check_ptr_alignment(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg, int off,
int size, bool strict_alignment_once)
{
bool strict = env->strict_alignment || strict_alignment_once;
const char *pointer_desc = "";
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
/* Special case, because of NET_IP_ALIGN. Given metadata sits
* right in front, treat it the very same way.
*/
return check_pkt_ptr_alignment(env, reg, off, size, strict);
case PTR_TO_MAP_VALUE:
pointer_desc = "value ";
break;
case PTR_TO_CTX:
pointer_desc = "context ";
break;
case PTR_TO_STACK:
pointer_desc = "stack ";
/* The stack spill tracking logic in check_stack_write()
* and check_stack_read() relies on stack accesses being
* aligned.
*/
strict = true;
break;
default:
break;
}
return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
strict);
}
static int update_stack_depth(struct bpf_verifier_env *env,
const struct bpf_func_state *func,
int off)
{
u16 stack = env->subprog_info[func->subprogno].stack_depth;
if (stack >= -off)
return 0;
/* update known max for given subprogram */
env->subprog_info[func->subprogno].stack_depth = -off;
return 0;
}
/* starting from main bpf function walk all instructions of the function
* and recursively walk all callees that given function can call.
* Ignore jump and exit insns.
* Since recursion is prevented by check_cfg() this algorithm
* only needs a local stack of MAX_CALL_FRAMES to remember callsites
*/
static int check_max_stack_depth(struct bpf_verifier_env *env)
{
int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
struct bpf_subprog_info *subprog = env->subprog_info;
struct bpf_insn *insn = env->prog->insnsi;
int ret_insn[MAX_CALL_FRAMES];
int ret_prog[MAX_CALL_FRAMES];
process_func:
/* round up to 32-bytes, since this is granularity
* of interpreter stack size
*/
depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
if (depth > MAX_BPF_STACK) {
verbose(env, "combined stack size of %d calls is %d. Too large\n",
frame + 1, depth);
return -EACCES;
}
continue_func:
subprog_end = subprog[idx + 1].start;
for (; i < subprog_end; i++) {
if (insn[i].code != (BPF_JMP | BPF_CALL))
continue;
if (insn[i].src_reg != BPF_PSEUDO_CALL)
continue;
/* remember insn and function to return to */
ret_insn[frame] = i + 1;
ret_prog[frame] = idx;
/* find the callee */
i = i + insn[i].imm + 1;
idx = find_subprog(env, i);
if (idx < 0) {
WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
i);
return -EFAULT;
}
frame++;
if (frame >= MAX_CALL_FRAMES) {
WARN_ONCE(1, "verifier bug. Call stack is too deep\n");
return -EFAULT;
}
goto process_func;
}
/* end of for() loop means the last insn of the 'subprog'
* was reached. Doesn't matter whether it was JA or EXIT
*/
if (frame == 0)
return 0;
depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
frame--;
i = ret_insn[frame];
idx = ret_prog[frame];
goto continue_func;
}
#ifndef CONFIG_BPF_JIT_ALWAYS_ON
static int get_callee_stack_depth(struct bpf_verifier_env *env,
const struct bpf_insn *insn, int idx)
{
int start = idx + insn->imm + 1, subprog;
subprog = find_subprog(env, start);
if (subprog < 0) {
WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
start);
return -EFAULT;
}
return env->subprog_info[subprog].stack_depth;
}
#endif
static int check_ctx_reg(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg, int regno)
{
/* Access to ctx or passing it to a helper is only allowed in
* its original, unmodified form.
*/
if (reg->off) {
verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
regno, reg->off);
return -EACCES;
}
if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
return -EACCES;
}
return 0;
}
/* truncate register to smaller size (in bytes)
* must be called with size < BPF_REG_SIZE
*/
static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
{
u64 mask;
/* clear high bits in bit representation */
reg->var_off = tnum_cast(reg->var_off, size);
/* fix arithmetic bounds */
mask = ((u64)1 << (size * 8)) - 1;
if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
reg->umin_value &= mask;
reg->umax_value &= mask;
} else {
reg->umin_value = 0;
reg->umax_value = mask;
}
reg->smin_value = reg->umin_value;
reg->smax_value = reg->umax_value;
}
/* check whether memory at (regno + off) is accessible for t = (read | write)
* if t==write, value_regno is a register which value is stored into memory
* if t==read, value_regno is a register which will receive the value from memory
* if t==write && value_regno==-1, some unknown value is stored into memory
* if t==read && value_regno==-1, don't care what we read from memory
*/
static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
int off, int bpf_size, enum bpf_access_type t,
int value_regno, bool strict_alignment_once)
{
struct bpf_reg_state *regs = cur_regs(env);
struct bpf_reg_state *reg = regs + regno;
struct bpf_func_state *state;
int size, err = 0;
size = bpf_size_to_bytes(bpf_size);
if (size < 0)
return size;
/* alignment checks will add in reg->off themselves */
err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
if (err)
return err;
/* for access checks, reg->off is just part of off */
off += reg->off;
if (reg->type == PTR_TO_MAP_VALUE) {
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into map\n", value_regno);
return -EACCES;
}
err = check_map_access(env, regno, off, size, false);
if (!err && t == BPF_READ && value_regno >= 0)
mark_reg_unknown(env, regs, value_regno);
} else if (reg->type == PTR_TO_CTX) {
enum bpf_reg_type reg_type = SCALAR_VALUE;
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into ctx\n", value_regno);
return -EACCES;
}
err = check_ctx_reg(env, reg, regno);
if (err < 0)
return err;
err = check_ctx_access(env, insn_idx, off, size, t, ®_type);
if (!err && t == BPF_READ && value_regno >= 0) {
/* ctx access returns either a scalar, or a
* PTR_TO_PACKET[_META,_END]. In the latter
* case, we know the offset is zero.
*/
if (reg_type == SCALAR_VALUE)
mark_reg_unknown(env, regs, value_regno);
else
mark_reg_known_zero(env, regs,
value_regno);
regs[value_regno].id = 0;
regs[value_regno].off = 0;
regs[value_regno].range = 0;
regs[value_regno].type = reg_type;
}
} else if (reg->type == PTR_TO_STACK) {
/* stack accesses must be at a fixed offset, so that we can
* determine what type of data were returned.
* See check_stack_read().
*/
if (!tnum_is_const(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "variable stack access var_off=%s off=%d size=%d",
tn_buf, off, size);
return -EACCES;
}
off += reg->var_off.value;
if (off >= 0 || off < -MAX_BPF_STACK) {
verbose(env, "invalid stack off=%d size=%d\n", off,
size);
return -EACCES;
}
state = func(env, reg);
err = update_stack_depth(env, state, off);
if (err)
return err;
if (t == BPF_WRITE)
err = check_stack_write(env, state, off, size,
value_regno, insn_idx);
else
err = check_stack_read(env, state, off, size,
value_regno);
} else if (reg_is_pkt_pointer(reg)) {
if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
verbose(env, "cannot write into packet\n");
return -EACCES;
}
if (t == BPF_WRITE && value_regno >= 0 &&
is_pointer_value(env, value_regno)) {
verbose(env, "R%d leaks addr into packet\n",
value_regno);
return -EACCES;
}
err = check_packet_access(env, regno, off, size, false);
if (!err && t == BPF_READ && value_regno >= 0)
mark_reg_unknown(env, regs, value_regno);
} else {
verbose(env, "R%d invalid mem access '%s'\n", regno,
reg_type_str[reg->type]);
return -EACCES;
}
if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
regs[value_regno].type == SCALAR_VALUE) {
/* b/h/w load zero-extends, mark upper bits as known 0 */
coerce_reg_to_size(®s[value_regno], size);
}
return err;
}
static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
{
int err;
if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
insn->imm != 0) {
verbose(env, "BPF_XADD uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->src_reg)) {
verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
return -EACCES;
}
if (is_ctx_reg(env, insn->dst_reg) ||
is_pkt_reg(env, insn->dst_reg)) {
verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
insn->dst_reg, is_ctx_reg(env, insn->dst_reg) ?
"context" : "packet");
return -EACCES;
}
/* check whether atomic_add can read the memory */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_READ, -1, true);
if (err)
return err;
/* check whether atomic_add can write into the same memory */
return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE, -1, true);
}
/* when register 'regno' is passed into function that will read 'access_size'
* bytes from that pointer, make sure that it's within stack boundary
* and all elements of stack are initialized.
* Unlike most pointer bounds-checking functions, this one doesn't take an
* 'off' argument, so it has to add in reg->off itself.
*/
static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
int access_size, bool zero_size_allowed,
struct bpf_call_arg_meta *meta)
{
struct bpf_reg_state *reg = cur_regs(env) + regno;
struct bpf_func_state *state = func(env, reg);
int off, i, slot, spi;
if (reg->type != PTR_TO_STACK) {
/* Allow zero-byte read from NULL, regardless of pointer type */
if (zero_size_allowed && access_size == 0 &&
register_is_null(reg))
return 0;
verbose(env, "R%d type=%s expected=%s\n", regno,
reg_type_str[reg->type],
reg_type_str[PTR_TO_STACK]);
return -EACCES;
}
/* Only allow fixed-offset stack reads */
if (!tnum_is_const(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "invalid variable stack read R%d var_off=%s\n",
regno, tn_buf);
return -EACCES;
}
off = reg->off + reg->var_off.value;
if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
regno, off, access_size);
return -EACCES;
}
if (meta && meta->raw_mode) {
meta->access_size = access_size;
meta->regno = regno;
return 0;
}
for (i = 0; i < access_size; i++) {
u8 *stype;
slot = -(off + i) - 1;
spi = slot / BPF_REG_SIZE;
if (state->allocated_stack <= slot)
goto err;
stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
if (*stype == STACK_MISC)
goto mark;
if (*stype == STACK_ZERO) {
/* helper can write anything into the stack */
*stype = STACK_MISC;
goto mark;
}
err:
verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
off, i, access_size);
return -EACCES;
mark:
/* reading any byte out of 8-byte 'spill_slot' will cause
* the whole slot to be marked as 'read'
*/
mark_stack_slot_read(env, env->cur_state, env->cur_state->parent,
spi, state->frameno);
}
return update_stack_depth(env, state, off);
}
static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
int access_size, bool zero_size_allowed,
struct bpf_call_arg_meta *meta)
{
struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
switch (reg->type) {
case PTR_TO_PACKET:
case PTR_TO_PACKET_META:
return check_packet_access(env, regno, reg->off, access_size,
zero_size_allowed);
case PTR_TO_MAP_VALUE:
return check_map_access(env, regno, reg->off, access_size,
zero_size_allowed);
default: /* scalar_value|ptr_to_stack or invalid ptr */
return check_stack_boundary(env, regno, access_size,
zero_size_allowed, meta);
}
}
static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
{
return type == ARG_PTR_TO_MEM ||
type == ARG_PTR_TO_MEM_OR_NULL ||
type == ARG_PTR_TO_UNINIT_MEM;
}
static bool arg_type_is_mem_size(enum bpf_arg_type type)
{
return type == ARG_CONST_SIZE ||
type == ARG_CONST_SIZE_OR_ZERO;
}
static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
enum bpf_arg_type arg_type,
struct bpf_call_arg_meta *meta)
{
struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
enum bpf_reg_type expected_type, type = reg->type;
int err = 0;
if (arg_type == ARG_DONTCARE)
return 0;
err = check_reg_arg(env, regno, SRC_OP);
if (err)
return err;
if (arg_type == ARG_ANYTHING) {
if (is_pointer_value(env, regno)) {
verbose(env, "R%d leaks addr into helper function\n",
regno);
return -EACCES;
}
return 0;
}
if (type_is_pkt_pointer(type) &&
!may_access_direct_pkt_data(env, meta, BPF_READ)) {
verbose(env, "helper access to the packet is not allowed\n");
return -EACCES;
}
if (arg_type == ARG_PTR_TO_MAP_KEY ||
arg_type == ARG_PTR_TO_MAP_VALUE) {
expected_type = PTR_TO_STACK;
if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE &&
type != expected_type)
goto err_type;
} else if (arg_type == ARG_CONST_SIZE ||
arg_type == ARG_CONST_SIZE_OR_ZERO) {
expected_type = SCALAR_VALUE;
if (type != expected_type)
goto err_type;
} else if (arg_type == ARG_CONST_MAP_PTR) {
expected_type = CONST_PTR_TO_MAP;
if (type != expected_type)
goto err_type;
} else if (arg_type == ARG_PTR_TO_CTX) {
expected_type = PTR_TO_CTX;
if (type != expected_type)
goto err_type;
err = check_ctx_reg(env, reg, regno);
if (err < 0)
return err;
} else if (arg_type_is_mem_ptr(arg_type)) {
expected_type = PTR_TO_STACK;
/* One exception here. In case function allows for NULL to be
* passed in as argument, it's a SCALAR_VALUE type. Final test
* happens during stack boundary checking.
*/
if (register_is_null(reg) &&
arg_type == ARG_PTR_TO_MEM_OR_NULL)
/* final test in check_stack_boundary() */;
else if (!type_is_pkt_pointer(type) &&
type != PTR_TO_MAP_VALUE &&
type != expected_type)
goto err_type;
meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
} else {
verbose(env, "unsupported arg_type %d\n", arg_type);
return -EFAULT;
}
if (arg_type == ARG_CONST_MAP_PTR) {
/* bpf_map_xxx(map_ptr) call: remember that map_ptr */
meta->map_ptr = reg->map_ptr;
} else if (arg_type == ARG_PTR_TO_MAP_KEY) {
/* bpf_map_xxx(..., map_ptr, ..., key) call:
* check that [key, key + map->key_size) are within
* stack limits and initialized
*/
if (!meta->map_ptr) {
/* in function declaration map_ptr must come before
* map_key, so that it's verified and known before
* we have to check map_key here. Otherwise it means
* that kernel subsystem misconfigured verifier
*/
verbose(env, "invalid map_ptr to access map->key\n");
return -EACCES;
}
err = check_helper_mem_access(env, regno,
meta->map_ptr->key_size, false,
NULL);
} else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
/* bpf_map_xxx(..., map_ptr, ..., value) call:
* check [value, value + map->value_size) validity
*/
if (!meta->map_ptr) {
/* kernel subsystem misconfigured verifier */
verbose(env, "invalid map_ptr to access map->value\n");
return -EACCES;
}
err = check_helper_mem_access(env, regno,
meta->map_ptr->value_size, false,
NULL);
} else if (arg_type_is_mem_size(arg_type)) {
bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
/* remember the mem_size which may be used later
* to refine return values.
*/
meta->msize_smax_value = reg->smax_value;
meta->msize_umax_value = reg->umax_value;
/* The register is SCALAR_VALUE; the access check
* happens using its boundaries.
*/
if (!tnum_is_const(reg->var_off))
/* For unprivileged variable accesses, disable raw
* mode so that the program is required to
* initialize all the memory that the helper could
* just partially fill up.
*/
meta = NULL;
if (reg->smin_value < 0) {
verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
regno);
return -EACCES;
}
if (reg->umin_value == 0) {
err = check_helper_mem_access(env, regno - 1, 0,
zero_size_allowed,
meta);
if (err)
return err;
}
if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
regno);
return -EACCES;
}
err = check_helper_mem_access(env, regno - 1,
reg->umax_value,
zero_size_allowed, meta);
}
return err;
err_type:
verbose(env, "R%d type=%s expected=%s\n", regno,
reg_type_str[type], reg_type_str[expected_type]);
return -EACCES;
}
static int check_map_func_compatibility(struct bpf_verifier_env *env,
struct bpf_map *map, int func_id)
{
if (!map)
return 0;
/* We need a two way check, first is from map perspective ... */
switch (map->map_type) {
case BPF_MAP_TYPE_PROG_ARRAY:
if (func_id != BPF_FUNC_tail_call)
goto error;
break;
case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
if (func_id != BPF_FUNC_perf_event_read &&
func_id != BPF_FUNC_perf_event_output &&
func_id != BPF_FUNC_perf_event_read_value)
goto error;
break;
case BPF_MAP_TYPE_STACK_TRACE:
if (func_id != BPF_FUNC_get_stackid)
goto error;
break;
case BPF_MAP_TYPE_CGROUP_ARRAY:
if (func_id != BPF_FUNC_skb_under_cgroup &&
func_id != BPF_FUNC_current_task_under_cgroup)
goto error;
break;
case BPF_MAP_TYPE_CGROUP_STORAGE:
if (func_id != BPF_FUNC_get_local_storage)
goto error;
break;
/* devmap returns a pointer to a live net_device ifindex that we cannot
* allow to be modified from bpf side. So do not allow lookup elements
* for now.
*/
case BPF_MAP_TYPE_DEVMAP:
if (func_id != BPF_FUNC_redirect_map)
goto error;
break;
/* Restrict bpf side of cpumap and xskmap, open when use-cases
* appear.
*/
case BPF_MAP_TYPE_CPUMAP:
case BPF_MAP_TYPE_XSKMAP:
if (func_id != BPF_FUNC_redirect_map)
goto error;
break;
case BPF_MAP_TYPE_ARRAY_OF_MAPS:
case BPF_MAP_TYPE_HASH_OF_MAPS:
if (func_id != BPF_FUNC_map_lookup_elem)
goto error;
break;
case BPF_MAP_TYPE_SOCKMAP:
if (func_id != BPF_FUNC_sk_redirect_map &&
func_id != BPF_FUNC_sock_map_update &&
func_id != BPF_FUNC_map_delete_elem &&
func_id != BPF_FUNC_msg_redirect_map)
goto error;
break;
case BPF_MAP_TYPE_SOCKHASH:
if (func_id != BPF_FUNC_sk_redirect_hash &&
func_id != BPF_FUNC_sock_hash_update &&
func_id != BPF_FUNC_map_delete_elem &&
func_id != BPF_FUNC_msg_redirect_hash)
goto error;
break;
case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
if (func_id != BPF_FUNC_sk_select_reuseport)
goto error;
break;
default:
break;
}
/* ... and second from the function itself. */
switch (func_id) {
case BPF_FUNC_tail_call:
if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
goto error;
if (env->subprog_cnt > 1) {
verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
return -EINVAL;
}
break;
case BPF_FUNC_perf_event_read:
case BPF_FUNC_perf_event_output:
case BPF_FUNC_perf_event_read_value:
if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
goto error;
break;
case BPF_FUNC_get_stackid:
if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
goto error;
break;
case BPF_FUNC_current_task_under_cgroup:
case BPF_FUNC_skb_under_cgroup:
if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
goto error;
break;
case BPF_FUNC_redirect_map:
if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
map->map_type != BPF_MAP_TYPE_CPUMAP &&
map->map_type != BPF_MAP_TYPE_XSKMAP)
goto error;
break;
case BPF_FUNC_sk_redirect_map:
case BPF_FUNC_msg_redirect_map:
case BPF_FUNC_sock_map_update:
if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
goto error;
break;
case BPF_FUNC_sk_redirect_hash:
case BPF_FUNC_msg_redirect_hash:
case BPF_FUNC_sock_hash_update:
if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
goto error;
break;
case BPF_FUNC_get_local_storage:
if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE)
goto error;
break;
case BPF_FUNC_sk_select_reuseport:
if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY)
goto error;
break;
default:
break;
}
return 0;
error:
verbose(env, "cannot pass map_type %d into func %s#%d\n",
map->map_type, func_id_name(func_id), func_id);
return -EINVAL;
}
static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
{
int count = 0;
if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
count++;
if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
count++;
/* We only support one arg being in raw mode at the moment,
* which is sufficient for the helper functions we have
* right now.
*/
return count <= 1;
}
static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
enum bpf_arg_type arg_next)
{
return (arg_type_is_mem_ptr(arg_curr) &&
!arg_type_is_mem_size(arg_next)) ||
(!arg_type_is_mem_ptr(arg_curr) &&
arg_type_is_mem_size(arg_next));
}
static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
{
/* bpf_xxx(..., buf, len) call will access 'len'
* bytes from memory 'buf'. Both arg types need
* to be paired, so make sure there's no buggy
* helper function specification.
*/
if (arg_type_is_mem_size(fn->arg1_type) ||
arg_type_is_mem_ptr(fn->arg5_type) ||
check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
return false;
return true;
}
static int check_func_proto(const struct bpf_func_proto *fn)
{
return check_raw_mode_ok(fn) &&
check_arg_pair_ok(fn) ? 0 : -EINVAL;
}
/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
* are now invalid, so turn them into unknown SCALAR_VALUE.
*/
static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
struct bpf_func_state *state)
{
struct bpf_reg_state *regs = state->regs, *reg;
int i;
for (i = 0; i < MAX_BPF_REG; i++)
if (reg_is_pkt_pointer_any(®s[i]))
mark_reg_unknown(env, regs, i);
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
reg = &state->stack[i].spilled_ptr;
if (reg_is_pkt_pointer_any(reg))
__mark_reg_unknown(reg);
}
}
static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
{
struct bpf_verifier_state *vstate = env->cur_state;
int i;
for (i = 0; i <= vstate->curframe; i++)
__clear_all_pkt_pointers(env, vstate->frame[i]);
}
static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
int *insn_idx)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_func_state *caller, *callee;
int i, subprog, target_insn;
if (state->curframe + 1 >= MAX_CALL_FRAMES) {
verbose(env, "the call stack of %d frames is too deep\n",
state->curframe + 2);
return -E2BIG;
}
target_insn = *insn_idx + insn->imm;
subprog = find_subprog(env, target_insn + 1);
if (subprog < 0) {
verbose(env, "verifier bug. No program starts at insn %d\n",
target_insn + 1);
return -EFAULT;
}
caller = state->frame[state->curframe];
if (state->frame[state->curframe + 1]) {
verbose(env, "verifier bug. Frame %d already allocated\n",
state->curframe + 1);
return -EFAULT;
}
callee = kzalloc(sizeof(*callee), GFP_KERNEL);
if (!callee)
return -ENOMEM;
state->frame[state->curframe + 1] = callee;
/* callee cannot access r0, r6 - r9 for reading and has to write
* into its own stack before reading from it.
* callee can read/write into caller's stack
*/
init_func_state(env, callee,
/* remember the callsite, it will be used by bpf_exit */
*insn_idx /* callsite */,
state->curframe + 1 /* frameno within this callchain */,
subprog /* subprog number within this prog */);
/* copy r1 - r5 args that callee can access */
for (i = BPF_REG_1; i <= BPF_REG_5; i++)
callee->regs[i] = caller->regs[i];
/* after the call regsiters r0 - r5 were scratched */
for (i = 0; i < CALLER_SAVED_REGS; i++) {
mark_reg_not_init(env, caller->regs, caller_saved[i]);
check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
}
/* only increment it after check_reg_arg() finished */
state->curframe++;
/* and go analyze first insn of the callee */
*insn_idx = target_insn;
if (env->log.level) {
verbose(env, "caller:\n");
print_verifier_state(env, caller);
verbose(env, "callee:\n");
print_verifier_state(env, callee);
}
return 0;
}
static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_func_state *caller, *callee;
struct bpf_reg_state *r0;
callee = state->frame[state->curframe];
r0 = &callee->regs[BPF_REG_0];
if (r0->type == PTR_TO_STACK) {
/* technically it's ok to return caller's stack pointer
* (or caller's caller's pointer) back to the caller,
* since these pointers are valid. Only current stack
* pointer will be invalid as soon as function exits,
* but let's be conservative
*/
verbose(env, "cannot return stack pointer to the caller\n");
return -EINVAL;
}
state->curframe--;
caller = state->frame[state->curframe];
/* return to the caller whatever r0 had in the callee */
caller->regs[BPF_REG_0] = *r0;
*insn_idx = callee->callsite + 1;
if (env->log.level) {
verbose(env, "returning from callee:\n");
print_verifier_state(env, callee);
verbose(env, "to caller at %d:\n", *insn_idx);
print_verifier_state(env, caller);
}
/* clear everything in the callee */
free_func_state(callee);
state->frame[state->curframe + 1] = NULL;
return 0;
}
static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
int func_id,
struct bpf_call_arg_meta *meta)
{
struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
if (ret_type != RET_INTEGER ||
(func_id != BPF_FUNC_get_stack &&
func_id != BPF_FUNC_probe_read_str))
return;
ret_reg->smax_value = meta->msize_smax_value;
ret_reg->umax_value = meta->msize_umax_value;
__reg_deduce_bounds(ret_reg);
__reg_bound_offset(ret_reg);
}
static int
record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
int func_id, int insn_idx)
{
struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
if (func_id != BPF_FUNC_tail_call &&
func_id != BPF_FUNC_map_lookup_elem &&
func_id != BPF_FUNC_map_update_elem &&
func_id != BPF_FUNC_map_delete_elem)
return 0;
if (meta->map_ptr == NULL) {
verbose(env, "kernel subsystem misconfigured verifier\n");
return -EINVAL;
}
if (!BPF_MAP_PTR(aux->map_state))
bpf_map_ptr_store(aux, meta->map_ptr,
meta->map_ptr->unpriv_array);
else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr)
bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
meta->map_ptr->unpriv_array);
return 0;
}
static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
{
const struct bpf_func_proto *fn = NULL;
struct bpf_reg_state *regs;
struct bpf_call_arg_meta meta;
bool changes_data;
int i, err;
/* find function prototype */
if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
func_id);
return -EINVAL;
}
if (env->ops->get_func_proto)
fn = env->ops->get_func_proto(func_id, env->prog);
if (!fn) {
verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
func_id);
return -EINVAL;
}
/* eBPF programs must be GPL compatible to use GPL-ed functions */
if (!env->prog->gpl_compatible && fn->gpl_only) {
verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
return -EINVAL;
}
/* With LD_ABS/IND some JITs save/restore skb from r1. */
changes_data = bpf_helper_changes_pkt_data(fn->func);
if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
func_id_name(func_id), func_id);
return -EINVAL;
}
memset(&meta, 0, sizeof(meta));
meta.pkt_access = fn->pkt_access;
err = check_func_proto(fn);
if (err) {
verbose(env, "kernel subsystem misconfigured func %s#%d\n",
func_id_name(func_id), func_id);
return err;
}
/* check args */
err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
if (err)
return err;
err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
if (err)
return err;
err = record_func_map(env, &meta, func_id, insn_idx);
if (err)
return err;
/* Mark slots with STACK_MISC in case of raw mode, stack offset
* is inferred from register state.
*/
for (i = 0; i < meta.access_size; i++) {
err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
BPF_WRITE, -1, false);
if (err)
return err;
}
regs = cur_regs(env);
/* check that flags argument in get_local_storage(map, flags) is 0,
* this is required because get_local_storage() can't return an error.
*/
if (func_id == BPF_FUNC_get_local_storage &&
!register_is_null(®s[BPF_REG_2])) {
verbose(env, "get_local_storage() doesn't support non-zero flags\n");
return -EINVAL;
}
/* reset caller saved regs */
for (i = 0; i < CALLER_SAVED_REGS; i++) {
mark_reg_not_init(env, regs, caller_saved[i]);
check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
}
/* update return register (already marked as written above) */
if (fn->ret_type == RET_INTEGER) {
/* sets type to SCALAR_VALUE */
mark_reg_unknown(env, regs, BPF_REG_0);
} else if (fn->ret_type == RET_VOID) {
regs[BPF_REG_0].type = NOT_INIT;
} else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
fn->ret_type == RET_PTR_TO_MAP_VALUE) {
if (fn->ret_type == RET_PTR_TO_MAP_VALUE)
regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
else
regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
/* There is no offset yet applied, variable or fixed */
mark_reg_known_zero(env, regs, BPF_REG_0);
regs[BPF_REG_0].off = 0;
/* remember map_ptr, so that check_map_access()
* can check 'value_size' boundary of memory access
* to map element returned from bpf_map_lookup_elem()
*/
if (meta.map_ptr == NULL) {
verbose(env,
"kernel subsystem misconfigured verifier\n");
return -EINVAL;
}
regs[BPF_REG_0].map_ptr = meta.map_ptr;
regs[BPF_REG_0].id = ++env->id_gen;
} else {
verbose(env, "unknown return type %d of func %s#%d\n",
fn->ret_type, func_id_name(func_id), func_id);
return -EINVAL;
}
do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
err = check_map_func_compatibility(env, meta.map_ptr, func_id);
if (err)
return err;
if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
const char *err_str;
#ifdef CONFIG_PERF_EVENTS
err = get_callchain_buffers(sysctl_perf_event_max_stack);
err_str = "cannot get callchain buffer for func %s#%d\n";
#else
err = -ENOTSUPP;
err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
#endif
if (err) {
verbose(env, err_str, func_id_name(func_id), func_id);
return err;
}
env->prog->has_callchain_buf = true;
}
if (changes_data)
clear_all_pkt_pointers(env);
return 0;
}
static bool signed_add_overflows(s64 a, s64 b)
{
/* Do the add in u64, where overflow is well-defined */
s64 res = (s64)((u64)a + (u64)b);
if (b < 0)
return res > a;
return res < a;
}
static bool signed_sub_overflows(s64 a, s64 b)
{
/* Do the sub in u64, where overflow is well-defined */
s64 res = (s64)((u64)a - (u64)b);
if (b < 0)
return res < a;
return res > a;
}
static bool check_reg_sane_offset(struct bpf_verifier_env *env,
const struct bpf_reg_state *reg,
enum bpf_reg_type type)
{
bool known = tnum_is_const(reg->var_off);
s64 val = reg->var_off.value;
s64 smin = reg->smin_value;
if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
verbose(env, "math between %s pointer and %lld is not allowed\n",
reg_type_str[type], val);
return false;
}
if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
verbose(env, "%s pointer offset %d is not allowed\n",
reg_type_str[type], reg->off);
return false;
}
if (smin == S64_MIN) {
verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
reg_type_str[type]);
return false;
}
if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
verbose(env, "value %lld makes %s pointer be out of bounds\n",
smin, reg_type_str[type]);
return false;
}
return true;
}
/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
* Caller should also handle BPF_MOV case separately.
* If we return -EACCES, caller may want to try again treating pointer as a
* scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
*/
static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
const struct bpf_reg_state *ptr_reg,
const struct bpf_reg_state *off_reg)
{
struct bpf_verifier_state *vstate = env->cur_state;
struct bpf_func_state *state = vstate->frame[vstate->curframe];
struct bpf_reg_state *regs = state->regs, *dst_reg;
bool known = tnum_is_const(off_reg->var_off);
s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
u8 opcode = BPF_OP(insn->code);
u32 dst = insn->dst_reg;
dst_reg = ®s[dst];
if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
smin_val > smax_val || umin_val > umax_val) {
/* Taint dst register if offset had invalid bounds derived from
* e.g. dead branches.
*/
__mark_reg_unknown(dst_reg);
return 0;
}
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops on pointers produce (meaningless) scalars */
verbose(env,
"R%d 32-bit pointer arithmetic prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
dst);
return -EACCES;
}
if (ptr_reg->type == CONST_PTR_TO_MAP) {
verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
dst);
return -EACCES;
}
if (ptr_reg->type == PTR_TO_PACKET_END) {
verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
dst);
return -EACCES;
}
/* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
* The id may be overwritten later if we create a new variable offset.
*/
dst_reg->type = ptr_reg->type;
dst_reg->id = ptr_reg->id;
if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
!check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
return -EINVAL;
switch (opcode) {
case BPF_ADD:
/* We can take a fixed offset as long as it doesn't overflow
* the s32 'off' field
*/
if (known && (ptr_reg->off + smin_val ==
(s64)(s32)(ptr_reg->off + smin_val))) {
/* pointer += K. Accumulate it into fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->off = ptr_reg->off + smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. Note that off_reg->off
* == 0, since it's a scalar.
* dst_reg gets the pointer type and since some positive
* integer value was added to the pointer, give it a new 'id'
* if it's a PTR_TO_PACKET.
* this creates a new 'base' pointer, off_reg (variable) gets
* added into the variable offset, and we copy the fixed offset
* from ptr_reg.
*/
if (signed_add_overflows(smin_ptr, smin_val) ||
signed_add_overflows(smax_ptr, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr + smin_val;
dst_reg->smax_value = smax_ptr + smax_val;
}
if (umin_ptr + umin_val < umin_ptr ||
umax_ptr + umax_val < umax_ptr) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value = umin_ptr + umin_val;
dst_reg->umax_value = umax_ptr + umax_val;
}
dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
dst_reg->range = 0;
}
break;
case BPF_SUB:
if (dst_reg == off_reg) {
/* scalar -= pointer. Creates an unknown scalar */
verbose(env, "R%d tried to subtract pointer from scalar\n",
dst);
return -EACCES;
}
/* We don't allow subtraction from FP, because (according to
* test_verifier.c test "invalid fp arithmetic", JITs might not
* be able to deal with it.
*/
if (ptr_reg->type == PTR_TO_STACK) {
verbose(env, "R%d subtraction from stack pointer prohibited\n",
dst);
return -EACCES;
}
if (known && (ptr_reg->off - smin_val ==
(s64)(s32)(ptr_reg->off - smin_val))) {
/* pointer -= K. Subtract it from fixed offset */
dst_reg->smin_value = smin_ptr;
dst_reg->smax_value = smax_ptr;
dst_reg->umin_value = umin_ptr;
dst_reg->umax_value = umax_ptr;
dst_reg->var_off = ptr_reg->var_off;
dst_reg->id = ptr_reg->id;
dst_reg->off = ptr_reg->off - smin_val;
dst_reg->range = ptr_reg->range;
break;
}
/* A new variable offset is created. If the subtrahend is known
* nonnegative, then any reg->range we had before is still good.
*/
if (signed_sub_overflows(smin_ptr, smax_val) ||
signed_sub_overflows(smax_ptr, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = smin_ptr - smax_val;
dst_reg->smax_value = smax_ptr - smin_val;
}
if (umin_ptr < umax_val) {
/* Overflow possible, we know nothing */
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
/* Cannot overflow (as long as bounds are consistent) */
dst_reg->umin_value = umin_ptr - umax_val;
dst_reg->umax_value = umax_ptr - umin_val;
}
dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
dst_reg->off = ptr_reg->off;
if (reg_is_pkt_pointer(ptr_reg)) {
dst_reg->id = ++env->id_gen;
/* something was added to pkt_ptr, set range to zero */
if (smin_val < 0)
dst_reg->range = 0;
}
break;
case BPF_AND:
case BPF_OR:
case BPF_XOR:
/* bitwise ops on pointers are troublesome, prohibit. */
verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
default:
/* other operators (e.g. MUL,LSH) produce non-pointer results */
verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
dst, bpf_alu_string[opcode >> 4]);
return -EACCES;
}
if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
return -EINVAL;
__update_reg_bounds(dst_reg);
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
}
/* WARNING: This function does calculations on 64-bit values, but the actual
* execution may occur on 32-bit values. Therefore, things like bitshifts
* need extra checks in the 32-bit case.
*/
static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn,
struct bpf_reg_state *dst_reg,
struct bpf_reg_state src_reg)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
bool src_known, dst_known;
s64 smin_val, smax_val;
u64 umin_val, umax_val;
u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
if (insn_bitness == 32) {
/* Relevant for 32-bit RSH: Information can propagate towards
* LSB, so it isn't sufficient to only truncate the output to
* 32 bits.
*/
coerce_reg_to_size(dst_reg, 4);
coerce_reg_to_size(&src_reg, 4);
}
smin_val = src_reg.smin_value;
smax_val = src_reg.smax_value;
umin_val = src_reg.umin_value;
umax_val = src_reg.umax_value;
src_known = tnum_is_const(src_reg.var_off);
dst_known = tnum_is_const(dst_reg->var_off);
if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
smin_val > smax_val || umin_val > umax_val) {
/* Taint dst register if offset had invalid bounds derived from
* e.g. dead branches.
*/
__mark_reg_unknown(dst_reg);
return 0;
}
if (!src_known &&
opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
__mark_reg_unknown(dst_reg);
return 0;
}
switch (opcode) {
case BPF_ADD:
if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
signed_add_overflows(dst_reg->smax_value, smax_val)) {
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value += smin_val;
dst_reg->smax_value += smax_val;
}
if (dst_reg->umin_value + umin_val < umin_val ||
dst_reg->umax_value + umax_val < umax_val) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value += umin_val;
dst_reg->umax_value += umax_val;
}
dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
break;
case BPF_SUB:
if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
signed_sub_overflows(dst_reg->smax_value, smin_val)) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value -= smax_val;
dst_reg->smax_value -= smin_val;
}
if (dst_reg->umin_value < umax_val) {
/* Overflow possible, we know nothing */
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
/* Cannot overflow (as long as bounds are consistent) */
dst_reg->umin_value -= umax_val;
dst_reg->umax_value -= umin_val;
}
dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
break;
case BPF_MUL:
dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
if (smin_val < 0 || dst_reg->smin_value < 0) {
/* Ain't nobody got time to multiply that sign */
__mark_reg_unbounded(dst_reg);
__update_reg_bounds(dst_reg);
break;
}
/* Both values are positive, so we can work with unsigned and
* copy the result to signed (unless it exceeds S64_MAX).
*/
if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
/* Potential overflow, we know nothing */
__mark_reg_unbounded(dst_reg);
/* (except what we can learn from the var_off) */
__update_reg_bounds(dst_reg);
break;
}
dst_reg->umin_value *= umin_val;
dst_reg->umax_value *= umax_val;
if (dst_reg->umax_value > S64_MAX) {
/* Overflow possible, we know nothing */
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
break;
case BPF_AND:
if (src_known && dst_known) {
__mark_reg_known(dst_reg, dst_reg->var_off.value &
src_reg.var_off.value);
break;
}
/* We get our minimum from the var_off, since that's inherently
* bitwise. Our maximum is the minimum of the operands' maxima.
*/
dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
dst_reg->umin_value = dst_reg->var_off.value;
dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
if (dst_reg->smin_value < 0 || smin_val < 0) {
/* Lose signed bounds when ANDing negative numbers,
* ain't nobody got time for that.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
/* ANDing two positives gives a positive, so safe to
* cast result into s64.
*/
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_OR:
if (src_known && dst_known) {
__mark_reg_known(dst_reg, dst_reg->var_off.value |
src_reg.var_off.value);
break;
}
/* We get our maximum from the var_off, and our minimum is the
* maximum of the operands' minima
*/
dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
dst_reg->umax_value = dst_reg->var_off.value |
dst_reg->var_off.mask;
if (dst_reg->smin_value < 0 || smin_val < 0) {
/* Lose signed bounds when ORing negative numbers,
* ain't nobody got time for that.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
} else {
/* ORing two positives gives a positive, so safe to
* cast result into s64.
*/
dst_reg->smin_value = dst_reg->umin_value;
dst_reg->smax_value = dst_reg->umax_value;
}
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_LSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* We lose all sign bit information (except what we can pick
* up from var_off)
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
/* If we might shift our top bit out, then we know nothing */
if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
} else {
dst_reg->umin_value <<= umin_val;
dst_reg->umax_value <<= umax_val;
}
dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_RSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* BPF_RSH is an unsigned shift. If the value in dst_reg might
* be negative, then either:
* 1) src_reg might be zero, so the sign bit of the result is
* unknown, so we lose our signed bounds
* 2) it's known negative, thus the unsigned bounds capture the
* signed bounds
* 3) the signed bounds cross zero, so they tell us nothing
* about the result
* If the value in dst_reg is known nonnegative, then again the
* unsigned bounts capture the signed bounds.
* Thus, in all cases it suffices to blow away our signed bounds
* and rely on inferring new ones from the unsigned bounds and
* var_off of the result.
*/
dst_reg->smin_value = S64_MIN;
dst_reg->smax_value = S64_MAX;
dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
dst_reg->umin_value >>= umax_val;
dst_reg->umax_value >>= umin_val;
/* We may learn something more from the var_off */
__update_reg_bounds(dst_reg);
break;
case BPF_ARSH:
if (umax_val >= insn_bitness) {
/* Shifts greater than 31 or 63 are undefined.
* This includes shifts by a negative number.
*/
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
/* Upon reaching here, src_known is true and
* umax_val is equal to umin_val.
*/
dst_reg->smin_value >>= umin_val;
dst_reg->smax_value >>= umin_val;
dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val);
/* blow away the dst_reg umin_value/umax_value and rely on
* dst_reg var_off to refine the result.
*/
dst_reg->umin_value = 0;
dst_reg->umax_value = U64_MAX;
__update_reg_bounds(dst_reg);
break;
default:
mark_reg_unknown(env, regs, insn->dst_reg);
break;
}
if (BPF_CLASS(insn->code) != BPF_ALU64) {
/* 32-bit ALU ops are (32,32)->32 */
coerce_reg_to_size(dst_reg, 4);
}
__reg_deduce_bounds(dst_reg);
__reg_bound_offset(dst_reg);
return 0;
}
/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
* and var_off.
*/
static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
struct bpf_insn *insn)
{
struct bpf_verifier_state *vstate = env->cur_state;
struct bpf_func_state *state = vstate->frame[vstate->curframe];
struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
u8 opcode = BPF_OP(insn->code);
dst_reg = ®s[insn->dst_reg];
src_reg = NULL;
if (dst_reg->type != SCALAR_VALUE)
ptr_reg = dst_reg;
if (BPF_SRC(insn->code) == BPF_X) {
src_reg = ®s[insn->src_reg];
if (src_reg->type != SCALAR_VALUE) {
if (dst_reg->type != SCALAR_VALUE) {
/* Combining two pointers by any ALU op yields
* an arbitrary scalar. Disallow all math except
* pointer subtraction
*/
if (opcode == BPF_SUB && env->allow_ptr_leaks) {
mark_reg_unknown(env, regs, insn->dst_reg);
return 0;
}
verbose(env, "R%d pointer %s pointer prohibited\n",
insn->dst_reg,
bpf_alu_string[opcode >> 4]);
return -EACCES;
} else {
/* scalar += pointer
* This is legal, but we have to reverse our
* src/dest handling in computing the range
*/
return adjust_ptr_min_max_vals(env, insn,
src_reg, dst_reg);
}
} else if (ptr_reg) {
/* pointer += scalar */
return adjust_ptr_min_max_vals(env, insn,
dst_reg, src_reg);
}
} else {
/* Pretend the src is a reg with a known value, since we only
* need to be able to read from this state.
*/
off_reg.type = SCALAR_VALUE;
__mark_reg_known(&off_reg, insn->imm);
src_reg = &off_reg;
if (ptr_reg) /* pointer += K */
return adjust_ptr_min_max_vals(env, insn,
ptr_reg, src_reg);
}
/* Got here implies adding two SCALAR_VALUEs */
if (WARN_ON_ONCE(ptr_reg)) {
print_verifier_state(env, state);
verbose(env, "verifier internal error: unexpected ptr_reg\n");
return -EINVAL;
}
if (WARN_ON(!src_reg)) {
print_verifier_state(env, state);
verbose(env, "verifier internal error: no src_reg\n");
return -EINVAL;
}
return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
}
/* check validity of 32-bit and 64-bit arithmetic operations */
static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode == BPF_END || opcode == BPF_NEG) {
if (opcode == BPF_NEG) {
if (BPF_SRC(insn->code) != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->off != 0 || insn->imm != 0) {
verbose(env, "BPF_NEG uses reserved fields\n");
return -EINVAL;
}
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
(insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
BPF_CLASS(insn->code) == BPF_ALU64) {
verbose(env, "BPF_END uses reserved fields\n");
return -EINVAL;
}
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer arithmetic prohibited\n",
insn->dst_reg);
return -EACCES;
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
} else if (opcode == BPF_MOV) {
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
}
/* check dest operand, mark as required later */
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
if (BPF_SRC(insn->code) == BPF_X) {
if (BPF_CLASS(insn->code) == BPF_ALU64) {
/* case: R1 = R2
* copy register state to dest reg
*/
regs[insn->dst_reg] = regs[insn->src_reg];
regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
} else {
/* R1 = (u32) R2 */
if (is_pointer_value(env, insn->src_reg)) {
verbose(env,
"R%d partial copy of pointer\n",
insn->src_reg);
return -EACCES;
}
mark_reg_unknown(env, regs, insn->dst_reg);
coerce_reg_to_size(®s[insn->dst_reg], 4);
}
} else {
/* case: R = imm
* remember the value we stored into this reg
*/
/* clear any state __mark_reg_known doesn't set */
mark_reg_unknown(env, regs, insn->dst_reg);
regs[insn->dst_reg].type = SCALAR_VALUE;
if (BPF_CLASS(insn->code) == BPF_ALU64) {
__mark_reg_known(regs + insn->dst_reg,
insn->imm);
} else {
__mark_reg_known(regs + insn->dst_reg,
(u32)insn->imm);
}
}
} else if (opcode > BPF_END) {
verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
return -EINVAL;
} else { /* all other ALU ops: and, sub, xor, add, ... */
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
verbose(env, "div by zero\n");
return -EINVAL;
}
if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
verbose(env, "BPF_ARSH not supported for 32 bit ALU\n");
return -EINVAL;
}
if ((opcode == BPF_LSH || opcode == BPF_RSH ||
opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
if (insn->imm < 0 || insn->imm >= size) {
verbose(env, "invalid shift %d\n", insn->imm);
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
return adjust_reg_min_max_vals(env, insn);
}
return 0;
}
static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
struct bpf_reg_state *dst_reg,
enum bpf_reg_type type,
bool range_right_open)
{
struct bpf_func_state *state = vstate->frame[vstate->curframe];
struct bpf_reg_state *regs = state->regs, *reg;
u16 new_range;
int i, j;
if (dst_reg->off < 0 ||
(dst_reg->off == 0 && range_right_open))
/* This doesn't give us any range */
return;
if (dst_reg->umax_value > MAX_PACKET_OFF ||
dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
/* Risk of overflow. For instance, ptr + (1<<63) may be less
* than pkt_end, but that's because it's also less than pkt.
*/
return;
new_range = dst_reg->off;
if (range_right_open)
new_range--;
/* Examples for register markings:
*
* pkt_data in dst register:
*
* r2 = r3;
* r2 += 8;
* if (r2 > pkt_end) goto <handle exception>
* <access okay>
*
* r2 = r3;
* r2 += 8;
* if (r2 < pkt_end) goto <access okay>
* <handle exception>
*
* Where:
* r2 == dst_reg, pkt_end == src_reg
* r2=pkt(id=n,off=8,r=0)
* r3=pkt(id=n,off=0,r=0)
*
* pkt_data in src register:
*
* r2 = r3;
* r2 += 8;
* if (pkt_end >= r2) goto <access okay>
* <handle exception>
*
* r2 = r3;
* r2 += 8;
* if (pkt_end <= r2) goto <handle exception>
* <access okay>
*
* Where:
* pkt_end == dst_reg, r2 == src_reg
* r2=pkt(id=n,off=8,r=0)
* r3=pkt(id=n,off=0,r=0)
*
* Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
* or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
* and [r3, r3 + 8-1) respectively is safe to access depending on
* the check.
*/
/* If our ids match, then we must have the same max_value. And we
* don't care about the other reg's fixed offset, since if it's too big
* the range won't allow anything.
* dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
*/
for (i = 0; i < MAX_BPF_REG; i++)
if (regs[i].type == type && regs[i].id == dst_reg->id)
/* keep the maximum range already checked */
regs[i].range = max(regs[i].range, new_range);
for (j = 0; j <= vstate->curframe; j++) {
state = vstate->frame[j];
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
reg = &state->stack[i].spilled_ptr;
if (reg->type == type && reg->id == dst_reg->id)
reg->range = max(reg->range, new_range);
}
}
}
/* Adjusts the register min/max values in the case that the dst_reg is the
* variable register that we are working on, and src_reg is a constant or we're
* simply doing a BPF_K check.
* In JEQ/JNE cases we also adjust the var_off values.
*/
static void reg_set_min_max(struct bpf_reg_state *true_reg,
struct bpf_reg_state *false_reg, u64 val,
u8 opcode)
{
/* If the dst_reg is a pointer, we can't learn anything about its
* variable offset from the compare (unless src_reg were a pointer into
* the same object, but we don't bother with that.
* Since false_reg and true_reg have the same type by construction, we
* only need to check one of them for pointerness.
*/
if (__is_pointer_value(false, false_reg))
return;
switch (opcode) {
case BPF_JEQ:
/* If this is false then we know nothing Jon Snow, but if it is
* true then we know for sure.
*/
__mark_reg_known(true_reg, val);
break;
case BPF_JNE:
/* If this is true we know nothing Jon Snow, but if it is false
* we know the value for sure;
*/
__mark_reg_known(false_reg, val);
break;
case BPF_JGT:
false_reg->umax_value = min(false_reg->umax_value, val);
true_reg->umin_value = max(true_reg->umin_value, val + 1);
break;
case BPF_JSGT:
false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
break;
case BPF_JLT:
false_reg->umin_value = max(false_reg->umin_value, val);
true_reg->umax_value = min(true_reg->umax_value, val - 1);
break;
case BPF_JSLT:
false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
break;
case BPF_JGE:
false_reg->umax_value = min(false_reg->umax_value, val - 1);
true_reg->umin_value = max(true_reg->umin_value, val);
break;
case BPF_JSGE:
false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
break;
case BPF_JLE:
false_reg->umin_value = max(false_reg->umin_value, val + 1);
true_reg->umax_value = min(true_reg->umax_value, val);
break;
case BPF_JSLE:
false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
break;
default:
break;
}
__reg_deduce_bounds(false_reg);
__reg_deduce_bounds(true_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(false_reg);
__reg_bound_offset(true_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(false_reg);
__update_reg_bounds(true_reg);
}
/* Same as above, but for the case that dst_reg holds a constant and src_reg is
* the variable reg.
*/
static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
struct bpf_reg_state *false_reg, u64 val,
u8 opcode)
{
if (__is_pointer_value(false, false_reg))
return;
switch (opcode) {
case BPF_JEQ:
/* If this is false then we know nothing Jon Snow, but if it is
* true then we know for sure.
*/
__mark_reg_known(true_reg, val);
break;
case BPF_JNE:
/* If this is true we know nothing Jon Snow, but if it is false
* we know the value for sure;
*/
__mark_reg_known(false_reg, val);
break;
case BPF_JGT:
true_reg->umax_value = min(true_reg->umax_value, val - 1);
false_reg->umin_value = max(false_reg->umin_value, val);
break;
case BPF_JSGT:
true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
break;
case BPF_JLT:
true_reg->umin_value = max(true_reg->umin_value, val + 1);
false_reg->umax_value = min(false_reg->umax_value, val);
break;
case BPF_JSLT:
true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
break;
case BPF_JGE:
true_reg->umax_value = min(true_reg->umax_value, val);
false_reg->umin_value = max(false_reg->umin_value, val + 1);
break;
case BPF_JSGE:
true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
break;
case BPF_JLE:
true_reg->umin_value = max(true_reg->umin_value, val);
false_reg->umax_value = min(false_reg->umax_value, val - 1);
break;
case BPF_JSLE:
true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
break;
default:
break;
}
__reg_deduce_bounds(false_reg);
__reg_deduce_bounds(true_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(false_reg);
__reg_bound_offset(true_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(false_reg);
__update_reg_bounds(true_reg);
}
/* Regs are known to be equal, so intersect their min/max/var_off */
static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
struct bpf_reg_state *dst_reg)
{
src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
dst_reg->umin_value);
src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
dst_reg->umax_value);
src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
dst_reg->smin_value);
src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
dst_reg->smax_value);
src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
dst_reg->var_off);
/* We might have learned new bounds from the var_off. */
__update_reg_bounds(src_reg);
__update_reg_bounds(dst_reg);
/* We might have learned something about the sign bit. */
__reg_deduce_bounds(src_reg);
__reg_deduce_bounds(dst_reg);
/* We might have learned some bits from the bounds. */
__reg_bound_offset(src_reg);
__reg_bound_offset(dst_reg);
/* Intersecting with the old var_off might have improved our bounds
* slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
* then new var_off is (0; 0x7f...fc) which improves our umax.
*/
__update_reg_bounds(src_reg);
__update_reg_bounds(dst_reg);
}
static void reg_combine_min_max(struct bpf_reg_state *true_src,
struct bpf_reg_state *true_dst,
struct bpf_reg_state *false_src,
struct bpf_reg_state *false_dst,
u8 opcode)
{
switch (opcode) {
case BPF_JEQ:
__reg_combine_min_max(true_src, true_dst);
break;
case BPF_JNE:
__reg_combine_min_max(false_src, false_dst);
break;
}
}
static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
bool is_null)
{
struct bpf_reg_state *reg = ®s[regno];
if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
/* Old offset (both fixed and variable parts) should
* have been known-zero, because we don't allow pointer
* arithmetic on pointers that might be NULL.
*/
if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
!tnum_equals_const(reg->var_off, 0) ||
reg->off)) {
__mark_reg_known_zero(reg);
reg->off = 0;
}
if (is_null) {
reg->type = SCALAR_VALUE;
} else if (reg->map_ptr->inner_map_meta) {
reg->type = CONST_PTR_TO_MAP;
reg->map_ptr = reg->map_ptr->inner_map_meta;
} else {
reg->type = PTR_TO_MAP_VALUE;
}
/* We don't need id from this point onwards anymore, thus we
* should better reset it, so that state pruning has chances
* to take effect.
*/
reg->id = 0;
}
}
/* The logic is similar to find_good_pkt_pointers(), both could eventually
* be folded together at some point.
*/
static void mark_map_regs(struct bpf_verifier_state *vstate, u32 regno,
bool is_null)
{
struct bpf_func_state *state = vstate->frame[vstate->curframe];
struct bpf_reg_state *regs = state->regs;
u32 id = regs[regno].id;
int i, j;
for (i = 0; i < MAX_BPF_REG; i++)
mark_map_reg(regs, i, id, is_null);
for (j = 0; j <= vstate->curframe; j++) {
state = vstate->frame[j];
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
}
}
}
static bool try_match_pkt_pointers(const struct bpf_insn *insn,
struct bpf_reg_state *dst_reg,
struct bpf_reg_state *src_reg,
struct bpf_verifier_state *this_branch,
struct bpf_verifier_state *other_branch)
{
if (BPF_SRC(insn->code) != BPF_X)
return false;
switch (BPF_OP(insn->code)) {
case BPF_JGT:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' > pkt_end, pkt_meta' > pkt_data */
find_good_pkt_pointers(this_branch, dst_reg,
dst_reg->type, false);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end > pkt_data', pkt_data > pkt_meta' */
find_good_pkt_pointers(other_branch, src_reg,
src_reg->type, true);
} else {
return false;
}
break;
case BPF_JLT:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' < pkt_end, pkt_meta' < pkt_data */
find_good_pkt_pointers(other_branch, dst_reg,
dst_reg->type, true);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end < pkt_data', pkt_data > pkt_meta' */
find_good_pkt_pointers(this_branch, src_reg,
src_reg->type, false);
} else {
return false;
}
break;
case BPF_JGE:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
find_good_pkt_pointers(this_branch, dst_reg,
dst_reg->type, true);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
find_good_pkt_pointers(other_branch, src_reg,
src_reg->type, false);
} else {
return false;
}
break;
case BPF_JLE:
if ((dst_reg->type == PTR_TO_PACKET &&
src_reg->type == PTR_TO_PACKET_END) ||
(dst_reg->type == PTR_TO_PACKET_META &&
reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
/* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
find_good_pkt_pointers(other_branch, dst_reg,
dst_reg->type, false);
} else if ((dst_reg->type == PTR_TO_PACKET_END &&
src_reg->type == PTR_TO_PACKET) ||
(reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
src_reg->type == PTR_TO_PACKET_META)) {
/* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
find_good_pkt_pointers(this_branch, src_reg,
src_reg->type, true);
} else {
return false;
}
break;
default:
return false;
}
return true;
}
static int check_cond_jmp_op(struct bpf_verifier_env *env,
struct bpf_insn *insn, int *insn_idx)
{
struct bpf_verifier_state *this_branch = env->cur_state;
struct bpf_verifier_state *other_branch;
struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
struct bpf_reg_state *dst_reg, *other_branch_regs;
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode > BPF_JSLE) {
verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
return -EINVAL;
}
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0) {
verbose(env, "BPF_JMP uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->src_reg)) {
verbose(env, "R%d pointer comparison prohibited\n",
insn->src_reg);
return -EACCES;
}
} else {
if (insn->src_reg != BPF_REG_0) {
verbose(env, "BPF_JMP uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
dst_reg = ®s[insn->dst_reg];
/* detect if R == 0 where R was initialized to zero earlier */
if (BPF_SRC(insn->code) == BPF_K &&
(opcode == BPF_JEQ || opcode == BPF_JNE) &&
dst_reg->type == SCALAR_VALUE &&
tnum_is_const(dst_reg->var_off)) {
if ((opcode == BPF_JEQ && dst_reg->var_off.value == insn->imm) ||
(opcode == BPF_JNE && dst_reg->var_off.value != insn->imm)) {
/* if (imm == imm) goto pc+off;
* only follow the goto, ignore fall-through
*/
*insn_idx += insn->off;
return 0;
} else {
/* if (imm != imm) goto pc+off;
* only follow fall-through branch, since
* that's where the program will go
*/
return 0;
}
}
other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
if (!other_branch)
return -EFAULT;
other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
/* detect if we are comparing against a constant value so we can adjust
* our min/max values for our dst register.
* this is only legit if both are scalars (or pointers to the same
* object, I suppose, but we don't support that right now), because
* otherwise the different base pointers mean the offsets aren't
* comparable.
*/
if (BPF_SRC(insn->code) == BPF_X) {
if (dst_reg->type == SCALAR_VALUE &&
regs[insn->src_reg].type == SCALAR_VALUE) {
if (tnum_is_const(regs[insn->src_reg].var_off))
reg_set_min_max(&other_branch_regs[insn->dst_reg],
dst_reg, regs[insn->src_reg].var_off.value,
opcode);
else if (tnum_is_const(dst_reg->var_off))
reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
®s[insn->src_reg],
dst_reg->var_off.value, opcode);
else if (opcode == BPF_JEQ || opcode == BPF_JNE)
/* Comparing for equality, we can combine knowledge */
reg_combine_min_max(&other_branch_regs[insn->src_reg],
&other_branch_regs[insn->dst_reg],
®s[insn->src_reg],
®s[insn->dst_reg], opcode);
}
} else if (dst_reg->type == SCALAR_VALUE) {
reg_set_min_max(&other_branch_regs[insn->dst_reg],
dst_reg, insn->imm, opcode);
}
/* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
if (BPF_SRC(insn->code) == BPF_K &&
insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
/* Mark all identical map registers in each branch as either
* safe or unknown depending R == 0 or R != 0 conditional.
*/
mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
} else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
this_branch, other_branch) &&
is_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer comparison prohibited\n",
insn->dst_reg);
return -EACCES;
}
if (env->log.level)
print_verifier_state(env, this_branch->frame[this_branch->curframe]);
return 0;
}
/* return the map pointer stored inside BPF_LD_IMM64 instruction */
static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
{
u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
return (struct bpf_map *) (unsigned long) imm64;
}
/* verify BPF_LD_IMM64 instruction */
static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
int err;
if (BPF_SIZE(insn->code) != BPF_DW) {
verbose(env, "invalid BPF_LD_IMM insn\n");
return -EINVAL;
}
if (insn->off != 0) {
verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
return -EINVAL;
}
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
if (insn->src_reg == 0) {
u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
regs[insn->dst_reg].type = SCALAR_VALUE;
__mark_reg_known(®s[insn->dst_reg], imm);
return 0;
}
/* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
return 0;
}
static bool may_access_skb(enum bpf_prog_type type)
{
switch (type) {
case BPF_PROG_TYPE_SOCKET_FILTER:
case BPF_PROG_TYPE_SCHED_CLS:
case BPF_PROG_TYPE_SCHED_ACT:
return true;
default:
return false;
}
}
/* verify safety of LD_ABS|LD_IND instructions:
* - they can only appear in the programs where ctx == skb
* - since they are wrappers of function calls, they scratch R1-R5 registers,
* preserve R6-R9, and store return value into R0
*
* Implicit input:
* ctx == skb == R6 == CTX
*
* Explicit input:
* SRC == any register
* IMM == 32-bit immediate
*
* Output:
* R0 - 8/16/32-bit skb data converted to cpu endianness
*/
static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 mode = BPF_MODE(insn->code);
int i, err;
if (!may_access_skb(env->prog->type)) {
verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
return -EINVAL;
}
if (!env->ops->gen_ld_abs) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
}
if (env->subprog_cnt > 1) {
/* when program has LD_ABS insn JITs and interpreter assume
* that r1 == ctx == skb which is not the case for callees
* that can have arbitrary arguments. It's problematic
* for main prog as well since JITs would need to analyze
* all functions in order to make proper register save/restore
* decisions in the main prog. Hence disallow LD_ABS with calls
*/
verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
return -EINVAL;
}
if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
BPF_SIZE(insn->code) == BPF_DW ||
(mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
return -EINVAL;
}
/* check whether implicit source operand (register R6) is readable */
err = check_reg_arg(env, BPF_REG_6, SRC_OP);
if (err)
return err;
if (regs[BPF_REG_6].type != PTR_TO_CTX) {
verbose(env,
"at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
return -EINVAL;
}
if (mode == BPF_IND) {
/* check explicit source operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
}
/* reset caller saved regs to unreadable */
for (i = 0; i < CALLER_SAVED_REGS; i++) {
mark_reg_not_init(env, regs, caller_saved[i]);
check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
}
/* mark destination R0 register as readable, since it contains
* the value fetched from the packet.
* Already marked as written above.
*/
mark_reg_unknown(env, regs, BPF_REG_0);
return 0;
}
static int check_return_code(struct bpf_verifier_env *env)
{
struct bpf_reg_state *reg;
struct tnum range = tnum_range(0, 1);
switch (env->prog->type) {
case BPF_PROG_TYPE_CGROUP_SKB:
case BPF_PROG_TYPE_CGROUP_SOCK:
case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
case BPF_PROG_TYPE_SOCK_OPS:
case BPF_PROG_TYPE_CGROUP_DEVICE:
break;
default:
return 0;
}
reg = cur_regs(env) + BPF_REG_0;
if (reg->type != SCALAR_VALUE) {
verbose(env, "At program exit the register R0 is not a known value (%s)\n",
reg_type_str[reg->type]);
return -EINVAL;
}
if (!tnum_in(range, reg->var_off)) {
verbose(env, "At program exit the register R0 ");
if (!tnum_is_unknown(reg->var_off)) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "has value %s", tn_buf);
} else {
verbose(env, "has unknown scalar value");
}
verbose(env, " should have been 0 or 1\n");
return -EINVAL;
}
return 0;
}
/* non-recursive DFS pseudo code
* 1 procedure DFS-iterative(G,v):
* 2 label v as discovered
* 3 let S be a stack
* 4 S.push(v)
* 5 while S is not empty
* 6 t <- S.pop()
* 7 if t is what we're looking for:
* 8 return t
* 9 for all edges e in G.adjacentEdges(t) do
* 10 if edge e is already labelled
* 11 continue with the next edge
* 12 w <- G.adjacentVertex(t,e)
* 13 if vertex w is not discovered and not explored
* 14 label e as tree-edge
* 15 label w as discovered
* 16 S.push(w)
* 17 continue at 5
* 18 else if vertex w is discovered
* 19 label e as back-edge
* 20 else
* 21 // vertex w is explored
* 22 label e as forward- or cross-edge
* 23 label t as explored
* 24 S.pop()
*
* convention:
* 0x10 - discovered
* 0x11 - discovered and fall-through edge labelled
* 0x12 - discovered and fall-through and branch edges labelled
* 0x20 - explored
*/
enum {
DISCOVERED = 0x10,
EXPLORED = 0x20,
FALLTHROUGH = 1,
BRANCH = 2,
};
#define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
static int *insn_stack; /* stack of insns to process */
static int cur_stack; /* current stack index */
static int *insn_state;
/* t, w, e - match pseudo-code above:
* t - index of current instruction
* w - next instruction
* e - edge
*/
static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
{
if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
return 0;
if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
return 0;
if (w < 0 || w >= env->prog->len) {
verbose(env, "jump out of range from insn %d to %d\n", t, w);
return -EINVAL;
}
if (e == BRANCH)
/* mark branch target for state pruning */
env->explored_states[w] = STATE_LIST_MARK;
if (insn_state[w] == 0) {
/* tree-edge */
insn_state[t] = DISCOVERED | e;
insn_state[w] = DISCOVERED;
if (cur_stack >= env->prog->len)
return -E2BIG;
insn_stack[cur_stack++] = w;
return 1;
} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
verbose(env, "back-edge from insn %d to %d\n", t, w);
return -EINVAL;
} else if (insn_state[w] == EXPLORED) {
/* forward- or cross-edge */
insn_state[t] = DISCOVERED | e;
} else {
verbose(env, "insn state internal bug\n");
return -EFAULT;
}
return 0;
}
/* non-recursive depth-first-search to detect loops in BPF program
* loop == back-edge in directed graph
*/
static int check_cfg(struct bpf_verifier_env *env)
{
struct bpf_insn *insns = env->prog->insnsi;
int insn_cnt = env->prog->len;
int ret = 0;
int i, t;
ret = check_subprogs(env);
if (ret < 0)
return ret;
insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
if (!insn_state)
return -ENOMEM;
insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
if (!insn_stack) {
kfree(insn_state);
return -ENOMEM;
}
insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
insn_stack[0] = 0; /* 0 is the first instruction */
cur_stack = 1;
peek_stack:
if (cur_stack == 0)
goto check_state;
t = insn_stack[cur_stack - 1];
if (BPF_CLASS(insns[t].code) == BPF_JMP) {
u8 opcode = BPF_OP(insns[t].code);
if (opcode == BPF_EXIT) {
goto mark_explored;
} else if (opcode == BPF_CALL) {
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
if (t + 1 < insn_cnt)
env->explored_states[t + 1] = STATE_LIST_MARK;
if (insns[t].src_reg == BPF_PSEUDO_CALL) {
env->explored_states[t] = STATE_LIST_MARK;
ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
}
} else if (opcode == BPF_JA) {
if (BPF_SRC(insns[t].code) != BPF_K) {
ret = -EINVAL;
goto err_free;
}
/* unconditional jump with single edge */
ret = push_insn(t, t + insns[t].off + 1,
FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
/* tell verifier to check for equivalent states
* after every call and jump
*/
if (t + 1 < insn_cnt)
env->explored_states[t + 1] = STATE_LIST_MARK;
} else {
/* conditional jump with two edges */
env->explored_states[t] = STATE_LIST_MARK;
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
}
} else {
/* all other non-branch instructions with single
* fall-through edge
*/
ret = push_insn(t, t + 1, FALLTHROUGH, env);
if (ret == 1)
goto peek_stack;
else if (ret < 0)
goto err_free;
}
mark_explored:
insn_state[t] = EXPLORED;
if (cur_stack-- <= 0) {
verbose(env, "pop stack internal bug\n");
ret = -EFAULT;
goto err_free;
}
goto peek_stack;
check_state:
for (i = 0; i < insn_cnt; i++) {
if (insn_state[i] != EXPLORED) {
verbose(env, "unreachable insn %d\n", i);
ret = -EINVAL;
goto err_free;
}
}
ret = 0; /* cfg looks good */
err_free:
kfree(insn_state);
kfree(insn_stack);
return ret;
}
/* check %cur's range satisfies %old's */
static bool range_within(struct bpf_reg_state *old,
struct bpf_reg_state *cur)
{
return old->umin_value <= cur->umin_value &&
old->umax_value >= cur->umax_value &&
old->smin_value <= cur->smin_value &&
old->smax_value >= cur->smax_value;
}
/* Maximum number of register states that can exist at once */
#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
struct idpair {
u32 old;
u32 cur;
};
/* If in the old state two registers had the same id, then they need to have
* the same id in the new state as well. But that id could be different from
* the old state, so we need to track the mapping from old to new ids.
* Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
* regs with old id 5 must also have new id 9 for the new state to be safe. But
* regs with a different old id could still have new id 9, we don't care about
* that.
* So we look through our idmap to see if this old id has been seen before. If
* so, we require the new id to match; otherwise, we add the id pair to the map.
*/
static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
{
unsigned int i;
for (i = 0; i < ID_MAP_SIZE; i++) {
if (!idmap[i].old) {
/* Reached an empty slot; haven't seen this id before */
idmap[i].old = old_id;
idmap[i].cur = cur_id;
return true;
}
if (idmap[i].old == old_id)
return idmap[i].cur == cur_id;
}
/* We ran out of idmap slots, which should be impossible */
WARN_ON_ONCE(1);
return false;
}
/* Returns true if (rold safe implies rcur safe) */
static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
struct idpair *idmap)
{
bool equal;
if (!(rold->live & REG_LIVE_READ))
/* explored state didn't use this */
return true;
equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, frameno)) == 0;
if (rold->type == PTR_TO_STACK)
/* two stack pointers are equal only if they're pointing to
* the same stack frame, since fp-8 in foo != fp-8 in bar
*/
return equal && rold->frameno == rcur->frameno;
if (equal)
return true;
if (rold->type == NOT_INIT)
/* explored state can't have used this */
return true;
if (rcur->type == NOT_INIT)
return false;
switch (rold->type) {
case SCALAR_VALUE:
if (rcur->type == SCALAR_VALUE) {
/* new val must satisfy old val knowledge */
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
} else {
/* We're trying to use a pointer in place of a scalar.
* Even if the scalar was unbounded, this could lead to
* pointer leaks because scalars are allowed to leak
* while pointers are not. We could make this safe in
* special cases if root is calling us, but it's
* probably not worth the hassle.
*/
return false;
}
case PTR_TO_MAP_VALUE:
/* If the new min/max/var_off satisfy the old ones and
* everything else matches, we are OK.
* We don't care about the 'id' value, because nothing
* uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
*/
return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_MAP_VALUE_OR_NULL:
/* a PTR_TO_MAP_VALUE could be safe to use as a
* PTR_TO_MAP_VALUE_OR_NULL into the same map.
* However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
* checked, doing so could have affected others with the same
* id, and we can't check for that because we lost the id when
* we converted to a PTR_TO_MAP_VALUE.
*/
if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
return false;
if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
return false;
/* Check our ids match any regs they're supposed to */
return check_ids(rold->id, rcur->id, idmap);
case PTR_TO_PACKET_META:
case PTR_TO_PACKET:
if (rcur->type != rold->type)
return false;
/* We must have at least as much range as the old ptr
* did, so that any accesses which were safe before are
* still safe. This is true even if old range < old off,
* since someone could have accessed through (ptr - k), or
* even done ptr -= k in a register, to get a safe access.
*/
if (rold->range > rcur->range)
return false;
/* If the offsets don't match, we can't trust our alignment;
* nor can we be sure that we won't fall out of range.
*/
if (rold->off != rcur->off)
return false;
/* id relations must be preserved */
if (rold->id && !check_ids(rold->id, rcur->id, idmap))
return false;
/* new val must satisfy old val knowledge */
return range_within(rold, rcur) &&
tnum_in(rold->var_off, rcur->var_off);
case PTR_TO_CTX:
case CONST_PTR_TO_MAP:
case PTR_TO_PACKET_END:
/* Only valid matches are exact, which memcmp() above
* would have accepted
*/
default:
/* Don't know what's going on, just say it's not safe */
return false;
}
/* Shouldn't get here; if we do, say it's not safe */
WARN_ON_ONCE(1);
return false;
}
static bool stacksafe(struct bpf_func_state *old,
struct bpf_func_state *cur,
struct idpair *idmap)
{
int i, spi;
/* if explored stack has more populated slots than current stack
* such stacks are not equivalent
*/
if (old->allocated_stack > cur->allocated_stack)
return false;
/* walk slots of the explored stack and ignore any additional
* slots in the current stack, since explored(safe) state
* didn't use them
*/
for (i = 0; i < old->allocated_stack; i++) {
spi = i / BPF_REG_SIZE;
if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ))
/* explored state didn't use this */
continue;
if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
continue;
/* if old state was safe with misc data in the stack
* it will be safe with zero-initialized stack.
* The opposite is not true
*/
if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
continue;
if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
cur->stack[spi].slot_type[i % BPF_REG_SIZE])
/* Ex: old explored (safe) state has STACK_SPILL in
* this stack slot, but current has has STACK_MISC ->
* this verifier states are not equivalent,
* return false to continue verification of this path
*/
return false;
if (i % BPF_REG_SIZE)
continue;
if (old->stack[spi].slot_type[0] != STACK_SPILL)
continue;
if (!regsafe(&old->stack[spi].spilled_ptr,
&cur->stack[spi].spilled_ptr,
idmap))
/* when explored and current stack slot are both storing
* spilled registers, check that stored pointers types
* are the same as well.
* Ex: explored safe path could have stored
* (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
* but current path has stored:
* (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
* such verifier states are not equivalent.
* return false to continue verification of this path
*/
return false;
}
return true;
}
/* compare two verifier states
*
* all states stored in state_list are known to be valid, since
* verifier reached 'bpf_exit' instruction through them
*
* this function is called when verifier exploring different branches of
* execution popped from the state stack. If it sees an old state that has
* more strict register state and more strict stack state then this execution
* branch doesn't need to be explored further, since verifier already
* concluded that more strict state leads to valid finish.
*
* Therefore two states are equivalent if register state is more conservative
* and explored stack state is more conservative than the current one.
* Example:
* explored current
* (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
* (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
*
* In other words if current stack state (one being explored) has more
* valid slots than old one that already passed validation, it means
* the verifier can stop exploring and conclude that current state is valid too
*
* Similarly with registers. If explored state has register type as invalid
* whereas register type in current state is meaningful, it means that
* the current state will reach 'bpf_exit' instruction safely
*/
static bool func_states_equal(struct bpf_func_state *old,
struct bpf_func_state *cur)
{
struct idpair *idmap;
bool ret = false;
int i;
idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
/* If we failed to allocate the idmap, just say it's not safe */
if (!idmap)
return false;
for (i = 0; i < MAX_BPF_REG; i++) {
if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
goto out_free;
}
if (!stacksafe(old, cur, idmap))
goto out_free;
ret = true;
out_free:
kfree(idmap);
return ret;
}
static bool states_equal(struct bpf_verifier_env *env,
struct bpf_verifier_state *old,
struct bpf_verifier_state *cur)
{
int i;
if (old->curframe != cur->curframe)
return false;
/* for states to be equal callsites have to be the same
* and all frame states need to be equivalent
*/
for (i = 0; i <= old->curframe; i++) {
if (old->frame[i]->callsite != cur->frame[i]->callsite)
return false;
if (!func_states_equal(old->frame[i], cur->frame[i]))
return false;
}
return true;
}
/* A write screens off any subsequent reads; but write marks come from the
* straight-line code between a state and its parent. When we arrive at an
* equivalent state (jump target or such) we didn't arrive by the straight-line
* code, so read marks in the state must propagate to the parent regardless
* of the state's write marks. That's what 'parent == state->parent' comparison
* in mark_reg_read() and mark_stack_slot_read() is for.
*/
static int propagate_liveness(struct bpf_verifier_env *env,
const struct bpf_verifier_state *vstate,
struct bpf_verifier_state *vparent)
{
int i, frame, err = 0;
struct bpf_func_state *state, *parent;
if (vparent->curframe != vstate->curframe) {
WARN(1, "propagate_live: parent frame %d current frame %d\n",
vparent->curframe, vstate->curframe);
return -EFAULT;
}
/* Propagate read liveness of registers... */
BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
/* We don't need to worry about FP liveness because it's read-only */
for (i = 0; i < BPF_REG_FP; i++) {
if (vparent->frame[vparent->curframe]->regs[i].live & REG_LIVE_READ)
continue;
if (vstate->frame[vstate->curframe]->regs[i].live & REG_LIVE_READ) {
err = mark_reg_read(env, vstate, vparent, i);
if (err)
return err;
}
}
/* ... and stack slots */
for (frame = 0; frame <= vstate->curframe; frame++) {
state = vstate->frame[frame];
parent = vparent->frame[frame];
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
i < parent->allocated_stack / BPF_REG_SIZE; i++) {
if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
continue;
if (state->stack[i].spilled_ptr.live & REG_LIVE_READ)
mark_stack_slot_read(env, vstate, vparent, i, frame);
}
}
return err;
}
static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
{
struct bpf_verifier_state_list *new_sl;
struct bpf_verifier_state_list *sl;
struct bpf_verifier_state *cur = env->cur_state;
int i, j, err;
sl = env->explored_states[insn_idx];
if (!sl)
/* this 'insn_idx' instruction wasn't marked, so we will not
* be doing state search here
*/
return 0;
while (sl != STATE_LIST_MARK) {
if (states_equal(env, &sl->state, cur)) {
/* reached equivalent register/stack state,
* prune the search.
* Registers read by the continuation are read by us.
* If we have any write marks in env->cur_state, they
* will prevent corresponding reads in the continuation
* from reaching our parent (an explored_state). Our
* own state will get the read marks recorded, but
* they'll be immediately forgotten as we're pruning
* this state and will pop a new one.
*/
err = propagate_liveness(env, &sl->state, cur);
if (err)
return err;
return 1;
}
sl = sl->next;
}
/* there were no equivalent states, remember current one.
* technically the current state is not proven to be safe yet,
* but it will either reach outer most bpf_exit (which means it's safe)
* or it will be rejected. Since there are no loops, we won't be
* seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
* again on the way to bpf_exit
*/
new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
if (!new_sl)
return -ENOMEM;
/* add new state to the head of linked list */
err = copy_verifier_state(&new_sl->state, cur);
if (err) {
free_verifier_state(&new_sl->state, false);
kfree(new_sl);
return err;
}
new_sl->next = env->explored_states[insn_idx];
env->explored_states[insn_idx] = new_sl;
/* connect new state to parentage chain */
cur->parent = &new_sl->state;
/* clear write marks in current state: the writes we did are not writes
* our child did, so they don't screen off its reads from us.
* (There are no read marks in current state, because reads always mark
* their parent and current state never has children yet. Only
* explored_states can get read marks.)
*/
for (i = 0; i < BPF_REG_FP; i++)
cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
/* all stack frames are accessible from callee, clear them all */
for (j = 0; j <= cur->curframe; j++) {
struct bpf_func_state *frame = cur->frame[j];
for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++)
frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
}
return 0;
}
static int do_check(struct bpf_verifier_env *env)
{
struct bpf_verifier_state *state;
struct bpf_insn *insns = env->prog->insnsi;
struct bpf_reg_state *regs;
int insn_cnt = env->prog->len, i;
int insn_idx, prev_insn_idx = 0;
int insn_processed = 0;
bool do_print_state = false;
state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
if (!state)
return -ENOMEM;
state->curframe = 0;
state->parent = NULL;
state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
if (!state->frame[0]) {
kfree(state);
return -ENOMEM;
}
env->cur_state = state;
init_func_state(env, state->frame[0],
BPF_MAIN_FUNC /* callsite */,
0 /* frameno */,
0 /* subprogno, zero == main subprog */);
insn_idx = 0;
for (;;) {
struct bpf_insn *insn;
u8 class;
int err;
if (insn_idx >= insn_cnt) {
verbose(env, "invalid insn idx %d insn_cnt %d\n",
insn_idx, insn_cnt);
return -EFAULT;
}
insn = &insns[insn_idx];
class = BPF_CLASS(insn->code);
if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
verbose(env,
"BPF program is too large. Processed %d insn\n",
insn_processed);
return -E2BIG;
}
err = is_state_visited(env, insn_idx);
if (err < 0)
return err;
if (err == 1) {
/* found equivalent state, can prune the search */
if (env->log.level) {
if (do_print_state)
verbose(env, "\nfrom %d to %d: safe\n",
prev_insn_idx, insn_idx);
else
verbose(env, "%d: safe\n", insn_idx);
}
goto process_bpf_exit;
}
if (need_resched())
cond_resched();
if (env->log.level > 1 || (env->log.level && do_print_state)) {
if (env->log.level > 1)
verbose(env, "%d:", insn_idx);
else
verbose(env, "\nfrom %d to %d:",
prev_insn_idx, insn_idx);
print_verifier_state(env, state->frame[state->curframe]);
do_print_state = false;
}
if (env->log.level) {
const struct bpf_insn_cbs cbs = {
.cb_print = verbose,
.private_data = env,
};
verbose(env, "%d: ", insn_idx);
print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
}
if (bpf_prog_is_dev_bound(env->prog->aux)) {
err = bpf_prog_offload_verify_insn(env, insn_idx,
prev_insn_idx);
if (err)
return err;
}
regs = cur_regs(env);
env->insn_aux_data[insn_idx].seen = true;
if (class == BPF_ALU || class == BPF_ALU64) {
err = check_alu_op(env, insn);
if (err)
return err;
} else if (class == BPF_LDX) {
enum bpf_reg_type *prev_src_type, src_reg_type;
/* check for reserved fields is already done */
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
src_reg_type = regs[insn->src_reg].type;
/* check that memory (src_reg + off) is readable,
* the state of dst_reg will be updated by this func
*/
err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
BPF_SIZE(insn->code), BPF_READ,
insn->dst_reg, false);
if (err)
return err;
prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
if (*prev_src_type == NOT_INIT) {
/* saw a valid insn
* dst_reg = *(u32 *)(src_reg + off)
* save type to validate intersecting paths
*/
*prev_src_type = src_reg_type;
} else if (src_reg_type != *prev_src_type &&
(src_reg_type == PTR_TO_CTX ||
*prev_src_type == PTR_TO_CTX)) {
/* ABuser program is trying to use the same insn
* dst_reg = *(u32*) (src_reg + off)
* with different pointer types:
* src_reg == ctx in one branch and
* src_reg == stack|map in some other branch.
* Reject it.
*/
verbose(env, "same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_STX) {
enum bpf_reg_type *prev_dst_type, dst_reg_type;
if (BPF_MODE(insn->code) == BPF_XADD) {
err = check_xadd(env, insn_idx, insn);
if (err)
return err;
insn_idx++;
continue;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
dst_reg_type = regs[insn->dst_reg].type;
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE,
insn->src_reg, false);
if (err)
return err;
prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
if (*prev_dst_type == NOT_INIT) {
*prev_dst_type = dst_reg_type;
} else if (dst_reg_type != *prev_dst_type &&
(dst_reg_type == PTR_TO_CTX ||
*prev_dst_type == PTR_TO_CTX)) {
verbose(env, "same insn cannot be used with different pointers\n");
return -EINVAL;
}
} else if (class == BPF_ST) {
if (BPF_MODE(insn->code) != BPF_MEM ||
insn->src_reg != BPF_REG_0) {
verbose(env, "BPF_ST uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_ctx_reg(env, insn->dst_reg)) {
verbose(env, "BPF_ST stores into R%d context is not allowed\n",
insn->dst_reg);
return -EACCES;
}
/* check that memory (dst_reg + off) is writeable */
err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
BPF_SIZE(insn->code), BPF_WRITE,
-1, false);
if (err)
return err;
} else if (class == BPF_JMP) {
u8 opcode = BPF_OP(insn->code);
if (opcode == BPF_CALL) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->off != 0 ||
(insn->src_reg != BPF_REG_0 &&
insn->src_reg != BPF_PSEUDO_CALL) ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_CALL uses reserved fields\n");
return -EINVAL;
}
if (insn->src_reg == BPF_PSEUDO_CALL)
err = check_func_call(env, insn, &insn_idx);
else
err = check_helper_call(env, insn->imm, insn_idx);
if (err)
return err;
} else if (opcode == BPF_JA) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_JA uses reserved fields\n");
return -EINVAL;
}
insn_idx += insn->off + 1;
continue;
} else if (opcode == BPF_EXIT) {
if (BPF_SRC(insn->code) != BPF_K ||
insn->imm != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->dst_reg != BPF_REG_0) {
verbose(env, "BPF_EXIT uses reserved fields\n");
return -EINVAL;
}
if (state->curframe) {
/* exit from nested function */
prev_insn_idx = insn_idx;
err = prepare_func_exit(env, &insn_idx);
if (err)
return err;
do_print_state = true;
continue;
}
/* eBPF calling convetion is such that R0 is used
* to return the value from eBPF program.
* Make sure that it's readable at this time
* of bpf_exit, which means that program wrote
* something into it earlier
*/
err = check_reg_arg(env, BPF_REG_0, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, BPF_REG_0)) {
verbose(env, "R0 leaks addr as return value\n");
return -EACCES;
}
err = check_return_code(env);
if (err)
return err;
process_bpf_exit:
err = pop_stack(env, &prev_insn_idx, &insn_idx);
if (err < 0) {
if (err != -ENOENT)
return err;
break;
} else {
do_print_state = true;
continue;
}
} else {
err = check_cond_jmp_op(env, insn, &insn_idx);
if (err)
return err;
}
} else if (class == BPF_LD) {
u8 mode = BPF_MODE(insn->code);
if (mode == BPF_ABS || mode == BPF_IND) {
err = check_ld_abs(env, insn);
if (err)
return err;
} else if (mode == BPF_IMM) {
err = check_ld_imm(env, insn);
if (err)
return err;
insn_idx++;
env->insn_aux_data[insn_idx].seen = true;
} else {
verbose(env, "invalid BPF_LD mode\n");
return -EINVAL;
}
} else {
verbose(env, "unknown insn class %d\n", class);
return -EINVAL;
}
insn_idx++;
}
verbose(env, "processed %d insns (limit %d), stack depth ",
insn_processed, BPF_COMPLEXITY_LIMIT_INSNS);
for (i = 0; i < env->subprog_cnt; i++) {
u32 depth = env->subprog_info[i].stack_depth;
verbose(env, "%d", depth);
if (i + 1 < env->subprog_cnt)
verbose(env, "+");
}
verbose(env, "\n");
env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
return 0;
}
static int check_map_prealloc(struct bpf_map *map)
{
return (map->map_type != BPF_MAP_TYPE_HASH &&
map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
!(map->map_flags & BPF_F_NO_PREALLOC);
}
static int check_map_prog_compatibility(struct bpf_verifier_env *env,
struct bpf_map *map,
struct bpf_prog *prog)
{
/* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
* preallocated hash maps, since doing memory allocation
* in overflow_handler can crash depending on where nmi got
* triggered.
*/
if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
if (!check_map_prealloc(map)) {
verbose(env, "perf_event programs can only use preallocated hash map\n");
return -EINVAL;
}
if (map->inner_map_meta &&
!check_map_prealloc(map->inner_map_meta)) {
verbose(env, "perf_event programs can only use preallocated inner hash map\n");
return -EINVAL;
}
}
if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
!bpf_offload_prog_map_match(prog, map)) {
verbose(env, "offload device mismatch between prog and map\n");
return -EINVAL;
}
return 0;
}
/* look for pseudo eBPF instructions that access map FDs and
* replace them with actual map pointers
*/
static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
{
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
int i, j, err;
err = bpf_prog_calc_tag(env->prog);
if (err)
return err;
for (i = 0; i < insn_cnt; i++, insn++) {
if (BPF_CLASS(insn->code) == BPF_LDX &&
(BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
verbose(env, "BPF_LDX uses reserved fields\n");
return -EINVAL;
}
if (BPF_CLASS(insn->code) == BPF_STX &&
((BPF_MODE(insn->code) != BPF_MEM &&
BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
verbose(env, "BPF_STX uses reserved fields\n");
return -EINVAL;
}
if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
struct bpf_map *map;
struct fd f;
if (i == insn_cnt - 1 || insn[1].code != 0 ||
insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
insn[1].off != 0) {
verbose(env, "invalid bpf_ld_imm64 insn\n");
return -EINVAL;
}
if (insn->src_reg == 0)
/* valid generic load 64-bit imm */
goto next_insn;
if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
verbose(env,
"unrecognized bpf_ld_imm64 insn\n");
return -EINVAL;
}
f = fdget(insn->imm);
map = __bpf_map_get(f);
if (IS_ERR(map)) {
verbose(env, "fd %d is not pointing to valid bpf_map\n",
insn->imm);
return PTR_ERR(map);
}
err = check_map_prog_compatibility(env, map, env->prog);
if (err) {
fdput(f);
return err;
}
/* store map pointer inside BPF_LD_IMM64 instruction */
insn[0].imm = (u32) (unsigned long) map;
insn[1].imm = ((u64) (unsigned long) map) >> 32;
/* check whether we recorded this map already */
for (j = 0; j < env->used_map_cnt; j++)
if (env->used_maps[j] == map) {
fdput(f);
goto next_insn;
}
if (env->used_map_cnt >= MAX_USED_MAPS) {
fdput(f);
return -E2BIG;
}
/* hold the map. If the program is rejected by verifier,
* the map will be released by release_maps() or it
* will be used by the valid program until it's unloaded
* and all maps are released in free_used_maps()
*/
map = bpf_map_inc(map, false);
if (IS_ERR(map)) {
fdput(f);
return PTR_ERR(map);
}
env->used_maps[env->used_map_cnt++] = map;
if (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE &&
bpf_cgroup_storage_assign(env->prog, map)) {
verbose(env,
"only one cgroup storage is allowed\n");
fdput(f);
return -EBUSY;
}
fdput(f);
next_insn:
insn++;
i++;
continue;
}
/* Basic sanity check before we invest more work here. */
if (!bpf_opcode_in_insntable(insn->code)) {
verbose(env, "unknown opcode %02x\n", insn->code);
return -EINVAL;
}
}
/* now all pseudo BPF_LD_IMM64 instructions load valid
* 'struct bpf_map *' into a register instead of user map_fd.
* These pointers will be used later by verifier to validate map access.
*/
return 0;
}
/* drop refcnt of maps used by the rejected program */
static void release_maps(struct bpf_verifier_env *env)
{
int i;
if (env->prog->aux->cgroup_storage)
bpf_cgroup_storage_release(env->prog,
env->prog->aux->cgroup_storage);
for (i = 0; i < env->used_map_cnt; i++)
bpf_map_put(env->used_maps[i]);
}
/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
{
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
int i;
for (i = 0; i < insn_cnt; i++, insn++)
if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
insn->src_reg = 0;
}
/* single env->prog->insni[off] instruction was replaced with the range
* insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
* [0, off) and [off, end) to new locations, so the patched range stays zero
*/
static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
u32 off, u32 cnt)
{
struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
int i;
if (cnt == 1)
return 0;
new_data = vzalloc(array_size(prog_len,
sizeof(struct bpf_insn_aux_data)));
if (!new_data)
return -ENOMEM;
memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
memcpy(new_data + off + cnt - 1, old_data + off,
sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
for (i = off; i < off + cnt - 1; i++)
new_data[i].seen = true;
env->insn_aux_data = new_data;
vfree(old_data);
return 0;
}
static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
{
int i;
if (len == 1)
return;
/* NOTE: fake 'exit' subprog should be updated as well. */
for (i = 0; i <= env->subprog_cnt; i++) {
if (env->subprog_info[i].start < off)
continue;
env->subprog_info[i].start += len - 1;
}
}
static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
const struct bpf_insn *patch, u32 len)
{
struct bpf_prog *new_prog;
new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
if (!new_prog)
return NULL;
if (adjust_insn_aux_data(env, new_prog->len, off, len))
return NULL;
adjust_subprog_starts(env, off, len);
return new_prog;
}
/* The verifier does more data flow analysis than llvm and will not
* explore branches that are dead at run time. Malicious programs can
* have dead code too. Therefore replace all dead at-run-time code
* with 'ja -1'.
*
* Just nops are not optimal, e.g. if they would sit at the end of the
* program and through another bug we would manage to jump there, then
* we'd execute beyond program memory otherwise. Returning exception
* code also wouldn't work since we can have subprogs where the dead
* code could be located.
*/
static void sanitize_dead_code(struct bpf_verifier_env *env)
{
struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
struct bpf_insn *insn = env->prog->insnsi;
const int insn_cnt = env->prog->len;
int i;
for (i = 0; i < insn_cnt; i++) {
if (aux_data[i].seen)
continue;
memcpy(insn + i, &trap, sizeof(trap));
}
}
/* convert load instructions that access fields of 'struct __sk_buff'
* into sequence of instructions that access fields of 'struct sk_buff'
*/
static int convert_ctx_accesses(struct bpf_verifier_env *env)
{
const struct bpf_verifier_ops *ops = env->ops;
int i, cnt, size, ctx_field_size, delta = 0;
const int insn_cnt = env->prog->len;
struct bpf_insn insn_buf[16], *insn;
struct bpf_prog *new_prog;
enum bpf_access_type type;
bool is_narrower_load;
u32 target_size;
if (ops->gen_prologue) {
cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
env->prog);
if (cnt >= ARRAY_SIZE(insn_buf)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
} else if (cnt) {
new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
env->prog = new_prog;
delta += cnt - 1;
}
}
if (!ops->convert_ctx_access || bpf_prog_is_dev_bound(env->prog->aux))
return 0;
insn = env->prog->insnsi + delta;
for (i = 0; i < insn_cnt; i++, insn++) {
if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
type = BPF_READ;
else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
insn->code == (BPF_STX | BPF_MEM | BPF_DW))
type = BPF_WRITE;
else
continue;
if (type == BPF_WRITE &&
env->insn_aux_data[i + delta].sanitize_stack_off) {
struct bpf_insn patch[] = {
/* Sanitize suspicious stack slot with zero.
* There are no memory dependencies for this store,
* since it's only using frame pointer and immediate
* constant of zero
*/
BPF_ST_MEM(BPF_DW, BPF_REG_FP,
env->insn_aux_data[i + delta].sanitize_stack_off,
0),
/* the original STX instruction will immediately
* overwrite the same stack slot with appropriate value
*/
*insn,
};
cnt = ARRAY_SIZE(patch);
new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
env->prog = new_prog;
insn = new_prog->insnsi + i + delta;
continue;
}
if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
continue;
ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
size = BPF_LDST_BYTES(insn);
/* If the read access is a narrower load of the field,
* convert to a 4/8-byte load, to minimum program type specific
* convert_ctx_access changes. If conversion is successful,
* we will apply proper mask to the result.
*/
is_narrower_load = size < ctx_field_size;
if (is_narrower_load) {
u32 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
u32 off = insn->off;
u8 size_code;
if (type == BPF_WRITE) {
verbose(env, "bpf verifier narrow ctx access misconfigured\n");
return -EINVAL;
}
size_code = BPF_H;
if (ctx_field_size == 4)
size_code = BPF_W;
else if (ctx_field_size == 8)
size_code = BPF_DW;
insn->off = off & ~(size_default - 1);
insn->code = BPF_LDX | BPF_MEM | size_code;
}
target_size = 0;
cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
&target_size);
if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
(ctx_field_size && !target_size)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
}
if (is_narrower_load && size < target_size) {
if (ctx_field_size <= 4)
insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
(1 << size * 8) - 1);
else
insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
(1 << size * 8) - 1);
}
new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
/* keep walking new program and skip insns we just inserted */
env->prog = new_prog;
insn = new_prog->insnsi + i + delta;
}
return 0;
}
static int jit_subprogs(struct bpf_verifier_env *env)
{
struct bpf_prog *prog = env->prog, **func, *tmp;
int i, j, subprog_start, subprog_end = 0, len, subprog;
struct bpf_insn *insn;
void *old_bpf_func;
int err = -ENOMEM;
if (env->subprog_cnt <= 1)
return 0;
for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
if (insn->code != (BPF_JMP | BPF_CALL) ||
insn->src_reg != BPF_PSEUDO_CALL)
continue;
/* Upon error here we cannot fall back to interpreter but
* need a hard reject of the program. Thus -EFAULT is
* propagated in any case.
*/
subprog = find_subprog(env, i + insn->imm + 1);
if (subprog < 0) {
WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
i + insn->imm + 1);
return -EFAULT;
}
/* temporarily remember subprog id inside insn instead of
* aux_data, since next loop will split up all insns into funcs
*/
insn->off = subprog;
/* remember original imm in case JIT fails and fallback
* to interpreter will be needed
*/
env->insn_aux_data[i].call_imm = insn->imm;
/* point imm to __bpf_call_base+1 from JITs point of view */
insn->imm = 1;
}
func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
if (!func)
goto out_undo_insn;
for (i = 0; i < env->subprog_cnt; i++) {
subprog_start = subprog_end;
subprog_end = env->subprog_info[i + 1].start;
len = subprog_end - subprog_start;
func[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER);
if (!func[i])
goto out_free;
memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
len * sizeof(struct bpf_insn));
func[i]->type = prog->type;
func[i]->len = len;
if (bpf_prog_calc_tag(func[i]))
goto out_free;
func[i]->is_func = 1;
/* Use bpf_prog_F_tag to indicate functions in stack traces.
* Long term would need debug info to populate names
*/
func[i]->aux->name[0] = 'F';
func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
func[i]->jit_requested = 1;
func[i] = bpf_int_jit_compile(func[i]);
if (!func[i]->jited) {
err = -ENOTSUPP;
goto out_free;
}
cond_resched();
}
/* at this point all bpf functions were successfully JITed
* now populate all bpf_calls with correct addresses and
* run last pass of JIT
*/
for (i = 0; i < env->subprog_cnt; i++) {
insn = func[i]->insnsi;
for (j = 0; j < func[i]->len; j++, insn++) {
if (insn->code != (BPF_JMP | BPF_CALL) ||
insn->src_reg != BPF_PSEUDO_CALL)
continue;
subprog = insn->off;
insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
func[subprog]->bpf_func -
__bpf_call_base;
}
/* we use the aux data to keep a list of the start addresses
* of the JITed images for each function in the program
*
* for some architectures, such as powerpc64, the imm field
* might not be large enough to hold the offset of the start
* address of the callee's JITed image from __bpf_call_base
*
* in such cases, we can lookup the start address of a callee
* by using its subprog id, available from the off field of
* the call instruction, as an index for this list
*/
func[i]->aux->func = func;
func[i]->aux->func_cnt = env->subprog_cnt;
}
for (i = 0; i < env->subprog_cnt; i++) {
old_bpf_func = func[i]->bpf_func;
tmp = bpf_int_jit_compile(func[i]);
if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
err = -ENOTSUPP;
goto out_free;
}
cond_resched();
}
/* finally lock prog and jit images for all functions and
* populate kallsysm
*/
for (i = 0; i < env->subprog_cnt; i++) {
bpf_prog_lock_ro(func[i]);
bpf_prog_kallsyms_add(func[i]);
}
/* Last step: make now unused interpreter insns from main
* prog consistent for later dump requests, so they can
* later look the same as if they were interpreted only.
*/
for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
if (insn->code != (BPF_JMP | BPF_CALL) ||
insn->src_reg != BPF_PSEUDO_CALL)
continue;
insn->off = env->insn_aux_data[i].call_imm;
subprog = find_subprog(env, i + insn->off + 1);
insn->imm = subprog;
}
prog->jited = 1;
prog->bpf_func = func[0]->bpf_func;
prog->aux->func = func;
prog->aux->func_cnt = env->subprog_cnt;
return 0;
out_free:
for (i = 0; i < env->subprog_cnt; i++)
if (func[i])
bpf_jit_free(func[i]);
kfree(func);
out_undo_insn:
/* cleanup main prog to be interpreted */
prog->jit_requested = 0;
for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
if (insn->code != (BPF_JMP | BPF_CALL) ||
insn->src_reg != BPF_PSEUDO_CALL)
continue;
insn->off = 0;
insn->imm = env->insn_aux_data[i].call_imm;
}
return err;
}
static int fixup_call_args(struct bpf_verifier_env *env)
{
#ifndef CONFIG_BPF_JIT_ALWAYS_ON
struct bpf_prog *prog = env->prog;
struct bpf_insn *insn = prog->insnsi;
int i, depth;
#endif
int err;
err = 0;
if (env->prog->jit_requested) {
err = jit_subprogs(env);
if (err == 0)
return 0;
if (err == -EFAULT)
return err;
}
#ifndef CONFIG_BPF_JIT_ALWAYS_ON
for (i = 0; i < prog->len; i++, insn++) {
if (insn->code != (BPF_JMP | BPF_CALL) ||
insn->src_reg != BPF_PSEUDO_CALL)
continue;
depth = get_callee_stack_depth(env, insn, i);
if (depth < 0)
return depth;
bpf_patch_call_args(insn, depth);
}
err = 0;
#endif
return err;
}
/* fixup insn->imm field of bpf_call instructions
* and inline eligible helpers as explicit sequence of BPF instructions
*
* this function is called after eBPF program passed verification
*/
static int fixup_bpf_calls(struct bpf_verifier_env *env)
{
struct bpf_prog *prog = env->prog;
struct bpf_insn *insn = prog->insnsi;
const struct bpf_func_proto *fn;
const int insn_cnt = prog->len;
const struct bpf_map_ops *ops;
struct bpf_insn_aux_data *aux;
struct bpf_insn insn_buf[16];
struct bpf_prog *new_prog;
struct bpf_map *map_ptr;
int i, cnt, delta = 0;
for (i = 0; i < insn_cnt; i++, insn++) {
if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
struct bpf_insn mask_and_div[] = {
BPF_MOV32_REG(insn->src_reg, insn->src_reg),
/* Rx div 0 -> 0 */
BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
BPF_JMP_IMM(BPF_JA, 0, 0, 1),
*insn,
};
struct bpf_insn mask_and_mod[] = {
BPF_MOV32_REG(insn->src_reg, insn->src_reg),
/* Rx mod 0 -> Rx */
BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
*insn,
};
struct bpf_insn *patchlet;
if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
patchlet = mask_and_div + (is64 ? 1 : 0);
cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
} else {
patchlet = mask_and_mod + (is64 ? 1 : 0);
cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
}
new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
continue;
}
if (BPF_CLASS(insn->code) == BPF_LD &&
(BPF_MODE(insn->code) == BPF_ABS ||
BPF_MODE(insn->code) == BPF_IND)) {
cnt = env->ops->gen_ld_abs(insn, insn_buf);
if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
}
new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
continue;
}
if (insn->code != (BPF_JMP | BPF_CALL))
continue;
if (insn->src_reg == BPF_PSEUDO_CALL)
continue;
if (insn->imm == BPF_FUNC_get_route_realm)
prog->dst_needed = 1;
if (insn->imm == BPF_FUNC_get_prandom_u32)
bpf_user_rnd_init_once();
if (insn->imm == BPF_FUNC_override_return)
prog->kprobe_override = 1;
if (insn->imm == BPF_FUNC_tail_call) {
/* If we tail call into other programs, we
* cannot make any assumptions since they can
* be replaced dynamically during runtime in
* the program array.
*/
prog->cb_access = 1;
env->prog->aux->stack_depth = MAX_BPF_STACK;
/* mark bpf_tail_call as different opcode to avoid
* conditional branch in the interpeter for every normal
* call and to prevent accidental JITing by JIT compiler
* that doesn't support bpf_tail_call yet
*/
insn->imm = 0;
insn->code = BPF_JMP | BPF_TAIL_CALL;
aux = &env->insn_aux_data[i + delta];
if (!bpf_map_ptr_unpriv(aux))
continue;
/* instead of changing every JIT dealing with tail_call
* emit two extra insns:
* if (index >= max_entries) goto out;
* index &= array->index_mask;
* to avoid out-of-bounds cpu speculation
*/
if (bpf_map_ptr_poisoned(aux)) {
verbose(env, "tail_call abusing map_ptr\n");
return -EINVAL;
}
map_ptr = BPF_MAP_PTR(aux->map_state);
insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
map_ptr->max_entries, 2);
insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
container_of(map_ptr,
struct bpf_array,
map)->index_mask);
insn_buf[2] = *insn;
cnt = 3;
new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
continue;
}
/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
* and other inlining handlers are currently limited to 64 bit
* only.
*/
if (prog->jit_requested && BITS_PER_LONG == 64 &&
(insn->imm == BPF_FUNC_map_lookup_elem ||
insn->imm == BPF_FUNC_map_update_elem ||
insn->imm == BPF_FUNC_map_delete_elem)) {
aux = &env->insn_aux_data[i + delta];
if (bpf_map_ptr_poisoned(aux))
goto patch_call_imm;
map_ptr = BPF_MAP_PTR(aux->map_state);
ops = map_ptr->ops;
if (insn->imm == BPF_FUNC_map_lookup_elem &&
ops->map_gen_lookup) {
cnt = ops->map_gen_lookup(map_ptr, insn_buf);
if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
verbose(env, "bpf verifier is misconfigured\n");
return -EINVAL;
}
new_prog = bpf_patch_insn_data(env, i + delta,
insn_buf, cnt);
if (!new_prog)
return -ENOMEM;
delta += cnt - 1;
env->prog = prog = new_prog;
insn = new_prog->insnsi + i + delta;
continue;
}
BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
(void *(*)(struct bpf_map *map, void *key))NULL));
BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
(int (*)(struct bpf_map *map, void *key))NULL));
BUILD_BUG_ON(!__same_type(ops->map_update_elem,
(int (*)(struct bpf_map *map, void *key, void *value,
u64 flags))NULL));
switch (insn->imm) {
case BPF_FUNC_map_lookup_elem:
insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
__bpf_call_base;
continue;
case BPF_FUNC_map_update_elem:
insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
__bpf_call_base;
continue;
case BPF_FUNC_map_delete_elem:
insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
__bpf_call_base;
continue;
}
goto patch_call_imm;
}
patch_call_imm:
fn = env->ops->get_func_proto(insn->imm, env->prog);
/* all functions that have prototype and verifier allowed
* programs to call them, must be real in-kernel functions
*/
if (!fn->func) {
verbose(env,
"kernel subsystem misconfigured func %s#%d\n",
func_id_name(insn->imm), insn->imm);
return -EFAULT;
}
insn->imm = fn->func - __bpf_call_base;
}
return 0;
}
static void free_states(struct bpf_verifier_env *env)
{
struct bpf_verifier_state_list *sl, *sln;
int i;
if (!env->explored_states)
return;
for (i = 0; i < env->prog->len; i++) {
sl = env->explored_states[i];
if (sl)
while (sl != STATE_LIST_MARK) {
sln = sl->next;
free_verifier_state(&sl->state, false);
kfree(sl);
sl = sln;
}
}
kfree(env->explored_states);
}
int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
{
struct bpf_verifier_env *env;
struct bpf_verifier_log *log;
int ret = -EINVAL;
/* no program is valid */
if (ARRAY_SIZE(bpf_verifier_ops) == 0)
return -EINVAL;
/* 'struct bpf_verifier_env' can be global, but since it's not small,
* allocate/free it every time bpf_check() is called
*/
env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
if (!env)
return -ENOMEM;
log = &env->log;
env->insn_aux_data =
vzalloc(array_size(sizeof(struct bpf_insn_aux_data),
(*prog)->len));
ret = -ENOMEM;
if (!env->insn_aux_data)
goto err_free_env;
env->prog = *prog;
env->ops = bpf_verifier_ops[env->prog->type];
/* grab the mutex to protect few globals used by verifier */
mutex_lock(&bpf_verifier_lock);
if (attr->log_level || attr->log_buf || attr->log_size) {
/* user requested verbose verifier output
* and supplied buffer to store the verification trace
*/
log->level = attr->log_level;
log->ubuf = (char __user *) (unsigned long) attr->log_buf;
log->len_total = attr->log_size;
ret = -EINVAL;
/* log attributes have to be sane */
if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
!log->level || !log->ubuf)
goto err_unlock;
}
env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
env->strict_alignment = true;
ret = replace_map_fd_with_map_ptr(env);
if (ret < 0)
goto skip_full_check;
if (bpf_prog_is_dev_bound(env->prog->aux)) {
ret = bpf_prog_offload_verifier_prep(env);
if (ret)
goto skip_full_check;
}
env->explored_states = kcalloc(env->prog->len,
sizeof(struct bpf_verifier_state_list *),
GFP_USER);
ret = -ENOMEM;
if (!env->explored_states)
goto skip_full_check;
env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
ret = check_cfg(env);
if (ret < 0)
goto skip_full_check;
ret = do_check(env);
if (env->cur_state) {
free_verifier_state(env->cur_state, true);
env->cur_state = NULL;
}
skip_full_check:
while (!pop_stack(env, NULL, NULL));
free_states(env);
if (ret == 0)
sanitize_dead_code(env);
if (ret == 0)
ret = check_max_stack_depth(env);
if (ret == 0)
/* program is valid, convert *(u32*)(ctx + off) accesses */
ret = convert_ctx_accesses(env);
if (ret == 0)
ret = fixup_bpf_calls(env);
if (ret == 0)
ret = fixup_call_args(env);
if (log->level && bpf_verifier_log_full(log))
ret = -ENOSPC;
if (log->level && !log->ubuf) {
ret = -EFAULT;
goto err_release_maps;
}
if (ret == 0 && env->used_map_cnt) {
/* if program passed verifier, update used_maps in bpf_prog_info */
env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
sizeof(env->used_maps[0]),
GFP_KERNEL);
if (!env->prog->aux->used_maps) {
ret = -ENOMEM;
goto err_release_maps;
}
memcpy(env->prog->aux->used_maps, env->used_maps,
sizeof(env->used_maps[0]) * env->used_map_cnt);
env->prog->aux->used_map_cnt = env->used_map_cnt;
/* program is valid. Convert pseudo bpf_ld_imm64 into generic
* bpf_ld_imm64 instructions
*/
convert_pseudo_ld_imm64(env);
}
err_release_maps:
if (!env->prog->aux->used_maps)
/* if we didn't copy map pointers into bpf_prog_info, release
* them now. Otherwise free_used_maps() will release them.
*/
release_maps(env);
*prog = env->prog;
err_unlock:
mutex_unlock(&bpf_verifier_lock);
vfree(env->insn_aux_data);
err_free_env:
kfree(env);
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_417_0 |
crossvul-cpp_data_bad_3358_0 | /*
* IPV6 GSO/GRO offload support
* Linux INET6 implementation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/kernel.h>
#include <linux/socket.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/printk.h>
#include <net/protocol.h>
#include <net/ipv6.h>
#include <net/inet_common.h>
#include "ip6_offload.h"
static int ipv6_gso_pull_exthdrs(struct sk_buff *skb, int proto)
{
const struct net_offload *ops = NULL;
for (;;) {
struct ipv6_opt_hdr *opth;
int len;
if (proto != NEXTHDR_HOP) {
ops = rcu_dereference(inet6_offloads[proto]);
if (unlikely(!ops))
break;
if (!(ops->flags & INET6_PROTO_GSO_EXTHDR))
break;
}
if (unlikely(!pskb_may_pull(skb, 8)))
break;
opth = (void *)skb->data;
len = ipv6_optlen(opth);
if (unlikely(!pskb_may_pull(skb, len)))
break;
opth = (void *)skb->data;
proto = opth->nexthdr;
__skb_pull(skb, len);
}
return proto;
}
static struct sk_buff *ipv6_gso_segment(struct sk_buff *skb,
netdev_features_t features)
{
struct sk_buff *segs = ERR_PTR(-EINVAL);
struct ipv6hdr *ipv6h;
const struct net_offload *ops;
int proto;
struct frag_hdr *fptr;
unsigned int unfrag_ip6hlen;
unsigned int payload_len;
u8 *prevhdr;
int offset = 0;
bool encap, udpfrag;
int nhoff;
bool gso_partial;
skb_reset_network_header(skb);
nhoff = skb_network_header(skb) - skb_mac_header(skb);
if (unlikely(!pskb_may_pull(skb, sizeof(*ipv6h))))
goto out;
encap = SKB_GSO_CB(skb)->encap_level > 0;
if (encap)
features &= skb->dev->hw_enc_features;
SKB_GSO_CB(skb)->encap_level += sizeof(*ipv6h);
ipv6h = ipv6_hdr(skb);
__skb_pull(skb, sizeof(*ipv6h));
segs = ERR_PTR(-EPROTONOSUPPORT);
proto = ipv6_gso_pull_exthdrs(skb, ipv6h->nexthdr);
if (skb->encapsulation &&
skb_shinfo(skb)->gso_type & (SKB_GSO_IPXIP4 | SKB_GSO_IPXIP6))
udpfrag = proto == IPPROTO_UDP && encap;
else
udpfrag = proto == IPPROTO_UDP && !skb->encapsulation;
ops = rcu_dereference(inet6_offloads[proto]);
if (likely(ops && ops->callbacks.gso_segment)) {
skb_reset_transport_header(skb);
segs = ops->callbacks.gso_segment(skb, features);
}
if (IS_ERR_OR_NULL(segs))
goto out;
gso_partial = !!(skb_shinfo(segs)->gso_type & SKB_GSO_PARTIAL);
for (skb = segs; skb; skb = skb->next) {
ipv6h = (struct ipv6hdr *)(skb_mac_header(skb) + nhoff);
if (gso_partial)
payload_len = skb_shinfo(skb)->gso_size +
SKB_GSO_CB(skb)->data_offset +
skb->head - (unsigned char *)(ipv6h + 1);
else
payload_len = skb->len - nhoff - sizeof(*ipv6h);
ipv6h->payload_len = htons(payload_len);
skb->network_header = (u8 *)ipv6h - skb->head;
if (udpfrag) {
unfrag_ip6hlen = ip6_find_1stfragopt(skb, &prevhdr);
fptr = (struct frag_hdr *)((u8 *)ipv6h + unfrag_ip6hlen);
fptr->frag_off = htons(offset);
if (skb->next)
fptr->frag_off |= htons(IP6_MF);
offset += (ntohs(ipv6h->payload_len) -
sizeof(struct frag_hdr));
}
if (encap)
skb_reset_inner_headers(skb);
}
out:
return segs;
}
/* Return the total length of all the extension hdrs, following the same
* logic in ipv6_gso_pull_exthdrs() when parsing ext-hdrs.
*/
static int ipv6_exthdrs_len(struct ipv6hdr *iph,
const struct net_offload **opps)
{
struct ipv6_opt_hdr *opth = (void *)iph;
int len = 0, proto, optlen = sizeof(*iph);
proto = iph->nexthdr;
for (;;) {
if (proto != NEXTHDR_HOP) {
*opps = rcu_dereference(inet6_offloads[proto]);
if (unlikely(!(*opps)))
break;
if (!((*opps)->flags & INET6_PROTO_GSO_EXTHDR))
break;
}
opth = (void *)opth + optlen;
optlen = ipv6_optlen(opth);
len += optlen;
proto = opth->nexthdr;
}
return len;
}
static struct sk_buff **ipv6_gro_receive(struct sk_buff **head,
struct sk_buff *skb)
{
const struct net_offload *ops;
struct sk_buff **pp = NULL;
struct sk_buff *p;
struct ipv6hdr *iph;
unsigned int nlen;
unsigned int hlen;
unsigned int off;
u16 flush = 1;
int proto;
off = skb_gro_offset(skb);
hlen = off + sizeof(*iph);
iph = skb_gro_header_fast(skb, off);
if (skb_gro_header_hard(skb, hlen)) {
iph = skb_gro_header_slow(skb, hlen, off);
if (unlikely(!iph))
goto out;
}
skb_set_network_header(skb, off);
skb_gro_pull(skb, sizeof(*iph));
skb_set_transport_header(skb, skb_gro_offset(skb));
flush += ntohs(iph->payload_len) != skb_gro_len(skb);
rcu_read_lock();
proto = iph->nexthdr;
ops = rcu_dereference(inet6_offloads[proto]);
if (!ops || !ops->callbacks.gro_receive) {
__pskb_pull(skb, skb_gro_offset(skb));
skb_gro_frag0_invalidate(skb);
proto = ipv6_gso_pull_exthdrs(skb, proto);
skb_gro_pull(skb, -skb_transport_offset(skb));
skb_reset_transport_header(skb);
__skb_push(skb, skb_gro_offset(skb));
ops = rcu_dereference(inet6_offloads[proto]);
if (!ops || !ops->callbacks.gro_receive)
goto out_unlock;
iph = ipv6_hdr(skb);
}
NAPI_GRO_CB(skb)->proto = proto;
flush--;
nlen = skb_network_header_len(skb);
for (p = *head; p; p = p->next) {
const struct ipv6hdr *iph2;
__be32 first_word; /* <Version:4><Traffic_Class:8><Flow_Label:20> */
if (!NAPI_GRO_CB(p)->same_flow)
continue;
iph2 = (struct ipv6hdr *)(p->data + off);
first_word = *(__be32 *)iph ^ *(__be32 *)iph2;
/* All fields must match except length and Traffic Class.
* XXX skbs on the gro_list have all been parsed and pulled
* already so we don't need to compare nlen
* (nlen != (sizeof(*iph2) + ipv6_exthdrs_len(iph2, &ops)))
* memcmp() alone below is suffcient, right?
*/
if ((first_word & htonl(0xF00FFFFF)) ||
memcmp(&iph->nexthdr, &iph2->nexthdr,
nlen - offsetof(struct ipv6hdr, nexthdr))) {
NAPI_GRO_CB(p)->same_flow = 0;
continue;
}
/* flush if Traffic Class fields are different */
NAPI_GRO_CB(p)->flush |= !!(first_word & htonl(0x0FF00000));
NAPI_GRO_CB(p)->flush |= flush;
/* If the previous IP ID value was based on an atomic
* datagram we can overwrite the value and ignore it.
*/
if (NAPI_GRO_CB(skb)->is_atomic)
NAPI_GRO_CB(p)->flush_id = 0;
}
NAPI_GRO_CB(skb)->is_atomic = true;
NAPI_GRO_CB(skb)->flush |= flush;
skb_gro_postpull_rcsum(skb, iph, nlen);
pp = call_gro_receive(ops->callbacks.gro_receive, head, skb);
out_unlock:
rcu_read_unlock();
out:
skb_gro_flush_final(skb, pp, flush);
return pp;
}
static struct sk_buff **sit_ip6ip6_gro_receive(struct sk_buff **head,
struct sk_buff *skb)
{
/* Common GRO receive for SIT and IP6IP6 */
if (NAPI_GRO_CB(skb)->encap_mark) {
NAPI_GRO_CB(skb)->flush = 1;
return NULL;
}
NAPI_GRO_CB(skb)->encap_mark = 1;
return ipv6_gro_receive(head, skb);
}
static struct sk_buff **ip4ip6_gro_receive(struct sk_buff **head,
struct sk_buff *skb)
{
/* Common GRO receive for SIT and IP6IP6 */
if (NAPI_GRO_CB(skb)->encap_mark) {
NAPI_GRO_CB(skb)->flush = 1;
return NULL;
}
NAPI_GRO_CB(skb)->encap_mark = 1;
return inet_gro_receive(head, skb);
}
static int ipv6_gro_complete(struct sk_buff *skb, int nhoff)
{
const struct net_offload *ops;
struct ipv6hdr *iph = (struct ipv6hdr *)(skb->data + nhoff);
int err = -ENOSYS;
if (skb->encapsulation) {
skb_set_inner_protocol(skb, cpu_to_be16(ETH_P_IPV6));
skb_set_inner_network_header(skb, nhoff);
}
iph->payload_len = htons(skb->len - nhoff - sizeof(*iph));
rcu_read_lock();
nhoff += sizeof(*iph) + ipv6_exthdrs_len(iph, &ops);
if (WARN_ON(!ops || !ops->callbacks.gro_complete))
goto out_unlock;
err = ops->callbacks.gro_complete(skb, nhoff);
out_unlock:
rcu_read_unlock();
return err;
}
static int sit_gro_complete(struct sk_buff *skb, int nhoff)
{
skb->encapsulation = 1;
skb_shinfo(skb)->gso_type |= SKB_GSO_IPXIP4;
return ipv6_gro_complete(skb, nhoff);
}
static int ip6ip6_gro_complete(struct sk_buff *skb, int nhoff)
{
skb->encapsulation = 1;
skb_shinfo(skb)->gso_type |= SKB_GSO_IPXIP6;
return ipv6_gro_complete(skb, nhoff);
}
static int ip4ip6_gro_complete(struct sk_buff *skb, int nhoff)
{
skb->encapsulation = 1;
skb_shinfo(skb)->gso_type |= SKB_GSO_IPXIP6;
return inet_gro_complete(skb, nhoff);
}
static struct packet_offload ipv6_packet_offload __read_mostly = {
.type = cpu_to_be16(ETH_P_IPV6),
.callbacks = {
.gso_segment = ipv6_gso_segment,
.gro_receive = ipv6_gro_receive,
.gro_complete = ipv6_gro_complete,
},
};
static const struct net_offload sit_offload = {
.callbacks = {
.gso_segment = ipv6_gso_segment,
.gro_receive = sit_ip6ip6_gro_receive,
.gro_complete = sit_gro_complete,
},
};
static const struct net_offload ip4ip6_offload = {
.callbacks = {
.gso_segment = inet_gso_segment,
.gro_receive = ip4ip6_gro_receive,
.gro_complete = ip4ip6_gro_complete,
},
};
static const struct net_offload ip6ip6_offload = {
.callbacks = {
.gso_segment = ipv6_gso_segment,
.gro_receive = sit_ip6ip6_gro_receive,
.gro_complete = ip6ip6_gro_complete,
},
};
static int __init ipv6_offload_init(void)
{
if (tcpv6_offload_init() < 0)
pr_crit("%s: Cannot add TCP protocol offload\n", __func__);
if (ipv6_exthdrs_offload_init() < 0)
pr_crit("%s: Cannot add EXTHDRS protocol offload\n", __func__);
dev_add_offload(&ipv6_packet_offload);
inet_add_offload(&sit_offload, IPPROTO_IPV6);
inet6_add_offload(&ip6ip6_offload, IPPROTO_IPV6);
inet6_add_offload(&ip4ip6_offload, IPPROTO_IPIP);
return 0;
}
fs_initcall(ipv6_offload_init);
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3358_0 |
crossvul-cpp_data_good_2644_6 | /*
* Copyright (c) 1992, 1993, 1994, 1995, 1996
* 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: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Original code by Matt Thomas, Digital Equipment Corporation
*
* Extensively modified by Hannes Gredler (hannes@gredler.at) for more
* complete IS-IS & CLNP support.
*/
/* \summary: ISO CLNS, ESIS, and ISIS printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "ether.h"
#include "nlpid.h"
#include "extract.h"
#include "gmpls.h"
#include "oui.h"
#include "signature.h"
static const char tstr[] = " [|isis]";
/*
* IS-IS is defined in ISO 10589. Look there for protocol definitions.
*/
#define SYSTEM_ID_LEN ETHER_ADDR_LEN
#define NODE_ID_LEN SYSTEM_ID_LEN+1
#define LSP_ID_LEN SYSTEM_ID_LEN+2
#define ISIS_VERSION 1
#define ESIS_VERSION 1
#define CLNP_VERSION 1
#define ISIS_PDU_TYPE_MASK 0x1F
#define ESIS_PDU_TYPE_MASK 0x1F
#define CLNP_PDU_TYPE_MASK 0x1F
#define CLNP_FLAG_MASK 0xE0
#define ISIS_LAN_PRIORITY_MASK 0x7F
#define ISIS_PDU_L1_LAN_IIH 15
#define ISIS_PDU_L2_LAN_IIH 16
#define ISIS_PDU_PTP_IIH 17
#define ISIS_PDU_L1_LSP 18
#define ISIS_PDU_L2_LSP 20
#define ISIS_PDU_L1_CSNP 24
#define ISIS_PDU_L2_CSNP 25
#define ISIS_PDU_L1_PSNP 26
#define ISIS_PDU_L2_PSNP 27
static const struct tok isis_pdu_values[] = {
{ ISIS_PDU_L1_LAN_IIH, "L1 Lan IIH"},
{ ISIS_PDU_L2_LAN_IIH, "L2 Lan IIH"},
{ ISIS_PDU_PTP_IIH, "p2p IIH"},
{ ISIS_PDU_L1_LSP, "L1 LSP"},
{ ISIS_PDU_L2_LSP, "L2 LSP"},
{ ISIS_PDU_L1_CSNP, "L1 CSNP"},
{ ISIS_PDU_L2_CSNP, "L2 CSNP"},
{ ISIS_PDU_L1_PSNP, "L1 PSNP"},
{ ISIS_PDU_L2_PSNP, "L2 PSNP"},
{ 0, NULL}
};
/*
* A TLV is a tuple of a type, length and a value and is normally used for
* encoding information in all sorts of places. This is an enumeration of
* the well known types.
*
* list taken from rfc3359 plus some memory from veterans ;-)
*/
#define ISIS_TLV_AREA_ADDR 1 /* iso10589 */
#define ISIS_TLV_IS_REACH 2 /* iso10589 */
#define ISIS_TLV_ESNEIGH 3 /* iso10589 */
#define ISIS_TLV_PART_DIS 4 /* iso10589 */
#define ISIS_TLV_PREFIX_NEIGH 5 /* iso10589 */
#define ISIS_TLV_ISNEIGH 6 /* iso10589 */
#define ISIS_TLV_ISNEIGH_VARLEN 7 /* iso10589 */
#define ISIS_TLV_PADDING 8 /* iso10589 */
#define ISIS_TLV_LSP 9 /* iso10589 */
#define ISIS_TLV_AUTH 10 /* iso10589, rfc3567 */
#define ISIS_TLV_CHECKSUM 12 /* rfc3358 */
#define ISIS_TLV_CHECKSUM_MINLEN 2
#define ISIS_TLV_POI 13 /* rfc6232 */
#define ISIS_TLV_LSP_BUFFERSIZE 14 /* iso10589 rev2 */
#define ISIS_TLV_LSP_BUFFERSIZE_MINLEN 2
#define ISIS_TLV_EXT_IS_REACH 22 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_IS_ALIAS_ID 24 /* draft-ietf-isis-ext-lsp-frags-02 */
#define ISIS_TLV_DECNET_PHASE4 42
#define ISIS_TLV_LUCENT_PRIVATE 66
#define ISIS_TLV_INT_IP_REACH 128 /* rfc1195, rfc2966 */
#define ISIS_TLV_PROTOCOLS 129 /* rfc1195 */
#define ISIS_TLV_EXT_IP_REACH 130 /* rfc1195, rfc2966 */
#define ISIS_TLV_IDRP_INFO 131 /* rfc1195 */
#define ISIS_TLV_IDRP_INFO_MINLEN 1
#define ISIS_TLV_IPADDR 132 /* rfc1195 */
#define ISIS_TLV_IPAUTH 133 /* rfc1195 */
#define ISIS_TLV_TE_ROUTER_ID 134 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_EXTD_IP_REACH 135 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_HOSTNAME 137 /* rfc2763 */
#define ISIS_TLV_SHARED_RISK_GROUP 138 /* draft-ietf-isis-gmpls-extensions */
#define ISIS_TLV_MT_PORT_CAP 143 /* rfc6165 */
#define ISIS_TLV_MT_CAPABILITY 144 /* rfc6329 */
#define ISIS_TLV_NORTEL_PRIVATE1 176
#define ISIS_TLV_NORTEL_PRIVATE2 177
#define ISIS_TLV_RESTART_SIGNALING 211 /* rfc3847 */
#define ISIS_TLV_RESTART_SIGNALING_FLAGLEN 1
#define ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN 2
#define ISIS_TLV_MT_IS_REACH 222 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_MT_SUPPORTED 229 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_MT_SUPPORTED_MINLEN 2
#define ISIS_TLV_IP6ADDR 232 /* draft-ietf-isis-ipv6-02 */
#define ISIS_TLV_MT_IP_REACH 235 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_IP6_REACH 236 /* draft-ietf-isis-ipv6-02 */
#define ISIS_TLV_MT_IP6_REACH 237 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_PTP_ADJ 240 /* rfc3373 */
#define ISIS_TLV_IIH_SEQNR 241 /* draft-shen-isis-iih-sequence-00 */
#define ISIS_TLV_IIH_SEQNR_MINLEN 4
#define ISIS_TLV_VENDOR_PRIVATE 250 /* draft-ietf-isis-experimental-tlv-01 */
#define ISIS_TLV_VENDOR_PRIVATE_MINLEN 3
static const struct tok isis_tlv_values[] = {
{ ISIS_TLV_AREA_ADDR, "Area address(es)"},
{ ISIS_TLV_IS_REACH, "IS Reachability"},
{ ISIS_TLV_ESNEIGH, "ES Neighbor(s)"},
{ ISIS_TLV_PART_DIS, "Partition DIS"},
{ ISIS_TLV_PREFIX_NEIGH, "Prefix Neighbors"},
{ ISIS_TLV_ISNEIGH, "IS Neighbor(s)"},
{ ISIS_TLV_ISNEIGH_VARLEN, "IS Neighbor(s) (variable length)"},
{ ISIS_TLV_PADDING, "Padding"},
{ ISIS_TLV_LSP, "LSP entries"},
{ ISIS_TLV_AUTH, "Authentication"},
{ ISIS_TLV_CHECKSUM, "Checksum"},
{ ISIS_TLV_POI, "Purge Originator Identifier"},
{ ISIS_TLV_LSP_BUFFERSIZE, "LSP Buffersize"},
{ ISIS_TLV_EXT_IS_REACH, "Extended IS Reachability"},
{ ISIS_TLV_IS_ALIAS_ID, "IS Alias ID"},
{ ISIS_TLV_DECNET_PHASE4, "DECnet Phase IV"},
{ ISIS_TLV_LUCENT_PRIVATE, "Lucent Proprietary"},
{ ISIS_TLV_INT_IP_REACH, "IPv4 Internal Reachability"},
{ ISIS_TLV_PROTOCOLS, "Protocols supported"},
{ ISIS_TLV_EXT_IP_REACH, "IPv4 External Reachability"},
{ ISIS_TLV_IDRP_INFO, "Inter-Domain Information Type"},
{ ISIS_TLV_IPADDR, "IPv4 Interface address(es)"},
{ ISIS_TLV_IPAUTH, "IPv4 authentication (deprecated)"},
{ ISIS_TLV_TE_ROUTER_ID, "Traffic Engineering Router ID"},
{ ISIS_TLV_EXTD_IP_REACH, "Extended IPv4 Reachability"},
{ ISIS_TLV_SHARED_RISK_GROUP, "Shared Risk Link Group"},
{ ISIS_TLV_MT_PORT_CAP, "Multi-Topology-Aware Port Capability"},
{ ISIS_TLV_MT_CAPABILITY, "Multi-Topology Capability"},
{ ISIS_TLV_NORTEL_PRIVATE1, "Nortel Proprietary"},
{ ISIS_TLV_NORTEL_PRIVATE2, "Nortel Proprietary"},
{ ISIS_TLV_HOSTNAME, "Hostname"},
{ ISIS_TLV_RESTART_SIGNALING, "Restart Signaling"},
{ ISIS_TLV_MT_IS_REACH, "Multi Topology IS Reachability"},
{ ISIS_TLV_MT_SUPPORTED, "Multi Topology"},
{ ISIS_TLV_IP6ADDR, "IPv6 Interface address(es)"},
{ ISIS_TLV_MT_IP_REACH, "Multi-Topology IPv4 Reachability"},
{ ISIS_TLV_IP6_REACH, "IPv6 reachability"},
{ ISIS_TLV_MT_IP6_REACH, "Multi-Topology IP6 Reachability"},
{ ISIS_TLV_PTP_ADJ, "Point-to-point Adjacency State"},
{ ISIS_TLV_IIH_SEQNR, "Hello PDU Sequence Number"},
{ ISIS_TLV_VENDOR_PRIVATE, "Vendor Private"},
{ 0, NULL }
};
#define ESIS_OPTION_PROTOCOLS 129
#define ESIS_OPTION_QOS_MAINTENANCE 195 /* iso9542 */
#define ESIS_OPTION_SECURITY 197 /* iso9542 */
#define ESIS_OPTION_ES_CONF_TIME 198 /* iso9542 */
#define ESIS_OPTION_PRIORITY 205 /* iso9542 */
#define ESIS_OPTION_ADDRESS_MASK 225 /* iso9542 */
#define ESIS_OPTION_SNPA_MASK 226 /* iso9542 */
static const struct tok esis_option_values[] = {
{ ESIS_OPTION_PROTOCOLS, "Protocols supported"},
{ ESIS_OPTION_QOS_MAINTENANCE, "QoS Maintenance" },
{ ESIS_OPTION_SECURITY, "Security" },
{ ESIS_OPTION_ES_CONF_TIME, "ES Configuration Time" },
{ ESIS_OPTION_PRIORITY, "Priority" },
{ ESIS_OPTION_ADDRESS_MASK, "Addressk Mask" },
{ ESIS_OPTION_SNPA_MASK, "SNPA Mask" },
{ 0, NULL }
};
#define CLNP_OPTION_DISCARD_REASON 193
#define CLNP_OPTION_QOS_MAINTENANCE 195 /* iso8473 */
#define CLNP_OPTION_SECURITY 197 /* iso8473 */
#define CLNP_OPTION_SOURCE_ROUTING 200 /* iso8473 */
#define CLNP_OPTION_ROUTE_RECORDING 203 /* iso8473 */
#define CLNP_OPTION_PADDING 204 /* iso8473 */
#define CLNP_OPTION_PRIORITY 205 /* iso8473 */
static const struct tok clnp_option_values[] = {
{ CLNP_OPTION_DISCARD_REASON, "Discard Reason"},
{ CLNP_OPTION_PRIORITY, "Priority"},
{ CLNP_OPTION_QOS_MAINTENANCE, "QoS Maintenance"},
{ CLNP_OPTION_SECURITY, "Security"},
{ CLNP_OPTION_SOURCE_ROUTING, "Source Routing"},
{ CLNP_OPTION_ROUTE_RECORDING, "Route Recording"},
{ CLNP_OPTION_PADDING, "Padding"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_class_values[] = {
{ 0x0, "General"},
{ 0x8, "Address"},
{ 0x9, "Source Routeing"},
{ 0xa, "Lifetime"},
{ 0xb, "PDU Discarded"},
{ 0xc, "Reassembly"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_general_values[] = {
{ 0x0, "Reason not specified"},
{ 0x1, "Protocol procedure error"},
{ 0x2, "Incorrect checksum"},
{ 0x3, "PDU discarded due to congestion"},
{ 0x4, "Header syntax error (cannot be parsed)"},
{ 0x5, "Segmentation needed but not permitted"},
{ 0x6, "Incomplete PDU received"},
{ 0x7, "Duplicate option"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_address_values[] = {
{ 0x0, "Destination address unreachable"},
{ 0x1, "Destination address unknown"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_source_routeing_values[] = {
{ 0x0, "Unspecified source routeing error"},
{ 0x1, "Syntax error in source routeing field"},
{ 0x2, "Unknown address in source routeing field"},
{ 0x3, "Path not acceptable"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_lifetime_values[] = {
{ 0x0, "Lifetime expired while data unit in transit"},
{ 0x1, "Lifetime expired during reassembly"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_pdu_discard_values[] = {
{ 0x0, "Unsupported option not specified"},
{ 0x1, "Unsupported protocol version"},
{ 0x2, "Unsupported security option"},
{ 0x3, "Unsupported source routeing option"},
{ 0x4, "Unsupported recording of route option"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_reassembly_values[] = {
{ 0x0, "Reassembly interference"},
{ 0, NULL }
};
/* array of 16 error-classes */
static const struct tok *clnp_option_rfd_error_class[] = {
clnp_option_rfd_general_values,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
clnp_option_rfd_address_values,
clnp_option_rfd_source_routeing_values,
clnp_option_rfd_lifetime_values,
clnp_option_rfd_pdu_discard_values,
clnp_option_rfd_reassembly_values,
NULL,
NULL,
NULL
};
#define CLNP_OPTION_OPTION_QOS_MASK 0x3f
#define CLNP_OPTION_SCOPE_MASK 0xc0
#define CLNP_OPTION_SCOPE_SA_SPEC 0x40
#define CLNP_OPTION_SCOPE_DA_SPEC 0x80
#define CLNP_OPTION_SCOPE_GLOBAL 0xc0
static const struct tok clnp_option_scope_values[] = {
{ CLNP_OPTION_SCOPE_SA_SPEC, "Source Address Specific"},
{ CLNP_OPTION_SCOPE_DA_SPEC, "Destination Address Specific"},
{ CLNP_OPTION_SCOPE_GLOBAL, "Globally unique"},
{ 0, NULL }
};
static const struct tok clnp_option_sr_rr_values[] = {
{ 0x0, "partial"},
{ 0x1, "complete"},
{ 0, NULL }
};
static const struct tok clnp_option_sr_rr_string_values[] = {
{ CLNP_OPTION_SOURCE_ROUTING, "source routing"},
{ CLNP_OPTION_ROUTE_RECORDING, "recording of route in progress"},
{ 0, NULL }
};
static const struct tok clnp_option_qos_global_values[] = {
{ 0x20, "reserved"},
{ 0x10, "sequencing vs. delay"},
{ 0x08, "congested"},
{ 0x04, "delay vs. cost"},
{ 0x02, "error vs. delay"},
{ 0x01, "error vs. cost"},
{ 0, NULL }
};
#define ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP 3 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID 4 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID 5 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR 6 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR 8 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW 9 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW 10 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW 11 /* rfc4124 */
#define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD 12 /* draft-ietf-tewg-diff-te-proto-06 */
#define ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC 18 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE 19 /* draft-ietf-isis-link-attr-01 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE 20 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR 21 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS 22 /* rfc4124 */
#define ISIS_SUBTLV_SPB_METRIC 29 /* rfc6329 */
static const struct tok isis_ext_is_reach_subtlv_values[] = {
{ ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP, "Administrative groups" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID, "Link Local/Remote Identifier" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID, "Link Remote Identifier" },
{ ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR, "IPv4 interface address" },
{ ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR, "IPv4 neighbor address" },
{ ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW, "Maximum link bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW, "Reservable link bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW, "Unreserved bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC, "Traffic Engineering Metric" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE, "Link Attribute" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE, "Link Protection Type" },
{ ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR, "Interface Switching Capability" },
{ ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD, "Bandwidth Constraints (old)" },
{ ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS, "Bandwidth Constraints" },
{ ISIS_SUBTLV_SPB_METRIC, "SPB Metric" },
{ 250, "Reserved for cisco specific extensions" },
{ 251, "Reserved for cisco specific extensions" },
{ 252, "Reserved for cisco specific extensions" },
{ 253, "Reserved for cisco specific extensions" },
{ 254, "Reserved for cisco specific extensions" },
{ 255, "Reserved for future expansion" },
{ 0, NULL }
};
#define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32 1 /* draft-ietf-isis-admin-tags-01 */
#define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64 2 /* draft-ietf-isis-admin-tags-01 */
#define ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR 117 /* draft-ietf-isis-wg-multi-topology-05 */
static const struct tok isis_ext_ip_reach_subtlv_values[] = {
{ ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32, "32-Bit Administrative tag" },
{ ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64, "64-Bit Administrative tag" },
{ ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR, "Management Prefix Color" },
{ 0, NULL }
};
static const struct tok isis_subtlv_link_attribute_values[] = {
{ 0x01, "Local Protection Available" },
{ 0x02, "Link excluded from local protection path" },
{ 0x04, "Local maintenance required"},
{ 0, NULL }
};
#define ISIS_SUBTLV_AUTH_SIMPLE 1
#define ISIS_SUBTLV_AUTH_GENERIC 3 /* rfc 5310 */
#define ISIS_SUBTLV_AUTH_MD5 54
#define ISIS_SUBTLV_AUTH_MD5_LEN 16
#define ISIS_SUBTLV_AUTH_PRIVATE 255
static const struct tok isis_subtlv_auth_values[] = {
{ ISIS_SUBTLV_AUTH_SIMPLE, "simple text password"},
{ ISIS_SUBTLV_AUTH_GENERIC, "Generic Crypto key-id"},
{ ISIS_SUBTLV_AUTH_MD5, "HMAC-MD5 password"},
{ ISIS_SUBTLV_AUTH_PRIVATE, "Routing Domain private password"},
{ 0, NULL }
};
#define ISIS_SUBTLV_IDRP_RES 0
#define ISIS_SUBTLV_IDRP_LOCAL 1
#define ISIS_SUBTLV_IDRP_ASN 2
static const struct tok isis_subtlv_idrp_values[] = {
{ ISIS_SUBTLV_IDRP_RES, "Reserved"},
{ ISIS_SUBTLV_IDRP_LOCAL, "Routing-Domain Specific"},
{ ISIS_SUBTLV_IDRP_ASN, "AS Number Tag"},
{ 0, NULL}
};
#define ISIS_SUBTLV_SPB_MCID 4
#define ISIS_SUBTLV_SPB_DIGEST 5
#define ISIS_SUBTLV_SPB_BVID 6
#define ISIS_SUBTLV_SPB_INSTANCE 1
#define ISIS_SUBTLV_SPBM_SI 3
#define ISIS_SPB_MCID_LEN 51
#define ISIS_SUBTLV_SPB_MCID_MIN_LEN 102
#define ISIS_SUBTLV_SPB_DIGEST_MIN_LEN 33
#define ISIS_SUBTLV_SPB_BVID_MIN_LEN 6
#define ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN 19
#define ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN 8
static const struct tok isis_mt_port_cap_subtlv_values[] = {
{ ISIS_SUBTLV_SPB_MCID, "SPB MCID" },
{ ISIS_SUBTLV_SPB_DIGEST, "SPB Digest" },
{ ISIS_SUBTLV_SPB_BVID, "SPB BVID" },
{ 0, NULL }
};
static const struct tok isis_mt_capability_subtlv_values[] = {
{ ISIS_SUBTLV_SPB_INSTANCE, "SPB Instance" },
{ ISIS_SUBTLV_SPBM_SI, "SPBM Service Identifier and Unicast Address" },
{ 0, NULL }
};
struct isis_spb_mcid {
uint8_t format_id;
uint8_t name[32];
uint8_t revision_lvl[2];
uint8_t digest[16];
};
struct isis_subtlv_spb_mcid {
struct isis_spb_mcid mcid;
struct isis_spb_mcid aux_mcid;
};
struct isis_subtlv_spb_instance {
uint8_t cist_root_id[8];
uint8_t cist_external_root_path_cost[4];
uint8_t bridge_priority[2];
uint8_t spsourceid[4];
uint8_t no_of_trees;
};
#define CLNP_SEGMENT_PART 0x80
#define CLNP_MORE_SEGMENTS 0x40
#define CLNP_REQUEST_ER 0x20
static const struct tok clnp_flag_values[] = {
{ CLNP_SEGMENT_PART, "Segmentation permitted"},
{ CLNP_MORE_SEGMENTS, "more Segments"},
{ CLNP_REQUEST_ER, "request Error Report"},
{ 0, NULL}
};
#define ISIS_MASK_LSP_OL_BIT(x) ((x)&0x4)
#define ISIS_MASK_LSP_ISTYPE_BITS(x) ((x)&0x3)
#define ISIS_MASK_LSP_PARTITION_BIT(x) ((x)&0x80)
#define ISIS_MASK_LSP_ATT_BITS(x) ((x)&0x78)
#define ISIS_MASK_LSP_ATT_ERROR_BIT(x) ((x)&0x40)
#define ISIS_MASK_LSP_ATT_EXPENSE_BIT(x) ((x)&0x20)
#define ISIS_MASK_LSP_ATT_DELAY_BIT(x) ((x)&0x10)
#define ISIS_MASK_LSP_ATT_DEFAULT_BIT(x) ((x)&0x8)
#define ISIS_MASK_MTID(x) ((x)&0x0fff)
#define ISIS_MASK_MTFLAGS(x) ((x)&0xf000)
static const struct tok isis_mt_flag_values[] = {
{ 0x4000, "ATT bit set"},
{ 0x8000, "Overload bit set"},
{ 0, NULL}
};
#define ISIS_MASK_TLV_EXTD_IP_UPDOWN(x) ((x)&0x80)
#define ISIS_MASK_TLV_EXTD_IP_SUBTLV(x) ((x)&0x40)
#define ISIS_MASK_TLV_EXTD_IP6_IE(x) ((x)&0x40)
#define ISIS_MASK_TLV_EXTD_IP6_SUBTLV(x) ((x)&0x20)
#define ISIS_LSP_TLV_METRIC_SUPPORTED(x) ((x)&0x80)
#define ISIS_LSP_TLV_METRIC_IE(x) ((x)&0x40)
#define ISIS_LSP_TLV_METRIC_UPDOWN(x) ((x)&0x80)
#define ISIS_LSP_TLV_METRIC_VALUE(x) ((x)&0x3f)
#define ISIS_MASK_TLV_SHARED_RISK_GROUP(x) ((x)&0x1)
static const struct tok isis_mt_values[] = {
{ 0, "IPv4 unicast"},
{ 1, "In-Band Management"},
{ 2, "IPv6 unicast"},
{ 3, "Multicast"},
{ 4095, "Development, Experimental or Proprietary"},
{ 0, NULL }
};
static const struct tok isis_iih_circuit_type_values[] = {
{ 1, "Level 1 only"},
{ 2, "Level 2 only"},
{ 3, "Level 1, Level 2"},
{ 0, NULL}
};
#define ISIS_LSP_TYPE_UNUSED0 0
#define ISIS_LSP_TYPE_LEVEL_1 1
#define ISIS_LSP_TYPE_UNUSED2 2
#define ISIS_LSP_TYPE_LEVEL_2 3
static const struct tok isis_lsp_istype_values[] = {
{ ISIS_LSP_TYPE_UNUSED0, "Unused 0x0 (invalid)"},
{ ISIS_LSP_TYPE_LEVEL_1, "L1 IS"},
{ ISIS_LSP_TYPE_UNUSED2, "Unused 0x2 (invalid)"},
{ ISIS_LSP_TYPE_LEVEL_2, "L2 IS"},
{ 0, NULL }
};
/*
* Katz's point to point adjacency TLV uses codes to tell us the state of
* the remote adjacency. Enumerate them.
*/
#define ISIS_PTP_ADJ_UP 0
#define ISIS_PTP_ADJ_INIT 1
#define ISIS_PTP_ADJ_DOWN 2
static const struct tok isis_ptp_adjancey_values[] = {
{ ISIS_PTP_ADJ_UP, "Up" },
{ ISIS_PTP_ADJ_INIT, "Initializing" },
{ ISIS_PTP_ADJ_DOWN, "Down" },
{ 0, NULL}
};
struct isis_tlv_ptp_adj {
uint8_t adjacency_state;
uint8_t extd_local_circuit_id[4];
uint8_t neighbor_sysid[SYSTEM_ID_LEN];
uint8_t neighbor_extd_local_circuit_id[4];
};
static void osi_print_cksum(netdissect_options *, const uint8_t *pptr,
uint16_t checksum, int checksum_offset, u_int length);
static int clnp_print(netdissect_options *, const uint8_t *, u_int);
static void esis_print(netdissect_options *, const uint8_t *, u_int);
static int isis_print(netdissect_options *, const uint8_t *, u_int);
struct isis_metric_block {
uint8_t metric_default;
uint8_t metric_delay;
uint8_t metric_expense;
uint8_t metric_error;
};
struct isis_tlv_is_reach {
struct isis_metric_block isis_metric_block;
uint8_t neighbor_nodeid[NODE_ID_LEN];
};
struct isis_tlv_es_reach {
struct isis_metric_block isis_metric_block;
uint8_t neighbor_sysid[SYSTEM_ID_LEN];
};
struct isis_tlv_ip_reach {
struct isis_metric_block isis_metric_block;
uint8_t prefix[4];
uint8_t mask[4];
};
static const struct tok isis_is_reach_virtual_values[] = {
{ 0, "IsNotVirtual"},
{ 1, "IsVirtual"},
{ 0, NULL }
};
static const struct tok isis_restart_flag_values[] = {
{ 0x1, "Restart Request"},
{ 0x2, "Restart Acknowledgement"},
{ 0x4, "Suppress adjacency advertisement"},
{ 0, NULL }
};
struct isis_common_header {
uint8_t nlpid;
uint8_t fixed_len;
uint8_t version; /* Protocol version */
uint8_t id_length;
uint8_t pdu_type; /* 3 MSbits are reserved */
uint8_t pdu_version; /* Packet format version */
uint8_t reserved;
uint8_t max_area;
};
struct isis_iih_lan_header {
uint8_t circuit_type;
uint8_t source_id[SYSTEM_ID_LEN];
uint8_t holding_time[2];
uint8_t pdu_len[2];
uint8_t priority;
uint8_t lan_id[NODE_ID_LEN];
};
struct isis_iih_ptp_header {
uint8_t circuit_type;
uint8_t source_id[SYSTEM_ID_LEN];
uint8_t holding_time[2];
uint8_t pdu_len[2];
uint8_t circuit_id;
};
struct isis_lsp_header {
uint8_t pdu_len[2];
uint8_t remaining_lifetime[2];
uint8_t lsp_id[LSP_ID_LEN];
uint8_t sequence_number[4];
uint8_t checksum[2];
uint8_t typeblock;
};
struct isis_csnp_header {
uint8_t pdu_len[2];
uint8_t source_id[NODE_ID_LEN];
uint8_t start_lsp_id[LSP_ID_LEN];
uint8_t end_lsp_id[LSP_ID_LEN];
};
struct isis_psnp_header {
uint8_t pdu_len[2];
uint8_t source_id[NODE_ID_LEN];
};
struct isis_tlv_lsp {
uint8_t remaining_lifetime[2];
uint8_t lsp_id[LSP_ID_LEN];
uint8_t sequence_number[4];
uint8_t checksum[2];
};
#define ISIS_COMMON_HEADER_SIZE (sizeof(struct isis_common_header))
#define ISIS_IIH_LAN_HEADER_SIZE (sizeof(struct isis_iih_lan_header))
#define ISIS_IIH_PTP_HEADER_SIZE (sizeof(struct isis_iih_ptp_header))
#define ISIS_LSP_HEADER_SIZE (sizeof(struct isis_lsp_header))
#define ISIS_CSNP_HEADER_SIZE (sizeof(struct isis_csnp_header))
#define ISIS_PSNP_HEADER_SIZE (sizeof(struct isis_psnp_header))
void
isoclns_print(netdissect_options *ndo, const uint8_t *p, u_int length)
{
if (!ND_TTEST(*p)) { /* enough bytes on the wire ? */
ND_PRINT((ndo, "|OSI"));
return;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p));
switch (*p) {
case NLPID_CLNP:
if (!clnp_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_ESIS:
esis_print(ndo, p, length);
return;
case NLPID_ISIS:
if (!isis_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_NULLNS:
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
break;
case NLPID_Q933:
q933_print(ndo, p + 1, length - 1);
break;
case NLPID_IP:
ip_print(ndo, p + 1, length - 1);
break;
case NLPID_IP6:
ip6_print(ndo, p + 1, length - 1);
break;
case NLPID_PPP:
ppp_print(ndo, p + 1, length - 1);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p));
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
if (length > 1)
print_unknown_data(ndo, p, "\n\t", length);
break;
}
}
#define CLNP_PDU_ER 1
#define CLNP_PDU_DT 28
#define CLNP_PDU_MD 29
#define CLNP_PDU_ERQ 30
#define CLNP_PDU_ERP 31
static const struct tok clnp_pdu_values[] = {
{ CLNP_PDU_ER, "Error Report"},
{ CLNP_PDU_MD, "MD"},
{ CLNP_PDU_DT, "Data"},
{ CLNP_PDU_ERQ, "Echo Request"},
{ CLNP_PDU_ERP, "Echo Response"},
{ 0, NULL }
};
struct clnp_header_t {
uint8_t nlpid;
uint8_t length_indicator;
uint8_t version;
uint8_t lifetime; /* units of 500ms */
uint8_t type;
uint8_t segment_length[2];
uint8_t cksum[2];
};
struct clnp_segment_header_t {
uint8_t data_unit_id[2];
uint8_t segment_offset[2];
uint8_t total_length[2];
};
/*
* clnp_print
* Decode CLNP packets. Return 0 on error.
*/
static int
clnp_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr,*source_address,*dest_address;
u_int li,tlen,nsap_offset,source_address_length,dest_address_length, clnp_pdu_type, clnp_flags;
const struct clnp_header_t *clnp_header;
const struct clnp_segment_header_t *clnp_segment_header;
uint8_t rfd_error_major,rfd_error_minor;
clnp_header = (const struct clnp_header_t *) pptr;
ND_TCHECK(*clnp_header);
li = clnp_header->length_indicator;
optr = pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "CLNP"));
/*
* Sanity checking of the header.
*/
if (clnp_header->version != CLNP_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", clnp_header->version));
return (0);
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return (0);
}
if (li < sizeof(struct clnp_header_t)) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return (0);
}
/* FIXME further header sanity checking */
clnp_pdu_type = clnp_header->type & CLNP_PDU_TYPE_MASK;
clnp_flags = clnp_header->type & CLNP_FLAG_MASK;
pptr += sizeof(struct clnp_header_t);
li -= sizeof(struct clnp_header_t);
if (li < 1) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK(*pptr);
dest_address_length = *pptr;
pptr += 1;
li -= 1;
if (li < dest_address_length) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK2(*pptr, dest_address_length);
dest_address = pptr;
pptr += dest_address_length;
li -= dest_address_length;
if (li < 1) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK(*pptr);
source_address_length = *pptr;
pptr += 1;
li -= 1;
if (li < source_address_length) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK2(*pptr, source_address_length);
source_address = pptr;
pptr += source_address_length;
li -= source_address_length;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s > %s, %s, length %u",
ndo->ndo_eflag ? "" : ", ",
isonsap_string(ndo, source_address, source_address_length),
isonsap_string(ndo, dest_address, dest_address_length),
tok2str(clnp_pdu_values,"unknown (%u)",clnp_pdu_type),
length));
return (1);
}
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s PDU, hlen: %u, v: %u, lifetime: %u.%us, Segment PDU length: %u, checksum: 0x%04x",
tok2str(clnp_pdu_values, "unknown (%u)",clnp_pdu_type),
clnp_header->length_indicator,
clnp_header->version,
clnp_header->lifetime/2,
(clnp_header->lifetime%2)*5,
EXTRACT_16BITS(clnp_header->segment_length),
EXTRACT_16BITS(clnp_header->cksum)));
osi_print_cksum(ndo, optr, EXTRACT_16BITS(clnp_header->cksum), 7,
clnp_header->length_indicator);
ND_PRINT((ndo, "\n\tFlags [%s]",
bittok2str(clnp_flag_values, "none", clnp_flags)));
ND_PRINT((ndo, "\n\tsource address (length %u): %s\n\tdest address (length %u): %s",
source_address_length,
isonsap_string(ndo, source_address, source_address_length),
dest_address_length,
isonsap_string(ndo, dest_address, dest_address_length)));
if (clnp_flags & CLNP_SEGMENT_PART) {
if (li < sizeof(const struct clnp_segment_header_t)) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header, addresses, and segment part"));
return (0);
}
clnp_segment_header = (const struct clnp_segment_header_t *) pptr;
ND_TCHECK(*clnp_segment_header);
ND_PRINT((ndo, "\n\tData Unit ID: 0x%04x, Segment Offset: %u, Total PDU Length: %u",
EXTRACT_16BITS(clnp_segment_header->data_unit_id),
EXTRACT_16BITS(clnp_segment_header->segment_offset),
EXTRACT_16BITS(clnp_segment_header->total_length)));
pptr+=sizeof(const struct clnp_segment_header_t);
li-=sizeof(const struct clnp_segment_header_t);
}
/* now walk the options */
while (li >= 2) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return (0);
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return (0);
}
ND_TCHECK2(*pptr, opli);
li -= opli;
tptr = pptr;
tlen = opli;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(clnp_option_values,"Unknown",op),
op,
opli));
/*
* We've already checked that the entire option is present
* in the captured packet with the ND_TCHECK2() call.
* Therefore, we don't need to do ND_TCHECK()/ND_TCHECK2()
* checks.
* We do, however, need to check tlen, to make sure we
* don't run past the end of the option.
*/
switch (op) {
case CLNP_OPTION_ROUTE_RECORDING: /* those two options share the format */
case CLNP_OPTION_SOURCE_ROUTING:
if (tlen < 2) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "%s %s",
tok2str(clnp_option_sr_rr_values,"Unknown",*tptr),
tok2str(clnp_option_sr_rr_string_values, "Unknown Option %u", op)));
nsap_offset=*(tptr+1);
if (nsap_offset == 0) {
ND_PRINT((ndo, " Bad NSAP offset (0)"));
break;
}
nsap_offset-=1; /* offset to nsap list */
if (nsap_offset > tlen) {
ND_PRINT((ndo, " Bad NSAP offset (past end of option)"));
break;
}
tptr+=nsap_offset;
tlen-=nsap_offset;
while (tlen > 0) {
source_address_length=*tptr;
if (tlen < source_address_length+1) {
ND_PRINT((ndo, "\n\t NSAP address goes past end of option"));
break;
}
if (source_address_length > 0) {
source_address=(tptr+1);
ND_TCHECK2(*source_address, source_address_length);
ND_PRINT((ndo, "\n\t NSAP address (length %u): %s",
source_address_length,
isonsap_string(ndo, source_address, source_address_length)));
}
tlen-=source_address_length+1;
}
break;
case CLNP_OPTION_PRIORITY:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "0x%1x", *tptr&0x0f));
break;
case CLNP_OPTION_QOS_MAINTENANCE:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "\n\t Format Code: %s",
tok2str(clnp_option_scope_values, "Reserved", *tptr&CLNP_OPTION_SCOPE_MASK)));
if ((*tptr&CLNP_OPTION_SCOPE_MASK) == CLNP_OPTION_SCOPE_GLOBAL)
ND_PRINT((ndo, "\n\t QoS Flags [%s]",
bittok2str(clnp_option_qos_global_values,
"none",
*tptr&CLNP_OPTION_OPTION_QOS_MASK)));
break;
case CLNP_OPTION_SECURITY:
if (tlen < 2) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "\n\t Format Code: %s, Security-Level %u",
tok2str(clnp_option_scope_values,"Reserved",*tptr&CLNP_OPTION_SCOPE_MASK),
*(tptr+1)));
break;
case CLNP_OPTION_DISCARD_REASON:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
rfd_error_major = (*tptr&0xf0) >> 4;
rfd_error_minor = *tptr&0x0f;
ND_PRINT((ndo, "\n\t Class: %s Error (0x%01x), %s (0x%01x)",
tok2str(clnp_option_rfd_class_values,"Unknown",rfd_error_major),
rfd_error_major,
tok2str(clnp_option_rfd_error_class[rfd_error_major],"Unknown",rfd_error_minor),
rfd_error_minor));
break;
case CLNP_OPTION_PADDING:
ND_PRINT((ndo, "padding data"));
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
switch (clnp_pdu_type) {
case CLNP_PDU_ER: /* fall through */
case CLNP_PDU_ERP:
ND_TCHECK(*pptr);
if (*(pptr) == NLPID_CLNP) {
ND_PRINT((ndo, "\n\t-----original packet-----\n\t"));
/* FIXME recursion protection */
clnp_print(ndo, pptr, length - clnp_header->length_indicator);
break;
}
case CLNP_PDU_DT:
case CLNP_PDU_MD:
case CLNP_PDU_ERQ:
default:
/* dump the PDU specific data */
if (length-(pptr-optr) > 0) {
ND_PRINT((ndo, "\n\t undecoded non-header data, length %u", length-clnp_header->length_indicator));
print_unknown_data(ndo, pptr, "\n\t ", length - (pptr - optr));
}
}
return (1);
trunc:
ND_PRINT((ndo, "[|clnp]"));
return (1);
}
#define ESIS_PDU_REDIRECT 6
#define ESIS_PDU_ESH 2
#define ESIS_PDU_ISH 4
static const struct tok esis_pdu_values[] = {
{ ESIS_PDU_REDIRECT, "redirect"},
{ ESIS_PDU_ESH, "ESH"},
{ ESIS_PDU_ISH, "ISH"},
{ 0, NULL }
};
struct esis_header_t {
uint8_t nlpid;
uint8_t length_indicator;
uint8_t version;
uint8_t reserved;
uint8_t type;
uint8_t holdtime[2];
uint8_t cksum[2];
};
static void
esis_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr;
u_int li,esis_pdu_type,source_address_length, source_address_number;
const struct esis_header_t *esis_header;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "ES-IS"));
if (length <= 2) {
ND_PRINT((ndo, ndo->ndo_qflag ? "bad pkt!" : "no header at all!"));
return;
}
esis_header = (const struct esis_header_t *) pptr;
ND_TCHECK(*esis_header);
li = esis_header->length_indicator;
optr = pptr;
/*
* Sanity checking of the header.
*/
if (esis_header->nlpid != NLPID_ESIS) {
ND_PRINT((ndo, " nlpid 0x%02x packet not supported", esis_header->nlpid));
return;
}
if (esis_header->version != ESIS_VERSION) {
ND_PRINT((ndo, " version %d packet not supported", esis_header->version));
return;
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return;
}
if (li < sizeof(struct esis_header_t) + 2) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return;
}
esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s, length %u",
ndo->ndo_eflag ? "" : ", ",
tok2str(esis_pdu_values,"unknown type (%u)",esis_pdu_type),
length));
return;
} else
ND_PRINT((ndo, "%slength %u\n\t%s (%u)",
ndo->ndo_eflag ? "" : ", ",
length,
tok2str(esis_pdu_values,"unknown type: %u", esis_pdu_type),
esis_pdu_type));
ND_PRINT((ndo, ", v: %u%s", esis_header->version, esis_header->version == ESIS_VERSION ? "" : "unsupported" ));
ND_PRINT((ndo, ", checksum: 0x%04x", EXTRACT_16BITS(esis_header->cksum)));
osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li);
ND_PRINT((ndo, ", holding time: %us, length indicator: %u",
EXTRACT_16BITS(esis_header->holdtime), li));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, optr, "\n\t", sizeof(struct esis_header_t));
pptr += sizeof(struct esis_header_t);
li -= sizeof(struct esis_header_t);
switch (esis_pdu_type) {
case ESIS_PDU_REDIRECT: {
const uint8_t *dst, *snpa, *neta;
u_int dstl, snpal, netal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dstl = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, dstl);
if (li < dstl) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dst = pptr;
pptr += dstl;
li -= dstl;
ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, dst, dstl)));
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpal = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, snpal);
if (li < snpal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpa = pptr;
pptr += snpal;
li -= snpal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
netal = *pptr;
pptr++;
ND_TCHECK2(*pptr, netal);
if (li < netal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
neta = pptr;
pptr += netal;
li -= netal;
if (netal == 0)
ND_PRINT((ndo, "\n\t %s", etheraddr_string(ndo, snpa)));
else
ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, neta, netal)));
break;
}
case ESIS_PDU_ESH:
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_number = *pptr;
pptr++;
li--;
ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number));
while (source_address_number > 0) {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s",
source_address_length,
isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
source_address_number--;
}
break;
case ESIS_PDU_ISH: {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
break;
}
default:
if (ndo->ndo_vflag <= 1) {
if (pptr < ndo->ndo_snapend)
print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr);
}
return;
}
/* now walk the options */
while (li != 0) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return;
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return;
}
li -= opli;
tptr = pptr;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(esis_option_values,"Unknown",op),
op,
opli));
switch (op) {
case ESIS_OPTION_ES_CONF_TIME:
if (opli == 2) {
ND_TCHECK2(*pptr, 2);
ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr)));
} else
ND_PRINT((ndo, "(bad length)"));
break;
case ESIS_OPTION_PROTOCOLS:
while (opli>0) {
ND_TCHECK(*pptr);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (opli>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
opli--;
}
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
case ESIS_OPTION_QOS_MAINTENANCE:
case ESIS_OPTION_SECURITY:
case ESIS_OPTION_PRIORITY:
case ESIS_OPTION_ADDRESS_MASK:
case ESIS_OPTION_SNPA_MASK:
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
trunc:
return;
}
static void
isis_print_mcid(netdissect_options *ndo,
const struct isis_spb_mcid *mcid)
{
int i;
ND_TCHECK(*mcid);
ND_PRINT((ndo, "ID: %d, Name: ", mcid->format_id));
if (fn_printzp(ndo, mcid->name, 32, ndo->ndo_snapend))
goto trunc;
ND_PRINT((ndo, "\n\t Lvl: %d", EXTRACT_16BITS(mcid->revision_lvl)));
ND_PRINT((ndo, ", Digest: "));
for(i=0;i<16;i++)
ND_PRINT((ndo, "%.2x ", mcid->digest[i]));
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static int
isis_print_mt_port_cap_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len;
const struct isis_subtlv_spb_mcid *subtlv_spb_mcid;
int i;
while (len > 2)
{
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
/*len -= TLV_TYPE_LEN_OFFSET;*/
len = len -2;
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_MCID:
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_MCID_MIN_LEN);
subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr;
ND_PRINT((ndo, "\n\t MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
ND_PRINT((ndo, "\n\t AUX-MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
tptr = tptr + sizeof(struct isis_subtlv_spb_mcid);
len = len - sizeof(struct isis_subtlv_spb_mcid);
break;
}
case ISIS_SUBTLV_SPB_DIGEST:
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_DIGEST_MIN_LEN);
ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d",
(*(tptr) >> 5), (((*tptr)>> 4) & 0x01),
((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03)));
tptr++;
ND_PRINT((ndo, "\n\t Digest: "));
for(i=1;i<=8; i++)
{
ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr)));
if (i%4 == 0 && i != 8)
ND_PRINT((ndo, "\n\t "));
tptr = tptr + 4;
}
len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_BVID:
{
ND_TCHECK2(*(tptr), stlv_len);
while (len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN)
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_BVID_MIN_LEN);
ND_PRINT((ndo, "\n\t ECT: %08x",
EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ",
(EXTRACT_16BITS (tptr) >> 4) ,
(EXTRACT_16BITS (tptr) >> 3) & 0x01,
(EXTRACT_16BITS (tptr) >> 2) & 0x01));
tptr = tptr + 2;
len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
}
break;
}
default:
break;
}
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
static int
isis_print_mt_capability_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len, tmp;
while (len > 2)
{
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
len = len - 2;
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_INSTANCE:
ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN);
ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr)));
tptr = tptr + 2;
ND_PRINT((ndo, "\n\t RES: %d",
EXTRACT_16BITS(tptr) >> 5));
ND_PRINT((ndo, ", V: %d",
(EXTRACT_16BITS(tptr) >> 4) & 0x0001));
ND_PRINT((ndo, ", SPSource-ID: %d",
(EXTRACT_32BITS(tptr) & 0x000fffff)));
tptr = tptr+4;
ND_PRINT((ndo, ", No of Trees: %x", *(tptr)));
tmp = *(tptr++);
len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;
while (tmp)
{
ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN);
ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d",
*(tptr) >> 7, (*(tptr) >> 6) & 0x01,
(*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f)));
tptr++;
ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr + 4;
ND_PRINT((ndo, ", BVID: %d, SPVID: %d",
(EXTRACT_24BITS(tptr) >> 12) & 0x000fff,
EXTRACT_24BITS(tptr) & 0x000fff));
tptr = tptr + 3;
len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;
tmp--;
}
break;
case ISIS_SUBTLV_SPBM_SI:
ND_TCHECK2(*tptr, 8);
ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr)));
tptr = tptr+2;
ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12,
(EXTRACT_16BITS(tptr)) & 0x0fff));
tptr = tptr+2;
len = len - 8;
stlv_len = stlv_len - 8;
while (stlv_len >= 4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d",
(EXTRACT_32BITS(tptr) >> 31),
(EXTRACT_32BITS(tptr) >> 30) & 0x01,
(EXTRACT_32BITS(tptr) >> 24) & 0x03f,
(EXTRACT_32BITS(tptr)) & 0x0ffffff));
tptr = tptr + 4;
len = len - 4;
stlv_len = stlv_len - 4;
}
break;
default:
break;
}
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
/* shared routine for printing system, node and lsp-ids */
static char *
isis_print_id(const uint8_t *cp, int id_len)
{
int i;
static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")];
char *pos = id;
for (i = 1; i <= SYSTEM_ID_LEN; i++) {
snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++);
pos += strlen(pos);
if (i == 2 || i == 4)
*pos++ = '.';
}
if (id_len >= NODE_ID_LEN) {
snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++);
pos += strlen(pos);
}
if (id_len == LSP_ID_LEN)
snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp);
return (id);
}
/* print the 4-byte metric block which is common found in the old-style TLVs */
static int
isis_print_metric_block(netdissect_options *ndo,
const struct isis_metric_block *isis_metric_block)
{
ND_PRINT((ndo, ", Default Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_default),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_delay))
ND_PRINT((ndo, "\n\t\t Delay Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_delay),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_expense))
ND_PRINT((ndo, "\n\t\t Expense Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_expense),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_error))
ND_PRINT((ndo, "\n\t\t Error Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_error),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_error) ? "External" : "Internal"));
return(1); /* everything is ok */
}
static int
isis_print_tlv_ip_reach(netdissect_options *ndo,
const uint8_t *cp, const char *ident, int length)
{
int prefix_len;
const struct isis_tlv_ip_reach *tlv_ip_reach;
tlv_ip_reach = (const struct isis_tlv_ip_reach *)cp;
while (length > 0) {
if ((size_t)length < sizeof(*tlv_ip_reach)) {
ND_PRINT((ndo, "short IPv4 Reachability (%d vs %lu)",
length,
(unsigned long)sizeof(*tlv_ip_reach)));
return (0);
}
if (!ND_TTEST(*tlv_ip_reach))
return (0);
prefix_len = mask2plen(EXTRACT_32BITS(tlv_ip_reach->mask));
if (prefix_len == -1)
ND_PRINT((ndo, "%sIPv4 prefix: %s mask %s",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
ipaddr_string(ndo, (tlv_ip_reach->mask))));
else
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
prefix_len));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u, %s",
ISIS_LSP_TLV_METRIC_UPDOWN(tlv_ip_reach->isis_metric_block.metric_default) ? "down" : "up",
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_default),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_delay))
ND_PRINT((ndo, "%s Delay Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_delay),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_expense))
ND_PRINT((ndo, "%s Expense Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_expense),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_error))
ND_PRINT((ndo, "%s Error Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_error),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_error) ? "External" : "Internal"));
length -= sizeof(struct isis_tlv_ip_reach);
tlv_ip_reach++;
}
return (1);
}
/*
* this is the common IP-REACH subTLV decoder it is called
* from various EXTD-IP REACH TLVs (135,235,236,237)
*/
static int
isis_print_ip_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int subt, int subl,
const char *ident)
{
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_ip_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr,subl);
switch(subt) {
case ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR: /* fall through */
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32:
while (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x (=%u)",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr)));
tptr+=4;
subl-=4;
}
break;
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64:
while (subl >= 8) {
ND_PRINT((ndo, ", 0x%08x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr+4)));
tptr+=8;
subl-=8;
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
ND_PRINT((ndo, "%s", ident));
ND_PRINT((ndo, "%s", tstr));
return(0);
}
/*
* this is the common IS-REACH subTLV decoder it is called
* from isis_print_ext_is_reach()
*/
static int
isis_print_is_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, u_int subt, u_int subl,
const char *ident)
{
u_int te_class,priority_level,gmpls_switch_cap;
union { /* int to float conversion buffer for several subTLVs */
float f;
uint32_t i;
} bw;
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr, subl);
switch(subt) {
case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID:
if (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr)));
if (subl == 8) /* rfc4205 */
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR:
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR:
if (subl >= sizeof(struct in_addr))
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW :
case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW:
if (subl >= 4) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW :
if (subl >= 32) {
for (te_class = 0; te_class < 8; te_class++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD:
ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)",
ident,
tok2str(diffserv_te_bc_values, "unknown", *tptr),
*tptr));
tptr++;
/* decode BCs until the subTLV ends */
for (te_class = 0; te_class < (subl-1)/4; te_class++) {
ND_TCHECK2(*tptr, 4);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC:
if (subl >= 3)
ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE:
if (subl == 2) {
ND_PRINT((ndo, ", [ %s ] (0x%04x)",
bittok2str(isis_subtlv_link_attribute_values,
"Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE:
if (subl >= 2) {
ND_PRINT((ndo, ", %s, Priority %u",
bittok2str(gmpls_link_prot_values, "none", *tptr),
*(tptr+1)));
}
break;
case ISIS_SUBTLV_SPB_METRIC:
if (subl >= 6) {
ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr)));
tptr=tptr+3;
ND_PRINT((ndo, ", P: %u", *(tptr)));
tptr++;
ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR:
if (subl >= 36) {
gmpls_switch_cap = *tptr;
ND_PRINT((ndo, "%s Interface Switching Capability:%s",
ident,
tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap)));
ND_PRINT((ndo, ", LSP Encoding: %s",
tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1))));
tptr+=4;
ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident));
for (priority_level = 0; priority_level < 8; priority_level++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s priority level %d: %.3f Mbps",
ident,
priority_level,
bw.f * 8 / 1000000));
tptr+=4;
}
subl-=36;
switch (gmpls_switch_cap) {
case GMPLS_PSC1:
case GMPLS_PSC2:
case GMPLS_PSC3:
case GMPLS_PSC4:
ND_TCHECK2(*tptr, 6);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4)));
break;
case GMPLS_TSC:
ND_TCHECK2(*tptr, 8);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Indication %s", ident,
tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4))));
break;
default:
/* there is some optional stuff left to decode but this is as of yet
not specified so just lets hexdump what is left */
if(subl>0){
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
}
}
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
return(0);
}
/*
* this is the common IS-REACH decoder it is called
* from various EXTD-IS REACH style TLVs (22,24,222)
*/
static int
isis_print_ext_is_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, int tlv_type)
{
char ident_buffer[20];
int subtlv_type,subtlv_len,subtlv_sum_len;
int proc_bytes = 0; /* how many bytes did we process ? */
if (!ND_TTEST2(*tptr, NODE_ID_LEN))
return(0);
ND_PRINT((ndo, "%sIS Neighbor: %s", ident, isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
if (tlv_type != ISIS_TLV_IS_ALIAS_ID) { /* the Alias TLV Metric field is implicit 0 */
if (!ND_TTEST2(*tptr, 3)) /* and is therefore skipped */
return(0);
ND_PRINT((ndo, ", Metric: %d", EXTRACT_24BITS(tptr)));
tptr+=3;
}
if (!ND_TTEST2(*tptr, 1))
return(0);
subtlv_sum_len=*(tptr++); /* read out subTLV length */
proc_bytes=NODE_ID_LEN+3+1;
ND_PRINT((ndo, ", %ssub-TLVs present",subtlv_sum_len ? "" : "no "));
if (subtlv_sum_len) {
ND_PRINT((ndo, " (%u)", subtlv_sum_len));
while (subtlv_sum_len>0) {
if (!ND_TTEST2(*tptr,2))
return(0);
subtlv_type=*(tptr++);
subtlv_len=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_is_reach_subtlv(ndo, tptr, subtlv_type, subtlv_len, ident_buffer))
return(0);
tptr+=subtlv_len;
subtlv_sum_len-=(subtlv_len+2);
proc_bytes+=(subtlv_len+2);
}
}
return(proc_bytes);
}
/*
* this is the common Multi Topology ID decoder
* it is called from various MT-TLVs (222,229,235,237)
*/
static int
isis_print_mtid(netdissect_options *ndo,
const uint8_t *tptr, const char *ident)
{
if (!ND_TTEST2(*tptr, 2))
return(0);
ND_PRINT((ndo, "%s%s",
ident,
tok2str(isis_mt_values,
"Reserved for IETF Consensus",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)))));
ND_PRINT((ndo, " Topology (0x%03x), Flags: [%s]",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)),
bittok2str(isis_mt_flag_values, "none",ISIS_MASK_MTFLAGS(EXTRACT_16BITS(tptr)))));
return(2);
}
/*
* this is the common extended IP reach decoder
* it is called from TLVs (135,235,236,237)
* we process the TLV and optional subTLVs and return
* the amount of processed bytes
*/
static int
isis_print_extd_ip_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, uint16_t afi)
{
char ident_buffer[20];
uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */
u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen;
if (!ND_TTEST2(*tptr, 4))
return (0);
metric = EXTRACT_32BITS(tptr);
processed=4;
tptr+=4;
if (afi == AF_INET) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */
return (0);
status_byte=*(tptr++);
bit_length = status_byte&0x3f;
if (bit_length > 32) {
ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed++;
} else if (afi == AF_INET6) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status & prefix_len byte */
return (0);
status_byte=*(tptr++);
bit_length=*(tptr++);
if (bit_length > 128) {
ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed+=2;
} else
return (0); /* somebody is fooling us */
byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */
if (!ND_TTEST2(*tptr, byte_length))
return (0);
memset(prefix, 0, sizeof prefix); /* clear the copy buffer */
memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */
tptr+=byte_length;
processed+=byte_length;
if (afi == AF_INET)
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, prefix),
bit_length));
else if (afi == AF_INET6)
ND_PRINT((ndo, "%sIPv6 prefix: %s/%u",
ident,
ip6addr_string(ndo, prefix),
bit_length));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u",
ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up",
metric));
if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
ND_PRINT((ndo, ", sub-TLVs present"));
else if (afi == AF_INET6)
ND_PRINT((ndo, ", %s%s",
ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal",
ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : ""));
if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
|| (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte))
) {
/* assume that one prefix can hold more
than one subTLV - therefore the first byte must reflect
the aggregate bytecount of the subTLVs for this prefix
*/
if (!ND_TTEST2(*tptr, 1))
return (0);
sublen=*(tptr++);
processed+=sublen+1;
ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */
while (sublen>0) {
if (!ND_TTEST2(*tptr,2))
return (0);
subtlvtype=*(tptr++);
subtlvlen=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer))
return(0);
tptr+=subtlvlen;
sublen-=(subtlvlen+2);
}
}
return (processed);
}
/*
* Clear checksum and lifetime prior to signature verification.
*/
static void
isis_clear_checksum_lifetime(void *header)
{
struct isis_lsp_header *header_lsp = (struct isis_lsp_header *) header;
header_lsp->checksum[0] = 0;
header_lsp->checksum[1] = 0;
header_lsp->remaining_lifetime[0] = 0;
header_lsp->remaining_lifetime[1] = 0;
}
/*
* isis_print
* Decode IS-IS packets. Return 0 on error.
*/
static int
isis_print(netdissect_options *ndo,
const uint8_t *p, u_int length)
{
const struct isis_common_header *isis_header;
const struct isis_iih_lan_header *header_iih_lan;
const struct isis_iih_ptp_header *header_iih_ptp;
const struct isis_lsp_header *header_lsp;
const struct isis_csnp_header *header_csnp;
const struct isis_psnp_header *header_psnp;
const struct isis_tlv_lsp *tlv_lsp;
const struct isis_tlv_ptp_adj *tlv_ptp_adj;
const struct isis_tlv_is_reach *tlv_is_reach;
const struct isis_tlv_es_reach *tlv_es_reach;
uint8_t pdu_type, max_area, id_length, tlv_type, tlv_len, tmp, alen, lan_alen, prefix_len;
uint8_t ext_is_len, ext_ip_len, mt_len;
const uint8_t *optr, *pptr, *tptr;
u_short packet_len,pdu_len, key_id;
u_int i,vendor_id;
int sigcheck;
packet_len=length;
optr = p; /* initialize the _o_riginal pointer to the packet start -
need it for parsing the checksum TLV and authentication
TLV verification */
isis_header = (const struct isis_common_header *)p;
ND_TCHECK(*isis_header);
if (length < ISIS_COMMON_HEADER_SIZE)
goto trunc;
pptr = p+(ISIS_COMMON_HEADER_SIZE);
header_iih_lan = (const struct isis_iih_lan_header *)pptr;
header_iih_ptp = (const struct isis_iih_ptp_header *)pptr;
header_lsp = (const struct isis_lsp_header *)pptr;
header_csnp = (const struct isis_csnp_header *)pptr;
header_psnp = (const struct isis_psnp_header *)pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "IS-IS"));
/*
* Sanity checking of the header.
*/
if (isis_header->version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->version));
return (0);
}
if ((isis_header->id_length != SYSTEM_ID_LEN) && (isis_header->id_length != 0)) {
ND_PRINT((ndo, "system ID length of %d is not supported",
isis_header->id_length));
return (0);
}
if (isis_header->pdu_version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->pdu_version));
return (0);
}
if (length < isis_header->fixed_len) {
ND_PRINT((ndo, "fixed header length %u > packet length %u", isis_header->fixed_len, length));
return (0);
}
if (isis_header->fixed_len < ISIS_COMMON_HEADER_SIZE) {
ND_PRINT((ndo, "fixed header length %u < minimum header size %u", isis_header->fixed_len, (u_int)ISIS_COMMON_HEADER_SIZE));
return (0);
}
max_area = isis_header->max_area;
switch(max_area) {
case 0:
max_area = 3; /* silly shit */
break;
case 255:
ND_PRINT((ndo, "bad packet -- 255 areas"));
return (0);
default:
break;
}
id_length = isis_header->id_length;
switch(id_length) {
case 0:
id_length = 6; /* silly shit again */
break;
case 1: /* 1-8 are valid sys-ID lenghts */
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
break;
case 255:
id_length = 0; /* entirely useless */
break;
default:
break;
}
/* toss any non 6-byte sys-ID len PDUs */
if (id_length != 6 ) {
ND_PRINT((ndo, "bad packet -- illegal sys-ID length (%u)", id_length));
return (0);
}
pdu_type=isis_header->pdu_type;
/* in non-verbose mode print the basic PDU Type plus PDU specific brief information*/
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, "%s%s",
ndo->ndo_eflag ? "" : ", ",
tok2str(isis_pdu_values, "unknown PDU-Type %u", pdu_type)));
} else {
/* ok they seem to want to know everything - lets fully decode it */
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s, hlen: %u, v: %u, pdu-v: %u, sys-id-len: %u (%u), max-area: %u (%u)",
tok2str(isis_pdu_values,
"unknown, type %u",
pdu_type),
isis_header->fixed_len,
isis_header->version,
isis_header->pdu_version,
id_length,
isis_header->id_length,
max_area,
isis_header->max_area));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, optr, "\n\t", 8)) /* provide the _o_riginal pointer */
return (0); /* for optionally debugging the common header */
}
}
switch (pdu_type) {
case ISIS_PDU_L1_LAN_IIH:
case ISIS_PDU_L2_LAN_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_lan);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s",
isis_print_id(header_iih_lan->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", lan-id %s, prio %u",
isis_print_id(header_iih_lan->lan_id,NODE_ID_LEN),
header_iih_lan->priority));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_lan->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_lan->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_lan->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_lan->circuit_type)));
ND_PRINT((ndo, "\n\t lan-id: %s, Priority: %u, PDU length: %u",
isis_print_id(header_iih_lan->lan_id, NODE_ID_LEN),
(header_iih_lan->priority) & ISIS_LAN_PRIORITY_MASK,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_LAN_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
break;
case ISIS_PDU_PTP_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_ptp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_ptp->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_ptp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_ptp->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_ptp->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_ptp->circuit_type)));
ND_PRINT((ndo, "\n\t circuit-id: 0x%02x, PDU length: %u",
header_iih_ptp->circuit_id,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_PTP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
break;
case ISIS_PDU_L1_LSP:
case ISIS_PDU_L2_LSP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)ISIS_LSP_HEADER_SIZE));
return (0);
}
ND_TCHECK(*header_lsp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", lsp-id %s, seq 0x%08x, lifetime %5us",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_lsp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t lsp-id: %s, seq: 0x%08x, lifetime: %5us\n\t chksum: 0x%04x",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime),
EXTRACT_16BITS(header_lsp->checksum)));
osi_print_cksum(ndo, (const uint8_t *)header_lsp->lsp_id,
EXTRACT_16BITS(header_lsp->checksum),
12, length-12);
ND_PRINT((ndo, ", PDU length: %u, Flags: [ %s",
pdu_len,
ISIS_MASK_LSP_OL_BIT(header_lsp->typeblock) ? "Overload bit set, " : ""));
if (ISIS_MASK_LSP_ATT_BITS(header_lsp->typeblock)) {
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DEFAULT_BIT(header_lsp->typeblock) ? "default " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DELAY_BIT(header_lsp->typeblock) ? "delay " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_EXPENSE_BIT(header_lsp->typeblock) ? "expense " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_ERROR_BIT(header_lsp->typeblock) ? "error " : ""));
ND_PRINT((ndo, "ATT bit set, "));
}
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_PARTITION_BIT(header_lsp->typeblock) ? "P bit set, " : ""));
ND_PRINT((ndo, "%s ]", tok2str(isis_lsp_istype_values, "Unknown(0x%x)",
ISIS_MASK_LSP_ISTYPE_BITS(header_lsp->typeblock))));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_LSP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
break;
case ISIS_PDU_L1_CSNP:
case ISIS_PDU_L2_CSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_csnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_csnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_csnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_csnp->source_id, NODE_ID_LEN),
pdu_len));
ND_PRINT((ndo, "\n\t start lsp-id: %s",
isis_print_id(header_csnp->start_lsp_id, LSP_ID_LEN)));
ND_PRINT((ndo, "\n\t end lsp-id: %s",
isis_print_id(header_csnp->end_lsp_id, LSP_ID_LEN)));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_CSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
break;
case ISIS_PDU_L1_PSNP:
case ISIS_PDU_L2_PSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)) {
ND_PRINT((ndo, "- bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_psnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_psnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_psnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_psnp->source_id, NODE_ID_LEN),
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_PSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
break;
default:
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", length %u", length));
return (1);
}
(void)print_unknown_data(ndo, pptr, "\n\t ", length);
return (0);
}
/*
* Now print the TLV's.
*/
while (packet_len > 0) {
ND_TCHECK2(*pptr, 2);
if (packet_len < 2)
goto trunc;
tlv_type = *pptr++;
tlv_len = *pptr++;
tmp =tlv_len; /* copy temporary len & pointer to packet data */
tptr = pptr;
packet_len -= 2;
/* first lets see if we know the TLVs name*/
ND_PRINT((ndo, "\n\t %s TLV #%u, length: %u",
tok2str(isis_tlv_values,
"unknown",
tlv_type),
tlv_type,
tlv_len));
if (tlv_len == 0) /* something is invalid */
continue;
if (packet_len < tlv_len)
goto trunc;
/* now check if we have a decoder otherwise do a hexdump at the end*/
switch (tlv_type) {
case ISIS_TLV_AREA_ADDR:
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
while (tmp && alen < tmp) {
ND_PRINT((ndo, "\n\t Area address (length: %u): %s",
alen,
isonsap_string(ndo, tptr, alen)));
tptr += alen;
tmp -= alen + 1;
if (tmp==0) /* if this is the last area address do not attemt a boundary check */
break;
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
}
break;
case ISIS_TLV_ISNEIGH:
while (tmp >= ETHER_ADDR_LEN) {
ND_TCHECK2(*tptr, ETHER_ADDR_LEN);
ND_PRINT((ndo, "\n\t SNPA: %s", isis_print_id(tptr, ETHER_ADDR_LEN)));
tmp -= ETHER_ADDR_LEN;
tptr += ETHER_ADDR_LEN;
}
break;
case ISIS_TLV_ISNEIGH_VARLEN:
if (!ND_TTEST2(*tptr, 1) || tmp < 3) /* min. TLV length */
goto trunctlv;
lan_alen = *tptr++; /* LAN address length */
if (lan_alen == 0) {
ND_PRINT((ndo, "\n\t LAN address length 0 bytes (invalid)"));
break;
}
tmp --;
ND_PRINT((ndo, "\n\t LAN address length %u bytes ", lan_alen));
while (tmp >= lan_alen) {
ND_TCHECK2(*tptr, lan_alen);
ND_PRINT((ndo, "\n\t\tIS Neighbor: %s", isis_print_id(tptr, lan_alen)));
tmp -= lan_alen;
tptr +=lan_alen;
}
break;
case ISIS_TLV_PADDING:
break;
case ISIS_TLV_MT_IS_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
while (tmp >= 2+NODE_ID_LEN+3+1) {
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_ALIAS_ID:
while (tmp >= NODE_ID_LEN+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_EXT_IS_REACH:
while (tmp >= NODE_ID_LEN+3+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_REACH:
ND_TCHECK2(*tptr,1); /* check if there is one byte left to read out the virtual flag */
ND_PRINT((ndo, "\n\t %s",
tok2str(isis_is_reach_virtual_values,
"bogus virtual flag 0x%02x",
*tptr++)));
tlv_is_reach = (const struct isis_tlv_is_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_is_reach)) {
ND_TCHECK(*tlv_is_reach);
ND_PRINT((ndo, "\n\t IS Neighbor: %s",
isis_print_id(tlv_is_reach->neighbor_nodeid, NODE_ID_LEN)));
isis_print_metric_block(ndo, &tlv_is_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_is_reach);
tlv_is_reach++;
}
break;
case ISIS_TLV_ESNEIGH:
tlv_es_reach = (const struct isis_tlv_es_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_es_reach)) {
ND_TCHECK(*tlv_es_reach);
ND_PRINT((ndo, "\n\t ES Neighbor: %s",
isis_print_id(tlv_es_reach->neighbor_sysid, SYSTEM_ID_LEN)));
isis_print_metric_block(ndo, &tlv_es_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_es_reach);
tlv_es_reach++;
}
break;
/* those two TLVs share the same format */
case ISIS_TLV_INT_IP_REACH:
case ISIS_TLV_EXT_IP_REACH:
if (!isis_print_tlv_ip_reach(ndo, pptr, "\n\t ", tlv_len))
return (1);
break;
case ISIS_TLV_EXTD_IP_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP6_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6ADDR:
while (tmp>=sizeof(struct in6_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in6_addr));
ND_PRINT((ndo, "\n\t IPv6 interface address: %s",
ip6addr_string(ndo, tptr)));
tptr += sizeof(struct in6_addr);
tmp -= sizeof(struct in6_addr);
}
break;
case ISIS_TLV_AUTH:
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t %s: ",
tok2str(isis_subtlv_auth_values,
"unknown Authentication type 0x%02x",
*tptr)));
switch (*tptr) {
case ISIS_SUBTLV_AUTH_SIMPLE:
if (fn_printzp(ndo, tptr + 1, tlv_len - 1, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_SUBTLV_AUTH_MD5:
for(i=1;i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
if (tlv_len != ISIS_SUBTLV_AUTH_MD5_LEN+1)
ND_PRINT((ndo, ", (invalid subTLV) "));
sigcheck = signature_verify(ndo, optr, length, tptr + 1,
isis_clear_checksum_lifetime,
header_lsp);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
break;
case ISIS_SUBTLV_AUTH_GENERIC:
ND_TCHECK2(*(tptr + 1), 2);
key_id = EXTRACT_16BITS((tptr+1));
ND_PRINT((ndo, "%u, password: ", key_id));
for(i=1 + sizeof(uint16_t);i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
break;
case ISIS_SUBTLV_AUTH_PRIVATE:
default:
if (!print_unknown_data(ndo, tptr + 1, "\n\t\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_PTP_ADJ:
tlv_ptp_adj = (const struct isis_tlv_ptp_adj *)tptr;
if(tmp>=1) {
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t Adjacency State: %s (%u)",
tok2str(isis_ptp_adjancey_values, "unknown", *tptr),
*tptr));
tmp--;
}
if(tmp>sizeof(tlv_ptp_adj->extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->extd_local_circuit_id)));
tmp-=sizeof(tlv_ptp_adj->extd_local_circuit_id);
}
if(tmp>=SYSTEM_ID_LEN) {
ND_TCHECK2(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t Neighbor System-ID: %s",
isis_print_id(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN)));
tmp-=SYSTEM_ID_LEN;
}
if(tmp>=sizeof(tlv_ptp_adj->neighbor_extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->neighbor_extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Neighbor Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->neighbor_extd_local_circuit_id)));
}
break;
case ISIS_TLV_PROTOCOLS:
ND_PRINT((ndo, "\n\t NLPID(s): "));
while (tmp>0) {
ND_TCHECK2(*(tptr), 1);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (tmp>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
tmp--;
}
break;
case ISIS_TLV_MT_PORT_CAP:
{
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t RES: %d, MTID(s): %d",
(EXTRACT_16BITS (tptr) >> 12),
(EXTRACT_16BITS (tptr) & 0x0fff)));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_port_cap_subtlv(ndo, tptr, tmp);
break;
}
case ISIS_TLV_MT_CAPABILITY:
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t O: %d, RES: %d, MTID(s): %d",
(EXTRACT_16BITS(tptr) >> 15) & 0x01,
(EXTRACT_16BITS(tptr) >> 12) & 0x07,
EXTRACT_16BITS(tptr) & 0x0fff));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_capability_subtlv(ndo, tptr, tmp);
break;
case ISIS_TLV_TE_ROUTER_ID:
ND_TCHECK2(*pptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t Traffic Engineering Router ID: %s", ipaddr_string(ndo, pptr)));
break;
case ISIS_TLV_IPADDR:
while (tmp>=sizeof(struct in_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr += sizeof(struct in_addr);
tmp -= sizeof(struct in_addr);
}
break;
case ISIS_TLV_HOSTNAME:
ND_PRINT((ndo, "\n\t Hostname: "));
if (fn_printzp(ndo, tptr, tmp, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_TLV_SHARED_RISK_GROUP:
if (tmp < NODE_ID_LEN)
break;
ND_TCHECK2(*tptr, NODE_ID_LEN);
ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
tmp-=(NODE_ID_LEN);
if (tmp < 1)
break;
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, ", Flags: [%s]", ISIS_MASK_TLV_SHARED_RISK_GROUP(*tptr++) ? "numbered" : "unnumbered"));
tmp--;
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 neighbor address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
while (tmp>=4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Link-ID: 0x%08x", EXTRACT_32BITS(tptr)));
tptr+=4;
tmp-=4;
}
break;
case ISIS_TLV_LSP:
tlv_lsp = (const struct isis_tlv_lsp *)tptr;
while(tmp>=sizeof(struct isis_tlv_lsp)) {
ND_TCHECK((tlv_lsp->lsp_id)[LSP_ID_LEN-1]);
ND_PRINT((ndo, "\n\t lsp-id: %s",
isis_print_id(tlv_lsp->lsp_id, LSP_ID_LEN)));
ND_TCHECK2(tlv_lsp->sequence_number, 4);
ND_PRINT((ndo, ", seq: 0x%08x", EXTRACT_32BITS(tlv_lsp->sequence_number)));
ND_TCHECK2(tlv_lsp->remaining_lifetime, 2);
ND_PRINT((ndo, ", lifetime: %5ds", EXTRACT_16BITS(tlv_lsp->remaining_lifetime)));
ND_TCHECK2(tlv_lsp->checksum, 2);
ND_PRINT((ndo, ", chksum: 0x%04x", EXTRACT_16BITS(tlv_lsp->checksum)));
tmp-=sizeof(struct isis_tlv_lsp);
tlv_lsp++;
}
break;
case ISIS_TLV_CHECKSUM:
if (tmp < ISIS_TLV_CHECKSUM_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_CHECKSUM_MINLEN);
ND_PRINT((ndo, "\n\t checksum: 0x%04x ", EXTRACT_16BITS(tptr)));
/* do not attempt to verify the checksum if it is zero
* most likely a HMAC-MD5 TLV is also present and
* to avoid conflicts the checksum TLV is zeroed.
* see rfc3358 for details
*/
osi_print_cksum(ndo, optr, EXTRACT_16BITS(tptr), tptr-optr,
length);
break;
case ISIS_TLV_POI:
if (tlv_len >= SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Purge Originator System-ID: %s",
isis_print_id(tptr + 1, SYSTEM_ID_LEN)));
}
if (tlv_len == 2 * SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, 2 * SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Received from System-ID: %s",
isis_print_id(tptr + SYSTEM_ID_LEN + 1, SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_MT_SUPPORTED:
if (tmp < ISIS_TLV_MT_SUPPORTED_MINLEN)
break;
while (tmp>1) {
/* length can only be a multiple of 2, otherwise there is
something broken -> so decode down until length is 1 */
if (tmp!=1) {
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
} else {
ND_PRINT((ndo, "\n\t invalid MT-ID"));
break;
}
}
break;
case ISIS_TLV_RESTART_SIGNALING:
/* first attempt to decode the flags */
if (tmp < ISIS_TLV_RESTART_SIGNALING_FLAGLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_FLAGLEN);
ND_PRINT((ndo, "\n\t Flags [%s]",
bittok2str(isis_restart_flag_values, "none", *tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
/* is there anything other than the flags field? */
if (tmp == 0)
break;
if (tmp < ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN);
ND_PRINT((ndo, ", Remaining holding time %us", EXTRACT_16BITS(tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
/* is there an additional sysid field present ?*/
if (tmp == SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, ", for %s", isis_print_id(tptr,SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_IDRP_INFO:
if (tmp < ISIS_TLV_IDRP_INFO_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IDRP_INFO_MINLEN);
ND_PRINT((ndo, "\n\t Inter-Domain Information Type: %s",
tok2str(isis_subtlv_idrp_values,
"Unknown (0x%02x)",
*tptr)));
switch (*tptr++) {
case ISIS_SUBTLV_IDRP_ASN:
ND_TCHECK2(*tptr, 2); /* fetch AS number */
ND_PRINT((ndo, "AS Number: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_SUBTLV_IDRP_LOCAL:
case ISIS_SUBTLV_IDRP_RES:
default:
if (!print_unknown_data(ndo, tptr, "\n\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_LSP_BUFFERSIZE:
if (tmp < ISIS_TLV_LSP_BUFFERSIZE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_LSP_BUFFERSIZE_MINLEN);
ND_PRINT((ndo, "\n\t LSP Buffersize: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_TLV_PART_DIS:
while (tmp >= SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t %s", isis_print_id(tptr, SYSTEM_ID_LEN)));
tptr+=SYSTEM_ID_LEN;
tmp-=SYSTEM_ID_LEN;
}
break;
case ISIS_TLV_PREFIX_NEIGH:
if (tmp < sizeof(struct isis_metric_block))
break;
ND_TCHECK2(*tptr, sizeof(struct isis_metric_block));
ND_PRINT((ndo, "\n\t Metric Block"));
isis_print_metric_block(ndo, (const struct isis_metric_block *)tptr);
tptr+=sizeof(struct isis_metric_block);
tmp-=sizeof(struct isis_metric_block);
while(tmp>0) {
ND_TCHECK2(*tptr, 1);
prefix_len=*tptr++; /* read out prefix length in semioctets*/
if (prefix_len < 2) {
ND_PRINT((ndo, "\n\t\tAddress: prefix length %u < 2", prefix_len));
break;
}
tmp--;
if (tmp < prefix_len/2)
break;
ND_TCHECK2(*tptr, prefix_len / 2);
ND_PRINT((ndo, "\n\t\tAddress: %s/%u",
isonsap_string(ndo, tptr, prefix_len / 2), prefix_len * 4));
tptr+=prefix_len/2;
tmp-=prefix_len/2;
}
break;
case ISIS_TLV_IIH_SEQNR:
if (tmp < ISIS_TLV_IIH_SEQNR_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IIH_SEQNR_MINLEN); /* check if four bytes are on the wire */
ND_PRINT((ndo, "\n\t Sequence number: %u", EXTRACT_32BITS(tptr)));
break;
case ISIS_TLV_VENDOR_PRIVATE:
if (tmp < ISIS_TLV_VENDOR_PRIVATE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_VENDOR_PRIVATE_MINLEN); /* check if enough byte for a full oui */
vendor_id = EXTRACT_24BITS(tptr);
ND_PRINT((ndo, "\n\t Vendor: %s (%u)",
tok2str(oui_values, "Unknown", vendor_id),
vendor_id));
tptr+=3;
tmp-=3;
if (tmp > 0) /* hexdump the rest */
if (!print_unknown_data(ndo, tptr, "\n\t\t", tmp))
return(0);
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case ISIS_TLV_DECNET_PHASE4:
case ISIS_TLV_LUCENT_PRIVATE:
case ISIS_TLV_IPAUTH:
case ISIS_TLV_NORTEL_PRIVATE1:
case ISIS_TLV_NORTEL_PRIVATE2:
default:
if (ndo->ndo_vflag <= 1) {
if (!print_unknown_data(ndo, pptr, "\n\t\t", tlv_len))
return(0);
}
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", tlv_len))
return(0);
}
pptr += tlv_len;
packet_len -= tlv_len;
}
if (packet_len != 0) {
ND_PRINT((ndo, "\n\t %u straggler bytes", packet_len));
}
return (1);
trunc:
ND_PRINT((ndo, "%s", tstr));
return (1);
trunctlv:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
static void
osi_print_cksum(netdissect_options *ndo, const uint8_t *pptr,
uint16_t checksum, int checksum_offset, u_int length)
{
uint16_t calculated_checksum;
/* do not attempt to verify the checksum if it is zero,
* if the offset is nonsense,
* or the base pointer is not sane
*/
if (!checksum
|| checksum_offset < 0
|| !ND_TTEST2(*(pptr + checksum_offset), 2)
|| (u_int)checksum_offset > length
|| !ND_TTEST2(*pptr, length)) {
ND_PRINT((ndo, " (unverified)"));
} else {
#if 0
printf("\nosi_print_cksum: %p %u %u\n", pptr, checksum_offset, length);
#endif
calculated_checksum = create_osi_cksum(pptr, checksum_offset, length);
if (checksum == calculated_checksum) {
ND_PRINT((ndo, " (correct)"));
} else {
ND_PRINT((ndo, " (incorrect should be 0x%04x)", calculated_checksum));
}
}
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2644_6 |
crossvul-cpp_data_bad_457_0 | ////////////////////////////////////////////////////////////////////////////
// **** WAVPACK **** //
// Hybrid Lossless Wavefile Compressor //
// Copyright (c) 1998 - 2018 David Bryant. //
// All Rights Reserved. //
// Distributed under the BSD Software License (see license.txt) //
////////////////////////////////////////////////////////////////////////////
// open_utils.c
// This module provides all the code required to open an existing WavPack file
// for reading by using a reader callback mechanism (NOT a filename). This
// includes the code required to find and parse WavPack blocks, process any
// included metadata, and queue up the bitstreams containing the encoded audio
// data. It does not the actual code to unpack audio data and this was done so
// that programs that just want to query WavPack files for information (like,
// for example, taggers) don't need to link in a lot of unnecessary code.
#include <stdlib.h>
#include <string.h>
#include "wavpack_local.h"
// This function is identical to WavpackOpenFileInput() except that instead
// of providing a filename to open, the caller provides a pointer to a set of
// reader callbacks and instances of up to two streams. The first of these
// streams is required and contains the regular WavPack data stream; the second
// contains the "correction" file if desired. Unlike the standard open
// function which handles the correction file transparently, in this case it
// is the responsibility of the caller to be aware of correction files.
static int seek_eof_information (WavpackContext *wpc, int64_t *final_index, int get_wrapper);
WavpackContext *WavpackOpenFileInputEx64 (WavpackStreamReader64 *reader, void *wv_id, void *wvc_id, char *error, int flags, int norm_offset)
{
WavpackContext *wpc = (WavpackContext *)malloc (sizeof (WavpackContext));
WavpackStream *wps;
int num_blocks = 0;
unsigned char first_byte;
uint32_t bcount;
if (!wpc) {
if (error) strcpy (error, "can't allocate memory");
return NULL;
}
CLEAR (*wpc);
wpc->wv_in = wv_id;
wpc->wvc_in = wvc_id;
wpc->reader = reader;
wpc->total_samples = -1;
wpc->norm_offset = norm_offset;
wpc->max_streams = OLD_MAX_STREAMS; // use this until overwritten with actual number
wpc->open_flags = flags;
wpc->filelen = wpc->reader->get_length (wpc->wv_in);
#ifndef NO_TAGS
if ((flags & (OPEN_TAGS | OPEN_EDIT_TAGS)) && wpc->reader->can_seek (wpc->wv_in)) {
load_tag (wpc);
wpc->reader->set_pos_abs (wpc->wv_in, 0);
if ((flags & OPEN_EDIT_TAGS) && !editable_tag (&wpc->m_tag)) {
if (error) strcpy (error, "can't edit tags located at the beginning of files!");
return WavpackCloseFile (wpc);
}
}
#endif
if (wpc->reader->read_bytes (wpc->wv_in, &first_byte, 1) != 1) {
if (error) strcpy (error, "can't read all of WavPack file!");
return WavpackCloseFile (wpc);
}
wpc->reader->push_back_byte (wpc->wv_in, first_byte);
if (first_byte == 'R') {
#ifdef ENABLE_LEGACY
return open_file3 (wpc, error);
#else
if (error) strcpy (error, "this legacy WavPack file is deprecated, use version 4.80.0 to transcode");
return WavpackCloseFile (wpc);
#endif
}
wpc->streams = (WavpackStream **)(malloc ((wpc->num_streams = 1) * sizeof (wpc->streams [0])));
if (!wpc->streams) {
if (error) strcpy (error, "can't allocate memory");
return WavpackCloseFile (wpc);
}
wpc->streams [0] = wps = (WavpackStream *)malloc (sizeof (WavpackStream));
if (!wps) {
if (error) strcpy (error, "can't allocate memory");
return WavpackCloseFile (wpc);
}
CLEAR (*wps);
while (!wps->wphdr.block_samples) {
wpc->filepos = wpc->reader->get_pos (wpc->wv_in);
bcount = read_next_header (wpc->reader, wpc->wv_in, &wps->wphdr);
if (bcount == (uint32_t) -1 ||
(!wps->wphdr.block_samples && num_blocks++ > 16)) {
if (error) strcpy (error, "not compatible with this version of WavPack file!");
return WavpackCloseFile (wpc);
}
wpc->filepos += bcount;
wps->blockbuff = (unsigned char *)malloc (wps->wphdr.ckSize + 8);
if (!wps->blockbuff) {
if (error) strcpy (error, "can't allocate memory");
return WavpackCloseFile (wpc);
}
memcpy (wps->blockbuff, &wps->wphdr, 32);
if (wpc->reader->read_bytes (wpc->wv_in, wps->blockbuff + 32, wps->wphdr.ckSize - 24) != wps->wphdr.ckSize - 24) {
if (error) strcpy (error, "can't read all of WavPack file!");
return WavpackCloseFile (wpc);
}
// if block does not verify, flag error, free buffer, and continue
if (!WavpackVerifySingleBlock (wps->blockbuff, !(flags & OPEN_NO_CHECKSUM))) {
wps->wphdr.block_samples = 0;
free (wps->blockbuff);
wps->blockbuff = NULL;
wpc->crc_errors++;
continue;
}
wps->init_done = FALSE;
if (wps->wphdr.block_samples) {
if (flags & OPEN_STREAMING)
SET_BLOCK_INDEX (wps->wphdr, 0);
else if (wpc->total_samples == -1) {
if (GET_BLOCK_INDEX (wps->wphdr) || GET_TOTAL_SAMPLES (wps->wphdr) == -1) {
wpc->initial_index = GET_BLOCK_INDEX (wps->wphdr);
SET_BLOCK_INDEX (wps->wphdr, 0);
if (wpc->reader->can_seek (wpc->wv_in)) {
int64_t final_index = -1;
seek_eof_information (wpc, &final_index, FALSE);
if (final_index != -1)
wpc->total_samples = final_index - wpc->initial_index;
}
}
else
wpc->total_samples = GET_TOTAL_SAMPLES (wps->wphdr);
}
}
else if (wpc->total_samples == -1 && !GET_BLOCK_INDEX (wps->wphdr) && GET_TOTAL_SAMPLES (wps->wphdr))
wpc->total_samples = GET_TOTAL_SAMPLES (wps->wphdr);
if (wpc->wvc_in && wps->wphdr.block_samples && (wps->wphdr.flags & HYBRID_FLAG)) {
unsigned char ch;
if (wpc->reader->read_bytes (wpc->wvc_in, &ch, 1) == 1) {
wpc->reader->push_back_byte (wpc->wvc_in, ch);
wpc->file2len = wpc->reader->get_length (wpc->wvc_in);
wpc->wvc_flag = TRUE;
}
}
if (wpc->wvc_flag && !read_wvc_block (wpc)) {
if (error) strcpy (error, "not compatible with this version of correction file!");
return WavpackCloseFile (wpc);
}
if (!wps->init_done && !unpack_init (wpc)) {
if (error) strcpy (error, wpc->error_message [0] ? wpc->error_message :
"not compatible with this version of WavPack file!");
return WavpackCloseFile (wpc);
}
wps->init_done = TRUE;
}
wpc->config.flags &= ~0xff;
wpc->config.flags |= wps->wphdr.flags & 0xff;
if (!wpc->config.num_channels) {
wpc->config.num_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2;
wpc->config.channel_mask = 0x5 - wpc->config.num_channels;
}
if ((flags & OPEN_2CH_MAX) && !(wps->wphdr.flags & FINAL_BLOCK))
wpc->reduced_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2;
if (wps->wphdr.flags & DSD_FLAG) {
#ifdef ENABLE_DSD
if (flags & OPEN_DSD_NATIVE) {
wpc->config.bytes_per_sample = 1;
wpc->config.bits_per_sample = 8;
}
else if (flags & OPEN_DSD_AS_PCM) {
wpc->decimation_context = decimate_dsd_init (wpc->reduced_channels ?
wpc->reduced_channels : wpc->config.num_channels);
wpc->config.bytes_per_sample = 3;
wpc->config.bits_per_sample = 24;
}
else {
if (error) strcpy (error, "not configured to handle DSD WavPack files!");
return WavpackCloseFile (wpc);
}
#else
if (error) strcpy (error, "not configured to handle DSD WavPack files!");
return WavpackCloseFile (wpc);
#endif
}
else {
wpc->config.bytes_per_sample = (wps->wphdr.flags & BYTES_STORED) + 1;
wpc->config.float_norm_exp = wps->float_norm_exp;
wpc->config.bits_per_sample = (wpc->config.bytes_per_sample * 8) -
((wps->wphdr.flags & SHIFT_MASK) >> SHIFT_LSB);
}
if (!wpc->config.sample_rate) {
if (!wps->wphdr.block_samples || (wps->wphdr.flags & SRATE_MASK) == SRATE_MASK)
wpc->config.sample_rate = 44100;
else
wpc->config.sample_rate = sample_rates [(wps->wphdr.flags & SRATE_MASK) >> SRATE_LSB];
}
return wpc;
}
// This function returns the major version number of the WavPack program
// (or library) that created the open file. Currently, this can be 1 to 5.
// Minor versions are not recorded in WavPack files.
int WavpackGetVersion (WavpackContext *wpc)
{
if (wpc) {
#ifdef ENABLE_LEGACY
if (wpc->stream3)
return get_version3 (wpc);
#endif
return wpc->version_five ? 5 : 4;
}
return 0;
}
// Return the file format specified in the call to WavpackSetFileInformation()
// when the file was created. For all files created prior to WavPack 5.0 this
// will 0 (WP_FORMAT_WAV).
unsigned char WavpackGetFileFormat (WavpackContext *wpc)
{
return wpc->file_format;
}
// Return a string representing the recommended file extension for the open
// WavPack file. For all files created prior to WavPack 5.0 this will be "wav",
// even for raw files with no RIFF into. This string is specified in the
// call to WavpackSetFileInformation() when the file was created.
char *WavpackGetFileExtension (WavpackContext *wpc)
{
if (wpc && wpc->file_extension [0])
return wpc->file_extension;
else
return "wav";
}
// This function initializes everything required to unpack a WavPack block
// and must be called before unpack_samples() is called to obtain audio data.
// It is assumed that the WavpackHeader has been read into the wps->wphdr
// (in the current WavpackStream) and that the entire block has been read at
// wps->blockbuff. If a correction file is available (wpc->wvc_flag = TRUE)
// then the corresponding correction block must be read into wps->block2buff
// and its WavpackHeader has overwritten the header at wps->wphdr. This is
// where all the metadata blocks are scanned including those that contain
// bitstream data.
static int read_metadata_buff (WavpackMetadata *wpmd, unsigned char *blockbuff, unsigned char **buffptr);
static int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd);
static void bs_open_read (Bitstream *bs, void *buffer_start, void *buffer_end);
int unpack_init (WavpackContext *wpc)
{
WavpackStream *wps = wpc->streams [wpc->current_stream];
unsigned char *blockptr, *block2ptr;
WavpackMetadata wpmd;
wps->num_terms = 0;
wps->mute_error = FALSE;
wps->crc = wps->crc_x = 0xffffffff;
wps->dsd.ready = 0;
CLEAR (wps->wvbits);
CLEAR (wps->wvcbits);
CLEAR (wps->wvxbits);
CLEAR (wps->decorr_passes);
CLEAR (wps->dc);
CLEAR (wps->w);
if (!(wps->wphdr.flags & MONO_FLAG) && wpc->config.num_channels && wps->wphdr.block_samples &&
(wpc->reduced_channels == 1 || wpc->config.num_channels == 1)) {
wps->mute_error = TRUE;
return FALSE;
}
if ((wps->wphdr.flags & UNKNOWN_FLAGS) || (wps->wphdr.flags & MONO_DATA) == MONO_DATA) {
wps->mute_error = TRUE;
return FALSE;
}
blockptr = wps->blockbuff + sizeof (WavpackHeader);
while (read_metadata_buff (&wpmd, wps->blockbuff, &blockptr))
if (!process_metadata (wpc, &wpmd)) {
wps->mute_error = TRUE;
return FALSE;
}
if (wps->wphdr.block_samples && wpc->wvc_flag && wps->block2buff) {
block2ptr = wps->block2buff + sizeof (WavpackHeader);
while (read_metadata_buff (&wpmd, wps->block2buff, &block2ptr))
if (!process_metadata (wpc, &wpmd)) {
wps->mute_error = TRUE;
return FALSE;
}
}
if (wps->wphdr.block_samples && ((wps->wphdr.flags & DSD_FLAG) ? !wps->dsd.ready : !bs_is_open (&wps->wvbits))) {
if (bs_is_open (&wps->wvcbits))
strcpy (wpc->error_message, "can't unpack correction files alone!");
wps->mute_error = TRUE;
return FALSE;
}
if (wps->wphdr.block_samples && !bs_is_open (&wps->wvxbits)) {
if ((wps->wphdr.flags & INT32_DATA) && wps->int32_sent_bits)
wpc->lossy_blocks = TRUE;
if ((wps->wphdr.flags & FLOAT_DATA) &&
wps->float_flags & (FLOAT_EXCEPTIONS | FLOAT_ZEROS_SENT | FLOAT_SHIFT_SENT | FLOAT_SHIFT_SAME))
wpc->lossy_blocks = TRUE;
}
if (wps->wphdr.block_samples)
wps->sample_index = GET_BLOCK_INDEX (wps->wphdr);
return TRUE;
}
//////////////////////////////// matadata handlers ///////////////////////////////
// These functions handle specific metadata types and are called directly
// during WavPack block parsing by process_metadata() at the bottom.
// This function initializes the main bitstream for audio samples, which must
// be in the "wv" file.
static int init_wv_bitstream (WavpackStream *wps, WavpackMetadata *wpmd)
{
if (!wpmd->byte_length || (wpmd->byte_length & 1))
return FALSE;
bs_open_read (&wps->wvbits, wpmd->data, (unsigned char *) wpmd->data + wpmd->byte_length);
return TRUE;
}
// This function initializes the "correction" bitstream for audio samples,
// which currently must be in the "wvc" file.
static int init_wvc_bitstream (WavpackStream *wps, WavpackMetadata *wpmd)
{
if (!wpmd->byte_length || (wpmd->byte_length & 1))
return FALSE;
bs_open_read (&wps->wvcbits, wpmd->data, (unsigned char *) wpmd->data + wpmd->byte_length);
return TRUE;
}
// This function initializes the "extra" bitstream for audio samples which
// contains the information required to losslessly decompress 32-bit float data
// or integer data that exceeds 24 bits. This bitstream is in the "wv" file
// for pure lossless data or the "wvc" file for hybrid lossless. This data
// would not be used for hybrid lossy mode. There is also a 32-bit CRC stored
// in the first 4 bytes of these blocks.
static int init_wvx_bitstream (WavpackStream *wps, WavpackMetadata *wpmd)
{
unsigned char *cp = (unsigned char *)wpmd->data;
if (wpmd->byte_length <= 4 || (wpmd->byte_length & 1))
return FALSE;
wps->crc_wvx = *cp++;
wps->crc_wvx |= (int32_t) *cp++ << 8;
wps->crc_wvx |= (int32_t) *cp++ << 16;
wps->crc_wvx |= (int32_t) *cp++ << 24;
bs_open_read (&wps->wvxbits, cp, (unsigned char *) wpmd->data + wpmd->byte_length);
return TRUE;
}
// Read the int32 data from the specified metadata into the specified stream.
// This data is used for integer data that has more than 24 bits of magnitude
// or, in some cases, used to eliminate redundant bits from any audio stream.
static int read_int32_info (WavpackStream *wps, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
char *byteptr = (char *)wpmd->data;
if (bytecnt != 4)
return FALSE;
wps->int32_sent_bits = *byteptr++;
wps->int32_zeros = *byteptr++;
wps->int32_ones = *byteptr++;
wps->int32_dups = *byteptr;
return TRUE;
}
static int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
char *byteptr = (char *)wpmd->data;
if (bytecnt != 4)
return FALSE;
wps->float_flags = *byteptr++;
wps->float_shift = *byteptr++;
wps->float_max_exp = *byteptr++;
wps->float_norm_exp = *byteptr;
return TRUE;
}
// Read multichannel information from metadata. The first byte is the total
// number of channels and the following bytes represent the channel_mask
// as described for Microsoft WAVEFORMATEX.
static int read_channel_info (WavpackContext *wpc, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length, shift = 0, mask_bits;
unsigned char *byteptr = (unsigned char *)wpmd->data;
uint32_t mask = 0;
if (!bytecnt || bytecnt > 7)
return FALSE;
if (!wpc->config.num_channels) {
// if bytecnt is 6 or 7 we are using new configuration with "unlimited" streams
if (bytecnt >= 6) {
wpc->config.num_channels = (byteptr [0] | ((byteptr [2] & 0xf) << 8)) + 1;
wpc->max_streams = (byteptr [1] | ((byteptr [2] & 0xf0) << 4)) + 1;
if (wpc->config.num_channels < wpc->max_streams)
return FALSE;
byteptr += 3;
mask = *byteptr++;
mask |= (uint32_t) *byteptr++ << 8;
mask |= (uint32_t) *byteptr++ << 16;
if (bytecnt == 7) // this was introduced in 5.0
mask |= (uint32_t) *byteptr << 24;
}
else {
wpc->config.num_channels = *byteptr++;
while (--bytecnt) {
mask |= (uint32_t) *byteptr++ << shift;
shift += 8;
}
}
if (wpc->config.num_channels > wpc->max_streams * 2)
return FALSE;
wpc->config.channel_mask = mask;
for (mask_bits = 0; mask; mask >>= 1)
if ((mask & 1) && ++mask_bits > wpc->config.num_channels)
return FALSE;
}
return TRUE;
}
// Read multichannel identity information from metadata. Data is an array of
// unsigned characters representing any channels in the file that DO NOT
// match one the 18 Microsoft standard channels (and are represented in the
// channel mask). A value of 0 is not allowed and 0xff means an unknown or
// undefined channel identity.
static int read_channel_identities (WavpackContext *wpc, WavpackMetadata *wpmd)
{
if (!wpc->channel_identities) {
wpc->channel_identities = (unsigned char *)malloc (wpmd->byte_length + 1);
memcpy (wpc->channel_identities, wpmd->data, wpmd->byte_length);
wpc->channel_identities [wpmd->byte_length] = 0;
}
return TRUE;
}
// Read configuration information from metadata.
static int read_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
unsigned char *byteptr = (unsigned char *)wpmd->data;
if (bytecnt >= 3) {
wpc->config.flags &= 0xff;
wpc->config.flags |= (int32_t) *byteptr++ << 8;
wpc->config.flags |= (int32_t) *byteptr++ << 16;
wpc->config.flags |= (int32_t) *byteptr++ << 24;
bytecnt -= 3;
if (bytecnt && (wpc->config.flags & CONFIG_EXTRA_MODE)) {
wpc->config.xmode = *byteptr++;
bytecnt--;
}
// we used an extra config byte here for the 5.0.0 alpha, so still
// honor it now (but this has been replaced with NEW_CONFIG)
if (bytecnt) {
wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr;
wpc->version_five = 1;
}
}
return TRUE;
}
// Read "new" configuration information from metadata.
static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
unsigned char *byteptr = (unsigned char *)wpmd->data;
wpc->version_five = 1; // just having this block signals version 5.0
wpc->file_format = wpc->config.qmode = wpc->channel_layout = 0;
if (wpc->channel_reordering) {
free (wpc->channel_reordering);
wpc->channel_reordering = NULL;
}
// if there's any data, the first two bytes are file_format and qmode flags
if (bytecnt >= 2) {
wpc->file_format = *byteptr++;
wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr++;
bytecnt -= 2;
// another byte indicates a channel layout
if (bytecnt) {
int nchans, i;
wpc->channel_layout = (int32_t) *byteptr++ << 16;
bytecnt--;
// another byte means we have a channel count for the layout and maybe a reordering
if (bytecnt) {
wpc->channel_layout += nchans = *byteptr++;
bytecnt--;
// any more means there's a reordering string
if (bytecnt) {
if (bytecnt > nchans)
return FALSE;
wpc->channel_reordering = (unsigned char *)malloc (nchans);
// note that redundant reordering info is not stored, so we fill in the rest
if (wpc->channel_reordering) {
for (i = 0; i < nchans; ++i)
if (bytecnt) {
wpc->channel_reordering [i] = *byteptr++;
if (wpc->channel_reordering [i] >= nchans) // make sure index is in range
wpc->channel_reordering [i] = 0;
bytecnt--;
}
else
wpc->channel_reordering [i] = i;
}
}
}
else
wpc->channel_layout += wpc->config.num_channels;
}
}
return TRUE;
}
// Read non-standard sampling rate from metadata.
static int read_sample_rate (WavpackContext *wpc, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
unsigned char *byteptr = (unsigned char *)wpmd->data;
if (bytecnt == 3 || bytecnt == 4) {
wpc->config.sample_rate = (int32_t) *byteptr++;
wpc->config.sample_rate |= (int32_t) *byteptr++ << 8;
wpc->config.sample_rate |= (int32_t) *byteptr++ << 16;
// for sampling rates > 16777215 (non-audio probably, or ...)
if (bytecnt == 4)
wpc->config.sample_rate |= (int32_t) (*byteptr & 0x7f) << 24;
}
return TRUE;
}
// Read wrapper data from metadata. Currently, this consists of the RIFF
// header and trailer that wav files contain around the audio data but could
// be used for other formats as well. Because WavPack files contain all the
// information required for decoding and playback, this data can probably
// be ignored except when an exact wavefile restoration is needed.
static int read_wrapper_data (WavpackContext *wpc, WavpackMetadata *wpmd)
{
if ((wpc->open_flags & OPEN_WRAPPER) && wpc->wrapper_bytes < MAX_WRAPPER_BYTES && wpmd->byte_length) {
wpc->wrapper_data = (unsigned char *)realloc (wpc->wrapper_data, wpc->wrapper_bytes + wpmd->byte_length);
if (!wpc->wrapper_data)
return FALSE;
memcpy (wpc->wrapper_data + wpc->wrapper_bytes, wpmd->data, wpmd->byte_length);
wpc->wrapper_bytes += wpmd->byte_length;
}
return TRUE;
}
static int read_metadata_buff (WavpackMetadata *wpmd, unsigned char *blockbuff, unsigned char **buffptr)
{
WavpackHeader *wphdr = (WavpackHeader *) blockbuff;
unsigned char *buffend = blockbuff + wphdr->ckSize + 8;
if (buffend - *buffptr < 2)
return FALSE;
wpmd->id = *(*buffptr)++;
wpmd->byte_length = *(*buffptr)++ << 1;
if (wpmd->id & ID_LARGE) {
wpmd->id &= ~ID_LARGE;
if (buffend - *buffptr < 2)
return FALSE;
wpmd->byte_length += *(*buffptr)++ << 9;
wpmd->byte_length += *(*buffptr)++ << 17;
}
if (wpmd->id & ID_ODD_SIZE) {
if (!wpmd->byte_length) // odd size and zero length makes no sense
return FALSE;
wpmd->id &= ~ID_ODD_SIZE;
wpmd->byte_length--;
}
if (wpmd->byte_length) {
if (buffend - *buffptr < wpmd->byte_length + (wpmd->byte_length & 1)) {
wpmd->data = NULL;
return FALSE;
}
wpmd->data = *buffptr;
(*buffptr) += wpmd->byte_length + (wpmd->byte_length & 1);
}
else
wpmd->data = NULL;
return TRUE;
}
static int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd)
{
WavpackStream *wps = wpc->streams [wpc->current_stream];
switch (wpmd->id) {
case ID_DUMMY:
return TRUE;
case ID_DECORR_TERMS:
return read_decorr_terms (wps, wpmd);
case ID_DECORR_WEIGHTS:
return read_decorr_weights (wps, wpmd);
case ID_DECORR_SAMPLES:
return read_decorr_samples (wps, wpmd);
case ID_ENTROPY_VARS:
return read_entropy_vars (wps, wpmd);
case ID_HYBRID_PROFILE:
return read_hybrid_profile (wps, wpmd);
case ID_SHAPING_WEIGHTS:
return read_shaping_info (wps, wpmd);
case ID_FLOAT_INFO:
return read_float_info (wps, wpmd);
case ID_INT32_INFO:
return read_int32_info (wps, wpmd);
case ID_CHANNEL_INFO:
return read_channel_info (wpc, wpmd);
case ID_CHANNEL_IDENTITIES:
return read_channel_identities (wpc, wpmd);
case ID_CONFIG_BLOCK:
return read_config_info (wpc, wpmd);
case ID_NEW_CONFIG_BLOCK:
return read_new_config_info (wpc, wpmd);
case ID_SAMPLE_RATE:
return read_sample_rate (wpc, wpmd);
case ID_WV_BITSTREAM:
return init_wv_bitstream (wps, wpmd);
case ID_WVC_BITSTREAM:
return init_wvc_bitstream (wps, wpmd);
case ID_WVX_BITSTREAM:
return init_wvx_bitstream (wps, wpmd);
case ID_DSD_BLOCK:
#ifdef ENABLE_DSD
return init_dsd_block (wpc, wpmd);
#else
strcpy (wpc->error_message, "not configured to handle DSD WavPack files!");
return FALSE;
#endif
case ID_ALT_HEADER: case ID_ALT_TRAILER:
if (!(wpc->open_flags & OPEN_ALT_TYPES))
return TRUE;
case ID_RIFF_HEADER: case ID_RIFF_TRAILER:
return read_wrapper_data (wpc, wpmd);
case ID_ALT_MD5_CHECKSUM:
if (!(wpc->open_flags & OPEN_ALT_TYPES))
return TRUE;
case ID_MD5_CHECKSUM:
if (wpmd->byte_length == 16) {
memcpy (wpc->config.md5_checksum, wpmd->data, 16);
wpc->config.flags |= CONFIG_MD5_CHECKSUM;
wpc->config.md5_read = 1;
}
return TRUE;
case ID_ALT_EXTENSION:
if (wpmd->byte_length && wpmd->byte_length < sizeof (wpc->file_extension)) {
memcpy (wpc->file_extension, wpmd->data, wpmd->byte_length);
wpc->file_extension [wpmd->byte_length] = 0;
}
return TRUE;
// we don't actually verify the checksum here (it's done right after the
// block is read), but it's a good indicator of version 5 files
case ID_BLOCK_CHECKSUM:
wpc->version_five = 1;
return TRUE;
default:
return (wpmd->id & ID_OPTIONAL_DATA) ? TRUE : FALSE;
}
}
//////////////////////////////// bitstream management ///////////////////////////////
// Open the specified BitStream and associate with the specified buffer.
static void bs_read (Bitstream *bs);
static void bs_open_read (Bitstream *bs, void *buffer_start, void *buffer_end)
{
bs->error = bs->sr = bs->bc = 0;
bs->ptr = ((bs->buf = (uint16_t *)buffer_start) - 1);
bs->end = (uint16_t *)buffer_end;
bs->wrap = bs_read;
}
// This function is only called from the getbit() and getbits() macros when
// the BitStream has been exhausted and more data is required. Sinve these
// bistreams no longer access files, this function simple sets an error and
// resets the buffer.
static void bs_read (Bitstream *bs)
{
bs->ptr = bs->buf;
bs->error = 1;
}
// This function is called to close the bitstream. It returns the number of
// full bytes actually read as bits.
uint32_t bs_close_read (Bitstream *bs)
{
uint32_t bytes_read;
if (bs->bc < sizeof (*(bs->ptr)) * 8)
bs->ptr++;
bytes_read = (uint32_t)(bs->ptr - bs->buf) * sizeof (*(bs->ptr));
if (!(bytes_read & 1))
++bytes_read;
CLEAR (*bs);
return bytes_read;
}
// Normally the trailing wrapper will not be available when a WavPack file is first
// opened for reading because it is stored in the final block of the file. This
// function forces a seek to the end of the file to pick up any trailing wrapper
// stored there (then use WavPackGetWrapper**() to obtain). This can obviously only
// be used for seekable files (not pipes) and is not available for pre-4.0 WavPack
// files.
void WavpackSeekTrailingWrapper (WavpackContext *wpc)
{
if ((wpc->open_flags & OPEN_WRAPPER) &&
wpc->reader->can_seek (wpc->wv_in) && !wpc->stream3)
seek_eof_information (wpc, NULL, TRUE);
}
// Get any MD5 checksum stored in the metadata (should be called after reading
// last sample or an extra seek will occur). A return value of FALSE indicates
// that no MD5 checksum was stored.
int WavpackGetMD5Sum (WavpackContext *wpc, unsigned char data [16])
{
if (wpc->config.flags & CONFIG_MD5_CHECKSUM) {
if (!wpc->config.md5_read && wpc->reader->can_seek (wpc->wv_in))
seek_eof_information (wpc, NULL, FALSE);
if (wpc->config.md5_read) {
memcpy (data, wpc->config.md5_checksum, 16);
return TRUE;
}
}
return FALSE;
}
// Read from current file position until a valid 32-byte WavPack 4.0 header is
// found and read into the specified pointer. The number of bytes skipped is
// returned. If no WavPack header is found within 1 meg, then a -1 is returned
// to indicate the error. No additional bytes are read past the header and it
// is returned in the processor's native endian mode. Seeking is not required.
uint32_t read_next_header (WavpackStreamReader64 *reader, void *id, WavpackHeader *wphdr)
{
unsigned char buffer [sizeof (*wphdr)], *sp = buffer + sizeof (*wphdr), *ep = sp;
uint32_t bytes_skipped = 0;
int bleft;
while (1) {
if (sp < ep) {
bleft = (int)(ep - sp);
memmove (buffer, sp, bleft);
}
else
bleft = 0;
if (reader->read_bytes (id, buffer + bleft, sizeof (*wphdr) - bleft) != sizeof (*wphdr) - bleft)
return -1;
sp = buffer;
if (*sp++ == 'w' && *sp == 'v' && *++sp == 'p' && *++sp == 'k' &&
!(*++sp & 1) && sp [2] < 16 && !sp [3] && (sp [2] || sp [1] || *sp >= 24) && sp [5] == 4 &&
sp [4] >= (MIN_STREAM_VERS & 0xff) && sp [4] <= (MAX_STREAM_VERS & 0xff) && sp [18] < 3 && !sp [19]) {
memcpy (wphdr, buffer, sizeof (*wphdr));
WavpackLittleEndianToNative (wphdr, WavpackHeaderFormat);
return bytes_skipped;
}
while (sp < ep && *sp != 'w')
sp++;
if ((bytes_skipped += (uint32_t)(sp - buffer)) > 1024 * 1024)
return -1;
}
}
// Compare the regular wv file block header to a potential matching wvc
// file block header and return action code based on analysis:
//
// 0 = use wvc block (assuming rest of block is readable)
// 1 = bad match; try to read next wvc block
// -1 = bad match; ignore wvc file for this block and backup fp (if
// possible) and try to use this block next time
static int match_wvc_header (WavpackHeader *wv_hdr, WavpackHeader *wvc_hdr)
{
if (GET_BLOCK_INDEX (*wv_hdr) == GET_BLOCK_INDEX (*wvc_hdr) &&
wv_hdr->block_samples == wvc_hdr->block_samples) {
int wvi = 0, wvci = 0;
if (wv_hdr->flags == wvc_hdr->flags)
return 0;
if (wv_hdr->flags & INITIAL_BLOCK)
wvi -= 1;
if (wv_hdr->flags & FINAL_BLOCK)
wvi += 1;
if (wvc_hdr->flags & INITIAL_BLOCK)
wvci -= 1;
if (wvc_hdr->flags & FINAL_BLOCK)
wvci += 1;
return (wvci - wvi < 0) ? 1 : -1;
}
if (((GET_BLOCK_INDEX (*wvc_hdr) - GET_BLOCK_INDEX (*wv_hdr)) << 24) < 0)
return 1;
else
return -1;
}
// Read the wvc block that matches the regular wv block that has been
// read for the current stream. If an exact match is not found then
// we either keep reading or back up and (possibly) use the block
// later. The skip_wvc flag is set if not matching wvc block is found
// so that we can still decode using only the lossy version (although
// we flag this as an error). A return of FALSE indicates a serious
// error (not just that we missed one wvc block).
int read_wvc_block (WavpackContext *wpc)
{
WavpackStream *wps = wpc->streams [wpc->current_stream];
int64_t bcount, file2pos;
WavpackHeader orig_wphdr;
WavpackHeader wphdr;
int compare_result;
while (1) {
file2pos = wpc->reader->get_pos (wpc->wvc_in);
bcount = read_next_header (wpc->reader, wpc->wvc_in, &wphdr);
if (bcount == (uint32_t) -1) {
wps->wvc_skip = TRUE;
wpc->crc_errors++;
return FALSE;
}
memcpy (&orig_wphdr, &wphdr, 32); // save original header for verify step
if (wpc->open_flags & OPEN_STREAMING)
SET_BLOCK_INDEX (wphdr, wps->sample_index = 0);
else
SET_BLOCK_INDEX (wphdr, GET_BLOCK_INDEX (wphdr) - wpc->initial_index);
if (wphdr.flags & INITIAL_BLOCK)
wpc->file2pos = file2pos + bcount;
compare_result = match_wvc_header (&wps->wphdr, &wphdr);
if (!compare_result) {
wps->block2buff = (unsigned char *)malloc (wphdr.ckSize + 8);
if (!wps->block2buff)
return FALSE;
if (wpc->reader->read_bytes (wpc->wvc_in, wps->block2buff + 32, wphdr.ckSize - 24) !=
wphdr.ckSize - 24) {
free (wps->block2buff);
wps->block2buff = NULL;
wps->wvc_skip = TRUE;
wpc->crc_errors++;
return FALSE;
}
memcpy (wps->block2buff, &orig_wphdr, 32);
// don't use corrupt blocks
if (!WavpackVerifySingleBlock (wps->block2buff, !(wpc->open_flags & OPEN_NO_CHECKSUM))) {
free (wps->block2buff);
wps->block2buff = NULL;
wps->wvc_skip = TRUE;
wpc->crc_errors++;
return TRUE;
}
wps->wvc_skip = FALSE;
memcpy (wps->block2buff, &wphdr, 32);
memcpy (&wps->wphdr, &wphdr, 32);
return TRUE;
}
else if (compare_result == -1) {
wps->wvc_skip = TRUE;
wpc->reader->set_pos_rel (wpc->wvc_in, -32, SEEK_CUR);
wpc->crc_errors++;
return TRUE;
}
}
}
// This function is used to seek to end of a file to obtain certain information
// that is stored there at the file creation time because it is not known at
// the start. This includes the MD5 sum and and trailing part of the file
// wrapper, and in some rare cases may include the total number of samples in
// the file (although we usually try to back up and write that at the front of
// the file). Note this function restores the file position to its original
// location (and obviously requires a seekable file). The normal return value
// is TRUE indicating no errors, although this does not actually mean that any
// information was retrieved. An error return of FALSE usually means the file
// terminated unexpectedly. Note that this could be used to get all three
// types of information in one go, but it's not actually used that way now.
static int seek_eof_information (WavpackContext *wpc, int64_t *final_index, int get_wrapper)
{
int64_t restore_pos, last_pos = -1;
WavpackStreamReader64 *reader = wpc->reader;
int alt_types = wpc->open_flags & OPEN_ALT_TYPES;
uint32_t blocks = 0, audio_blocks = 0;
void *id = wpc->wv_in;
WavpackHeader wphdr;
restore_pos = reader->get_pos (id); // we restore file position when done
// start 1MB from the end-of-file, or from the start if the file is not that big
if (reader->get_length (id) > (int64_t) 1048576)
reader->set_pos_rel (id, -1048576, SEEK_END);
else
reader->set_pos_abs (id, 0);
// Note that we go backward (without parsing inside blocks) until we find a block
// with audio (careful to not get stuck in a loop). Only then do we go forward
// parsing all blocks in their entirety.
while (1) {
uint32_t bcount = read_next_header (reader, id, &wphdr);
int64_t current_pos = reader->get_pos (id);
// if we just got to the same place as last time, we're stuck and need to give up
if (current_pos == last_pos) {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
last_pos = current_pos;
// We enter here if we just read 1 MB without seeing any WavPack block headers.
// Since WavPack blocks are < 1 MB, that means we're in a big APE tag, or we got
// to the end-of-file.
if (bcount == (uint32_t) -1) {
// if we have not seen any blocks at all yet, back up almost 2 MB (or to the
// beginning of the file) and try again
if (!blocks) {
if (current_pos > (int64_t) 2000000)
reader->set_pos_rel (id, -2000000, SEEK_CUR);
else
reader->set_pos_abs (id, 0);
continue;
}
// if we have seen WavPack blocks, then this means we've done all we can do here
reader->set_pos_abs (id, restore_pos);
return TRUE;
}
blocks++;
// If the block has audio samples, calculate a final index, although this is not
// final since this may not be the last block with audio. On the other hand, if
// this block does not have audio, and we haven't seen one with audio, we have
// to go back some more.
if (wphdr.block_samples) {
if (final_index)
*final_index = GET_BLOCK_INDEX (wphdr) + wphdr.block_samples;
audio_blocks++;
}
else if (!audio_blocks) {
if (current_pos > (int64_t) 1048576)
reader->set_pos_rel (id, -1048576, SEEK_CUR);
else
reader->set_pos_abs (id, 0);
continue;
}
// at this point we have seen at least one block with audio, so we parse the
// entire block looking for MD5 metadata or (conditionally) trailing wrappers
bcount = wphdr.ckSize - sizeof (WavpackHeader) + 8;
while (bcount >= 2) {
unsigned char meta_id, c1, c2;
uint32_t meta_bc, meta_size;
if (reader->read_bytes (id, &meta_id, 1) != 1 ||
reader->read_bytes (id, &c1, 1) != 1) {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
meta_bc = c1 << 1;
bcount -= 2;
if (meta_id & ID_LARGE) {
if (bcount < 2 || reader->read_bytes (id, &c1, 1) != 1 ||
reader->read_bytes (id, &c2, 1) != 1) {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17);
bcount -= 2;
}
meta_size = (meta_id & ID_ODD_SIZE) ? meta_bc - 1 : meta_bc;
meta_id &= ID_UNIQUE;
if (get_wrapper && (meta_id == ID_RIFF_TRAILER || (alt_types && meta_id == ID_ALT_TRAILER)) && meta_bc) {
wpc->wrapper_data = (unsigned char *)realloc (wpc->wrapper_data, wpc->wrapper_bytes + meta_bc);
if (!wpc->wrapper_data) {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
if (reader->read_bytes (id, wpc->wrapper_data + wpc->wrapper_bytes, meta_bc) == meta_bc)
wpc->wrapper_bytes += meta_size;
else {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
}
else if (meta_id == ID_MD5_CHECKSUM || (alt_types && meta_id == ID_ALT_MD5_CHECKSUM)) {
if (meta_bc == 16 && bcount >= 16) {
if (reader->read_bytes (id, wpc->config.md5_checksum, 16) == 16)
wpc->config.md5_read = TRUE;
else {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
}
else
reader->set_pos_rel (id, meta_bc, SEEK_CUR);
}
else
reader->set_pos_rel (id, meta_bc, SEEK_CUR);
bcount -= meta_bc;
}
}
}
// Quickly verify the referenced block. It is assumed that the WavPack header has been converted
// to native endian format. If a block checksum is performed, that is done in little-endian
// (file) format. It is also assumed that the caller has made sure that the block length
// indicated in the header is correct (we won't overflow the buffer). If a checksum is present,
// then it is checked, otherwise we just check that all the metadata blocks are formatted
// correctly (without looking at their contents). Returns FALSE for bad block.
int WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum)
{
WavpackHeader *wphdr = (WavpackHeader *) buffer;
uint32_t checksum_passed = 0, bcount, meta_bc;
unsigned char *dp, meta_id, c1, c2;
if (strncmp (wphdr->ckID, "wvpk", 4) || wphdr->ckSize + 8 < sizeof (WavpackHeader))
return FALSE;
bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8;
dp = (unsigned char *)(wphdr + 1);
while (bcount >= 2) {
meta_id = *dp++;
c1 = *dp++;
meta_bc = c1 << 1;
bcount -= 2;
if (meta_id & ID_LARGE) {
if (bcount < 2)
return FALSE;
c1 = *dp++;
c2 = *dp++;
meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17);
bcount -= 2;
}
if (bcount < meta_bc)
return FALSE;
if (verify_checksum && (meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) {
#ifdef BITSTREAM_SHORTS
uint16_t *csptr = (uint16_t*) buffer;
#else
unsigned char *csptr = buffer;
#endif
int wcount = (int)(dp - 2 - buffer) >> 1;
uint32_t csum = (uint32_t) -1;
if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4)
return FALSE;
#ifdef BITSTREAM_SHORTS
while (wcount--)
csum = (csum * 3) + *csptr++;
#else
WavpackNativeToLittleEndian ((WavpackHeader *) buffer, WavpackHeaderFormat);
while (wcount--) {
csum = (csum * 3) + csptr [0] + (csptr [1] << 8);
csptr += 2;
}
WavpackLittleEndianToNative ((WavpackHeader *) buffer, WavpackHeaderFormat);
#endif
if (meta_bc == 4) {
if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff) || *dp++ != ((csum >> 16) & 0xff) || *dp++ != ((csum >> 24) & 0xff))
return FALSE;
}
else {
csum ^= csum >> 16;
if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff))
return FALSE;
}
checksum_passed++;
}
bcount -= meta_bc;
dp += meta_bc;
}
return (bcount == 0) && (!verify_checksum || !(wphdr->flags & HAS_CHECKSUM) || checksum_passed);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_457_0 |
crossvul-cpp_data_bad_2665_0 | /*
* Copyright (c) 1989, 1990, 1991, 1993, 1994
* 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: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IPv6 Routing Information Protocol (RIPng) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
/*
* Copyright (C) 1995, 1996, 1997 and 1998 WIDE Project.
* 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 project 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 PROJECT 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 PROJECT 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.
*/
#define RIP6_VERSION 1
#define RIP6_REQUEST 1
#define RIP6_RESPONSE 2
struct netinfo6 {
struct in6_addr rip6_dest;
uint16_t rip6_tag;
uint8_t rip6_plen;
uint8_t rip6_metric;
};
struct rip6 {
uint8_t rip6_cmd;
uint8_t rip6_vers;
uint8_t rip6_res1[2];
union {
struct netinfo6 ru6_nets[1];
char ru6_tracefile[1];
} rip6un;
#define rip6_nets rip6un.ru6_nets
#define rip6_tracefile rip6un.ru6_tracefile
};
#define HOPCNT_INFINITY6 16
#if !defined(IN6_IS_ADDR_UNSPECIFIED) && !defined(_MSC_VER) /* MSVC inline */
static int IN6_IS_ADDR_UNSPECIFIED(const struct in6_addr *addr)
{
static const struct in6_addr in6addr_any; /* :: */
return (memcmp(addr, &in6addr_any, sizeof(*addr)) == 0);
}
#endif
static int
rip6_entry_print(netdissect_options *ndo, register const struct netinfo6 *ni, int metric)
{
int l;
l = ND_PRINT((ndo, "%s/%d", ip6addr_string(ndo, &ni->rip6_dest), ni->rip6_plen));
if (ni->rip6_tag)
l += ND_PRINT((ndo, " [%d]", EXTRACT_16BITS(&ni->rip6_tag)));
if (metric)
l += ND_PRINT((ndo, " (%d)", ni->rip6_metric));
return l;
}
void
ripng_print(netdissect_options *ndo, const u_char *dat, unsigned int length)
{
register const struct rip6 *rp = (const struct rip6 *)dat;
register const struct netinfo6 *ni;
register u_int amt;
register u_int i;
int j;
int trunc;
if (ndo->ndo_snapend < dat)
return;
amt = ndo->ndo_snapend - dat;
i = min(length, amt);
if (i < (sizeof(struct rip6) - sizeof(struct netinfo6)))
return;
i -= (sizeof(struct rip6) - sizeof(struct netinfo6));
switch (rp->rip6_cmd) {
case RIP6_REQUEST:
j = length / sizeof(*ni);
if (j == 1
&& rp->rip6_nets->rip6_metric == HOPCNT_INFINITY6
&& IN6_IS_ADDR_UNSPECIFIED(&rp->rip6_nets->rip6_dest)) {
ND_PRINT((ndo, " ripng-req dump"));
break;
}
if (j * sizeof(*ni) != length - 4)
ND_PRINT((ndo, " ripng-req %d[%u]:", j, length));
else
ND_PRINT((ndo, " ripng-req %d:", j));
trunc = ((i / sizeof(*ni)) * sizeof(*ni) != i);
for (ni = rp->rip6_nets; i >= sizeof(*ni);
i -= sizeof(*ni), ++ni) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t"));
else
ND_PRINT((ndo, " "));
rip6_entry_print(ndo, ni, 0);
}
break;
case RIP6_RESPONSE:
j = length / sizeof(*ni);
if (j * sizeof(*ni) != length - 4)
ND_PRINT((ndo, " ripng-resp %d[%u]:", j, length));
else
ND_PRINT((ndo, " ripng-resp %d:", j));
trunc = ((i / sizeof(*ni)) * sizeof(*ni) != i);
for (ni = rp->rip6_nets; i >= sizeof(*ni);
i -= sizeof(*ni), ++ni) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t"));
else
ND_PRINT((ndo, " "));
rip6_entry_print(ndo, ni, ni->rip6_metric);
}
if (trunc)
ND_PRINT((ndo, "[|ripng]"));
break;
default:
ND_PRINT((ndo, " ripng-%d ?? %u", rp->rip6_cmd, length));
break;
}
if (rp->rip6_vers != RIP6_VERSION)
ND_PRINT((ndo, " [vers %d]", rp->rip6_vers));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2665_0 |
crossvul-cpp_data_bad_1369_0 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/***************************************************************************
* Copyright (C) 2017-2019 ZmartZone IAM
* Copyright (C) 2013-2017 Ping Identity Corporation
* All rights reserved.
*
* For further information please contact:
*
* Ping Identity Corporation
* 1099 18th St Suite 2950
* Denver, CO 80202
* 303.468.2900
* http://www.pingidentity.com
*
* DISCLAIMER OF WARRANTIES:
*
* THE SOFTWARE PROVIDED HEREUNDER IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
* ANY WARRANTIES OR REPRESENTATIONS EXPRESS, IMPLIED OR STATUTORY; INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF QUALITY, PERFORMANCE, NONINFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NOR ARE THERE ANY
* WARRANTIES CREATED BY A COURSE OR DEALING, COURSE OF PERFORMANCE OR TRADE
* USAGE. FURTHERMORE, THERE ARE NO WARRANTIES THAT THE SOFTWARE WILL MEET
* YOUR NEEDS OR BE FREE FROM ERRORS, OR THAT THE OPERATION OF THE SOFTWARE
* WILL BE UNINTERRUPTED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES 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.
*
* Initially based on mod_auth_cas.c:
* https://github.com/Jasig/mod_auth_cas
*
* Other code copied/borrowed/adapted:
* shared memory caching: mod_auth_mellon
*
* @Author: Hans Zandbelt - hans.zandbelt@zmartzone.eu
*
**************************************************************************/
#include "apr_hash.h"
#include "apr_strings.h"
#include "ap_config.h"
#include "ap_provider.h"
#include "apr_lib.h"
#include "apr_file_io.h"
#include "apr_sha1.h"
#include "apr_base64.h"
#include "httpd.h"
#include "http_core.h"
#include "http_config.h"
#include "http_log.h"
#include "http_protocol.h"
#include "http_request.h"
#include "mod_auth_openidc.h"
#define ERROR 2
static int oidc_handle_logout_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *url);
// TODO:
// - sort out oidc_cfg vs. oidc_dir_cfg stuff
// - rigid input checking on discovery responses
// - check self-issued support
// - README.quickstart
// - refresh metadata once-per too? (for non-signing key changes)
extern module AP_MODULE_DECLARE_DATA auth_openidc_module;
/*
* clean any suspicious headers in the HTTP request sent by the user agent
*/
static void oidc_scrub_request_headers(request_rec *r, const char *claim_prefix,
apr_hash_t *scrub) {
const int prefix_len = claim_prefix ? strlen(claim_prefix) : 0;
/* get an array representation of the incoming HTTP headers */
const apr_array_header_t * const h = apr_table_elts(r->headers_in);
/* table to keep the non-suspicious headers */
apr_table_t *clean_headers = apr_table_make(r->pool, h->nelts);
/* loop over the incoming HTTP headers */
const apr_table_entry_t * const e = (const apr_table_entry_t *) h->elts;
int i;
for (i = 0; i < h->nelts; i++) {
const char * const k = e[i].key;
/* is this header's name equivalent to a header that needs scrubbing? */
const char *hdr =
(k != NULL) && (scrub != NULL) ?
apr_hash_get(scrub, k, APR_HASH_KEY_STRING) : NULL;
const int header_matches = (hdr != NULL)
&& (oidc_strnenvcmp(k, hdr, -1) == 0);
/*
* would this header be interpreted as a mod_auth_openidc attribute? Note
* that prefix_len will be zero if no attr_prefix is defined,
* so this will always be false. Also note that we do not
* scrub headers if the prefix is empty because every header
* would match.
*/
const int prefix_matches = (k != NULL) && prefix_len
&& (oidc_strnenvcmp(k, claim_prefix, prefix_len) == 0);
/* add to the clean_headers if non-suspicious, skip and report otherwise */
if (!prefix_matches && !header_matches) {
apr_table_addn(clean_headers, k, e[i].val);
} else {
oidc_warn(r, "scrubbed suspicious request header (%s: %.32s)", k,
e[i].val);
}
}
/* overwrite the incoming headers with the cleaned result */
r->headers_in = clean_headers;
}
/*
* scrub all mod_auth_openidc related headers
*/
void oidc_scrub_headers(request_rec *r) {
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
const char *prefix = oidc_cfg_claim_prefix(r);
apr_hash_t *hdrs = apr_hash_make(r->pool);
if (apr_strnatcmp(prefix, "") == 0) {
if ((cfg->white_listed_claims != NULL)
&& (apr_hash_count(cfg->white_listed_claims) > 0))
hdrs = apr_hash_overlay(r->pool, cfg->white_listed_claims, hdrs);
else
oidc_warn(r,
"both " OIDCClaimPrefix " and " OIDCWhiteListedClaims " are empty: this renders an insecure setup!");
}
char *authn_hdr = oidc_cfg_dir_authn_header(r);
if (authn_hdr != NULL)
apr_hash_set(hdrs, authn_hdr, APR_HASH_KEY_STRING, authn_hdr);
/*
* scrub all headers starting with OIDC_ first
*/
oidc_scrub_request_headers(r, OIDC_DEFAULT_HEADER_PREFIX, hdrs);
/*
* then see if the claim headers need to be removed on top of that
* (i.e. the prefix does not start with the default OIDC_)
*/
if ((strstr(prefix, OIDC_DEFAULT_HEADER_PREFIX) != prefix)) {
oidc_scrub_request_headers(r, prefix, NULL);
}
}
/*
* strip the session cookie from the headers sent to the application/backend
*/
void oidc_strip_cookies(request_rec *r) {
char *cookie, *ctx, *result = NULL;
const char *name = NULL;
int i;
apr_array_header_t *strip = oidc_dir_cfg_strip_cookies(r);
char *cookies = apr_pstrdup(r->pool, oidc_util_hdr_in_cookie_get(r));
if ((cookies != NULL) && (strip != NULL)) {
oidc_debug(r,
"looking for the following cookies to strip from cookie header: %s",
apr_array_pstrcat(r->pool, strip, OIDC_CHAR_COMMA));
cookie = apr_strtok(cookies, OIDC_STR_SEMI_COLON, &ctx);
do {
while (cookie != NULL && *cookie == OIDC_CHAR_SPACE)
cookie++;
for (i = 0; i < strip->nelts; i++) {
name = ((const char**) strip->elts)[i];
if ((strncmp(cookie, name, strlen(name)) == 0)
&& (cookie[strlen(name)] == OIDC_CHAR_EQUAL)) {
oidc_debug(r, "stripping: %s", name);
break;
}
}
if (i == strip->nelts) {
result = result ? apr_psprintf(r->pool, "%s%s%s", result,
OIDC_STR_SEMI_COLON, cookie) :
cookie;
}
cookie = apr_strtok(NULL, OIDC_STR_SEMI_COLON, &ctx);
} while (cookie != NULL);
oidc_util_hdr_in_cookie_set(r, result);
}
}
#define OIDC_SHA1_LEN 20
/*
* calculates a hash value based on request fingerprint plus a provided nonce string.
*/
static char *oidc_get_browser_state_hash(request_rec *r, const char *nonce) {
oidc_debug(r, "enter");
/* helper to hold to header values */
const char *value = NULL;
/* the hash context */
apr_sha1_ctx_t sha1;
/* Initialize the hash context */
apr_sha1_init(&sha1);
/* get the X-FORWARDED-FOR header value */
value = oidc_util_hdr_in_x_forwarded_for_get(r);
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, strlen(value));
/* get the USER-AGENT header value */
value = oidc_util_hdr_in_user_agent_get(r);
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, strlen(value));
/* get the remote client IP address or host name */
/*
int remotehost_is_ip;
value = ap_get_remote_host(r->connection, r->per_dir_config,
REMOTE_NOLOOKUP, &remotehost_is_ip);
apr_sha1_update(&sha1, value, strlen(value));
*/
/* concat the nonce parameter to the hash input */
apr_sha1_update(&sha1, nonce, strlen(nonce));
/* concat the token binding ID if present */
value = oidc_util_get_provided_token_binding_id(r);
if (value != NULL) {
oidc_debug(r,
"Provided Token Binding ID environment variable found; adding its value to the state");
apr_sha1_update(&sha1, value, strlen(value));
}
/* finalize the hash input and calculate the resulting hash output */
unsigned char hash[OIDC_SHA1_LEN];
apr_sha1_final(hash, &sha1);
/* base64url-encode the resulting hash and return it */
char *result = NULL;
oidc_base64url_encode(r, &result, (const char *) hash, OIDC_SHA1_LEN, TRUE);
return result;
}
/*
* return the name for the state cookie
*/
static char *oidc_get_state_cookie_name(request_rec *r, const char *state) {
return apr_psprintf(r->pool, "%s%s", OIDC_STATE_COOKIE_PREFIX, state);
}
/*
* return the static provider configuration, i.e. from a metadata URL or configuration primitives
*/
static apr_byte_t oidc_provider_static_config(request_rec *r, oidc_cfg *c,
oidc_provider_t **provider) {
json_t *j_provider = NULL;
char *s_json = NULL;
/* see if we should configure a static provider based on external (cached) metadata */
if ((c->metadata_dir != NULL) || (c->provider.metadata_url == NULL)) {
*provider = &c->provider;
return TRUE;
}
oidc_cache_get_provider(r, c->provider.metadata_url, &s_json);
if (s_json == NULL) {
if (oidc_metadata_provider_retrieve(r, c, NULL,
c->provider.metadata_url, &j_provider, &s_json) == FALSE) {
oidc_error(r, "could not retrieve metadata from url: %s",
c->provider.metadata_url);
return FALSE;
}
oidc_cache_set_provider(r, c->provider.metadata_url, s_json,
apr_time_now() + (c->provider_metadata_refresh_interval <= 0 ? apr_time_from_sec( OIDC_CACHE_PROVIDER_METADATA_EXPIRY_DEFAULT) : c->provider_metadata_refresh_interval));
} else {
oidc_util_decode_json_object(r, s_json, &j_provider);
/* check to see if it is valid metadata */
if (oidc_metadata_provider_is_valid(r, c, j_provider, NULL) == FALSE) {
oidc_error(r,
"cache corruption detected: invalid metadata from url: %s",
c->provider.metadata_url);
return FALSE;
}
}
*provider = apr_pcalloc(r->pool, sizeof(oidc_provider_t));
memcpy(*provider, &c->provider, sizeof(oidc_provider_t));
if (oidc_metadata_provider_parse(r, c, j_provider, *provider) == FALSE) {
oidc_error(r, "could not parse metadata from url: %s",
c->provider.metadata_url);
if (j_provider)
json_decref(j_provider);
return FALSE;
}
json_decref(j_provider);
return TRUE;
}
/*
* return the oidc_provider_t struct for the specified issuer
*/
static oidc_provider_t *oidc_get_provider_for_issuer(request_rec *r,
oidc_cfg *c, const char *issuer, apr_byte_t allow_discovery) {
/* by default we'll assume that we're dealing with a single statically configured OP */
oidc_provider_t *provider = NULL;
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return NULL;
/* unless a metadata directory was configured, so we'll try and get the provider settings from there */
if (c->metadata_dir != NULL) {
/* try and get metadata from the metadata directory for the OP that sent this response */
if ((oidc_metadata_get(r, c, issuer, &provider, allow_discovery)
== FALSE) || (provider == NULL)) {
/* don't know nothing about this OP/issuer */
oidc_error(r, "no provider metadata found for issuer \"%s\"",
issuer);
return NULL;
}
}
return provider;
}
/*
* find out whether the request is a response from an IDP discovery page
*/
static apr_byte_t oidc_is_discovery_response(request_rec *r, oidc_cfg *cfg) {
/*
* prereq: this is a call to the configured redirect_uri, now see if:
* the OIDC_DISC_OP_PARAM is present
*/
return oidc_util_request_has_parameter(r, OIDC_DISC_OP_PARAM)
|| oidc_util_request_has_parameter(r, OIDC_DISC_USER_PARAM);
}
/*
* return the HTTP method being called: only for POST data persistence purposes
*/
static const char *oidc_original_request_method(request_rec *r, oidc_cfg *cfg,
apr_byte_t handle_discovery_response) {
const char *method = OIDC_METHOD_GET;
char *m = NULL;
if ((handle_discovery_response == TRUE)
&& (oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, cfg)))
&& (oidc_is_discovery_response(r, cfg))) {
oidc_util_get_request_parameter(r, OIDC_DISC_RM_PARAM, &m);
if (m != NULL)
method = apr_pstrdup(r->pool, m);
} else {
/*
* if POST preserve is not enabled for this location, there's no point in preserving
* the method either which would result in POSTing empty data on return;
* so we revert to legacy behavior
*/
if (oidc_cfg_dir_preserve_post(r) == 0)
return OIDC_METHOD_GET;
const char *content_type = oidc_util_hdr_in_content_type_get(r);
if ((r->method_number == M_POST) && (apr_strnatcmp(content_type,
OIDC_CONTENT_TYPE_FORM_ENCODED) == 0))
method = OIDC_METHOD_FORM_POST;
}
oidc_debug(r, "return: %s", method);
return method;
}
/*
* send an OpenID Connect authorization request to the specified provider preserving POST parameters using HTML5 storage
*/
apr_byte_t oidc_post_preserve_javascript(request_rec *r, const char *location,
char **javascript, char **javascript_method) {
if (oidc_cfg_dir_preserve_post(r) == 0)
return FALSE;
oidc_debug(r, "enter");
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
const char *method = oidc_original_request_method(r, cfg, FALSE);
if (apr_strnatcmp(method, OIDC_METHOD_FORM_POST) != 0)
return FALSE;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return FALSE;
}
const apr_array_header_t *arr = apr_table_elts(params);
const apr_table_entry_t *elts = (const apr_table_entry_t*) arr->elts;
int i;
char *json = "";
for (i = 0; i < arr->nelts; i++) {
json = apr_psprintf(r->pool, "%s'%s': '%s'%s", json,
oidc_util_escape_string(r, elts[i].key),
oidc_util_escape_string(r, elts[i].val),
i < arr->nelts - 1 ? "," : "");
}
json = apr_psprintf(r->pool, "{ %s }", json);
const char *jmethod = "preserveOnLoad";
const char *jscript =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function %s() {\n"
" sessionStorage.setItem('mod_auth_openidc_preserve_post_params', JSON.stringify(%s));\n"
" %s"
" }\n"
" </script>\n", jmethod, json,
location ?
apr_psprintf(r->pool, "window.location='%s';\n",
location) :
"");
if (location == NULL) {
if (javascript_method)
*javascript_method = apr_pstrdup(r->pool, jmethod);
if (javascript)
*javascript = apr_pstrdup(r->pool, jscript);
} else {
oidc_util_html_send(r, "Preserving...", jscript, jmethod,
"<p>Preserving...</p>", OK);
}
return TRUE;
}
/*
* restore POST parameters on original_url from HTML5 local storage
*/
static int oidc_request_post_preserved_restore(request_rec *r,
const char *original_url) {
oidc_debug(r, "enter: original_url=%s", original_url);
const char *method = "postOnLoad";
const char *script =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function str_decode(string) {\n"
" try {\n"
" result = decodeURIComponent(string);\n"
" } catch (e) {\n"
" result = unescape(string);\n"
" }\n"
" return result;\n"
" }\n"
" function %s() {\n"
" var mod_auth_openidc_preserve_post_params = JSON.parse(sessionStorage.getItem('mod_auth_openidc_preserve_post_params'));\n"
" sessionStorage.removeItem('mod_auth_openidc_preserve_post_params');\n"
" for (var key in mod_auth_openidc_preserve_post_params) {\n"
" var input = document.createElement(\"input\");\n"
" input.name = str_decode(key);\n"
" input.value = str_decode(mod_auth_openidc_preserve_post_params[key]);\n"
" input.type = \"hidden\";\n"
" document.forms[0].appendChild(input);\n"
" }\n"
" document.forms[0].action = '%s';\n"
" document.forms[0].submit();\n"
" }\n"
" </script>\n", method, original_url);
const char *body = " <p>Restoring...</p>\n"
" <form method=\"post\"></form>\n";
return oidc_util_html_send(r, "Restoring...", script, method, body,
OK);
}
/*
* parse state that was sent to us by the issuer
*/
static apr_byte_t oidc_unsolicited_proto_state(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t **proto_state) {
char *alg = NULL;
oidc_debug(r, "enter: state header=%s",
oidc_proto_peek_jwt_header(r, state, &alg));
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret,
oidc_alg2keysize(alg), OIDC_JOSE_ALG_SHA256,
TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwt_t *jwt = NULL;
if (oidc_jwt_parse(r->pool, state, &jwt,
oidc_util_merge_symmetric_key(r->pool, c->private_keys, jwk),
&err) == FALSE) {
oidc_error(r,
"could not parse JWT from state: invalid unsolicited response: %s",
oidc_jose_e2s(r->pool, err));
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully parsed JWT from state");
if (jwt->payload.iss == NULL) {
oidc_error(r, "no \"%s\" could be retrieved from JWT state, aborting",
OIDC_CLAIM_ISS);
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_provider_t *provider = oidc_get_provider_for_issuer(r, c,
jwt->payload.iss, FALSE);
if (provider == NULL) {
oidc_jwt_destroy(jwt);
return FALSE;
}
/* validate the state JWT, validating optional exp + iat */
if (oidc_proto_validate_jwt(r, jwt, provider->issuer, FALSE, FALSE,
provider->idtoken_iat_slack,
OIDC_TOKEN_BINDING_POLICY_DISABLED) == FALSE) {
oidc_jwt_destroy(jwt);
return FALSE;
}
char *rfp = NULL;
if (oidc_jose_get_string(r->pool, jwt->payload.value.json, OIDC_CLAIM_RFP,
TRUE, &rfp, &err) == FALSE) {
oidc_error(r,
"no \"%s\" claim could be retrieved from JWT state, aborting: %s",
OIDC_CLAIM_RFP, oidc_jose_e2s(r->pool, err));
oidc_jwt_destroy(jwt);
return FALSE;
}
if (apr_strnatcmp(rfp, OIDC_PROTO_ISS) != 0) {
oidc_error(r, "\"%s\" (%s) does not match \"%s\", aborting",
OIDC_CLAIM_RFP, rfp, OIDC_PROTO_ISS);
oidc_jwt_destroy(jwt);
return FALSE;
}
char *target_link_uri = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_TARGET_LINK_URI,
FALSE, &target_link_uri, NULL);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
oidc_error(r,
"no \"%s\" claim could be retrieved from JWT state and no " OIDCDefaultURL " is set, aborting",
OIDC_CLAIM_TARGET_LINK_URI);
oidc_jwt_destroy(jwt);
return FALSE;
}
target_link_uri = c->default_sso_url;
}
if (c->metadata_dir != NULL) {
if ((oidc_metadata_get(r, c, jwt->payload.iss, &provider, FALSE)
== FALSE) || (provider == NULL)) {
oidc_error(r, "no provider metadata found for provider \"%s\"",
jwt->payload.iss);
oidc_jwt_destroy(jwt);
return FALSE;
}
}
char *jti = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json, OIDC_CLAIM_JTI,
FALSE, &jti,
NULL);
if (jti == NULL) {
char *cser = oidc_jwt_serialize(r->pool, jwt, &err);
if (cser == NULL)
return FALSE;
if (oidc_util_hash_string_and_base64url_encode(r, OIDC_JOSE_ALG_SHA256,
cser, &jti) == FALSE) {
oidc_error(r,
"oidc_util_hash_string_and_base64url_encode returned an error");
return FALSE;
}
}
char *replay = NULL;
oidc_cache_get_jti(r, jti, &replay);
if (replay != NULL) {
oidc_error(r,
"the \"%s\" value (%s) passed in the browser state was found in the cache already; possible replay attack!?",
OIDC_CLAIM_JTI, jti);
oidc_jwt_destroy(jwt);
return FALSE;
}
/* jti cache duration is the configured replay prevention window for token issuance plus 10 seconds for safety */
apr_time_t jti_cache_duration = apr_time_from_sec(
provider->idtoken_iat_slack * 2 + 10);
/* store it in the cache for the calculated duration */
oidc_cache_set_jti(r, jti, jti, apr_time_now() + jti_cache_duration);
oidc_debug(r,
"jti \"%s\" validated successfully and is now cached for %" APR_TIME_T_FMT " seconds",
jti, apr_time_sec(jti_cache_duration));
jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret, 0,
NULL, TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwks_uri_t jwks_uri = { provider->jwks_uri,
provider->jwks_refresh_interval, provider->ssl_validate_server };
if (oidc_proto_jwt_verify(r, c, jwt, &jwks_uri,
oidc_util_merge_symmetric_key(r->pool, NULL, jwk)) == FALSE) {
oidc_error(r, "state JWT could not be validated, aborting");
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully verified state JWT");
*proto_state = oidc_proto_state_new();
oidc_proto_state_set_issuer(*proto_state, jwt->payload.iss);
oidc_proto_state_set_original_url(*proto_state, target_link_uri);
oidc_proto_state_set_original_method(*proto_state, OIDC_METHOD_GET);
oidc_proto_state_set_response_mode(*proto_state, provider->response_mode);
oidc_proto_state_set_response_type(*proto_state, provider->response_type);
oidc_proto_state_set_timestamp_now(*proto_state);
oidc_jwt_destroy(jwt);
return TRUE;
}
typedef struct oidc_state_cookies_t {
char *name;
apr_time_t timestamp;
struct oidc_state_cookies_t *next;
} oidc_state_cookies_t;
static int oidc_delete_oldest_state_cookies(request_rec *r,
int number_of_valid_state_cookies, int max_number_of_state_cookies,
oidc_state_cookies_t *first) {
oidc_state_cookies_t *cur = NULL, *prev = NULL, *prev_oldest = NULL,
*oldest = NULL;
while (number_of_valid_state_cookies >= max_number_of_state_cookies) {
oldest = first;
prev_oldest = NULL;
prev = first;
cur = first->next;
while (cur) {
if ((cur->timestamp < oldest->timestamp)) {
oldest = cur;
prev_oldest = prev;
}
prev = cur;
cur = cur->next;
}
oidc_warn(r,
"deleting oldest state cookie: %s (time until expiry %" APR_TIME_T_FMT " seconds)",
oldest->name, apr_time_sec(oldest->timestamp - apr_time_now()));
oidc_util_set_cookie(r, oldest->name, "", 0, NULL);
if (prev_oldest)
prev_oldest->next = oldest->next;
else
first = first->next;
number_of_valid_state_cookies--;
}
return number_of_valid_state_cookies;
}
/*
* clean state cookies that have expired i.e. for outstanding requests that will never return
* successfully and return the number of remaining valid cookies/outstanding-requests while
* doing so
*/
static int oidc_clean_expired_state_cookies(request_rec *r, oidc_cfg *c,
const char *currentCookieName, int delete_oldest) {
int number_of_valid_state_cookies = 0;
oidc_state_cookies_t *first = NULL, *last = NULL;
char *cookie, *tokenizerCtx = NULL;
char *cookies = apr_pstrdup(r->pool, oidc_util_hdr_in_cookie_get(r));
if (cookies != NULL) {
cookie = apr_strtok(cookies, OIDC_STR_SEMI_COLON, &tokenizerCtx);
while (cookie != NULL) {
while (*cookie == OIDC_CHAR_SPACE)
cookie++;
if (strstr(cookie, OIDC_STATE_COOKIE_PREFIX) == cookie) {
char *cookieName = cookie;
while (cookie != NULL && *cookie != OIDC_CHAR_EQUAL)
cookie++;
if (*cookie == OIDC_CHAR_EQUAL) {
*cookie = '\0';
cookie++;
if ((currentCookieName == NULL)
|| (apr_strnatcmp(cookieName, currentCookieName)
!= 0)) {
oidc_proto_state_t *proto_state =
oidc_proto_state_from_cookie(r, c, cookie);
if (proto_state != NULL) {
json_int_t ts = oidc_proto_state_get_timestamp(
proto_state);
if (apr_time_now() > ts + apr_time_from_sec(c->state_timeout)) {
oidc_error(r,
"state (%s) has expired (original_url=%s)",
cookieName,
oidc_proto_state_get_original_url(
proto_state));
oidc_util_set_cookie(r, cookieName, "", 0,
NULL);
} else {
if (first == NULL) {
first = apr_pcalloc(r->pool,
sizeof(oidc_state_cookies_t));
last = first;
} else {
last->next = apr_pcalloc(r->pool,
sizeof(oidc_state_cookies_t));
last = last->next;
}
last->name = cookieName;
last->timestamp = ts;
last->next = NULL;
number_of_valid_state_cookies++;
}
oidc_proto_state_destroy(proto_state);
}
}
}
}
cookie = apr_strtok(NULL, OIDC_STR_SEMI_COLON, &tokenizerCtx);
}
}
if (delete_oldest > 0)
number_of_valid_state_cookies = oidc_delete_oldest_state_cookies(r,
number_of_valid_state_cookies, c->max_number_of_state_cookies,
first);
return number_of_valid_state_cookies;
}
/*
* restore the state that was maintained between authorization request and response in an encrypted cookie
*/
static apr_byte_t oidc_restore_proto_state(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t **proto_state) {
oidc_debug(r, "enter");
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* clean expired state cookies to avoid pollution */
oidc_clean_expired_state_cookies(r, c, cookieName, FALSE);
/* get the state cookie value first */
char *cookieValue = oidc_util_get_cookie(r, cookieName);
if (cookieValue == NULL) {
oidc_error(r, "no \"%s\" state cookie found", cookieName);
return oidc_unsolicited_proto_state(r, c, state, proto_state);
}
/* clear state cookie because we don't need it anymore */
oidc_util_set_cookie(r, cookieName, "", 0, NULL);
*proto_state = oidc_proto_state_from_cookie(r, c, cookieValue);
if (*proto_state == NULL)
return FALSE;
const char *nonce = oidc_proto_state_get_nonce(*proto_state);
/* calculate the hash of the browser fingerprint concatenated with the nonce */
char *calc = oidc_get_browser_state_hash(r, nonce);
/* compare the calculated hash with the value provided in the authorization response */
if (apr_strnatcmp(calc, state) != 0) {
oidc_error(r,
"calculated state from cookie does not match state parameter passed back in URL: \"%s\" != \"%s\"",
state, calc);
oidc_proto_state_destroy(*proto_state);
return FALSE;
}
apr_time_t ts = oidc_proto_state_get_timestamp(*proto_state);
/* check that the timestamp is not beyond the valid interval */
if (apr_time_now() > ts + apr_time_from_sec(c->state_timeout)) {
oidc_error(r, "state has expired");
/*
* note that this overrides redirection to the OIDCDefaultURL as done later...
* see: https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!msg/mod_auth_openidc/L4JFBw-XCNU/BWi2Fmk2AwAJ
*/
oidc_util_html_send_error(r, c->error_template,
"Invalid Authentication Response",
apr_psprintf(r->pool,
"This is due to a timeout; please restart your authentication session by re-entering the URL/bookmark you originally wanted to access: %s",
oidc_proto_state_get_original_url(*proto_state)),
OK);
oidc_proto_state_destroy(*proto_state);
return FALSE;
}
/* add the state */
oidc_proto_state_set_state(*proto_state, state);
/* log the restored state object */
oidc_debug(r, "restored state: %s",
oidc_proto_state_to_string(r, *proto_state));
/* we've made it */
return TRUE;
}
/*
* set the state that is maintained between an authorization request and an authorization response
* in a cookie in the browser that is cryptographically bound to that state
*/
static int oidc_authorization_request_set_cookie(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t *proto_state) {
/*
* create a cookie consisting of 8 elements:
* random value, original URL, original method, issuer, response_type, response_mod, prompt and timestamp
* encoded as JSON, encrypting the resulting JSON value
*/
char *cookieValue = oidc_proto_state_to_cookie(r, c, proto_state);
if (cookieValue == NULL)
return HTTP_INTERNAL_SERVER_ERROR;
/*
* clean expired state cookies to avoid pollution and optionally
* try to avoid the number of state cookies exceeding a max
*/
int number_of_cookies = oidc_clean_expired_state_cookies(r, c, NULL,
oidc_cfg_delete_oldest_state_cookies(c));
int max_number_of_cookies = oidc_cfg_max_number_of_state_cookies(c);
if ((max_number_of_cookies > 0)
&& (number_of_cookies >= max_number_of_cookies)) {
oidc_warn(r,
"the number of existing, valid state cookies (%d) has exceeded the limit (%d), no additional authorization request + state cookie can be generated, aborting the request",
number_of_cookies, max_number_of_cookies);
/*
* TODO: the html_send code below caters for the case that there's a user behind a
* browser generating this request, rather than a piece of XHR code; how would an
* XHR client handle this?
*/
/*
* it appears that sending content with a 503 turns the HTTP status code
* into a 200 so we'll avoid that for now: the user will see Apache specific
* readable text anyway
*
return oidc_util_html_send_error(r, c->error_template,
"Too Many Outstanding Requests",
apr_psprintf(r->pool,
"No authentication request could be generated since there are too many outstanding authentication requests already; you may have to wait up to %d seconds to be able to create a new request",
c->state_timeout),
HTTP_SERVICE_UNAVAILABLE);
*/
return HTTP_SERVICE_UNAVAILABLE;
}
/* assemble the cookie name for the state cookie */
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* set it as a cookie */
oidc_util_set_cookie(r, cookieName, cookieValue, -1,
c->cookie_same_site ? OIDC_COOKIE_EXT_SAME_SITE_LAX : NULL);
return HTTP_OK;
}
/*
* get the mod_auth_openidc related context from the (userdata in the) request
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
static apr_table_t *oidc_request_state(request_rec *rr) {
/* our state is always stored in the main request */
request_rec *r = (rr->main != NULL) ? rr->main : rr;
/* our state is a table, get it */
apr_table_t *state = NULL;
apr_pool_userdata_get((void **) &state, OIDC_USERDATA_KEY, r->pool);
/* if it does not exist, we'll create a new table */
if (state == NULL) {
state = apr_table_make(r->pool, 5);
apr_pool_userdata_set(state, OIDC_USERDATA_KEY, NULL, r->pool);
}
/* return the resulting table, always non-null now */
return state;
}
/*
* set a name/value pair in the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
void oidc_request_state_set(request_rec *r, const char *key, const char *value) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* put the name/value pair in that table */
apr_table_set(state, key, value);
}
/*
* get a name/value pair from the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
const char*oidc_request_state_get(request_rec *r, const char *key) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* return the value from the table */
return apr_table_get(state, key);
}
/*
* set the claims from a JSON object (c.q. id_token or user_info response) stored
* in the session in to HTTP headers passed on to the application
*/
static apr_byte_t oidc_set_app_claims(request_rec *r,
const oidc_cfg * const cfg, oidc_session_t *session,
const char *s_claims) {
json_t *j_claims = NULL;
/* decode the string-encoded attributes in to a JSON structure */
if (s_claims != NULL) {
if (oidc_util_decode_json_object(r, s_claims, &j_claims) == FALSE)
return FALSE;
}
/* set the resolved claims a HTTP headers for the application */
if (j_claims != NULL) {
oidc_util_set_app_infos(r, j_claims, oidc_cfg_claim_prefix(r),
cfg->claim_delimiter, oidc_cfg_dir_pass_info_in_headers(r),
oidc_cfg_dir_pass_info_in_envvars(r));
/* release resources */
json_decref(j_claims);
}
return TRUE;
}
static int oidc_authenticate_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, const char *original_url,
const char *login_hint, const char *id_token_hint, const char *prompt,
const char *auth_request_params, const char *path_scope);
/*
* log message about max session duration
*/
static void oidc_log_session_expires(request_rec *r, const char *msg,
apr_time_t session_expires) {
char buf[APR_RFC822_DATE_LEN + 1];
apr_rfc822_date(buf, session_expires);
oidc_debug(r, "%s: %s (in %" APR_TIME_T_FMT " secs from now)", msg, buf,
apr_time_sec(session_expires - apr_time_now()));
}
/*
* see if this is a non-browser request
*/
static apr_byte_t oidc_is_xml_http_request(request_rec *r) {
if ((oidc_util_hdr_in_x_requested_with_get(r) != NULL)
&& (apr_strnatcasecmp(oidc_util_hdr_in_x_requested_with_get(r),
OIDC_HTTP_HDR_VAL_XML_HTTP_REQUEST) == 0))
return TRUE;
if ((oidc_util_hdr_in_accept_contains(r, OIDC_CONTENT_TYPE_TEXT_HTML)
== FALSE) && (oidc_util_hdr_in_accept_contains(r,
OIDC_CONTENT_TYPE_APP_XHTML_XML) == FALSE)
&& (oidc_util_hdr_in_accept_contains(r,
OIDC_CONTENT_TYPE_ANY) == FALSE))
return TRUE;
return FALSE;
}
/*
* find out which action we need to take when encountering an unauthenticated request
*/
static int oidc_handle_unauthenticated_user(request_rec *r, oidc_cfg *c) {
/* see if we've configured OIDCUnAuthAction for this path */
switch (oidc_dir_cfg_unauth_action(r)) {
case OIDC_UNAUTH_RETURN410:
return HTTP_GONE;
case OIDC_UNAUTH_RETURN401:
return HTTP_UNAUTHORIZED;
case OIDC_UNAUTH_PASS:
r->user = "";
/*
* we're not going to pass information about an authenticated user to the application,
* but we do need to scrub the headers that mod_auth_openidc would set for security reasons
*/
oidc_scrub_headers(r);
return OK;
case OIDC_UNAUTH_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return HTTP_UNAUTHORIZED;
}
/*
* else: no session (regardless of whether it is main or sub-request),
* and we need to authenticate the user
*/
return oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
}
/*
* check if maximum session duration was exceeded
*/
static int oidc_check_max_session_duration(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
/* get the session expiry from the session data */
apr_time_t session_expires = oidc_session_get_session_expires(r, session);
/* check the expire timestamp against the current time */
if (apr_time_now() > session_expires) {
oidc_warn(r, "maximum session duration exceeded for user: %s",
session->remote_user);
oidc_session_kill(r, session);
return oidc_handle_unauthenticated_user(r, cfg);
}
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
return OK;
}
/*
* validate received session cookie against the domain it was issued for:
*
* this handles the case where the cache configured is a the same single memcache, Redis, or file
* backend for different (virtual) hosts, or a client-side cookie protected with the same secret
*
* it also handles the case that a cookie is unexpectedly shared across multiple hosts in
* name-based virtual hosting even though the OP(s) would be the same
*/
static apr_byte_t oidc_check_cookie_domain(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
const char *c_cookie_domain =
cfg->cookie_domain ?
cfg->cookie_domain : oidc_get_current_url_host(r);
const char *s_cookie_domain = oidc_session_get_cookie_domain(r, session);
if ((s_cookie_domain == NULL)
|| (apr_strnatcmp(c_cookie_domain, s_cookie_domain) != 0)) {
oidc_warn(r,
"aborting: detected attempt to play cookie against a different domain/host than issued for! (issued=%s, current=%s)",
s_cookie_domain, c_cookie_domain);
return FALSE;
}
return TRUE;
}
/*
* get a handle to the provider configuration via the "issuer" stored in the session
*/
apr_byte_t oidc_get_provider_from_session(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t **provider) {
oidc_debug(r, "enter");
/* get the issuer value from the session state */
const char *issuer = oidc_session_get_issuer(r, session);
if (issuer == NULL) {
oidc_error(r, "session corrupted: no issuer found in session");
return FALSE;
}
/* get the provider info associated with the issuer value */
oidc_provider_t *p = oidc_get_provider_for_issuer(r, c, issuer, FALSE);
if (p == NULL) {
oidc_error(r, "session corrupted: no provider found for issuer: %s",
issuer);
return FALSE;
}
*provider = p;
return TRUE;
}
/*
* store claims resolved from the userinfo endpoint in the session
*/
static void oidc_store_userinfo_claims(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider, const char *claims,
const char *userinfo_jwt) {
oidc_debug(r, "enter");
/* see if we've resolved any claims */
if (claims != NULL) {
/*
* Successfully decoded a set claims from the response so we can store them
* (well actually the stringified representation in the response)
* in the session context safely now
*/
oidc_session_set_userinfo_claims(r, session, claims);
if (c->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* this will also clear the entry if a JWT was not returned at this point */
oidc_session_set_userinfo_jwt(r, session, userinfo_jwt);
}
} else {
/*
* clear the existing claims because we could not refresh them
*/
oidc_session_set_userinfo_claims(r, session, NULL);
oidc_session_set_userinfo_jwt(r, session, NULL);
}
/* store the last refresh time if we've configured a userinfo refresh interval */
if (provider->userinfo_refresh_interval > 0)
oidc_session_reset_userinfo_last_refresh(r, session);
}
/*
* execute refresh token grant to refresh the existing access token
*/
static apr_byte_t oidc_refresh_access_token(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider,
char **new_access_token) {
oidc_debug(r, "enter");
/* get the refresh token that was stored in the session */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if (refresh_token == NULL) {
oidc_warn(r,
"refresh token routine called but no refresh_token found in the session");
return FALSE;
}
/* elements returned in the refresh response */
char *s_id_token = NULL;
int expires_in = -1;
char *s_token_type = NULL;
char *s_access_token = NULL;
char *s_refresh_token = NULL;
/* refresh the tokens by calling the token endpoint */
if (oidc_proto_refresh_request(r, c, provider, refresh_token, &s_id_token,
&s_access_token, &s_token_type, &expires_in,
&s_refresh_token) == FALSE) {
oidc_error(r, "access_token could not be refreshed");
return FALSE;
}
/* store the new access_token in the session and discard the old one */
oidc_session_set_access_token(r, session, s_access_token);
oidc_session_set_access_token_expires(r, session, expires_in);
/* reset the access token refresh timestamp */
oidc_session_reset_access_token_last_refresh(r, session);
/* see if we need to return it as a parameter */
if (new_access_token != NULL)
*new_access_token = s_access_token;
/* if we have a new refresh token (rolling refresh), store it in the session and overwrite the old one */
if (s_refresh_token != NULL)
oidc_session_set_refresh_token(r, session, s_refresh_token);
return TRUE;
}
/*
* retrieve claims from the userinfo endpoint and return the stringified response
*/
static const char *oidc_retrieve_claims_from_userinfo_endpoint(request_rec *r,
oidc_cfg *c, oidc_provider_t *provider, const char *access_token,
oidc_session_t *session, char *id_token_sub, char **userinfo_jwt) {
oidc_debug(r, "enter");
char *result = NULL;
char *refreshed_access_token = NULL;
/* see if a userinfo endpoint is set, otherwise there's nothing to do for us */
if (provider->userinfo_endpoint_url == NULL) {
oidc_debug(r,
"not retrieving userinfo claims because userinfo_endpoint is not set");
return NULL;
}
/* see if there's an access token, otherwise we can't call the userinfo endpoint at all */
if (access_token == NULL) {
oidc_debug(r,
"not retrieving userinfo claims because access_token is not provided");
return NULL;
}
if ((id_token_sub == NULL) && (session != NULL)) {
// when refreshing claims from the userinfo endpoint
json_t *id_token_claims = oidc_session_get_idtoken_claims_json(r,
session);
if (id_token_claims == NULL) {
oidc_error(r, "no id_token_claims found in session");
return NULL;
}
oidc_jose_get_string(r->pool, id_token_claims, OIDC_CLAIM_SUB, FALSE,
&id_token_sub, NULL);
}
// TODO: return code should indicate whether the token expired or some other error occurred
// TODO: long-term: session storage should be JSON (with explicit types and less conversion, using standard routines)
/* try to get claims from the userinfo endpoint using the provided access token */
if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub, access_token,
&result, userinfo_jwt) == FALSE) {
/* see if we have an existing session and we are refreshing the user info claims */
if (session != NULL) {
/* first call to user info endpoint failed, but the access token may have just expired, so refresh it */
if (oidc_refresh_access_token(r, c, session, provider,
&refreshed_access_token) == TRUE) {
/* try again with the new access token */
if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub,
refreshed_access_token, &result, userinfo_jwt) == FALSE) {
oidc_error(r,
"resolving user info claims with the refreshed access token failed, nothing will be stored in the session");
result = NULL;
}
} else {
oidc_warn(r,
"refreshing access token failed, claims will not be retrieved/refreshed from the userinfo endpoint");
result = NULL;
}
} else {
oidc_error(r,
"resolving user info claims with the existing/provided access token failed, nothing will be stored in the session");
result = NULL;
}
}
return result;
}
/*
* get (new) claims from the userinfo endpoint
*/
static apr_byte_t oidc_refresh_claims_from_userinfo_endpoint(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session) {
oidc_provider_t *provider = NULL;
const char *claims = NULL;
const char *access_token = NULL;
char *userinfo_jwt = NULL;
/* get the current provider info */
if (oidc_get_provider_from_session(r, cfg, session, &provider) == FALSE)
return FALSE;
/* see if we can do anything here, i.e. we have a userinfo endpoint and a refresh interval is configured */
apr_time_t interval = apr_time_from_sec(
provider->userinfo_refresh_interval);
oidc_debug(r, "userinfo_endpoint=%s, interval=%d",
provider->userinfo_endpoint_url,
provider->userinfo_refresh_interval);
if ((provider->userinfo_endpoint_url != NULL) && (interval > 0)) {
/* get the last refresh timestamp from the session info */
apr_time_t last_refresh = oidc_session_get_userinfo_last_refresh(r,
session);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(last_refresh + interval - apr_time_now()));
/* see if we need to refresh again */
if (last_refresh + interval < apr_time_now()) {
/* get the current access token */
access_token = oidc_session_get_access_token(r, session);
/* retrieve the current claims */
claims = oidc_retrieve_claims_from_userinfo_endpoint(r, cfg,
provider, access_token, session, NULL, &userinfo_jwt);
/* store claims resolved from userinfo endpoint */
oidc_store_userinfo_claims(r, cfg, session, provider, claims,
userinfo_jwt);
/* indicated something changed */
return TRUE;
}
}
return FALSE;
}
/*
* copy the claims and id_token from the session to the request state and optionally return them
*/
static void oidc_copy_tokens_to_request_state(request_rec *r,
oidc_session_t *session, const char **s_id_token, const char **s_claims) {
const char *id_token = oidc_session_get_idtoken_claims(r, session);
const char *claims = oidc_session_get_userinfo_claims(r, session);
oidc_debug(r, "id_token=%s claims=%s", id_token, claims);
if (id_token != NULL) {
oidc_request_state_set(r, OIDC_REQUEST_STATE_KEY_IDTOKEN, id_token);
if (s_id_token != NULL)
*s_id_token = id_token;
}
if (claims != NULL) {
oidc_request_state_set(r, OIDC_REQUEST_STATE_KEY_CLAIMS, claims);
if (s_claims != NULL)
*s_claims = claims;
}
}
/*
* pass refresh_token, access_token and access_token_expires as headers/environment variables to the application
*/
static apr_byte_t oidc_session_pass_tokens_and_save(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session, apr_byte_t needs_save) {
apr_byte_t pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
apr_byte_t pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
/* set the refresh_token in the app headers/variables, if enabled for this location/directory */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if ((oidc_cfg_dir_pass_refresh_token(r) != 0) && (refresh_token != NULL)) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_REFRESH_TOKEN, refresh_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* set the access_token in the app headers/variables */
const char *access_token = oidc_session_get_access_token(r, session);
if (access_token != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ACCESS_TOKEN, access_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* set the expiry timestamp in the app headers/variables */
const char *access_token_expires = oidc_session_get_access_token_expires(r,
session);
if (access_token_expires != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ACCESS_TOKEN_EXP,
access_token_expires,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/*
* reset the session inactivity timer
* but only do this once per 10% of the inactivity timeout interval (with a max to 60 seconds)
* for performance reasons
*
* now there's a small chance that the session ends 10% (or a minute) earlier than configured/expected
* cq. when there's a request after a recent save (so no update) and then no activity happens until
* a request comes in just before the session should expire
* ("recent" and "just before" refer to 10%-with-a-max-of-60-seconds of the inactivity interval after
* the start/last-update and before the expiry of the session respectively)
*
* this is be deemed acceptable here because of performance gain
*/
apr_time_t interval = apr_time_from_sec(cfg->session_inactivity_timeout);
apr_time_t now = apr_time_now();
apr_time_t slack = interval / 10;
if (slack > apr_time_from_sec(60))
slack = apr_time_from_sec(60);
if (session->expiry - now < interval - slack) {
session->expiry = now + interval;
needs_save = TRUE;
}
/* log message about session expiry */
oidc_log_session_expires(r, "session inactivity timeout", session->expiry);
/* check if something was updated in the session and we need to save it again */
if (needs_save)
if (oidc_session_save(r, session, FALSE) == FALSE)
return FALSE;
return TRUE;
}
static apr_byte_t oidc_refresh_access_token_before_expiry(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session, int ttl_minimum, int logout_on_error) {
const char *s_access_token_expires = NULL;
apr_time_t t_expires = -1;
oidc_provider_t *provider = NULL;
oidc_debug(r, "ttl_minimum=%d", ttl_minimum);
if (ttl_minimum < 0)
return FALSE;
s_access_token_expires = oidc_session_get_access_token_expires(r, session);
if (s_access_token_expires == NULL) {
oidc_debug(r,
"no access token expires_in stored in the session (i.e. returned from in the authorization response), so cannot refresh the access token based on TTL requirement");
return FALSE;
}
if (oidc_session_get_refresh_token(r, session) == NULL) {
oidc_debug(r,
"no refresh token stored in the session, so cannot refresh the access token based on TTL requirement");
return FALSE;
}
if (sscanf(s_access_token_expires, "%" APR_TIME_T_FMT, &t_expires) != 1) {
oidc_error(r, "could not parse s_access_token_expires %s",
s_access_token_expires);
return FALSE;
}
t_expires = apr_time_from_sec(t_expires - ttl_minimum);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(t_expires - apr_time_now()));
if (t_expires > apr_time_now())
return FALSE;
if (oidc_get_provider_from_session(r, cfg, session, &provider) == FALSE)
return FALSE;
if (oidc_refresh_access_token(r, cfg, session, provider,
NULL) == FALSE) {
oidc_warn(r, "access_token could not be refreshed, logout=%d", logout_on_error & OIDC_LOGOUT_ON_ERROR_REFRESH);
if (logout_on_error & OIDC_LOGOUT_ON_ERROR_REFRESH)
return ERROR;
else
return FALSE;
}
return TRUE;
}
/*
* handle the case where we have identified an existing authentication session for a user
*/
static int oidc_handle_existing_session(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
oidc_debug(r, "enter");
/* track if the session needs to be updated/saved into the cache */
apr_byte_t needs_save = FALSE;
/* set the user in the main request for further (incl. sub-request) processing */
r->user = apr_pstrdup(r->pool, session->remote_user);
oidc_debug(r, "set remote_user to \"%s\"", r->user);
/* get the header name in which the remote user name needs to be passed */
char *authn_header = oidc_cfg_dir_authn_header(r);
apr_byte_t pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
apr_byte_t pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
/* verify current cookie domain against issued cookie domain */
if (oidc_check_cookie_domain(r, cfg, session) == FALSE)
return HTTP_UNAUTHORIZED;
/* check if the maximum session duration was exceeded */
int rc = oidc_check_max_session_duration(r, cfg, session);
if (rc != OK)
return rc;
/* if needed, refresh the access token */
needs_save = oidc_refresh_access_token_before_expiry(r, cfg, session,
oidc_cfg_dir_refresh_access_token_before_expiry(r),
oidc_cfg_dir_logout_on_error_refresh(r));
if (needs_save == ERROR)
return oidc_handle_logout_request(r, cfg, session, cfg->default_slo_url);
/* if needed, refresh claims from the user info endpoint */
if (oidc_refresh_claims_from_userinfo_endpoint(r, cfg, session) == TRUE)
needs_save = TRUE;
/*
* we're going to pass the information that we have to the application,
* but first we need to scrub the headers that we're going to use for security reasons
*/
oidc_scrub_headers(r);
/* set the user authentication HTTP header if set and required */
if ((r->user != NULL) && (authn_header != NULL))
oidc_util_hdr_in_set(r, authn_header, r->user);
const char *s_claims = NULL;
const char *s_id_token = NULL;
/* copy id_token and claims from session to request state and obtain their values */
oidc_copy_tokens_to_request_state(r, session, &s_id_token, &s_claims);
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_CLAIMS)) {
/* set the userinfo claims in the app headers */
if (oidc_set_app_claims(r, cfg, session, s_claims) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_JSON_OBJECT)) {
/* pass the userinfo JSON object to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_USERINFO_JSON, s_claims,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_JWT)) {
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* get the compact serialized JWT from the session */
const char *s_userinfo_jwt = oidc_session_get_userinfo_jwt(r,
session);
if (s_userinfo_jwt != NULL) {
/* pass the compact serialized JWT to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_USERINFO_JWT,
s_userinfo_jwt,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
} else {
oidc_debug(r,
"configured to pass userinfo in a JWT, but no such JWT was found in the session (probably no such JWT was returned from the userinfo endpoint)");
}
} else {
oidc_error(r,
"session type \"client-cookie\" does not allow storing/passing a userinfo JWT; use \"" OIDCSessionType " server-cache\" for that");
}
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_CLAIMS)) {
/* set the id_token in the app headers */
if (oidc_set_app_claims(r, cfg, session, s_id_token) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_PAYLOAD)) {
/* pass the id_token JSON object to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ID_TOKEN_PAYLOAD, s_id_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_SERIALIZED)) {
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* get the compact serialized JWT from the session */
const char *s_id_token = oidc_session_get_idtoken(r, session);
/* pass the compact serialized JWT to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ID_TOKEN, s_id_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
} else {
oidc_error(r,
"session type \"client-cookie\" does not allow storing/passing the id_token; use \"" OIDCSessionType " server-cache\" for that");
}
}
/* pass the at, rt and at expiry to the application, possibly update the session expiry and save the session */
if (oidc_session_pass_tokens_and_save(r, cfg, session, needs_save) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* return "user authenticated" status */
return OK;
}
/*
* helper function for basic/implicit client flows upon receiving an authorization response:
* check that it matches the state stored in the browser and return the variables associated
* with the state, such as original_url and OP oidc_provider_t pointer.
*/
static apr_byte_t oidc_authorization_response_match_state(request_rec *r,
oidc_cfg *c, const char *state, struct oidc_provider_t **provider,
oidc_proto_state_t **proto_state) {
oidc_debug(r, "enter (state=%s)", state);
if ((state == NULL) || (apr_strnatcmp(state, "") == 0)) {
oidc_error(r, "state parameter is not set");
return FALSE;
}
/* check the state parameter against what we stored in a cookie */
if (oidc_restore_proto_state(r, c, state, proto_state) == FALSE) {
oidc_error(r, "unable to restore state");
return FALSE;
}
*provider = oidc_get_provider_for_issuer(r, c,
oidc_proto_state_get_issuer(*proto_state), FALSE);
return (*provider != NULL);
}
/*
* redirect the browser to the session logout endpoint
*/
static int oidc_session_redirect_parent_window_to_logout(request_rec *r,
oidc_cfg *c) {
oidc_debug(r, "enter");
char *java_script = apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" window.top.location.href = '%s?session=logout';\n"
" </script>\n", oidc_get_redirect_uri(r, c));
return oidc_util_html_send(r, "Redirecting...", java_script, NULL, NULL,
OK);
}
/*
* handle an error returned by the OP
*/
static int oidc_authorization_response_error(request_rec *r, oidc_cfg *c,
oidc_proto_state_t *proto_state, const char *error,
const char *error_description) {
const char *prompt = oidc_proto_state_get_prompt(proto_state);
if (prompt != NULL)
prompt = apr_pstrdup(r->pool, prompt);
oidc_proto_state_destroy(proto_state);
if ((prompt != NULL)
&& (apr_strnatcmp(prompt, OIDC_PROTO_PROMPT_NONE) == 0)) {
return oidc_session_redirect_parent_window_to_logout(r, c);
}
return oidc_util_html_send_error(r, c->error_template,
apr_psprintf(r->pool, "OpenID Connect Provider error: %s", error),
error_description, OK);
}
/*
* get the r->user for this request based on the configuration for OIDC/OAuth
*/
apr_byte_t oidc_get_remote_user(request_rec *r, const char *claim_name,
const char *reg_exp, const char *replace, json_t *json,
char **request_user) {
/* get the claim value from the JSON object */
json_t *username = json_object_get(json, claim_name);
if ((username == NULL) || (!json_is_string(username))) {
oidc_warn(r, "JSON object did not contain a \"%s\" string", claim_name);
return FALSE;
}
*request_user = apr_pstrdup(r->pool, json_string_value(username));
if (reg_exp != NULL) {
char *error_str = NULL;
if (replace == NULL) {
if (oidc_util_regexp_first_match(r->pool, *request_user, reg_exp,
request_user, &error_str) == FALSE) {
oidc_error(r, "oidc_util_regexp_first_match failed: %s",
error_str);
*request_user = NULL;
return FALSE;
}
} else if (oidc_util_regexp_substitute(r->pool, *request_user, reg_exp,
replace, request_user, &error_str) == FALSE) {
oidc_error(r, "oidc_util_regexp_substitute failed: %s", error_str);
*request_user = NULL;
return FALSE;
}
}
return TRUE;
}
/*
* set the unique user identifier that will be propagated in the Apache r->user and REMOTE_USER variables
*/
static apr_byte_t oidc_set_request_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, oidc_jwt_t *jwt, const char *s_claims) {
char *issuer = provider->issuer;
char *claim_name = apr_pstrdup(r->pool, c->remote_user_claim.claim_name);
int n = strlen(claim_name);
apr_byte_t post_fix_with_issuer = (claim_name[n - 1] == OIDC_CHAR_AT);
if (post_fix_with_issuer == TRUE) {
claim_name[n - 1] = '\0';
issuer =
(strstr(issuer, "https://") == NULL) ?
apr_pstrdup(r->pool, issuer) :
apr_pstrdup(r->pool, issuer + strlen("https://"));
}
/* extract the username claim (default: "sub") from the id_token payload or user claims */
apr_byte_t rc = FALSE;
char *remote_user = NULL;
json_t *claims = NULL;
oidc_util_decode_json_object(r, s_claims, &claims);
if (claims == NULL) {
rc = oidc_get_remote_user(r, claim_name, c->remote_user_claim.reg_exp,
c->remote_user_claim.replace, jwt->payload.value.json,
&remote_user);
} else {
oidc_util_json_merge(r, jwt->payload.value.json, claims);
rc = oidc_get_remote_user(r, claim_name, c->remote_user_claim.reg_exp,
c->remote_user_claim.replace, claims, &remote_user);
json_decref(claims);
}
if ((rc == FALSE) || (remote_user == NULL)) {
oidc_error(r,
"" OIDCRemoteUserClaim "is set to \"%s\", but could not set the remote user based on the requested claim \"%s\" and the available claims for the user",
c->remote_user_claim.claim_name, claim_name);
return FALSE;
}
if (post_fix_with_issuer == TRUE)
remote_user = apr_psprintf(r->pool, "%s%s%s", remote_user, OIDC_STR_AT,
issuer);
r->user = apr_pstrdup(r->pool, remote_user);
oidc_debug(r, "set remote_user to \"%s\" based on claim: \"%s\"%s", r->user,
c->remote_user_claim.claim_name,
c->remote_user_claim.reg_exp ?
apr_psprintf(r->pool,
" and expression: \"%s\" and replace string: \"%s\"",
c->remote_user_claim.reg_exp,
c->remote_user_claim.replace) :
"");
return TRUE;
}
static char *oidc_make_sid_iss_unique(request_rec *r, const char *sid,
const char *issuer) {
return apr_psprintf(r->pool, "%s@%s", sid, issuer);
}
/*
* store resolved information in the session
*/
static apr_byte_t oidc_save_in_session(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider,
const char *remoteUser, const char *id_token, oidc_jwt_t *id_token_jwt,
const char *claims, const char *access_token, const int expires_in,
const char *refresh_token, const char *session_state, const char *state,
const char *original_url, const char *userinfo_jwt) {
/* store the user in the session */
session->remote_user = remoteUser;
/* set the session expiry to the inactivity timeout */
session->expiry =
apr_time_now() + apr_time_from_sec(c->session_inactivity_timeout);
/* store the claims payload in the id_token for later reference */
oidc_session_set_idtoken_claims(r, session,
id_token_jwt->payload.value.str);
if (c->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* store the compact serialized representation of the id_token for later reference */
oidc_session_set_idtoken(r, session, id_token);
}
/* store the issuer in the session (at least needed for session mgmt and token refresh */
oidc_session_set_issuer(r, session, provider->issuer);
/* store the state and original URL in the session for handling browser-back more elegantly */
oidc_session_set_request_state(r, session, state);
oidc_session_set_original_url(r, session, original_url);
if ((session_state != NULL) && (provider->check_session_iframe != NULL)) {
/* store the session state and required parameters session management */
oidc_session_set_session_state(r, session, session_state);
oidc_debug(r,
"session management enabled: stored session_state (%s), check_session_iframe (%s) and client_id (%s) in the session",
session_state, provider->check_session_iframe,
provider->client_id);
} else if (provider->check_session_iframe == NULL) {
oidc_debug(r,
"session management disabled: \"check_session_iframe\" is not set in provider configuration");
} else {
oidc_debug(r,
"session management disabled: no \"session_state\" value is provided in the authentication response even though \"check_session_iframe\" (%s) is set in the provider configuration",
provider->check_session_iframe);
}
/* store claims resolved from userinfo endpoint */
oidc_store_userinfo_claims(r, c, session, provider, claims, userinfo_jwt);
/* see if we have an access_token */
if (access_token != NULL) {
/* store the access_token in the session context */
oidc_session_set_access_token(r, session, access_token);
/* store the associated expires_in value */
oidc_session_set_access_token_expires(r, session, expires_in);
/* reset the access token refresh timestamp */
oidc_session_reset_access_token_last_refresh(r, session);
}
/* see if we have a refresh_token */
if (refresh_token != NULL) {
/* store the refresh_token in the session context */
oidc_session_set_refresh_token(r, session, refresh_token);
}
/* store max session duration in the session as a hard cut-off expiry timestamp */
apr_time_t session_expires =
(provider->session_max_duration == 0) ?
apr_time_from_sec(id_token_jwt->payload.exp) :
(apr_time_now()
+ apr_time_from_sec(provider->session_max_duration));
oidc_session_set_session_expires(r, session, session_expires);
oidc_debug(r,
"provider->session_max_duration = %d, session_expires=%" APR_TIME_T_FMT,
provider->session_max_duration, session_expires);
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
/* store the domain for which this session is valid */
oidc_session_set_cookie_domain(r, session,
c->cookie_domain ? c->cookie_domain : oidc_get_current_url_host(r));
char *sid = NULL;
oidc_debug(r, "provider->backchannel_logout_supported=%d",
provider->backchannel_logout_supported);
if (provider->backchannel_logout_supported > 0) {
oidc_jose_get_string(r->pool, id_token_jwt->payload.value.json,
OIDC_CLAIM_SID, FALSE, &sid, NULL);
if (sid == NULL)
sid = id_token_jwt->payload.sub;
session->sid = oidc_make_sid_iss_unique(r, sid, provider->issuer);
}
/* store the session */
return oidc_session_save(r, session, TRUE);
}
/*
* parse the expiry for the access token
*/
static int oidc_parse_expires_in(request_rec *r, const char *expires_in) {
if (expires_in != NULL) {
char *ptr = NULL;
long number = strtol(expires_in, &ptr, 10);
if (number <= 0) {
oidc_warn(r,
"could not convert \"expires_in\" value (%s) to a number",
expires_in);
return -1;
}
return number;
}
return -1;
}
/*
* handle the different flows (hybrid, implicit, Authorization Code)
*/
static apr_byte_t oidc_handle_flows(request_rec *r, oidc_cfg *c,
oidc_proto_state_t *proto_state, oidc_provider_t *provider,
apr_table_t *params, const char *response_mode, oidc_jwt_t **jwt) {
apr_byte_t rc = FALSE;
const char *requested_response_type = oidc_proto_state_get_response_type(
proto_state);
/* handle the requested response type/mode */
if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_IDTOKEN_TOKEN)) {
rc = oidc_proto_authorization_response_code_idtoken_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_IDTOKEN)) {
rc = oidc_proto_authorization_response_code_idtoken(r, c, proto_state,
provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_TOKEN)) {
rc = oidc_proto_handle_authorization_response_code_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE)) {
rc = oidc_proto_handle_authorization_response_code(r, c, proto_state,
provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_IDTOKEN_TOKEN)) {
rc = oidc_proto_handle_authorization_response_idtoken_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_IDTOKEN)) {
rc = oidc_proto_handle_authorization_response_idtoken(r, c, proto_state,
provider, params, response_mode, jwt);
} else {
oidc_error(r, "unsupported response type: \"%s\"",
requested_response_type);
}
if ((rc == FALSE) && (*jwt != NULL)) {
oidc_jwt_destroy(*jwt);
*jwt = NULL;
}
return rc;
}
/* handle the browser back on an authorization response */
static apr_byte_t oidc_handle_browser_back(request_rec *r, const char *r_state,
oidc_session_t *session) {
/* see if we have an existing session and browser-back was used */
const char *s_state = NULL, *o_url = NULL;
if (session->remote_user != NULL) {
s_state = oidc_session_get_request_state(r, session);
o_url = oidc_session_get_original_url(r, session);
if ((r_state != NULL) && (s_state != NULL)
&& (apr_strnatcmp(r_state, s_state) == 0)) {
/* log the browser back event detection */
oidc_warn(r,
"browser back detected, redirecting to original URL: %s",
o_url);
/* go back to the URL that he originally tried to access */
oidc_util_hdr_out_location_set(r, o_url);
return TRUE;
}
}
return FALSE;
}
/*
* complete the handling of an authorization response by obtaining, parsing and verifying the
* id_token and storing the authenticated user state in the session
*/
static int oidc_handle_authorization_response(request_rec *r, oidc_cfg *c,
oidc_session_t *session, apr_table_t *params, const char *response_mode) {
oidc_debug(r, "enter, response_mode=%s", response_mode);
oidc_provider_t *provider = NULL;
oidc_proto_state_t *proto_state = NULL;
oidc_jwt_t *jwt = NULL;
/* see if this response came from a browser-back event */
if (oidc_handle_browser_back(r, apr_table_get(params, OIDC_PROTO_STATE),
session) == TRUE)
return HTTP_MOVED_TEMPORARILY;
/* match the returned state parameter against the state stored in the browser */
if (oidc_authorization_response_match_state(r, c,
apr_table_get(params, OIDC_PROTO_STATE), &provider,
&proto_state) == FALSE) {
if (c->default_sso_url != NULL) {
oidc_warn(r,
"invalid authorization response state; a default SSO URL is set, sending the user there: %s",
c->default_sso_url);
oidc_util_hdr_out_location_set(r, c->default_sso_url);
return HTTP_MOVED_TEMPORARILY;
}
oidc_error(r,
"invalid authorization response state and no default SSO URL is set, sending an error...");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if the response is an error response */
if (apr_table_get(params, OIDC_PROTO_ERROR) != NULL)
return oidc_authorization_response_error(r, c, proto_state,
apr_table_get(params, OIDC_PROTO_ERROR),
apr_table_get(params, OIDC_PROTO_ERROR_DESCRIPTION));
/* handle the code, implicit or hybrid flow */
if (oidc_handle_flows(r, c, proto_state, provider, params, response_mode,
&jwt) == FALSE)
return oidc_authorization_response_error(r, c, proto_state,
"Error in handling response type.", NULL);
if (jwt == NULL) {
oidc_error(r, "no id_token was provided");
return oidc_authorization_response_error(r, c, proto_state,
"No id_token was provided.", NULL);
}
int expires_in = oidc_parse_expires_in(r,
apr_table_get(params, OIDC_PROTO_EXPIRES_IN));
char *userinfo_jwt = NULL;
/*
* optionally resolve additional claims against the userinfo endpoint
* parsed claims are not actually used here but need to be parsed anyway for error checking purposes
*/
const char *claims = oidc_retrieve_claims_from_userinfo_endpoint(r, c,
provider, apr_table_get(params, OIDC_PROTO_ACCESS_TOKEN), NULL,
jwt->payload.sub, &userinfo_jwt);
/* restore the original protected URL that the user was trying to access */
const char *original_url = oidc_proto_state_get_original_url(proto_state);
if (original_url != NULL)
original_url = apr_pstrdup(r->pool, original_url);
const char *original_method = oidc_proto_state_get_original_method(
proto_state);
if (original_method != NULL)
original_method = apr_pstrdup(r->pool, original_method);
const char *prompt = oidc_proto_state_get_prompt(proto_state);
/* set the user */
if (oidc_set_request_user(r, c, provider, jwt, claims) == TRUE) {
/* session management: if the user in the new response is not equal to the old one, error out */
if ((prompt != NULL)
&& (apr_strnatcmp(prompt, OIDC_PROTO_PROMPT_NONE) == 0)) {
// TOOD: actually need to compare sub? (need to store it in the session separately then
//const char *sub = NULL;
//oidc_session_get(r, session, "sub", &sub);
//if (apr_strnatcmp(sub, jwt->payload.sub) != 0) {
if (apr_strnatcmp(session->remote_user, r->user) != 0) {
oidc_warn(r,
"user set from new id_token is different from current one");
oidc_jwt_destroy(jwt);
return oidc_authorization_response_error(r, c, proto_state,
"User changed!", NULL);
}
}
/* store resolved information in the session */
if (oidc_save_in_session(r, c, session, provider, r->user,
apr_table_get(params, OIDC_PROTO_ID_TOKEN), jwt, claims,
apr_table_get(params, OIDC_PROTO_ACCESS_TOKEN), expires_in,
apr_table_get(params, OIDC_PROTO_REFRESH_TOKEN),
apr_table_get(params, OIDC_PROTO_SESSION_STATE),
apr_table_get(params, OIDC_PROTO_STATE), original_url,
userinfo_jwt) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
} else {
oidc_error(r, "remote user could not be set");
return oidc_authorization_response_error(r, c, proto_state,
"Remote user could not be set: contact the website administrator",
NULL);
}
/* cleanup */
oidc_proto_state_destroy(proto_state);
oidc_jwt_destroy(jwt);
/* check that we've actually authenticated a user; functions as error handling for oidc_get_remote_user */
if (r->user == NULL)
return HTTP_UNAUTHORIZED;
/* log the successful response */
oidc_debug(r,
"session created and stored, returning to original URL: %s, original method: %s",
original_url, original_method);
/* check whether form post data was preserved; if so restore it */
if (apr_strnatcmp(original_method, OIDC_METHOD_FORM_POST) == 0) {
return oidc_request_post_preserved_restore(r, original_url);
}
/* now we've authenticated the user so go back to the URL that he originally tried to access */
oidc_util_hdr_out_location_set(r, original_url);
/* do the actual redirect to the original URL */
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle an OpenID Connect Authorization Response using the POST (+fragment->POST) response_mode
*/
static int oidc_handle_post_authorization_response(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
oidc_debug(r, "enter");
/* initialize local variables */
char *response_mode = NULL;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if we've got any POST-ed data at all */
if ((apr_table_elts(params)->nelts < 1)
|| ((apr_table_elts(params)->nelts == 1)
&& apr_table_get(params, OIDC_PROTO_RESPONSE_MODE)
&& (apr_strnatcmp(
apr_table_get(params, OIDC_PROTO_RESPONSE_MODE),
OIDC_PROTO_RESPONSE_MODE_FRAGMENT) == 0))) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"You've hit an OpenID Connect Redirect URI with no parameters, this is an invalid request; you should not open this URL in your browser directly, or have the server administrator use a different " OIDCRedirectURI " setting.",
HTTP_INTERNAL_SERVER_ERROR);
}
/* get the parameters */
response_mode = (char *) apr_table_get(params, OIDC_PROTO_RESPONSE_MODE);
/* do the actual implicit work */
return oidc_handle_authorization_response(r, c, session, params,
response_mode ? response_mode : OIDC_PROTO_RESPONSE_MODE_FORM_POST);
}
/*
* handle an OpenID Connect Authorization Response using the redirect response_mode
*/
static int oidc_handle_redirect_authorization_response(request_rec *r,
oidc_cfg *c, oidc_session_t *session) {
oidc_debug(r, "enter");
/* read the parameters from the query string */
apr_table_t *params = apr_table_make(r->pool, 8);
oidc_util_read_form_encoded_params(r, params, r->args);
/* do the actual work */
return oidc_handle_authorization_response(r, c, session, params,
OIDC_PROTO_RESPONSE_MODE_QUERY);
}
/*
* present the user with an OP selection screen
*/
static int oidc_discovery(request_rec *r, oidc_cfg *cfg) {
oidc_debug(r, "enter");
/* obtain the URL we're currently accessing, to be stored in the state/session */
char *current_url = oidc_get_current_url(r);
const char *method = oidc_original_request_method(r, cfg, FALSE);
/* generate CSRF token */
char *csrf = NULL;
if (oidc_proto_generate_nonce(r, &csrf, 8) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
char *path_scopes = oidc_dir_cfg_path_scope(r);
char *path_auth_request_params = oidc_dir_cfg_path_auth_request_params(r);
char *discover_url = oidc_cfg_dir_discover_url(r);
/* see if there's an external discovery page configured */
if (discover_url != NULL) {
/* yes, assemble the parameters for external discovery */
char *url = apr_psprintf(r->pool, "%s%s%s=%s&%s=%s&%s=%s&%s=%s",
discover_url,
strchr(discover_url, OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
OIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url),
OIDC_DISC_RM_PARAM, method,
OIDC_DISC_CB_PARAM,
oidc_util_escape_string(r, oidc_get_redirect_uri(r, cfg)),
OIDC_CSRF_NAME, oidc_util_escape_string(r, csrf));
if (path_scopes != NULL)
url = apr_psprintf(r->pool, "%s&%s=%s", url, OIDC_DISC_SC_PARAM,
oidc_util_escape_string(r, path_scopes));
if (path_auth_request_params != NULL)
url = apr_psprintf(r->pool, "%s&%s=%s", url, OIDC_DISC_AR_PARAM,
oidc_util_escape_string(r, path_auth_request_params));
/* log what we're about to do */
oidc_debug(r, "redirecting to external discovery page: %s", url);
/* set CSRF cookie */
oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1,
cfg->cookie_same_site ?
OIDC_COOKIE_EXT_SAME_SITE_STRICT :
NULL);
/* see if we need to preserve POST parameters through Javascript/HTML5 storage */
if (oidc_post_preserve_javascript(r, url, NULL, NULL) == TRUE)
return OK;
/* do the actual redirect to an external discovery page */
oidc_util_hdr_out_location_set(r, url);
return HTTP_MOVED_TEMPORARILY;
}
/* get a list of all providers configured in the metadata directory */
apr_array_header_t *arr = NULL;
if (oidc_metadata_list(r, cfg, &arr) == FALSE)
return oidc_util_html_send_error(r, cfg->error_template,
"Configuration Error",
"No configured providers found, contact your administrator",
HTTP_UNAUTHORIZED);
/* assemble a where-are-you-from IDP discovery HTML page */
const char *s = " <h3>Select your OpenID Connect Identity Provider</h3>\n";
/* list all configured providers in there */
int i;
for (i = 0; i < arr->nelts; i++) {
const char *issuer = ((const char**) arr->elts)[i];
// TODO: html escape (especially & character)
char *href = apr_psprintf(r->pool,
"%s?%s=%s&%s=%s&%s=%s&%s=%s",
oidc_get_redirect_uri(r, cfg), OIDC_DISC_OP_PARAM,
oidc_util_escape_string(r, issuer),
OIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url),
OIDC_DISC_RM_PARAM, method,
OIDC_CSRF_NAME, csrf);
if (path_scopes != NULL)
href = apr_psprintf(r->pool, "%s&%s=%s", href,
OIDC_DISC_SC_PARAM, oidc_util_escape_string(r, path_scopes));
if (path_auth_request_params != NULL)
href = apr_psprintf(r->pool, "%s&%s=%s", href,
OIDC_DISC_AR_PARAM,
oidc_util_escape_string(r, path_auth_request_params));
char *display =
(strstr(issuer, "https://") == NULL) ?
apr_pstrdup(r->pool, issuer) :
apr_pstrdup(r->pool, issuer + strlen("https://"));
/* strip port number */
//char *p = strstr(display, ":");
//if (p != NULL) *p = '\0';
/* point back to the redirect_uri, where the selection is handled, with an IDP selection and return_to URL */
s = apr_psprintf(r->pool, "%s<p><a href=\"%s\">%s</a></p>\n", s, href,
display);
}
/* add an option to enter an account or issuer name for dynamic OP discovery */
s = apr_psprintf(r->pool, "%s<form method=\"get\" action=\"%s\">\n", s,
oidc_get_redirect_uri(r, cfg));
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_RT_PARAM, current_url);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_RM_PARAM, method);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_CSRF_NAME, csrf);
if (path_scopes != NULL)
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_SC_PARAM, path_scopes);
if (path_auth_request_params != NULL)
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_AR_PARAM, path_auth_request_params);
s =
apr_psprintf(r->pool,
"%s<p>Or enter your account name (eg. "mike@seed.gluu.org", or an IDP identifier (eg. "mitreid.org"):</p>\n",
s);
s = apr_psprintf(r->pool,
"%s<p><input type=\"text\" name=\"%s\" value=\"%s\"></p>\n", s,
OIDC_DISC_OP_PARAM, "");
s = apr_psprintf(r->pool,
"%s<p><input type=\"submit\" value=\"Submit\"></p>\n", s);
s = apr_psprintf(r->pool, "%s</form>\n", s);
oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1,
cfg->cookie_same_site ? OIDC_COOKIE_EXT_SAME_SITE_STRICT : NULL);
char *javascript = NULL, *javascript_method = NULL;
char *html_head =
"<style type=\"text/css\">body {text-align: center}</style>";
if (oidc_post_preserve_javascript(r, NULL, &javascript,
&javascript_method) == TRUE)
html_head = apr_psprintf(r->pool, "%s%s", html_head, javascript);
/* now send the HTML contents to the user agent */
return oidc_util_html_send(r, "OpenID Connect Provider Discovery",
html_head, javascript_method, s, OK);
}
/*
* authenticate the user to the selected OP, if the OP is not selected yet perform discovery first
*/
static int oidc_authenticate_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, const char *original_url,
const char *login_hint, const char *id_token_hint, const char *prompt,
const char *auth_request_params, const char *path_scope) {
oidc_debug(r, "enter");
if (provider == NULL) {
// TODO: should we use an explicit redirect to the discovery endpoint (maybe a "discovery" param to the redirect_uri)?
if (c->metadata_dir != NULL)
return oidc_discovery(r, c);
/* we're not using multiple OP's configured in a metadata directory, pick the statically configured OP */
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
/* generate the random nonce value that correlates requests and responses */
char *nonce = NULL;
if (oidc_proto_generate_nonce(r, &nonce, OIDC_PROTO_NONCE_LENGTH) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
char *pkce_state = NULL;
char *code_challenge = NULL;
if ((oidc_util_spaced_string_contains(r->pool, provider->response_type,
OIDC_PROTO_CODE) == TRUE) && (provider->pkce != NULL)) {
/* generate the code verifier value that correlates authorization requests and code exchange requests */
if (provider->pkce->state(r, &pkce_state) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* generate the PKCE code challenge */
if (provider->pkce->challenge(r, pkce_state, &code_challenge) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
/* create the state between request/response */
oidc_proto_state_t *proto_state = oidc_proto_state_new();
oidc_proto_state_set_original_url(proto_state, original_url);
oidc_proto_state_set_original_method(proto_state,
oidc_original_request_method(r, c, TRUE));
oidc_proto_state_set_issuer(proto_state, provider->issuer);
oidc_proto_state_set_response_type(proto_state, provider->response_type);
oidc_proto_state_set_nonce(proto_state, nonce);
oidc_proto_state_set_timestamp_now(proto_state);
if (provider->response_mode)
oidc_proto_state_set_response_mode(proto_state,
provider->response_mode);
if (prompt)
oidc_proto_state_set_prompt(proto_state, prompt);
if (pkce_state)
oidc_proto_state_set_pkce_state(proto_state, pkce_state);
/* get a hash value that fingerprints the browser concatenated with the random input */
char *state = oidc_get_browser_state_hash(r, nonce);
/*
* create state that restores the context when the authorization response comes in
* and cryptographically bind it to the browser
*/
int rc = oidc_authorization_request_set_cookie(r, c, state, proto_state);
if (rc != HTTP_OK) {
oidc_proto_state_destroy(proto_state);
return rc;
}
/*
* printout errors if Cookie settings are not going to work
* TODO: separate this code out into its own function
*/
apr_uri_t o_uri;
memset(&o_uri, 0, sizeof(apr_uri_t));
apr_uri_t r_uri;
memset(&r_uri, 0, sizeof(apr_uri_t));
apr_uri_parse(r->pool, original_url, &o_uri);
apr_uri_parse(r->pool, oidc_get_redirect_uri(r, c), &r_uri);
if ((apr_strnatcmp(o_uri.scheme, r_uri.scheme) != 0)
&& (apr_strnatcmp(r_uri.scheme, "https") == 0)) {
oidc_error(r,
"the URL scheme (%s) of the configured " OIDCRedirectURI " does not match the URL scheme of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!",
r_uri.scheme, o_uri.scheme);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
if (c->cookie_domain == NULL) {
if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
char *p = strstr(o_uri.hostname, r_uri.hostname);
if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
oidc_error(r,
"the URL hostname (%s) of the configured " OIDCRedirectURI " does not match the URL hostname of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!",
r_uri.hostname, o_uri.hostname);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
} else {
if (!oidc_util_cookie_domain_valid(r_uri.hostname, c->cookie_domain)) {
oidc_error(r,
"the domain (%s) configured in " OIDCCookieDomain " does not match the URL hostname (%s) of the URL being accessed (%s): setting \"state\" and \"session\" cookies will not work!!",
c->cookie_domain, o_uri.hostname, original_url);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
/* send off to the OpenID Connect Provider */
// TODO: maybe show intermediate/progress screen "redirecting to"
return oidc_proto_authorization_request(r, provider, login_hint,
oidc_get_redirect_uri_iss(r, c, provider), state, proto_state,
id_token_hint, code_challenge, auth_request_params, path_scope);
}
/*
* check if the target_link_uri matches to configuration settings to prevent an open redirect
*/
static int oidc_target_link_uri_matches_configuration(request_rec *r,
oidc_cfg *cfg, const char *target_link_uri) {
apr_uri_t o_uri;
apr_uri_parse(r->pool, target_link_uri, &o_uri);
if (o_uri.hostname == NULL) {
oidc_error(r,
"could not parse the \"target_link_uri\" (%s) in to a valid URL: aborting.",
target_link_uri);
return FALSE;
}
apr_uri_t r_uri;
apr_uri_parse(r->pool, oidc_get_redirect_uri(r, cfg), &r_uri);
if (cfg->cookie_domain == NULL) {
/* cookie_domain set: see if the target_link_uri matches the redirect_uri host (because the session cookie will be set host-wide) */
if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
char *p = strstr(o_uri.hostname, r_uri.hostname);
if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
oidc_error(r,
"the URL hostname (%s) of the configured " OIDCRedirectURI " does not match the URL hostname of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
r_uri.hostname, o_uri.hostname);
return FALSE;
}
}
} else {
/* cookie_domain set: see if the target_link_uri is within the cookie_domain */
char *p = strstr(o_uri.hostname, cfg->cookie_domain);
if ((p == NULL) || (apr_strnatcmp(cfg->cookie_domain, p) != 0)) {
oidc_error(r,
"the domain (%s) configured in " OIDCCookieDomain " does not match the URL hostname (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.hostname, target_link_uri);
return FALSE;
}
}
/* see if the cookie_path setting matches the target_link_uri path */
char *cookie_path = oidc_cfg_dir_cookie_path(r);
if (cookie_path != NULL) {
char *p = (o_uri.path != NULL) ? strstr(o_uri.path, cookie_path) : NULL;
if ((p == NULL) || (p != o_uri.path)) {
oidc_error(r,
"the path (%s) configured in " OIDCCookiePath " does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.path, target_link_uri);
return FALSE;
} else if (strlen(o_uri.path) > strlen(cookie_path)) {
int n = strlen(cookie_path);
if (cookie_path[n - 1] == OIDC_CHAR_FORWARD_SLASH)
n--;
if (o_uri.path[n] != OIDC_CHAR_FORWARD_SLASH) {
oidc_error(r,
"the path (%s) configured in " OIDCCookiePath " does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.path, target_link_uri);
return FALSE;
}
}
}
return TRUE;
}
/*
* handle a response from an IDP discovery page and/or handle 3rd-party initiated SSO
*/
static int oidc_handle_discovery_response(request_rec *r, oidc_cfg *c) {
/* variables to hold the values returned in the response */
char *issuer = NULL, *target_link_uri = NULL, *login_hint = NULL,
*auth_request_params = NULL, *csrf_cookie, *csrf_query = NULL,
*user = NULL, *path_scopes;
oidc_provider_t *provider = NULL;
oidc_util_get_request_parameter(r, OIDC_DISC_OP_PARAM, &issuer);
oidc_util_get_request_parameter(r, OIDC_DISC_USER_PARAM, &user);
oidc_util_get_request_parameter(r, OIDC_DISC_RT_PARAM, &target_link_uri);
oidc_util_get_request_parameter(r, OIDC_DISC_LH_PARAM, &login_hint);
oidc_util_get_request_parameter(r, OIDC_DISC_SC_PARAM, &path_scopes);
oidc_util_get_request_parameter(r, OIDC_DISC_AR_PARAM,
&auth_request_params);
oidc_util_get_request_parameter(r, OIDC_CSRF_NAME, &csrf_query);
csrf_cookie = oidc_util_get_cookie(r, OIDC_CSRF_NAME);
/* do CSRF protection if not 3rd party initiated SSO */
if (csrf_cookie) {
/* clean CSRF cookie */
oidc_util_set_cookie(r, OIDC_CSRF_NAME, "", 0, NULL);
/* compare CSRF cookie value with query parameter value */
if ((csrf_query == NULL)
|| apr_strnatcmp(csrf_query, csrf_cookie) != 0) {
oidc_warn(r,
"CSRF protection failed, no Discovery and dynamic client registration will be allowed");
csrf_cookie = NULL;
}
}
// TODO: trim issuer/accountname/domain input and do more input validation
oidc_debug(r,
"issuer=\"%s\", target_link_uri=\"%s\", login_hint=\"%s\", user=\"%s\"",
issuer, target_link_uri, login_hint, user);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"SSO to this module without specifying a \"target_link_uri\" parameter is not possible because " OIDCDefaultURL " is not set.",
HTTP_INTERNAL_SERVER_ERROR);
}
target_link_uri = c->default_sso_url;
}
/* do open redirect prevention */
if (oidc_target_link_uri_matches_configuration(r, c,
target_link_uri) == FALSE) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"\"target_link_uri\" parameter does not match configuration settings, aborting to prevent an open redirect.",
HTTP_UNAUTHORIZED);
}
/* see if this is a static setup */
if (c->metadata_dir == NULL) {
if ((oidc_provider_static_config(r, c, &provider) == TRUE)
&& (issuer != NULL)) {
if (apr_strnatcmp(provider->issuer, issuer) != 0) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
apr_psprintf(r->pool,
"The \"iss\" value must match the configured providers' one (%s != %s).",
issuer, c->provider.issuer),
HTTP_INTERNAL_SERVER_ERROR);
}
}
return oidc_authenticate_user(r, c, NULL, target_link_uri, login_hint,
NULL, NULL, auth_request_params, path_scopes);
}
/* find out if the user entered an account name or selected an OP manually */
if (user != NULL) {
if (login_hint == NULL)
login_hint = apr_pstrdup(r->pool, user);
/* normalize the user identifier */
if (strstr(user, "https://") != user)
user = apr_psprintf(r->pool, "https://%s", user);
/* got an user identifier as input, perform OP discovery with that */
if (oidc_proto_url_based_discovery(r, c, user, &issuer) == FALSE) {
/* something did not work out, show a user facing error */
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"Could not resolve the provided user identifier to an OpenID Connect provider; check your syntax.",
HTTP_NOT_FOUND);
}
/* issuer is set now, so let's continue as planned */
} else if (strstr(issuer, OIDC_STR_AT) != NULL) {
if (login_hint == NULL) {
login_hint = apr_pstrdup(r->pool, issuer);
//char *p = strstr(issuer, OIDC_STR_AT);
//*p = '\0';
}
/* got an account name as input, perform OP discovery with that */
if (oidc_proto_account_based_discovery(r, c, issuer, &issuer) == FALSE) {
/* something did not work out, show a user facing error */
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"Could not resolve the provided account name to an OpenID Connect provider; check your syntax.",
HTTP_NOT_FOUND);
}
/* issuer is set now, so let's continue as planned */
}
/* strip trailing '/' */
int n = strlen(issuer);
if (issuer[n - 1] == OIDC_CHAR_FORWARD_SLASH)
issuer[n - 1] = '\0';
/* try and get metadata from the metadata directories for the selected OP */
if ((oidc_metadata_get(r, c, issuer, &provider, csrf_cookie != NULL) == TRUE)
&& (provider != NULL)) {
/* now we've got a selected OP, send the user there to authenticate */
return oidc_authenticate_user(r, c, provider, target_link_uri,
login_hint, NULL, NULL, auth_request_params, path_scopes);
}
/* something went wrong */
return oidc_util_html_send_error(r, c->error_template, "Invalid Request",
"Could not find valid provider metadata for the selected OpenID Connect provider; contact the administrator",
HTTP_NOT_FOUND);
}
static apr_uint32_t oidc_transparent_pixel[17] = { 0x474e5089, 0x0a1a0a0d,
0x0d000000, 0x52444849, 0x01000000, 0x01000000, 0x00000408, 0x0c1cb500,
0x00000002, 0x4144490b, 0x639c7854, 0x0000cffa, 0x02010702, 0x71311c9a,
0x00000000, 0x444e4549, 0x826042ae };
static apr_byte_t oidc_is_front_channel_logout(const char *logout_param_value) {
return ((logout_param_value != NULL)
&& ((apr_strnatcmp(logout_param_value,
OIDC_GET_STYLE_LOGOUT_PARAM_VALUE) == 0)
|| (apr_strnatcmp(logout_param_value,
OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0)));
}
static apr_byte_t oidc_is_back_channel_logout(const char *logout_param_value) {
return ((logout_param_value != NULL) && (apr_strnatcmp(logout_param_value,
OIDC_BACKCHANNEL_STYLE_LOGOUT_PARAM_VALUE) == 0));
}
/*
* revoke refresh token and access token stored in the session if the
* OP has an RFC 7009 compliant token revocation endpoint
*/
static void oidc_revoke_tokens(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *response = NULL;
char *basic_auth = NULL;
char *bearer_auth = NULL;
apr_table_t *params = NULL;
const char *token = NULL;
oidc_provider_t *provider = NULL;
oidc_debug(r, "enter");
if (oidc_get_provider_from_session(r, c, session, &provider) == FALSE)
goto out;
oidc_debug(r, "revocation_endpoint=%s",
provider->revocation_endpoint_url ?
provider->revocation_endpoint_url : "(null)");
if (provider->revocation_endpoint_url == NULL)
goto out;
params = apr_table_make(r->pool, 4);
// add the token endpoint authentication credentials to the revocation endpoint call...
if (oidc_proto_token_endpoint_auth(r, c, provider->token_endpoint_auth,
provider->client_id, provider->client_secret,
provider->client_signing_keys, provider->token_endpoint_url, params,
NULL, &basic_auth, &bearer_auth) == FALSE)
goto out;
// TODO: use oauth.ssl_validate_server ...
token = oidc_session_get_refresh_token(r, session);
if (token != NULL) {
apr_table_addn(params, "token_type_hint", "refresh_token");
apr_table_addn(params, "token", token);
if (oidc_util_http_post_form(r, provider->revocation_endpoint_url,
params, basic_auth, bearer_auth, c->oauth.ssl_validate_server,
&response, c->http_timeout_long, c->outgoing_proxy,
oidc_dir_cfg_pass_cookies(r), NULL,
NULL) == FALSE) {
oidc_warn(r, "revoking refresh token failed");
}
apr_table_clear(params);
}
token = oidc_session_get_access_token(r, session);
if (token != NULL) {
apr_table_addn(params, "token_type_hint", "access_token");
apr_table_addn(params, "token", token);
if (oidc_util_http_post_form(r, provider->revocation_endpoint_url,
params, basic_auth, bearer_auth, c->oauth.ssl_validate_server,
&response, c->http_timeout_long, c->outgoing_proxy,
oidc_dir_cfg_pass_cookies(r), NULL,
NULL) == FALSE) {
oidc_warn(r, "revoking access token failed");
}
}
out:
oidc_debug(r, "leave");
}
/*
* handle a local logout
*/
static int oidc_handle_logout_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *url) {
oidc_debug(r, "enter (url=%s)", url);
/* if there's no remote_user then there's no (stored) session to kill */
if (session->remote_user != NULL) {
oidc_revoke_tokens(r, c, session);
/* remove session state (cq. cache entry and cookie) */
oidc_session_kill(r, session);
}
/* see if this is the OP calling us */
if (oidc_is_front_channel_logout(url)) {
/* set recommended cache control headers */
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_CACHE_CONTROL,
"no-cache, no-store");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_PRAGMA, "no-cache");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_P3P, "CAO PSA OUR");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_EXPIRES, "0");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_X_FRAME_OPTIONS, "DENY");
/* see if this is PF-PA style logout in which case we return a transparent pixel */
const char *accept = oidc_util_hdr_in_accept_get(r);
if ((apr_strnatcmp(url, OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0)
|| ((accept) && strstr(accept, OIDC_CONTENT_TYPE_IMAGE_PNG))) {
return oidc_util_http_send(r,
(const char *) &oidc_transparent_pixel,
sizeof(oidc_transparent_pixel), OIDC_CONTENT_TYPE_IMAGE_PNG,
OK);
}
/* standard HTTP based logout: should be called in an iframe from the OP */
return oidc_util_html_send(r, "Logged Out", NULL, NULL,
"<p>Logged Out</p>", OK);
}
/* see if we don't need to go somewhere special after killing the session locally */
if (url == NULL)
return oidc_util_html_send(r, "Logged Out", NULL, NULL,
"<p>Logged Out</p>", OK);
/* send the user to the specified where-to-go-after-logout URL */
oidc_util_hdr_out_location_set(r, url);
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle a backchannel logout
*/
#define OIDC_EVENTS_BLOGOUT_KEY "http://schemas.openid.net/event/backchannel-logout"
static int oidc_handle_logout_backchannel(request_rec *r, oidc_cfg *cfg) {
oidc_debug(r, "enter");
const char *logout_token = NULL;
oidc_jwt_t *jwt = NULL;
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
oidc_provider_t *provider = NULL;
char *sid = NULL, *uuid = NULL;
oidc_session_t session;
int rc = HTTP_BAD_REQUEST;
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r,
"could not read POST-ed parameters to the logout endpoint");
goto out;
}
logout_token = apr_table_get(params, OIDC_PROTO_LOGOUT_TOKEN);
if (logout_token == NULL) {
oidc_error(r,
"backchannel lggout endpoint was called but could not find a parameter named \"%s\"",
OIDC_PROTO_LOGOUT_TOKEN);
goto out;
}
// TODO: jwk symmetric key based on provider
// TODO: share more code with regular id_token validation and unsolicited state
if (oidc_jwt_parse(r->pool, logout_token, &jwt,
oidc_util_merge_symmetric_key(r->pool, cfg->private_keys, NULL),
&err) == FALSE) {
oidc_error(r, "oidc_jwt_parse failed: %s", oidc_jose_e2s(r->pool, err));
goto out;
}
provider = oidc_get_provider_for_issuer(r, cfg, jwt->payload.iss, FALSE);
if (provider == NULL) {
oidc_error(r, "no provider found for issuer: %s", jwt->payload.iss);
goto out;
}
// TODO: destroy the JWK used for decryption
jwk = NULL;
if (oidc_util_create_symmetric_key(r, provider->client_secret, 0,
NULL, TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwks_uri_t jwks_uri = { provider->jwks_uri,
provider->jwks_refresh_interval, provider->ssl_validate_server };
if (oidc_proto_jwt_verify(r, cfg, jwt, &jwks_uri,
oidc_util_merge_symmetric_key(r->pool, NULL, jwk)) == FALSE) {
oidc_error(r, "id_token signature could not be validated, aborting");
goto out;
}
// oidc_proto_validate_idtoken would try and require a token binding cnf
// if the policy is set to "required", so don't use that here
if (oidc_proto_validate_jwt(r, jwt, provider->issuer, FALSE, FALSE,
provider->idtoken_iat_slack,
OIDC_TOKEN_BINDING_POLICY_DISABLED) == FALSE)
goto out;
/* verify the "aud" and "azp" values */
if (oidc_proto_validate_aud_and_azp(r, cfg, provider,
&jwt->payload) == FALSE)
goto out;
json_t *events = json_object_get(jwt->payload.value.json,
OIDC_CLAIM_EVENTS);
if (events == NULL) {
oidc_error(r, "\"%s\" claim could not be found in logout token",
OIDC_CLAIM_EVENTS);
goto out;
}
json_t *blogout = json_object_get(events, OIDC_EVENTS_BLOGOUT_KEY);
if (!json_is_object(blogout)) {
oidc_error(r, "\"%s\" object could not be found in \"%s\" claim",
OIDC_EVENTS_BLOGOUT_KEY, OIDC_CLAIM_EVENTS);
goto out;
}
char *nonce = NULL;
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_NONCE, &nonce, NULL);
if (nonce != NULL) {
oidc_error(r,
"rejecting logout request/token since it contains a \"%s\" claim",
OIDC_CLAIM_NONCE);
goto out;
}
char *jti = NULL;
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_JTI, &jti, NULL);
if (jti != NULL) {
char *replay = NULL;
oidc_cache_get_jti(r, jti, &replay);
if (replay != NULL) {
oidc_error(r,
"the \"%s\" value (%s) passed in logout token was found in the cache already; possible replay attack!?",
OIDC_CLAIM_JTI, jti);
goto out;
}
}
/* jti cache duration is the configured replay prevention window for token issuance plus 10 seconds for safety */
apr_time_t jti_cache_duration = apr_time_from_sec(
provider->idtoken_iat_slack * 2 + 10);
/* store it in the cache for the calculated duration */
oidc_cache_set_jti(r, jti, jti, apr_time_now() + jti_cache_duration);
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_EVENTS, &sid, NULL);
// TODO: by-spec we should cater for the fact that "sid" has been provided
// in the id_token returned in the authentication request, but "sub"
// is used in the logout token but that requires a 2nd entry in the
// cache and a separate session "sub" member, ugh; we'll just assume
// that is "sid" is specified in the id_token, the OP will actually use
// this for logout
// (and probably call us multiple times or the same sub if needed)
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_SID, &sid, NULL);
if (sid == NULL)
sid = jwt->payload.sub;
if (sid == NULL) {
oidc_error(r, "no \"sub\" and no \"sid\" claim found in logout token");
goto out;
}
// TODO: when dealing with sub instead of a true sid, we'll be killing all sessions for
// a specific user, across hosts that share the *same* cache backend
// if those hosts haven't been configured with a different OIDCCryptoPassphrase
// - perhaps that's even acceptable since non-memory caching is encrypted by default
// and memory-based caching doesn't suffer from this (different shm segments)?
// - it will result in 400 errors returned from backchannel logout calls to the other hosts...
sid = oidc_make_sid_iss_unique(r, sid, provider->issuer);
oidc_cache_get_sid(r, sid, &uuid);
if (uuid == NULL) {
oidc_error(r,
"could not find session based on sid/sub provided in logout token: %s",
sid);
goto out;
}
// revoke tokens if we can get a handle on those
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
if (oidc_session_load_cache_by_uuid(r, cfg, uuid, &session) != FALSE)
if (oidc_session_extract(r, &session) != FALSE)
oidc_revoke_tokens(r, cfg, &session);
}
// clear the session cache
oidc_cache_set_sid(r, sid, NULL, 0);
oidc_cache_set_session(r, uuid, NULL, 0);
rc = OK;
out:
if (jwk != NULL) {
oidc_jwk_destroy(jwk);
jwk = NULL;
}
if (jwt != NULL) {
oidc_jwt_destroy(jwt);
jwt = NULL;
}
return rc;
}
static apr_byte_t oidc_validate_post_logout_url(request_rec *r, const char *url,
char **err_str, char **err_desc) {
apr_uri_t uri;
const char *c_host = NULL;
if (apr_uri_parse(r->pool, url, &uri) != APR_SUCCESS) {
*err_str = apr_pstrdup(r->pool, "Malformed URL");
*err_desc = apr_psprintf(r->pool, "Logout URL malformed: %s", url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
c_host = oidc_get_current_url_host(r);
if ((uri.hostname != NULL)
&& ((strstr(c_host, uri.hostname) == NULL)
|| (strstr(uri.hostname, c_host) == NULL))) {
*err_str = apr_pstrdup(r->pool, "Invalid Request");
*err_desc =
apr_psprintf(r->pool,
"logout value \"%s\" does not match the hostname of the current request \"%s\"",
apr_uri_unparse(r->pool, &uri, 0), c_host);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
} else if ((uri.hostname == NULL) && (strstr(url, "/") != url)) {
*err_str = apr_pstrdup(r->pool, "Malformed URL");
*err_desc =
apr_psprintf(r->pool,
"No hostname was parsed and it does not seem to be relative, i.e starting with '/': %s",
url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
} else if ((uri.hostname == NULL) && (strstr(url, "//") == url)) {
*err_str = apr_pstrdup(r->pool, "Malformed URL");
*err_desc =
apr_psprintf(r->pool,
"No hostname was parsed and starting with '//': %s",
url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
/* validate the URL to prevent HTTP header splitting */
if (((strstr(url, "\n") != NULL) || strstr(url, "\r") != NULL)) {
*err_str = apr_pstrdup(r->pool, "Invalid Request");
*err_desc =
apr_psprintf(r->pool,
"logout value \"%s\" contains illegal \"\n\" or \"\r\" character(s)",
url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
return TRUE;
}
/*
* perform (single) logout
*/
static int oidc_handle_logout(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
oidc_provider_t *provider = NULL;
/* pickup the command or URL where the user wants to go after logout */
char *url = NULL;
char *error_str = NULL;
char *error_description = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_LOGOUT, &url);
oidc_debug(r, "enter (url=%s)", url);
if (oidc_is_front_channel_logout(url)) {
return oidc_handle_logout_request(r, c, session, url);
} else if (oidc_is_back_channel_logout(url)) {
return oidc_handle_logout_backchannel(r, c);
}
if ((url == NULL) || (apr_strnatcmp(url, "") == 0)) {
url = c->default_slo_url;
} else {
/* do input validation on the logout parameter value */
if (oidc_validate_post_logout_url(r, url, &error_str,
&error_description) == FALSE) {
return oidc_util_html_send_error(r, c->error_template, error_str,
error_description,
HTTP_BAD_REQUEST);
}
}
oidc_get_provider_from_session(r, c, session, &provider);
if ((provider != NULL) && (provider->end_session_endpoint != NULL)) {
const char *id_token_hint = oidc_session_get_idtoken(r, session);
char *logout_request = apr_pstrdup(r->pool,
provider->end_session_endpoint);
if (id_token_hint != NULL) {
logout_request = apr_psprintf(r->pool, "%s%sid_token_hint=%s",
logout_request, strchr(logout_request ? logout_request : "",
OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
oidc_util_escape_string(r, id_token_hint));
}
if (url != NULL) {
logout_request = apr_psprintf(r->pool,
"%s%spost_logout_redirect_uri=%s", logout_request,
strchr(logout_request ? logout_request : "",
OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
oidc_util_escape_string(r, url));
}
url = logout_request;
}
return oidc_handle_logout_request(r, c, session, url);
}
/*
* handle request for JWKs
*/
int oidc_handle_jwks(request_rec *r, oidc_cfg *c) {
/* pickup requested JWKs type */
// char *jwks_type = NULL;
// oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_JWKS, &jwks_type);
char *jwks = apr_pstrdup(r->pool, "{ \"keys\" : [");
apr_hash_index_t *hi = NULL;
apr_byte_t first = TRUE;
oidc_jose_error_t err;
if (c->public_keys != NULL) {
/* loop over the RSA public keys */
for (hi = apr_hash_first(r->pool, c->public_keys); hi; hi =
apr_hash_next(hi)) {
const char *s_kid = NULL;
oidc_jwk_t *jwk = NULL;
char *s_json = NULL;
apr_hash_this(hi, (const void**) &s_kid, NULL, (void**) &jwk);
if (oidc_jwk_to_json(r->pool, jwk, &s_json, &err) == TRUE) {
jwks = apr_psprintf(r->pool, "%s%s %s ", jwks, first ? "" : ",",
s_json);
first = FALSE;
} else {
oidc_error(r,
"could not convert RSA JWK to JSON using oidc_jwk_to_json: %s",
oidc_jose_e2s(r->pool, err));
}
}
}
// TODO: send stuff if first == FALSE?
jwks = apr_psprintf(r->pool, "%s ] }", jwks);
return oidc_util_http_send(r, jwks, strlen(jwks), OIDC_CONTENT_TYPE_JSON,
OK);
}
static int oidc_handle_session_management_iframe_op(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *check_session_iframe) {
oidc_debug(r, "enter");
oidc_util_hdr_out_location_set(r, check_session_iframe);
return HTTP_MOVED_TEMPORARILY;
}
static int oidc_handle_session_management_iframe_rp(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *client_id,
const char *check_session_iframe) {
oidc_debug(r, "enter");
const char *java_script =
" <script type=\"text/javascript\">\n"
" var targetOrigin = '%s';\n"
" var message = '%s' + ' ' + '%s';\n"
" var timerID;\n"
"\n"
" function checkSession() {\n"
" console.debug('checkSession: posting ' + message + ' to ' + targetOrigin);\n"
" var win = window.parent.document.getElementById('%s').contentWindow;\n"
" win.postMessage( message, targetOrigin);\n"
" }\n"
"\n"
" function setTimer() {\n"
" checkSession();\n"
" timerID = setInterval('checkSession()', %d);\n"
" }\n"
"\n"
" function receiveMessage(e) {\n"
" console.debug('receiveMessage: ' + e.data + ' from ' + e.origin);\n"
" if (e.origin !== targetOrigin ) {\n"
" console.debug('receiveMessage: cross-site scripting attack?');\n"
" return;\n"
" }\n"
" if (e.data != 'unchanged') {\n"
" clearInterval(timerID);\n"
" if (e.data == 'changed') {\n"
" window.location.href = '%s?session=check';\n"
" } else {\n"
" window.location.href = '%s?session=logout';\n"
" }\n"
" }\n"
" }\n"
"\n"
" window.addEventListener('message', receiveMessage, false);\n"
"\n"
" </script>\n";
/* determine the origin for the check_session_iframe endpoint */
char *origin = apr_pstrdup(r->pool, check_session_iframe);
apr_uri_t uri;
apr_uri_parse(r->pool, check_session_iframe, &uri);
char *p = strstr(origin, uri.path);
*p = '\0';
/* the element identifier for the OP iframe */
const char *op_iframe_id = "openidc-op";
/* restore the OP session_state from the session */
const char *session_state = oidc_session_get_session_state(r, session);
if (session_state == NULL) {
oidc_warn(r,
"no session_state found in the session; the OP does probably not support session management!?");
return OK;
}
char *s_poll_interval = NULL;
oidc_util_get_request_parameter(r, "poll", &s_poll_interval);
int poll_interval = s_poll_interval ? strtol(s_poll_interval, NULL, 10) : 0;
if ((poll_interval <= 0) || (poll_interval > 3600 * 24))
poll_interval = 3000;
const char *redirect_uri = oidc_get_redirect_uri(r, c);
java_script = apr_psprintf(r->pool, java_script, origin, client_id,
session_state, op_iframe_id, poll_interval, redirect_uri,
redirect_uri);
return oidc_util_html_send(r, NULL, java_script, "setTimer", NULL, OK);
}
/*
* handle session management request
*/
static int oidc_handle_session_management(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *cmd = NULL;
const char *id_token_hint = NULL;
oidc_provider_t *provider = NULL;
/* get the command passed to the session management handler */
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_SESSION, &cmd);
if (cmd == NULL) {
oidc_error(r, "session management handler called with no command");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if this is a local logout during session management */
if (apr_strnatcmp("logout", cmd) == 0) {
oidc_debug(r,
"[session=logout] calling oidc_handle_logout_request because of session mgmt local logout call.");
return oidc_handle_logout_request(r, c, session, c->default_slo_url);
}
oidc_get_provider_from_session(r, c, session, &provider);
/* see if this is a request for the OP iframe */
if (apr_strnatcmp("iframe_op", cmd) == 0) {
if (provider->check_session_iframe != NULL) {
return oidc_handle_session_management_iframe_op(r, c, session,
provider->check_session_iframe);
}
return HTTP_NOT_FOUND;
}
/* see if this is a request for the RP iframe */
if (apr_strnatcmp("iframe_rp", cmd) == 0) {
if ((provider->client_id != NULL)
&& (provider->check_session_iframe != NULL)) {
return oidc_handle_session_management_iframe_rp(r, c, session,
provider->client_id, provider->check_session_iframe);
}
oidc_debug(r,
"iframe_rp command issued but no client (%s) and/or no check_session_iframe (%s) set",
provider->client_id, provider->check_session_iframe);
return HTTP_NOT_FOUND;
}
/* see if this is a request check the login state with the OP */
if (apr_strnatcmp("check", cmd) == 0) {
id_token_hint = oidc_session_get_idtoken(r, session);
if ((session->remote_user != NULL) && (provider != NULL)) {
/*
* TODO: this doesn't work with per-path provided auth_request_params and scopes
* as oidc_dir_cfg_path_auth_request_params and oidc_dir_cfg_path_scope will pick
* those for the redirect_uri itself; do we need to store those as part of the
* session now?
*/
return oidc_authenticate_user(r, c, provider,
apr_psprintf(r->pool, "%s?session=iframe_rp",
oidc_get_redirect_uri_iss(r, c, provider)), NULL,
id_token_hint, "none",
oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
}
oidc_debug(r,
"[session=check] calling oidc_handle_logout_request because no session found.");
return oidc_session_redirect_parent_window_to_logout(r, c);
}
/* handle failure in fallthrough */
oidc_error(r, "unknown command: %s", cmd);
return HTTP_INTERNAL_SERVER_ERROR;
}
/*
* handle refresh token request
*/
static int oidc_handle_refresh_token_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *return_to = NULL;
char *r_access_token = NULL;
char *error_code = NULL;
/* get the command passed to the session management handler */
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_REFRESH,
&return_to);
oidc_util_get_request_parameter(r, OIDC_PROTO_ACCESS_TOKEN,
&r_access_token);
/* check the input parameters */
if (return_to == NULL) {
oidc_error(r,
"refresh token request handler called with no URL to return to");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (r_access_token == NULL) {
oidc_error(r,
"refresh token request handler called with no access_token parameter");
error_code = "no_access_token";
goto end;
}
const char *s_access_token = oidc_session_get_access_token(r, session);
if (s_access_token == NULL) {
oidc_error(r,
"no existing access_token found in the session, nothing to refresh");
error_code = "no_access_token_exists";
goto end;
}
/* compare the access_token parameter used for XSRF protection */
if (apr_strnatcmp(s_access_token, r_access_token) != 0) {
oidc_error(r,
"access_token passed in refresh request does not match the one stored in the session");
error_code = "no_access_token_match";
goto end;
}
/* get a handle to the provider configuration */
oidc_provider_t *provider = NULL;
if (oidc_get_provider_from_session(r, c, session, &provider) == FALSE) {
error_code = "session_corruption";
goto end;
}
/* execute the actual refresh grant */
if (oidc_refresh_access_token(r, c, session, provider, NULL) == FALSE) {
oidc_error(r, "access_token could not be refreshed");
error_code = "refresh_failed";
goto end;
}
/* pass the tokens to the application and save the session, possibly updating the expiry */
if (oidc_session_pass_tokens_and_save(r, c, session, TRUE) == FALSE) {
error_code = "session_corruption";
goto end;
}
end:
/* pass optional error message to the return URL */
if (error_code != NULL)
return_to = apr_psprintf(r->pool, "%s%serror_code=%s", return_to,
strchr(return_to ? return_to : "", OIDC_CHAR_QUERY) ?
OIDC_STR_AMP :
OIDC_STR_QUERY, oidc_util_escape_string(r, error_code));
/* add the redirect location header */
oidc_util_hdr_out_location_set(r, return_to);
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle request object by reference request
*/
static int oidc_handle_request_uri(request_rec *r, oidc_cfg *c) {
char *request_ref = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_REQUEST_URI,
&request_ref);
if (request_ref == NULL) {
oidc_error(r, "no \"%s\" parameter found",
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI);
return HTTP_BAD_REQUEST;
}
char *jwt = NULL;
oidc_cache_get_request_uri(r, request_ref, &jwt);
if (jwt == NULL) {
oidc_error(r, "no cached JWT found for %s reference: %s",
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI, request_ref);
return HTTP_NOT_FOUND;
}
oidc_cache_set_request_uri(r, request_ref, NULL, 0);
return oidc_util_http_send(r, jwt, strlen(jwt), OIDC_CONTENT_TYPE_JWT, OK);
}
/*
* handle a request to invalidate a cached access token introspection result
*/
int oidc_handle_remove_at_cache(request_rec *r, oidc_cfg *c) {
char *access_token = NULL;
oidc_util_get_request_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REMOVE_AT_CACHE, &access_token);
char *cache_entry = NULL;
oidc_cache_get_access_token(r, access_token, &cache_entry);
if (cache_entry == NULL) {
oidc_error(r, "no cached access token found for value: %s",
access_token);
return HTTP_NOT_FOUND;
}
oidc_cache_set_access_token(r, access_token, NULL, 0);
return OK;
}
#define OIDC_INFO_PARAM_ACCESS_TOKEN_REFRESH_INTERVAL "access_token_refresh_interval"
/*
* handle request for session info
*/
static int oidc_handle_info_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
int rc = HTTP_UNAUTHORIZED;
apr_byte_t needs_save = FALSE;
char *s_format = NULL, *s_interval = NULL, *r_value = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_INFO,
&s_format);
oidc_util_get_request_parameter(r,
OIDC_INFO_PARAM_ACCESS_TOKEN_REFRESH_INTERVAL, &s_interval);
/* see if this is a request for a format that is supported */
if ((apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_JSON, s_format) != 0)
&& (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_HTML, s_format) != 0)) {
oidc_warn(r, "request for unknown format: %s", s_format);
return HTTP_UNSUPPORTED_MEDIA_TYPE;
}
/* check that we actually have a user session and this is someone calling with a proper session cookie */
if (session->remote_user == NULL) {
oidc_warn(r, "no user session found");
return HTTP_UNAUTHORIZED;
}
/* set the user in the main request for further (incl. sub-request and authz) processing */
r->user = apr_pstrdup(r->pool, session->remote_user);
if (c->info_hook_data == NULL) {
oidc_warn(r, "no data configured to return in " OIDCInfoHook);
return HTTP_NOT_FOUND;
}
/* see if we can and need to refresh the access token */
if ((s_interval != NULL)
&& (oidc_session_get_refresh_token(r, session) != NULL)) {
apr_time_t t_interval;
if (sscanf(s_interval, "%" APR_TIME_T_FMT, &t_interval) == 1) {
t_interval = apr_time_from_sec(t_interval);
/* get the last refresh timestamp from the session info */
apr_time_t last_refresh =
oidc_session_get_access_token_last_refresh(r, session);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(last_refresh + t_interval - apr_time_now()));
/* see if we need to refresh again */
if (last_refresh + t_interval < apr_time_now()) {
/* get the current provider info */
oidc_provider_t *provider = NULL;
if (oidc_get_provider_from_session(r, c, session,
&provider) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* execute the actual refresh grant */
if (oidc_refresh_access_token(r, c, session, provider,
NULL) == FALSE)
oidc_warn(r, "access_token could not be refreshed");
else
needs_save = TRUE;
}
}
}
/* create the JSON object */
json_t *json = json_object();
/* add a timestamp of creation in there for the caller */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_TIMESTAMP,
APR_HASH_KEY_STRING)) {
json_object_set_new(json, OIDC_HOOK_INFO_TIMESTAMP,
json_integer(apr_time_sec(apr_time_now())));
}
/*
* refresh the claims from the userinfo endpoint
* side-effect is that this may refresh the access token if not already done
* note that OIDCUserInfoRefreshInterval should be set to control the refresh policy
*/
needs_save |= oidc_refresh_claims_from_userinfo_endpoint(r, c, session);
/* include the access token in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ACCES_TOKEN,
APR_HASH_KEY_STRING)) {
const char *access_token = oidc_session_get_access_token(r, session);
if (access_token != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_ACCES_TOKEN,
json_string(access_token));
}
/* include the access token expiry timestamp in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ACCES_TOKEN_EXP,
APR_HASH_KEY_STRING)) {
const char *access_token_expires =
oidc_session_get_access_token_expires(r, session);
if (access_token_expires != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_ACCES_TOKEN_EXP,
json_string(access_token_expires));
}
/* include the id_token claims in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ID_TOKEN,
APR_HASH_KEY_STRING)) {
json_t *id_token = oidc_session_get_idtoken_claims_json(r, session);
if (id_token)
json_object_set_new(json, OIDC_HOOK_INFO_ID_TOKEN, id_token);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_USER_INFO,
APR_HASH_KEY_STRING)) {
/* include the claims from the userinfo endpoint the session info */
json_t *claims = oidc_session_get_userinfo_claims_json(r, session);
if (claims)
json_object_set_new(json, OIDC_HOOK_INFO_USER_INFO, claims);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_SESSION,
APR_HASH_KEY_STRING)) {
json_t *j_session = json_object();
json_object_set(j_session, OIDC_HOOK_INFO_SESSION_STATE,
session->state);
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_UUID,
json_string(session->uuid));
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_TIMEOUT,
json_integer(apr_time_sec(session->expiry)));
apr_time_t session_expires = oidc_session_get_session_expires(r,
session);
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_EXP,
json_integer(apr_time_sec(session_expires)));
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_REMOTE_USER,
json_string(session->remote_user));
json_object_set_new(json, OIDC_HOOK_INFO_SESSION, j_session);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_REFRESH_TOKEN,
APR_HASH_KEY_STRING)) {
/* include the refresh token in the session info */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if (refresh_token != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_REFRESH_TOKEN,
json_string(refresh_token));
}
if (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_JSON, s_format) == 0) {
/* JSON-encode the result */
r_value = oidc_util_encode_json_object(r, json, 0);
/* return the stringified JSON result */
rc = oidc_util_http_send(r, r_value, strlen(r_value),
OIDC_CONTENT_TYPE_JSON, OK);
} else if (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_HTML, s_format) == 0) {
/* JSON-encode the result */
r_value = oidc_util_encode_json_object(r, json, JSON_INDENT(2));
rc = oidc_util_html_send(r, "Session Info", NULL, NULL,
apr_psprintf(r->pool, "<pre>%s</pre>", r_value), OK);
}
/* free the allocated resources */
json_decref(json);
/* pass the tokens to the application and save the session, possibly updating the expiry */
if (oidc_session_pass_tokens_and_save(r, c, session, needs_save) == FALSE) {
oidc_warn(r, "error saving session");
rc = HTTP_INTERNAL_SERVER_ERROR;
}
return rc;
}
/*
* handle all requests to the redirect_uri
*/
int oidc_handle_redirect_uri_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
if (oidc_proto_is_redirect_authorization_response(r, c)) {
/* this is an authorization response from the OP using the Basic Client profile or a Hybrid flow*/
return oidc_handle_redirect_authorization_response(r, c, session);
/*
*
* Note that we are checking for logout *before* checking for a POST authorization response
* to handle backchannel POST-based logout
*
* so any POST to the Redirect URI that does not have a logout query parameter will be handled
* as an authorization response; alternatively we could assume that a POST response has no
* parameters
*/
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_LOGOUT)) {
/* handle logout */
return oidc_handle_logout(r, c, session);
} else if (oidc_proto_is_post_authorization_response(r, c)) {
/* this is an authorization response using the fragment(+POST) response_mode with the Implicit Client profile */
return oidc_handle_post_authorization_response(r, c, session);
} else if (oidc_is_discovery_response(r, c)) {
/* this is response from the OP discovery page */
return oidc_handle_discovery_response(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_JWKS)) {
/* handle JWKs request */
return oidc_handle_jwks(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_SESSION)) {
/* handle session management request */
return oidc_handle_session_management(r, c, session);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REFRESH)) {
/* handle refresh token request */
return oidc_handle_refresh_token_request(r, c, session);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI)) {
/* handle request object by reference request */
return oidc_handle_request_uri(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REMOVE_AT_CACHE)) {
/* handle request to invalidate access token cache */
return oidc_handle_remove_at_cache(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_INFO)) {
if (session->remote_user == NULL)
return HTTP_UNAUTHORIZED;
/* set r->user, set headers/env-vars, update expiry, update userinfo + AT */
int rc = oidc_handle_existing_session(r, c, session);
if (rc != OK)
return rc;
return oidc_handle_info_request(r, c, session);
} else if ((r->args == NULL) || (apr_strnatcmp(r->args, "") == 0)) {
/* this is a "bare" request to the redirect URI, indicating implicit flow using the fragment response_mode */
return oidc_proto_javascript_implicit(r, c);
}
/* this is not an authorization response or logout request */
/* check for "error" response */
if (oidc_util_request_has_parameter(r, OIDC_PROTO_ERROR)) {
// char *error = NULL, *descr = NULL;
// oidc_util_get_request_parameter(r, "error", &error);
// oidc_util_get_request_parameter(r, "error_description", &descr);
//
// /* send user facing error to browser */
// return oidc_util_html_send_error(r, error, descr, DONE);
return oidc_handle_redirect_authorization_response(r, c, session);
}
oidc_error(r,
"The OpenID Connect callback URL received an invalid request: %s; returning HTTP_INTERNAL_SERVER_ERROR",
r->args);
/* something went wrong */
return oidc_util_html_send_error(r, c->error_template, "Invalid Request",
apr_psprintf(r->pool,
"The OpenID Connect callback URL received an invalid request"),
HTTP_INTERNAL_SERVER_ERROR);
}
#define OIDC_AUTH_TYPE_OPENID_CONNECT "openid-connect"
#define OIDC_AUTH_TYPE_OPENID_OAUTH20 "oauth20"
#define OIDC_AUTH_TYPE_OPENID_BOTH "auth-openidc"
/*
* main routine: handle OpenID Connect authentication
*/
static int oidc_check_userid_openidc(request_rec *r, oidc_cfg *c) {
if (oidc_get_redirect_uri(r, c) == NULL) {
oidc_error(r,
"configuration error: the authentication type is set to \"" OIDC_AUTH_TYPE_OPENID_CONNECT "\" but " OIDCRedirectURI " has not been set");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* check if this is a sub-request or an initial request */
if (ap_is_initial_req(r)) {
int rc = OK;
/* load the session from the request state; this will be a new "empty" session if no state exists */
oidc_session_t *session = NULL;
oidc_session_load(r, &session);
/* see if the initial request is to the redirect URI; this handles potential logout too */
if (oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, c))) {
/* handle request to the redirect_uri */
rc = oidc_handle_redirect_uri_request(r, c, session);
/* free resources allocated for the session */
oidc_session_free(r, session);
return rc;
/* initial request to non-redirect URI, check if we have an existing session */
} else if (session->remote_user != NULL) {
/* this is initial request and we already have a session */
rc = oidc_handle_existing_session(r, c, session);
/* free resources allocated for the session */
oidc_session_free(r, session);
/* strip any cookies that we need to */
oidc_strip_cookies(r);
return rc;
}
/* free resources allocated for the session */
oidc_session_free(r, session);
/*
* else: initial request, we have no session and it is not an authorization or
* discovery response: just hit the default flow for unauthenticated users
*/
} else {
/* not an initial request, try to recycle what we've already established in the main request */
if (r->main != NULL)
r->user = r->main->user;
else if (r->prev != NULL)
r->user = r->prev->user;
if (r->user != NULL) {
/* this is a sub-request and we have a session (headers will have been scrubbed and set already) */
oidc_debug(r,
"recycling user '%s' from initial request for sub-request",
r->user);
/*
* apparently request state can get lost in sub-requests, so let's see
* if we need to restore id_token and/or claims from the session cache
*/
const char *s_id_token = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_IDTOKEN);
if (s_id_token == NULL) {
oidc_session_t *session = NULL;
oidc_session_load(r, &session);
oidc_copy_tokens_to_request_state(r, session, NULL, NULL);
/* free resources allocated for the session */
oidc_session_free(r, session);
}
/* strip any cookies that we need to */
oidc_strip_cookies(r);
return OK;
}
/*
* else: not initial request, but we could not find a session, so:
* just hit the default flow for unauthenticated users
*/
}
return oidc_handle_unauthenticated_user(r, c);
}
/*
* main routine: handle "mixed" OIDC/OAuth authentication
*/
static int oidc_check_mixed_userid_oauth(request_rec *r, oidc_cfg *c) {
/* get the bearer access token from the Authorization header */
const char *access_token = NULL;
if (oidc_oauth_get_bearer_token(r, &access_token) == TRUE)
return oidc_oauth_check_userid(r, c, access_token);
/* no bearer token found: then treat this as a regular OIDC browser request */
return oidc_check_userid_openidc(r, c);
}
/*
* generic Apache authentication hook for this module: dispatches to OpenID Connect or OAuth 2.0 specific routines
*/
int oidc_check_user_id(request_rec *r) {
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
/* log some stuff about the incoming HTTP request */
oidc_debug(r, "incoming request: \"%s?%s\", ap_is_initial_req(r)=%d",
r->parsed_uri.path, r->args, ap_is_initial_req(r));
/* see if any authentication has been defined at all */
if (ap_auth_type(r) == NULL)
return DECLINED;
/* see if we've configured OpenID Connect user authentication for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_CONNECT) == 0)
return oidc_check_userid_openidc(r, c);
/* see if we've configured OAuth 2.0 access control for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0)
return oidc_oauth_check_userid(r, c, NULL);
/* see if we've configured "mixed mode" for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_BOTH) == 0)
return oidc_check_mixed_userid_oauth(r, c);
/* this is not for us but for some other handler */
return DECLINED;
}
/*
* get the claims and id_token from request state
*/
static void oidc_authz_get_claims_and_idtoken(request_rec *r, json_t **claims,
json_t **id_token) {
const char *s_claims = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_CLAIMS);
if (s_claims != NULL)
oidc_util_decode_json_object(r, s_claims, claims);
const char *s_id_token = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_IDTOKEN);
if (s_id_token != NULL)
oidc_util_decode_json_object(r, s_id_token, id_token);
}
#if MODULE_MAGIC_NUMBER_MAJOR >= 20100714
/*
* find out which action we need to take when encountering an unauthorized request
*/
static authz_status oidc_handle_unauthorized_user24(request_rec *r) {
oidc_debug(r, "enter");
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0) {
oidc_oauth_return_www_authenticate(r, "insufficient_scope",
"Different scope(s) or other claims required");
return AUTHZ_DENIED;
}
/* see if we've configured OIDCUnAutzAction for this path */
switch (oidc_dir_cfg_unautz_action(r)) {
// TODO: document that AuthzSendForbiddenOnFailure is required to return 403 FORBIDDEN
case OIDC_UNAUTZ_RETURN403:
case OIDC_UNAUTZ_RETURN401:
return AUTHZ_DENIED;
break;
case OIDC_UNAUTZ_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return AUTHZ_DENIED;
break;
}
oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
const char *location = oidc_util_hdr_out_location_get(r);
if (location != NULL) {
oidc_debug(r, "send HTML refresh with authorization redirect: %s",
location);
char *html_head = apr_psprintf(r->pool,
"<meta http-equiv=\"refresh\" content=\"0; url=%s\">",
location);
oidc_util_html_send(r, "Stepup Authentication", html_head, NULL, NULL,
HTTP_UNAUTHORIZED);
}
return AUTHZ_DENIED;
}
/*
* generic Apache >=2.4 authorization hook for this module
* handles both OpenID Connect or OAuth 2.0 in the same way, based on the claims stored in the session
*/
authz_status oidc_authz_checker(request_rec *r, const char *require_args,
const void *parsed_require_args,
oidc_authz_match_claim_fn_type match_claim_fn) {
oidc_debug(r, "enter");
/* check for anonymous access and PASS mode */
if (r->user != NULL && strlen(r->user) == 0) {
r->user = NULL;
if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS)
return AUTHZ_GRANTED;
}
/* get the set of claims from the request state (they've been set in the authentication part earlier */
json_t *claims = NULL, *id_token = NULL;
oidc_authz_get_claims_and_idtoken(r, &claims, &id_token);
/* merge id_token claims (e.g. "iss") in to claims json object */
if (claims)
oidc_util_json_merge(r, id_token, claims);
/* dispatch to the >=2.4 specific authz routine */
authz_status rc = oidc_authz_worker24(r, claims ? claims : id_token,
require_args, match_claim_fn);
/* cleanup */
if (claims)
json_decref(claims);
if (id_token)
json_decref(id_token);
if ((rc == AUTHZ_DENIED) && ap_auth_type(r))
rc = oidc_handle_unauthorized_user24(r);
return rc;
}
authz_status oidc_authz_checker_claim(request_rec *r, const char *require_args,
const void *parsed_require_args) {
return oidc_authz_checker(r, require_args, parsed_require_args,
oidc_authz_match_claim);
}
#ifdef USE_LIBJQ
authz_status oidc_authz_checker_claims_expr(request_rec *r, const char *require_args, const void *parsed_require_args) {
return oidc_authz_checker(r, require_args, parsed_require_args, oidc_authz_match_claims_expr);
}
#endif
#else
/*
* find out which action we need to take when encountering an unauthorized request
*/
static int oidc_handle_unauthorized_user22(request_rec *r) {
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
if (apr_strnatcasecmp((const char *) ap_auth_type(r), OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0) {
oidc_oauth_return_www_authenticate(r, "insufficient_scope", "Different scope(s) or other claims required");
return HTTP_UNAUTHORIZED;
}
/* see if we've configured OIDCUnAutzAction for this path */
switch (oidc_dir_cfg_unautz_action(r)) {
case OIDC_UNAUTZ_RETURN403:
return HTTP_FORBIDDEN;
case OIDC_UNAUTZ_RETURN401:
return HTTP_UNAUTHORIZED;
case OIDC_UNAUTZ_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return HTTP_UNAUTHORIZED;
}
return oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r), oidc_dir_cfg_path_scope(r));
}
/*
* generic Apache <2.4 authorization hook for this module
* handles both OpenID Connect and OAuth 2.0 in the same way, based on the claims stored in the request context
*/
int oidc_auth_checker(request_rec *r) {
/* check for anonymous access and PASS mode */
if (r->user != NULL && strlen(r->user) == 0) {
r->user = NULL;
if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS)
return OK;
}
/* get the set of claims from the request state (they've been set in the authentication part earlier */
json_t *claims = NULL, *id_token = NULL;
oidc_authz_get_claims_and_idtoken(r, &claims, &id_token);
/* get the Require statements */
const apr_array_header_t * const reqs_arr = ap_requires(r);
/* see if we have any */
const require_line * const reqs =
reqs_arr ? (require_line *) reqs_arr->elts : NULL;
if (!reqs_arr) {
oidc_debug(r,
"no require statements found, so declining to perform authorization.");
return DECLINED;
}
/* merge id_token claims (e.g. "iss") in to claims json object */
if (claims)
oidc_util_json_merge(r, id_token, claims);
/* dispatch to the <2.4 specific authz routine */
int rc = oidc_authz_worker22(r, claims ? claims : id_token, reqs,
reqs_arr->nelts);
/* cleanup */
if (claims)
json_decref(claims);
if (id_token)
json_decref(id_token);
if ((rc == HTTP_UNAUTHORIZED) && ap_auth_type(r))
rc = oidc_handle_unauthorized_user22(r);
return rc;
}
#endif
apr_byte_t oidc_enabled(request_rec *r) {
if (ap_auth_type(r) == NULL)
return FALSE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_CONNECT) == 0)
return TRUE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0)
return TRUE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_BOTH) == 0)
return TRUE;
return FALSE;
}
/*
* handle content generating requests
*/
int oidc_content_handler(request_rec *r) {
if (oidc_enabled(r) == FALSE)
return DECLINED;
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
return oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, c)) ?
OK : DECLINED;
}
extern const command_rec oidc_config_cmds[];
module AP_MODULE_DECLARE_DATA auth_openidc_module = {
STANDARD20_MODULE_STUFF,
oidc_create_dir_config,
oidc_merge_dir_config,
oidc_create_server_config,
oidc_merge_server_config,
oidc_config_cmds,
oidc_register_hooks
};
| ./CrossVul/dataset_final_sorted/CWE-601/c/bad_1369_0 |
crossvul-cpp_data_bad_1002_2 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/***************************************************************************
* Copyright (C) 2017-2019 ZmartZone IAM
* Copyright (C) 2013-2017 Ping Identity Corporation
* All rights reserved.
*
* For further information please contact:
*
* Ping Identity Corporation
* 1099 18th St Suite 2950
* Denver, CO 80202
* 303.468.2900
* http://www.pingidentity.com
*
* DISCLAIMER OF WARRANTIES:
*
* THE SOFTWARE PROVIDED HEREUNDER IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
* ANY WARRANTIES OR REPRESENTATIONS EXPRESS, IMPLIED OR STATUTORY; INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF QUALITY, PERFORMANCE, NONINFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NOR ARE THERE ANY
* WARRANTIES CREATED BY A COURSE OR DEALING, COURSE OF PERFORMANCE OR TRADE
* USAGE. FURTHERMORE, THERE ARE NO WARRANTIES THAT THE SOFTWARE WILL MEET
* YOUR NEEDS OR BE FREE FROM ERRORS, OR THAT THE OPERATION OF THE SOFTWARE
* WILL BE UNINTERRUPTED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES 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.
*
* Initially based on mod_auth_cas.c:
* https://github.com/Jasig/mod_auth_cas
*
* Other code copied/borrowed/adapted:
* shared memory caching: mod_auth_mellon
*
* @Author: Hans Zandbelt - hans.zandbelt@zmartzone.eu
*
**************************************************************************/
#include "apr_hash.h"
#include "apr_strings.h"
#include "ap_config.h"
#include "ap_provider.h"
#include "apr_lib.h"
#include "apr_file_io.h"
#include "apr_sha1.h"
#include "apr_base64.h"
#include "httpd.h"
#include "http_core.h"
#include "http_config.h"
#include "http_log.h"
#include "http_protocol.h"
#include "http_request.h"
#include "mod_auth_openidc.h"
#define ERROR 2
static int oidc_handle_logout_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *url);
// TODO:
// - sort out oidc_cfg vs. oidc_dir_cfg stuff
// - rigid input checking on discovery responses
// - check self-issued support
// - README.quickstart
// - refresh metadata once-per too? (for non-signing key changes)
extern module AP_MODULE_DECLARE_DATA auth_openidc_module;
/*
* clean any suspicious headers in the HTTP request sent by the user agent
*/
static void oidc_scrub_request_headers(request_rec *r, const char *claim_prefix,
apr_hash_t *scrub) {
const int prefix_len = claim_prefix ? strlen(claim_prefix) : 0;
/* get an array representation of the incoming HTTP headers */
const apr_array_header_t * const h = apr_table_elts(r->headers_in);
/* table to keep the non-suspicious headers */
apr_table_t *clean_headers = apr_table_make(r->pool, h->nelts);
/* loop over the incoming HTTP headers */
const apr_table_entry_t * const e = (const apr_table_entry_t *) h->elts;
int i;
for (i = 0; i < h->nelts; i++) {
const char * const k = e[i].key;
/* is this header's name equivalent to a header that needs scrubbing? */
const char *hdr =
(k != NULL) && (scrub != NULL) ?
apr_hash_get(scrub, k, APR_HASH_KEY_STRING) : NULL;
const int header_matches = (hdr != NULL)
&& (oidc_strnenvcmp(k, hdr, -1) == 0);
/*
* would this header be interpreted as a mod_auth_openidc attribute? Note
* that prefix_len will be zero if no attr_prefix is defined,
* so this will always be false. Also note that we do not
* scrub headers if the prefix is empty because every header
* would match.
*/
const int prefix_matches = (k != NULL) && prefix_len
&& (oidc_strnenvcmp(k, claim_prefix, prefix_len) == 0);
/* add to the clean_headers if non-suspicious, skip and report otherwise */
if (!prefix_matches && !header_matches) {
apr_table_addn(clean_headers, k, e[i].val);
} else {
oidc_warn(r, "scrubbed suspicious request header (%s: %.32s)", k,
e[i].val);
}
}
/* overwrite the incoming headers with the cleaned result */
r->headers_in = clean_headers;
}
/*
* scrub all mod_auth_openidc related headers
*/
void oidc_scrub_headers(request_rec *r) {
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
const char *prefix = oidc_cfg_claim_prefix(r);
apr_hash_t *hdrs = apr_hash_make(r->pool);
if (apr_strnatcmp(prefix, "") == 0) {
if ((cfg->white_listed_claims != NULL)
&& (apr_hash_count(cfg->white_listed_claims) > 0))
hdrs = apr_hash_overlay(r->pool, cfg->white_listed_claims, hdrs);
else
oidc_warn(r,
"both " OIDCClaimPrefix " and " OIDCWhiteListedClaims " are empty: this renders an insecure setup!");
}
char *authn_hdr = oidc_cfg_dir_authn_header(r);
if (authn_hdr != NULL)
apr_hash_set(hdrs, authn_hdr, APR_HASH_KEY_STRING, authn_hdr);
/*
* scrub all headers starting with OIDC_ first
*/
oidc_scrub_request_headers(r, OIDC_DEFAULT_HEADER_PREFIX, hdrs);
/*
* then see if the claim headers need to be removed on top of that
* (i.e. the prefix does not start with the default OIDC_)
*/
if ((strstr(prefix, OIDC_DEFAULT_HEADER_PREFIX) != prefix)) {
oidc_scrub_request_headers(r, prefix, NULL);
}
}
/*
* strip the session cookie from the headers sent to the application/backend
*/
void oidc_strip_cookies(request_rec *r) {
char *cookie, *ctx, *result = NULL;
const char *name = NULL;
int i;
apr_array_header_t *strip = oidc_dir_cfg_strip_cookies(r);
char *cookies = apr_pstrdup(r->pool, oidc_util_hdr_in_cookie_get(r));
if ((cookies != NULL) && (strip != NULL)) {
oidc_debug(r,
"looking for the following cookies to strip from cookie header: %s",
apr_array_pstrcat(r->pool, strip, OIDC_CHAR_COMMA));
cookie = apr_strtok(cookies, OIDC_STR_SEMI_COLON, &ctx);
do {
while (cookie != NULL && *cookie == OIDC_CHAR_SPACE)
cookie++;
for (i = 0; i < strip->nelts; i++) {
name = ((const char**) strip->elts)[i];
if ((strncmp(cookie, name, strlen(name)) == 0)
&& (cookie[strlen(name)] == OIDC_CHAR_EQUAL)) {
oidc_debug(r, "stripping: %s", name);
break;
}
}
if (i == strip->nelts) {
result = result ? apr_psprintf(r->pool, "%s%s%s", result,
OIDC_STR_SEMI_COLON, cookie) :
cookie;
}
cookie = apr_strtok(NULL, OIDC_STR_SEMI_COLON, &ctx);
} while (cookie != NULL);
oidc_util_hdr_in_cookie_set(r, result);
}
}
#define OIDC_SHA1_LEN 20
/*
* calculates a hash value based on request fingerprint plus a provided nonce string.
*/
static char *oidc_get_browser_state_hash(request_rec *r, const char *nonce) {
oidc_debug(r, "enter");
/* helper to hold to header values */
const char *value = NULL;
/* the hash context */
apr_sha1_ctx_t sha1;
/* Initialize the hash context */
apr_sha1_init(&sha1);
/* get the X-FORWARDED-FOR header value */
value = oidc_util_hdr_in_x_forwarded_for_get(r);
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, strlen(value));
/* get the USER-AGENT header value */
value = oidc_util_hdr_in_user_agent_get(r);
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, strlen(value));
/* get the remote client IP address or host name */
/*
int remotehost_is_ip;
value = ap_get_remote_host(r->connection, r->per_dir_config,
REMOTE_NOLOOKUP, &remotehost_is_ip);
apr_sha1_update(&sha1, value, strlen(value));
*/
/* concat the nonce parameter to the hash input */
apr_sha1_update(&sha1, nonce, strlen(nonce));
/* concat the token binding ID if present */
value = oidc_util_get_provided_token_binding_id(r);
if (value != NULL) {
oidc_debug(r,
"Provided Token Binding ID environment variable found; adding its value to the state");
apr_sha1_update(&sha1, value, strlen(value));
}
/* finalize the hash input and calculate the resulting hash output */
unsigned char hash[OIDC_SHA1_LEN];
apr_sha1_final(hash, &sha1);
/* base64url-encode the resulting hash and return it */
char *result = NULL;
oidc_base64url_encode(r, &result, (const char *) hash, OIDC_SHA1_LEN, TRUE);
return result;
}
/*
* return the name for the state cookie
*/
static char *oidc_get_state_cookie_name(request_rec *r, const char *state) {
return apr_psprintf(r->pool, "%s%s", OIDC_STATE_COOKIE_PREFIX, state);
}
/*
* return the static provider configuration, i.e. from a metadata URL or configuration primitives
*/
static apr_byte_t oidc_provider_static_config(request_rec *r, oidc_cfg *c,
oidc_provider_t **provider) {
json_t *j_provider = NULL;
char *s_json = NULL;
/* see if we should configure a static provider based on external (cached) metadata */
if ((c->metadata_dir != NULL) || (c->provider.metadata_url == NULL)) {
*provider = &c->provider;
return TRUE;
}
oidc_cache_get_provider(r, c->provider.metadata_url, &s_json);
if (s_json == NULL) {
if (oidc_metadata_provider_retrieve(r, c, NULL,
c->provider.metadata_url, &j_provider, &s_json) == FALSE) {
oidc_error(r, "could not retrieve metadata from url: %s",
c->provider.metadata_url);
return FALSE;
}
oidc_cache_set_provider(r, c->provider.metadata_url, s_json,
apr_time_now() + (c->provider_metadata_refresh_interval <= 0 ? apr_time_from_sec( OIDC_CACHE_PROVIDER_METADATA_EXPIRY_DEFAULT) : c->provider_metadata_refresh_interval));
} else {
oidc_util_decode_json_object(r, s_json, &j_provider);
/* check to see if it is valid metadata */
if (oidc_metadata_provider_is_valid(r, c, j_provider, NULL) == FALSE) {
oidc_error(r,
"cache corruption detected: invalid metadata from url: %s",
c->provider.metadata_url);
return FALSE;
}
}
*provider = apr_pcalloc(r->pool, sizeof(oidc_provider_t));
memcpy(*provider, &c->provider, sizeof(oidc_provider_t));
if (oidc_metadata_provider_parse(r, c, j_provider, *provider) == FALSE) {
oidc_error(r, "could not parse metadata from url: %s",
c->provider.metadata_url);
if (j_provider)
json_decref(j_provider);
return FALSE;
}
json_decref(j_provider);
return TRUE;
}
/*
* return the oidc_provider_t struct for the specified issuer
*/
static oidc_provider_t *oidc_get_provider_for_issuer(request_rec *r,
oidc_cfg *c, const char *issuer, apr_byte_t allow_discovery) {
/* by default we'll assume that we're dealing with a single statically configured OP */
oidc_provider_t *provider = NULL;
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return NULL;
/* unless a metadata directory was configured, so we'll try and get the provider settings from there */
if (c->metadata_dir != NULL) {
/* try and get metadata from the metadata directory for the OP that sent this response */
if ((oidc_metadata_get(r, c, issuer, &provider, allow_discovery)
== FALSE) || (provider == NULL)) {
/* don't know nothing about this OP/issuer */
oidc_error(r, "no provider metadata found for issuer \"%s\"",
issuer);
return NULL;
}
}
return provider;
}
/*
* find out whether the request is a response from an IDP discovery page
*/
static apr_byte_t oidc_is_discovery_response(request_rec *r, oidc_cfg *cfg) {
/*
* prereq: this is a call to the configured redirect_uri, now see if:
* the OIDC_DISC_OP_PARAM is present
*/
return oidc_util_request_has_parameter(r, OIDC_DISC_OP_PARAM)
|| oidc_util_request_has_parameter(r, OIDC_DISC_USER_PARAM);
}
/*
* return the HTTP method being called: only for POST data persistence purposes
*/
static const char *oidc_original_request_method(request_rec *r, oidc_cfg *cfg,
apr_byte_t handle_discovery_response) {
const char *method = OIDC_METHOD_GET;
char *m = NULL;
if ((handle_discovery_response == TRUE)
&& (oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, cfg)))
&& (oidc_is_discovery_response(r, cfg))) {
oidc_util_get_request_parameter(r, OIDC_DISC_RM_PARAM, &m);
if (m != NULL)
method = apr_pstrdup(r->pool, m);
} else {
/*
* if POST preserve is not enabled for this location, there's no point in preserving
* the method either which would result in POSTing empty data on return;
* so we revert to legacy behavior
*/
if (oidc_cfg_dir_preserve_post(r) == 0)
return OIDC_METHOD_GET;
const char *content_type = oidc_util_hdr_in_content_type_get(r);
if ((r->method_number == M_POST) && (apr_strnatcmp(content_type,
OIDC_CONTENT_TYPE_FORM_ENCODED) == 0))
method = OIDC_METHOD_FORM_POST;
}
oidc_debug(r, "return: %s", method);
return method;
}
/*
* send an OpenID Connect authorization request to the specified provider preserving POST parameters using HTML5 storage
*/
apr_byte_t oidc_post_preserve_javascript(request_rec *r, const char *location,
char **javascript, char **javascript_method) {
if (oidc_cfg_dir_preserve_post(r) == 0)
return FALSE;
oidc_debug(r, "enter");
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
const char *method = oidc_original_request_method(r, cfg, FALSE);
if (apr_strnatcmp(method, OIDC_METHOD_FORM_POST) != 0)
return FALSE;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return FALSE;
}
const apr_array_header_t *arr = apr_table_elts(params);
const apr_table_entry_t *elts = (const apr_table_entry_t*) arr->elts;
int i;
char *json = "";
for (i = 0; i < arr->nelts; i++) {
json = apr_psprintf(r->pool, "%s'%s': '%s'%s", json,
oidc_util_escape_string(r, elts[i].key),
oidc_util_escape_string(r, elts[i].val),
i < arr->nelts - 1 ? "," : "");
}
json = apr_psprintf(r->pool, "{ %s }", json);
const char *jmethod = "preserveOnLoad";
const char *jscript =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function %s() {\n"
" sessionStorage.setItem('mod_auth_openidc_preserve_post_params', JSON.stringify(%s));\n"
" %s"
" }\n"
" </script>\n", jmethod, json,
location ?
apr_psprintf(r->pool, "window.location='%s';\n",
location) :
"");
if (location == NULL) {
if (javascript_method)
*javascript_method = apr_pstrdup(r->pool, jmethod);
if (javascript)
*javascript = apr_pstrdup(r->pool, jscript);
} else {
oidc_util_html_send(r, "Preserving...", jscript, jmethod,
"<p>Preserving...</p>", OK);
}
return TRUE;
}
/*
* restore POST parameters on original_url from HTML5 local storage
*/
static int oidc_request_post_preserved_restore(request_rec *r,
const char *original_url) {
oidc_debug(r, "enter: original_url=%s", original_url);
const char *method = "postOnLoad";
const char *script =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function str_decode(string) {\n"
" try {\n"
" result = decodeURIComponent(string);\n"
" } catch (e) {\n"
" result = unescape(string);\n"
" }\n"
" return result;\n"
" }\n"
" function %s() {\n"
" var mod_auth_openidc_preserve_post_params = JSON.parse(sessionStorage.getItem('mod_auth_openidc_preserve_post_params'));\n"
" sessionStorage.removeItem('mod_auth_openidc_preserve_post_params');\n"
" for (var key in mod_auth_openidc_preserve_post_params) {\n"
" var input = document.createElement(\"input\");\n"
" input.name = str_decode(key);\n"
" input.value = str_decode(mod_auth_openidc_preserve_post_params[key]);\n"
" input.type = \"hidden\";\n"
" document.forms[0].appendChild(input);\n"
" }\n"
" document.forms[0].action = '%s';\n"
" document.forms[0].submit();\n"
" }\n"
" </script>\n", method, original_url);
const char *body = " <p>Restoring...</p>\n"
" <form method=\"post\"></form>\n";
return oidc_util_html_send(r, "Restoring...", script, method, body,
OK);
}
/*
* parse state that was sent to us by the issuer
*/
static apr_byte_t oidc_unsolicited_proto_state(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t **proto_state) {
char *alg = NULL;
oidc_debug(r, "enter: state header=%s",
oidc_proto_peek_jwt_header(r, state, &alg));
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret,
oidc_alg2keysize(alg), OIDC_JOSE_ALG_SHA256,
TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwt_t *jwt = NULL;
if (oidc_jwt_parse(r->pool, state, &jwt,
oidc_util_merge_symmetric_key(r->pool, c->private_keys, jwk),
&err) == FALSE) {
oidc_error(r,
"could not parse JWT from state: invalid unsolicited response: %s",
oidc_jose_e2s(r->pool, err));
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully parsed JWT from state");
if (jwt->payload.iss == NULL) {
oidc_error(r, "no \"%s\" could be retrieved from JWT state, aborting",
OIDC_CLAIM_ISS);
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_provider_t *provider = oidc_get_provider_for_issuer(r, c,
jwt->payload.iss, FALSE);
if (provider == NULL) {
oidc_jwt_destroy(jwt);
return FALSE;
}
/* validate the state JWT, validating optional exp + iat */
if (oidc_proto_validate_jwt(r, jwt, provider->issuer, FALSE, FALSE,
provider->idtoken_iat_slack,
OIDC_TOKEN_BINDING_POLICY_DISABLED) == FALSE) {
oidc_jwt_destroy(jwt);
return FALSE;
}
char *rfp = NULL;
if (oidc_jose_get_string(r->pool, jwt->payload.value.json, OIDC_CLAIM_RFP,
TRUE, &rfp, &err) == FALSE) {
oidc_error(r,
"no \"%s\" claim could be retrieved from JWT state, aborting: %s",
OIDC_CLAIM_RFP, oidc_jose_e2s(r->pool, err));
oidc_jwt_destroy(jwt);
return FALSE;
}
if (apr_strnatcmp(rfp, OIDC_PROTO_ISS) != 0) {
oidc_error(r, "\"%s\" (%s) does not match \"%s\", aborting",
OIDC_CLAIM_RFP, rfp, OIDC_PROTO_ISS);
oidc_jwt_destroy(jwt);
return FALSE;
}
char *target_link_uri = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_TARGET_LINK_URI,
FALSE, &target_link_uri, NULL);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
oidc_error(r,
"no \"%s\" claim could be retrieved from JWT state and no " OIDCDefaultURL " is set, aborting",
OIDC_CLAIM_TARGET_LINK_URI);
oidc_jwt_destroy(jwt);
return FALSE;
}
target_link_uri = c->default_sso_url;
}
if (c->metadata_dir != NULL) {
if ((oidc_metadata_get(r, c, jwt->payload.iss, &provider, FALSE)
== FALSE) || (provider == NULL)) {
oidc_error(r, "no provider metadata found for provider \"%s\"",
jwt->payload.iss);
oidc_jwt_destroy(jwt);
return FALSE;
}
}
char *jti = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json, OIDC_CLAIM_JTI,
FALSE, &jti,
NULL);
if (jti == NULL) {
char *cser = oidc_jwt_serialize(r->pool, jwt, &err);
if (cser == NULL)
return FALSE;
if (oidc_util_hash_string_and_base64url_encode(r, OIDC_JOSE_ALG_SHA256,
cser, &jti) == FALSE) {
oidc_error(r,
"oidc_util_hash_string_and_base64url_encode returned an error");
return FALSE;
}
}
char *replay = NULL;
oidc_cache_get_jti(r, jti, &replay);
if (replay != NULL) {
oidc_error(r,
"the \"%s\" value (%s) passed in the browser state was found in the cache already; possible replay attack!?",
OIDC_CLAIM_JTI, jti);
oidc_jwt_destroy(jwt);
return FALSE;
}
/* jti cache duration is the configured replay prevention window for token issuance plus 10 seconds for safety */
apr_time_t jti_cache_duration = apr_time_from_sec(
provider->idtoken_iat_slack * 2 + 10);
/* store it in the cache for the calculated duration */
oidc_cache_set_jti(r, jti, jti, apr_time_now() + jti_cache_duration);
oidc_debug(r,
"jti \"%s\" validated successfully and is now cached for %" APR_TIME_T_FMT " seconds",
jti, apr_time_sec(jti_cache_duration));
jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret, 0,
NULL, TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwks_uri_t jwks_uri = { provider->jwks_uri,
provider->jwks_refresh_interval, provider->ssl_validate_server };
if (oidc_proto_jwt_verify(r, c, jwt, &jwks_uri,
oidc_util_merge_symmetric_key(r->pool, NULL, jwk)) == FALSE) {
oidc_error(r, "state JWT could not be validated, aborting");
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully verified state JWT");
*proto_state = oidc_proto_state_new();
oidc_proto_state_set_issuer(*proto_state, jwt->payload.iss);
oidc_proto_state_set_original_url(*proto_state, target_link_uri);
oidc_proto_state_set_original_method(*proto_state, OIDC_METHOD_GET);
oidc_proto_state_set_response_mode(*proto_state, provider->response_mode);
oidc_proto_state_set_response_type(*proto_state, provider->response_type);
oidc_proto_state_set_timestamp_now(*proto_state);
oidc_jwt_destroy(jwt);
return TRUE;
}
typedef struct oidc_state_cookies_t {
char *name;
apr_time_t timestamp;
struct oidc_state_cookies_t *next;
} oidc_state_cookies_t;
static int oidc_delete_oldest_state_cookies(request_rec *r,
int number_of_valid_state_cookies, int max_number_of_state_cookies,
oidc_state_cookies_t *first) {
oidc_state_cookies_t *cur = NULL, *prev = NULL, *prev_oldest = NULL,
*oldest = NULL;
while (number_of_valid_state_cookies >= max_number_of_state_cookies) {
oldest = first;
prev_oldest = NULL;
prev = first;
cur = first->next;
while (cur) {
if ((cur->timestamp < oldest->timestamp)) {
oldest = cur;
prev_oldest = prev;
}
prev = cur;
cur = cur->next;
}
oidc_warn(r,
"deleting oldest state cookie: %s (time until expiry %" APR_TIME_T_FMT " seconds)",
oldest->name, apr_time_sec(oldest->timestamp - apr_time_now()));
oidc_util_set_cookie(r, oldest->name, "", 0, NULL);
if (prev_oldest)
prev_oldest->next = oldest->next;
else
first = first->next;
number_of_valid_state_cookies--;
}
return number_of_valid_state_cookies;
}
/*
* clean state cookies that have expired i.e. for outstanding requests that will never return
* successfully and return the number of remaining valid cookies/outstanding-requests while
* doing so
*/
static int oidc_clean_expired_state_cookies(request_rec *r, oidc_cfg *c,
const char *currentCookieName, int delete_oldest) {
int number_of_valid_state_cookies = 0;
oidc_state_cookies_t *first = NULL, *last = NULL;
char *cookie, *tokenizerCtx = NULL;
char *cookies = apr_pstrdup(r->pool, oidc_util_hdr_in_cookie_get(r));
if (cookies != NULL) {
cookie = apr_strtok(cookies, OIDC_STR_SEMI_COLON, &tokenizerCtx);
while (cookie != NULL) {
while (*cookie == OIDC_CHAR_SPACE)
cookie++;
if (strstr(cookie, OIDC_STATE_COOKIE_PREFIX) == cookie) {
char *cookieName = cookie;
while (cookie != NULL && *cookie != OIDC_CHAR_EQUAL)
cookie++;
if (*cookie == OIDC_CHAR_EQUAL) {
*cookie = '\0';
cookie++;
if ((currentCookieName == NULL)
|| (apr_strnatcmp(cookieName, currentCookieName)
!= 0)) {
oidc_proto_state_t *proto_state =
oidc_proto_state_from_cookie(r, c, cookie);
if (proto_state != NULL) {
json_int_t ts = oidc_proto_state_get_timestamp(
proto_state);
if (apr_time_now() > ts + apr_time_from_sec(c->state_timeout)) {
oidc_error(r,
"state (%s) has expired (original_url=%s)",
cookieName,
oidc_proto_state_get_original_url(
proto_state));
oidc_util_set_cookie(r, cookieName, "", 0,
NULL);
} else {
if (first == NULL) {
first = apr_pcalloc(r->pool,
sizeof(oidc_state_cookies_t));
last = first;
} else {
last->next = apr_pcalloc(r->pool,
sizeof(oidc_state_cookies_t));
last = last->next;
}
last->name = cookieName;
last->timestamp = ts;
last->next = NULL;
number_of_valid_state_cookies++;
}
oidc_proto_state_destroy(proto_state);
}
}
}
}
cookie = apr_strtok(NULL, OIDC_STR_SEMI_COLON, &tokenizerCtx);
}
}
if (delete_oldest > 0)
number_of_valid_state_cookies = oidc_delete_oldest_state_cookies(r,
number_of_valid_state_cookies, c->max_number_of_state_cookies,
first);
return number_of_valid_state_cookies;
}
/*
* restore the state that was maintained between authorization request and response in an encrypted cookie
*/
static apr_byte_t oidc_restore_proto_state(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t **proto_state) {
oidc_debug(r, "enter");
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* clean expired state cookies to avoid pollution */
oidc_clean_expired_state_cookies(r, c, cookieName, FALSE);
/* get the state cookie value first */
char *cookieValue = oidc_util_get_cookie(r, cookieName);
if (cookieValue == NULL) {
oidc_error(r, "no \"%s\" state cookie found", cookieName);
return oidc_unsolicited_proto_state(r, c, state, proto_state);
}
/* clear state cookie because we don't need it anymore */
oidc_util_set_cookie(r, cookieName, "", 0, NULL);
*proto_state = oidc_proto_state_from_cookie(r, c, cookieValue);
if (*proto_state == NULL)
return FALSE;
const char *nonce = oidc_proto_state_get_nonce(*proto_state);
/* calculate the hash of the browser fingerprint concatenated with the nonce */
char *calc = oidc_get_browser_state_hash(r, nonce);
/* compare the calculated hash with the value provided in the authorization response */
if (apr_strnatcmp(calc, state) != 0) {
oidc_error(r,
"calculated state from cookie does not match state parameter passed back in URL: \"%s\" != \"%s\"",
state, calc);
oidc_proto_state_destroy(*proto_state);
return FALSE;
}
apr_time_t ts = oidc_proto_state_get_timestamp(*proto_state);
/* check that the timestamp is not beyond the valid interval */
if (apr_time_now() > ts + apr_time_from_sec(c->state_timeout)) {
oidc_error(r, "state has expired");
/*
* note that this overrides redirection to the OIDCDefaultURL as done later...
* see: https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!msg/mod_auth_openidc/L4JFBw-XCNU/BWi2Fmk2AwAJ
*/
oidc_util_html_send_error(r, c->error_template,
"Invalid Authentication Response",
apr_psprintf(r->pool,
"This is due to a timeout; please restart your authentication session by re-entering the URL/bookmark you originally wanted to access: %s",
oidc_proto_state_get_original_url(*proto_state)),
OK);
oidc_proto_state_destroy(*proto_state);
return FALSE;
}
/* add the state */
oidc_proto_state_set_state(*proto_state, state);
/* log the restored state object */
oidc_debug(r, "restored state: %s",
oidc_proto_state_to_string(r, *proto_state));
/* we've made it */
return TRUE;
}
/*
* set the state that is maintained between an authorization request and an authorization response
* in a cookie in the browser that is cryptographically bound to that state
*/
static int oidc_authorization_request_set_cookie(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t *proto_state) {
/*
* create a cookie consisting of 8 elements:
* random value, original URL, original method, issuer, response_type, response_mod, prompt and timestamp
* encoded as JSON, encrypting the resulting JSON value
*/
char *cookieValue = oidc_proto_state_to_cookie(r, c, proto_state);
if (cookieValue == NULL)
return HTTP_INTERNAL_SERVER_ERROR;
/*
* clean expired state cookies to avoid pollution and optionally
* try to avoid the number of state cookies exceeding a max
*/
int number_of_cookies = oidc_clean_expired_state_cookies(r, c, NULL,
oidc_cfg_delete_oldest_state_cookies(c));
int max_number_of_cookies = oidc_cfg_max_number_of_state_cookies(c);
if ((max_number_of_cookies > 0)
&& (number_of_cookies >= max_number_of_cookies)) {
oidc_warn(r,
"the number of existing, valid state cookies (%d) has exceeded the limit (%d), no additional authorization request + state cookie can be generated, aborting the request",
number_of_cookies, max_number_of_cookies);
/*
* TODO: the html_send code below caters for the case that there's a user behind a
* browser generating this request, rather than a piece of XHR code; how would an
* XHR client handle this?
*/
/*
* it appears that sending content with a 503 turns the HTTP status code
* into a 200 so we'll avoid that for now: the user will see Apache specific
* readable text anyway
*
return oidc_util_html_send_error(r, c->error_template,
"Too Many Outstanding Requests",
apr_psprintf(r->pool,
"No authentication request could be generated since there are too many outstanding authentication requests already; you may have to wait up to %d seconds to be able to create a new request",
c->state_timeout),
HTTP_SERVICE_UNAVAILABLE);
*/
return HTTP_SERVICE_UNAVAILABLE;
}
/* assemble the cookie name for the state cookie */
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* set it as a cookie */
oidc_util_set_cookie(r, cookieName, cookieValue, -1,
c->cookie_same_site ? OIDC_COOKIE_EXT_SAME_SITE_LAX : NULL);
return HTTP_OK;
}
/*
* get the mod_auth_openidc related context from the (userdata in the) request
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
static apr_table_t *oidc_request_state(request_rec *rr) {
/* our state is always stored in the main request */
request_rec *r = (rr->main != NULL) ? rr->main : rr;
/* our state is a table, get it */
apr_table_t *state = NULL;
apr_pool_userdata_get((void **) &state, OIDC_USERDATA_KEY, r->pool);
/* if it does not exist, we'll create a new table */
if (state == NULL) {
state = apr_table_make(r->pool, 5);
apr_pool_userdata_set(state, OIDC_USERDATA_KEY, NULL, r->pool);
}
/* return the resulting table, always non-null now */
return state;
}
/*
* set a name/value pair in the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
void oidc_request_state_set(request_rec *r, const char *key, const char *value) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* put the name/value pair in that table */
apr_table_set(state, key, value);
}
/*
* get a name/value pair from the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
const char*oidc_request_state_get(request_rec *r, const char *key) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* return the value from the table */
return apr_table_get(state, key);
}
/*
* set the claims from a JSON object (c.q. id_token or user_info response) stored
* in the session in to HTTP headers passed on to the application
*/
static apr_byte_t oidc_set_app_claims(request_rec *r,
const oidc_cfg * const cfg, oidc_session_t *session,
const char *s_claims) {
json_t *j_claims = NULL;
/* decode the string-encoded attributes in to a JSON structure */
if (s_claims != NULL) {
if (oidc_util_decode_json_object(r, s_claims, &j_claims) == FALSE)
return FALSE;
}
/* set the resolved claims a HTTP headers for the application */
if (j_claims != NULL) {
oidc_util_set_app_infos(r, j_claims, oidc_cfg_claim_prefix(r),
cfg->claim_delimiter, oidc_cfg_dir_pass_info_in_headers(r),
oidc_cfg_dir_pass_info_in_envvars(r));
/* release resources */
json_decref(j_claims);
}
return TRUE;
}
static int oidc_authenticate_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, const char *original_url,
const char *login_hint, const char *id_token_hint, const char *prompt,
const char *auth_request_params, const char *path_scope);
/*
* log message about max session duration
*/
static void oidc_log_session_expires(request_rec *r, const char *msg,
apr_time_t session_expires) {
char buf[APR_RFC822_DATE_LEN + 1];
apr_rfc822_date(buf, session_expires);
oidc_debug(r, "%s: %s (in %" APR_TIME_T_FMT " secs from now)", msg, buf,
apr_time_sec(session_expires - apr_time_now()));
}
/*
* see if this is a non-browser request
*/
static apr_byte_t oidc_is_xml_http_request(request_rec *r) {
if ((oidc_util_hdr_in_x_requested_with_get(r) != NULL)
&& (apr_strnatcasecmp(oidc_util_hdr_in_x_requested_with_get(r),
OIDC_HTTP_HDR_VAL_XML_HTTP_REQUEST) == 0))
return TRUE;
if ((oidc_util_hdr_in_accept_contains(r, OIDC_CONTENT_TYPE_TEXT_HTML)
== FALSE) && (oidc_util_hdr_in_accept_contains(r,
OIDC_CONTENT_TYPE_APP_XHTML_XML) == FALSE)
&& (oidc_util_hdr_in_accept_contains(r,
OIDC_CONTENT_TYPE_ANY) == FALSE))
return TRUE;
return FALSE;
}
/*
* find out which action we need to take when encountering an unauthenticated request
*/
static int oidc_handle_unauthenticated_user(request_rec *r, oidc_cfg *c) {
/* see if we've configured OIDCUnAuthAction for this path */
switch (oidc_dir_cfg_unauth_action(r)) {
case OIDC_UNAUTH_RETURN410:
return HTTP_GONE;
case OIDC_UNAUTH_RETURN401:
return HTTP_UNAUTHORIZED;
case OIDC_UNAUTH_PASS:
r->user = "";
/*
* we're not going to pass information about an authenticated user to the application,
* but we do need to scrub the headers that mod_auth_openidc would set for security reasons
*/
oidc_scrub_headers(r);
return OK;
case OIDC_UNAUTH_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return HTTP_UNAUTHORIZED;
}
/*
* else: no session (regardless of whether it is main or sub-request),
* and we need to authenticate the user
*/
return oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
}
/*
* check if maximum session duration was exceeded
*/
static int oidc_check_max_session_duration(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
/* get the session expiry from the session data */
apr_time_t session_expires = oidc_session_get_session_expires(r, session);
/* check the expire timestamp against the current time */
if (apr_time_now() > session_expires) {
oidc_warn(r, "maximum session duration exceeded for user: %s",
session->remote_user);
oidc_session_kill(r, session);
return oidc_handle_unauthenticated_user(r, cfg);
}
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
return OK;
}
/*
* validate received session cookie against the domain it was issued for:
*
* this handles the case where the cache configured is a the same single memcache, Redis, or file
* backend for different (virtual) hosts, or a client-side cookie protected with the same secret
*
* it also handles the case that a cookie is unexpectedly shared across multiple hosts in
* name-based virtual hosting even though the OP(s) would be the same
*/
static apr_byte_t oidc_check_cookie_domain(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
const char *c_cookie_domain =
cfg->cookie_domain ?
cfg->cookie_domain : oidc_get_current_url_host(r);
const char *s_cookie_domain = oidc_session_get_cookie_domain(r, session);
if ((s_cookie_domain == NULL)
|| (apr_strnatcmp(c_cookie_domain, s_cookie_domain) != 0)) {
oidc_warn(r,
"aborting: detected attempt to play cookie against a different domain/host than issued for! (issued=%s, current=%s)",
s_cookie_domain, c_cookie_domain);
return FALSE;
}
return TRUE;
}
/*
* get a handle to the provider configuration via the "issuer" stored in the session
*/
apr_byte_t oidc_get_provider_from_session(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t **provider) {
oidc_debug(r, "enter");
/* get the issuer value from the session state */
const char *issuer = oidc_session_get_issuer(r, session);
if (issuer == NULL) {
oidc_error(r, "session corrupted: no issuer found in session");
return FALSE;
}
/* get the provider info associated with the issuer value */
oidc_provider_t *p = oidc_get_provider_for_issuer(r, c, issuer, FALSE);
if (p == NULL) {
oidc_error(r, "session corrupted: no provider found for issuer: %s",
issuer);
return FALSE;
}
*provider = p;
return TRUE;
}
/*
* store claims resolved from the userinfo endpoint in the session
*/
static void oidc_store_userinfo_claims(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider, const char *claims,
const char *userinfo_jwt) {
oidc_debug(r, "enter");
/* see if we've resolved any claims */
if (claims != NULL) {
/*
* Successfully decoded a set claims from the response so we can store them
* (well actually the stringified representation in the response)
* in the session context safely now
*/
oidc_session_set_userinfo_claims(r, session, claims);
if (c->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* this will also clear the entry if a JWT was not returned at this point */
oidc_session_set_userinfo_jwt(r, session, userinfo_jwt);
}
} else {
/*
* clear the existing claims because we could not refresh them
*/
oidc_session_set_userinfo_claims(r, session, NULL);
oidc_session_set_userinfo_jwt(r, session, NULL);
}
/* store the last refresh time if we've configured a userinfo refresh interval */
if (provider->userinfo_refresh_interval > 0)
oidc_session_reset_userinfo_last_refresh(r, session);
}
/*
* execute refresh token grant to refresh the existing access token
*/
static apr_byte_t oidc_refresh_access_token(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider,
char **new_access_token) {
oidc_debug(r, "enter");
/* get the refresh token that was stored in the session */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if (refresh_token == NULL) {
oidc_warn(r,
"refresh token routine called but no refresh_token found in the session");
return FALSE;
}
/* elements returned in the refresh response */
char *s_id_token = NULL;
int expires_in = -1;
char *s_token_type = NULL;
char *s_access_token = NULL;
char *s_refresh_token = NULL;
/* refresh the tokens by calling the token endpoint */
if (oidc_proto_refresh_request(r, c, provider, refresh_token, &s_id_token,
&s_access_token, &s_token_type, &expires_in,
&s_refresh_token) == FALSE) {
oidc_error(r, "access_token could not be refreshed");
return FALSE;
}
/* store the new access_token in the session and discard the old one */
oidc_session_set_access_token(r, session, s_access_token);
oidc_session_set_access_token_expires(r, session, expires_in);
/* reset the access token refresh timestamp */
oidc_session_reset_access_token_last_refresh(r, session);
/* see if we need to return it as a parameter */
if (new_access_token != NULL)
*new_access_token = s_access_token;
/* if we have a new refresh token (rolling refresh), store it in the session and overwrite the old one */
if (s_refresh_token != NULL)
oidc_session_set_refresh_token(r, session, s_refresh_token);
return TRUE;
}
/*
* retrieve claims from the userinfo endpoint and return the stringified response
*/
static const char *oidc_retrieve_claims_from_userinfo_endpoint(request_rec *r,
oidc_cfg *c, oidc_provider_t *provider, const char *access_token,
oidc_session_t *session, char *id_token_sub, char **userinfo_jwt) {
oidc_debug(r, "enter");
char *result = NULL;
char *refreshed_access_token = NULL;
/* see if a userinfo endpoint is set, otherwise there's nothing to do for us */
if (provider->userinfo_endpoint_url == NULL) {
oidc_debug(r,
"not retrieving userinfo claims because userinfo_endpoint is not set");
return NULL;
}
/* see if there's an access token, otherwise we can't call the userinfo endpoint at all */
if (access_token == NULL) {
oidc_debug(r,
"not retrieving userinfo claims because access_token is not provided");
return NULL;
}
if ((id_token_sub == NULL) && (session != NULL)) {
// when refreshing claims from the userinfo endpoint
json_t *id_token_claims = oidc_session_get_idtoken_claims_json(r,
session);
if (id_token_claims == NULL) {
oidc_error(r, "no id_token_claims found in session");
return NULL;
}
oidc_jose_get_string(r->pool, id_token_claims, OIDC_CLAIM_SUB, FALSE,
&id_token_sub, NULL);
}
// TODO: return code should indicate whether the token expired or some other error occurred
// TODO: long-term: session storage should be JSON (with explicit types and less conversion, using standard routines)
/* try to get claims from the userinfo endpoint using the provided access token */
if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub, access_token,
&result, userinfo_jwt) == FALSE) {
/* see if we have an existing session and we are refreshing the user info claims */
if (session != NULL) {
/* first call to user info endpoint failed, but the access token may have just expired, so refresh it */
if (oidc_refresh_access_token(r, c, session, provider,
&refreshed_access_token) == TRUE) {
/* try again with the new access token */
if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub,
refreshed_access_token, &result, userinfo_jwt) == FALSE) {
oidc_error(r,
"resolving user info claims with the refreshed access token failed, nothing will be stored in the session");
result = NULL;
}
} else {
oidc_warn(r,
"refreshing access token failed, claims will not be retrieved/refreshed from the userinfo endpoint");
result = NULL;
}
} else {
oidc_error(r,
"resolving user info claims with the existing/provided access token failed, nothing will be stored in the session");
result = NULL;
}
}
return result;
}
/*
* get (new) claims from the userinfo endpoint
*/
static apr_byte_t oidc_refresh_claims_from_userinfo_endpoint(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session) {
oidc_provider_t *provider = NULL;
const char *claims = NULL;
const char *access_token = NULL;
char *userinfo_jwt = NULL;
/* get the current provider info */
if (oidc_get_provider_from_session(r, cfg, session, &provider) == FALSE)
return FALSE;
/* see if we can do anything here, i.e. we have a userinfo endpoint and a refresh interval is configured */
apr_time_t interval = apr_time_from_sec(
provider->userinfo_refresh_interval);
oidc_debug(r, "userinfo_endpoint=%s, interval=%d",
provider->userinfo_endpoint_url,
provider->userinfo_refresh_interval);
if ((provider->userinfo_endpoint_url != NULL) && (interval > 0)) {
/* get the last refresh timestamp from the session info */
apr_time_t last_refresh = oidc_session_get_userinfo_last_refresh(r,
session);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(last_refresh + interval - apr_time_now()));
/* see if we need to refresh again */
if (last_refresh + interval < apr_time_now()) {
/* get the current access token */
access_token = oidc_session_get_access_token(r, session);
/* retrieve the current claims */
claims = oidc_retrieve_claims_from_userinfo_endpoint(r, cfg,
provider, access_token, session, NULL, &userinfo_jwt);
/* store claims resolved from userinfo endpoint */
oidc_store_userinfo_claims(r, cfg, session, provider, claims,
userinfo_jwt);
/* indicated something changed */
return TRUE;
}
}
return FALSE;
}
/*
* copy the claims and id_token from the session to the request state and optionally return them
*/
static void oidc_copy_tokens_to_request_state(request_rec *r,
oidc_session_t *session, const char **s_id_token, const char **s_claims) {
const char *id_token = oidc_session_get_idtoken_claims(r, session);
const char *claims = oidc_session_get_userinfo_claims(r, session);
oidc_debug(r, "id_token=%s claims=%s", id_token, claims);
if (id_token != NULL) {
oidc_request_state_set(r, OIDC_REQUEST_STATE_KEY_IDTOKEN, id_token);
if (s_id_token != NULL)
*s_id_token = id_token;
}
if (claims != NULL) {
oidc_request_state_set(r, OIDC_REQUEST_STATE_KEY_CLAIMS, claims);
if (s_claims != NULL)
*s_claims = claims;
}
}
/*
* pass refresh_token, access_token and access_token_expires as headers/environment variables to the application
*/
static apr_byte_t oidc_session_pass_tokens_and_save(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session, apr_byte_t needs_save) {
apr_byte_t pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
apr_byte_t pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
/* set the refresh_token in the app headers/variables, if enabled for this location/directory */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if ((oidc_cfg_dir_pass_refresh_token(r) != 0) && (refresh_token != NULL)) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_REFRESH_TOKEN, refresh_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* set the access_token in the app headers/variables */
const char *access_token = oidc_session_get_access_token(r, session);
if (access_token != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ACCESS_TOKEN, access_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* set the expiry timestamp in the app headers/variables */
const char *access_token_expires = oidc_session_get_access_token_expires(r,
session);
if (access_token_expires != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ACCESS_TOKEN_EXP,
access_token_expires,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/*
* reset the session inactivity timer
* but only do this once per 10% of the inactivity timeout interval (with a max to 60 seconds)
* for performance reasons
*
* now there's a small chance that the session ends 10% (or a minute) earlier than configured/expected
* cq. when there's a request after a recent save (so no update) and then no activity happens until
* a request comes in just before the session should expire
* ("recent" and "just before" refer to 10%-with-a-max-of-60-seconds of the inactivity interval after
* the start/last-update and before the expiry of the session respectively)
*
* this is be deemed acceptable here because of performance gain
*/
apr_time_t interval = apr_time_from_sec(cfg->session_inactivity_timeout);
apr_time_t now = apr_time_now();
apr_time_t slack = interval / 10;
if (slack > apr_time_from_sec(60))
slack = apr_time_from_sec(60);
if (session->expiry - now < interval - slack) {
session->expiry = now + interval;
needs_save = TRUE;
}
/* log message about session expiry */
oidc_log_session_expires(r, "session inactivity timeout", session->expiry);
/* check if something was updated in the session and we need to save it again */
if (needs_save)
if (oidc_session_save(r, session, FALSE) == FALSE)
return FALSE;
return TRUE;
}
static apr_byte_t oidc_refresh_access_token_before_expiry(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session, int ttl_minimum, int logout_on_error) {
const char *s_access_token_expires = NULL;
apr_time_t t_expires = -1;
oidc_provider_t *provider = NULL;
oidc_debug(r, "ttl_minimum=%d", ttl_minimum);
if (ttl_minimum < 0)
return FALSE;
s_access_token_expires = oidc_session_get_access_token_expires(r, session);
if (s_access_token_expires == NULL) {
oidc_debug(r,
"no access token expires_in stored in the session (i.e. returned from in the authorization response), so cannot refresh the access token based on TTL requirement");
return FALSE;
}
if (oidc_session_get_refresh_token(r, session) == NULL) {
oidc_debug(r,
"no refresh token stored in the session, so cannot refresh the access token based on TTL requirement");
return FALSE;
}
if (sscanf(s_access_token_expires, "%" APR_TIME_T_FMT, &t_expires) != 1) {
oidc_error(r, "could not parse s_access_token_expires %s",
s_access_token_expires);
return FALSE;
}
t_expires = apr_time_from_sec(t_expires - ttl_minimum);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(t_expires - apr_time_now()));
if (t_expires > apr_time_now())
return FALSE;
if (oidc_get_provider_from_session(r, cfg, session, &provider) == FALSE)
return FALSE;
if (oidc_refresh_access_token(r, cfg, session, provider,
NULL) == FALSE) {
oidc_warn(r, "access_token could not be refreshed, logout=%d", logout_on_error & OIDC_LOGOUT_ON_ERROR_REFRESH);
if (logout_on_error & OIDC_LOGOUT_ON_ERROR_REFRESH)
return ERROR;
else
return FALSE;
}
return TRUE;
}
/*
* handle the case where we have identified an existing authentication session for a user
*/
static int oidc_handle_existing_session(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
oidc_debug(r, "enter");
/* track if the session needs to be updated/saved into the cache */
apr_byte_t needs_save = FALSE;
/* set the user in the main request for further (incl. sub-request) processing */
r->user = apr_pstrdup(r->pool, session->remote_user);
oidc_debug(r, "set remote_user to \"%s\"", r->user);
/* get the header name in which the remote user name needs to be passed */
char *authn_header = oidc_cfg_dir_authn_header(r);
apr_byte_t pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
apr_byte_t pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
/* verify current cookie domain against issued cookie domain */
if (oidc_check_cookie_domain(r, cfg, session) == FALSE)
return HTTP_UNAUTHORIZED;
/* check if the maximum session duration was exceeded */
int rc = oidc_check_max_session_duration(r, cfg, session);
if (rc != OK)
return rc;
/* if needed, refresh the access token */
needs_save = oidc_refresh_access_token_before_expiry(r, cfg, session,
oidc_cfg_dir_refresh_access_token_before_expiry(r),
oidc_cfg_dir_logout_on_error_refresh(r));
if (needs_save == ERROR)
return oidc_handle_logout_request(r, cfg, session, cfg->default_slo_url);
/* if needed, refresh claims from the user info endpoint */
if (oidc_refresh_claims_from_userinfo_endpoint(r, cfg, session) == TRUE)
needs_save = TRUE;
/*
* we're going to pass the information that we have to the application,
* but first we need to scrub the headers that we're going to use for security reasons
*/
oidc_scrub_headers(r);
/* set the user authentication HTTP header if set and required */
if ((r->user != NULL) && (authn_header != NULL))
oidc_util_hdr_in_set(r, authn_header, r->user);
const char *s_claims = NULL;
const char *s_id_token = NULL;
/* copy id_token and claims from session to request state and obtain their values */
oidc_copy_tokens_to_request_state(r, session, &s_id_token, &s_claims);
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_CLAIMS)) {
/* set the userinfo claims in the app headers */
if (oidc_set_app_claims(r, cfg, session, s_claims) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_JSON_OBJECT)) {
/* pass the userinfo JSON object to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_USERINFO_JSON, s_claims,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_JWT)) {
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* get the compact serialized JWT from the session */
const char *s_userinfo_jwt = oidc_session_get_userinfo_jwt(r,
session);
if (s_userinfo_jwt != NULL) {
/* pass the compact serialized JWT to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_USERINFO_JWT,
s_userinfo_jwt,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
} else {
oidc_debug(r,
"configured to pass userinfo in a JWT, but no such JWT was found in the session (probably no such JWT was returned from the userinfo endpoint)");
}
} else {
oidc_error(r,
"session type \"client-cookie\" does not allow storing/passing a userinfo JWT; use \"" OIDCSessionType " server-cache\" for that");
}
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_CLAIMS)) {
/* set the id_token in the app headers */
if (oidc_set_app_claims(r, cfg, session, s_id_token) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_PAYLOAD)) {
/* pass the id_token JSON object to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ID_TOKEN_PAYLOAD, s_id_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_SERIALIZED)) {
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* get the compact serialized JWT from the session */
const char *s_id_token = oidc_session_get_idtoken(r, session);
/* pass the compact serialized JWT to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ID_TOKEN, s_id_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
} else {
oidc_error(r,
"session type \"client-cookie\" does not allow storing/passing the id_token; use \"" OIDCSessionType " server-cache\" for that");
}
}
/* pass the at, rt and at expiry to the application, possibly update the session expiry and save the session */
if (oidc_session_pass_tokens_and_save(r, cfg, session, needs_save) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* return "user authenticated" status */
return OK;
}
/*
* helper function for basic/implicit client flows upon receiving an authorization response:
* check that it matches the state stored in the browser and return the variables associated
* with the state, such as original_url and OP oidc_provider_t pointer.
*/
static apr_byte_t oidc_authorization_response_match_state(request_rec *r,
oidc_cfg *c, const char *state, struct oidc_provider_t **provider,
oidc_proto_state_t **proto_state) {
oidc_debug(r, "enter (state=%s)", state);
if ((state == NULL) || (apr_strnatcmp(state, "") == 0)) {
oidc_error(r, "state parameter is not set");
return FALSE;
}
/* check the state parameter against what we stored in a cookie */
if (oidc_restore_proto_state(r, c, state, proto_state) == FALSE) {
oidc_error(r, "unable to restore state");
return FALSE;
}
*provider = oidc_get_provider_for_issuer(r, c,
oidc_proto_state_get_issuer(*proto_state), FALSE);
return (*provider != NULL);
}
/*
* redirect the browser to the session logout endpoint
*/
static int oidc_session_redirect_parent_window_to_logout(request_rec *r,
oidc_cfg *c) {
oidc_debug(r, "enter");
char *java_script = apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" window.top.location.href = '%s?session=logout';\n"
" </script>\n", oidc_get_redirect_uri(r, c));
return oidc_util_html_send(r, "Redirecting...", java_script, NULL, NULL,
OK);
}
/*
* handle an error returned by the OP
*/
static int oidc_authorization_response_error(request_rec *r, oidc_cfg *c,
oidc_proto_state_t *proto_state, const char *error,
const char *error_description) {
const char *prompt = oidc_proto_state_get_prompt(proto_state);
if (prompt != NULL)
prompt = apr_pstrdup(r->pool, prompt);
oidc_proto_state_destroy(proto_state);
if ((prompt != NULL)
&& (apr_strnatcmp(prompt, OIDC_PROTO_PROMPT_NONE) == 0)) {
return oidc_session_redirect_parent_window_to_logout(r, c);
}
return oidc_util_html_send_error(r, c->error_template,
apr_psprintf(r->pool, "OpenID Connect Provider error: %s", error),
error_description, OK);
}
/*
* get the r->user for this request based on the configuration for OIDC/OAuth
*/
apr_byte_t oidc_get_remote_user(request_rec *r, const char *claim_name,
const char *reg_exp, const char *replace, json_t *json,
char **request_user) {
/* get the claim value from the JSON object */
json_t *username = json_object_get(json, claim_name);
if ((username == NULL) || (!json_is_string(username))) {
oidc_warn(r, "JSON object did not contain a \"%s\" string", claim_name);
return FALSE;
}
*request_user = apr_pstrdup(r->pool, json_string_value(username));
if (reg_exp != NULL) {
char *error_str = NULL;
if (replace == NULL) {
if (oidc_util_regexp_first_match(r->pool, *request_user, reg_exp,
request_user, &error_str) == FALSE) {
oidc_error(r, "oidc_util_regexp_first_match failed: %s",
error_str);
*request_user = NULL;
return FALSE;
}
} else if (oidc_util_regexp_substitute(r->pool, *request_user, reg_exp,
replace, request_user, &error_str) == FALSE) {
oidc_error(r, "oidc_util_regexp_substitute failed: %s", error_str);
*request_user = NULL;
return FALSE;
}
}
return TRUE;
}
/*
* set the unique user identifier that will be propagated in the Apache r->user and REMOTE_USER variables
*/
static apr_byte_t oidc_set_request_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, oidc_jwt_t *jwt, const char *s_claims) {
char *issuer = provider->issuer;
char *claim_name = apr_pstrdup(r->pool, c->remote_user_claim.claim_name);
int n = strlen(claim_name);
apr_byte_t post_fix_with_issuer = (claim_name[n - 1] == OIDC_CHAR_AT);
if (post_fix_with_issuer == TRUE) {
claim_name[n - 1] = '\0';
issuer =
(strstr(issuer, "https://") == NULL) ?
apr_pstrdup(r->pool, issuer) :
apr_pstrdup(r->pool, issuer + strlen("https://"));
}
/* extract the username claim (default: "sub") from the id_token payload or user claims */
apr_byte_t rc = FALSE;
char *remote_user = NULL;
json_t *claims = NULL;
oidc_util_decode_json_object(r, s_claims, &claims);
if (claims == NULL) {
rc = oidc_get_remote_user(r, claim_name, c->remote_user_claim.reg_exp,
c->remote_user_claim.replace, jwt->payload.value.json,
&remote_user);
} else {
oidc_util_json_merge(r, jwt->payload.value.json, claims);
rc = oidc_get_remote_user(r, claim_name, c->remote_user_claim.reg_exp,
c->remote_user_claim.replace, claims, &remote_user);
json_decref(claims);
}
if ((rc == FALSE) || (remote_user == NULL)) {
oidc_error(r,
"" OIDCRemoteUserClaim "is set to \"%s\", but could not set the remote user based on the requested claim \"%s\" and the available claims for the user",
c->remote_user_claim.claim_name, claim_name);
return FALSE;
}
if (post_fix_with_issuer == TRUE)
remote_user = apr_psprintf(r->pool, "%s%s%s", remote_user, OIDC_STR_AT,
issuer);
r->user = apr_pstrdup(r->pool, remote_user);
oidc_debug(r, "set remote_user to \"%s\" based on claim: \"%s\"%s", r->user,
c->remote_user_claim.claim_name,
c->remote_user_claim.reg_exp ?
apr_psprintf(r->pool,
" and expression: \"%s\" and replace string: \"%s\"",
c->remote_user_claim.reg_exp,
c->remote_user_claim.replace) :
"");
return TRUE;
}
static char *oidc_make_sid_iss_unique(request_rec *r, const char *sid,
const char *issuer) {
return apr_psprintf(r->pool, "%s@%s", sid, issuer);
}
/*
* store resolved information in the session
*/
static apr_byte_t oidc_save_in_session(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider,
const char *remoteUser, const char *id_token, oidc_jwt_t *id_token_jwt,
const char *claims, const char *access_token, const int expires_in,
const char *refresh_token, const char *session_state, const char *state,
const char *original_url, const char *userinfo_jwt) {
/* store the user in the session */
session->remote_user = remoteUser;
/* set the session expiry to the inactivity timeout */
session->expiry =
apr_time_now() + apr_time_from_sec(c->session_inactivity_timeout);
/* store the claims payload in the id_token for later reference */
oidc_session_set_idtoken_claims(r, session,
id_token_jwt->payload.value.str);
if (c->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* store the compact serialized representation of the id_token for later reference */
oidc_session_set_idtoken(r, session, id_token);
}
/* store the issuer in the session (at least needed for session mgmt and token refresh */
oidc_session_set_issuer(r, session, provider->issuer);
/* store the state and original URL in the session for handling browser-back more elegantly */
oidc_session_set_request_state(r, session, state);
oidc_session_set_original_url(r, session, original_url);
if ((session_state != NULL) && (provider->check_session_iframe != NULL)) {
/* store the session state and required parameters session management */
oidc_session_set_session_state(r, session, session_state);
oidc_debug(r,
"session management enabled: stored session_state (%s), check_session_iframe (%s) and client_id (%s) in the session",
session_state, provider->check_session_iframe,
provider->client_id);
} else if (provider->check_session_iframe == NULL) {
oidc_debug(r,
"session management disabled: \"check_session_iframe\" is not set in provider configuration");
} else {
oidc_debug(r,
"session management disabled: no \"session_state\" value is provided in the authentication response even though \"check_session_iframe\" (%s) is set in the provider configuration",
provider->check_session_iframe);
}
/* store claims resolved from userinfo endpoint */
oidc_store_userinfo_claims(r, c, session, provider, claims, userinfo_jwt);
/* see if we have an access_token */
if (access_token != NULL) {
/* store the access_token in the session context */
oidc_session_set_access_token(r, session, access_token);
/* store the associated expires_in value */
oidc_session_set_access_token_expires(r, session, expires_in);
/* reset the access token refresh timestamp */
oidc_session_reset_access_token_last_refresh(r, session);
}
/* see if we have a refresh_token */
if (refresh_token != NULL) {
/* store the refresh_token in the session context */
oidc_session_set_refresh_token(r, session, refresh_token);
}
/* store max session duration in the session as a hard cut-off expiry timestamp */
apr_time_t session_expires =
(provider->session_max_duration == 0) ?
apr_time_from_sec(id_token_jwt->payload.exp) :
(apr_time_now()
+ apr_time_from_sec(provider->session_max_duration));
oidc_session_set_session_expires(r, session, session_expires);
oidc_debug(r,
"provider->session_max_duration = %d, session_expires=%" APR_TIME_T_FMT,
provider->session_max_duration, session_expires);
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
/* store the domain for which this session is valid */
oidc_session_set_cookie_domain(r, session,
c->cookie_domain ? c->cookie_domain : oidc_get_current_url_host(r));
char *sid = NULL;
oidc_debug(r, "provider->backchannel_logout_supported=%d",
provider->backchannel_logout_supported);
if (provider->backchannel_logout_supported > 0) {
oidc_jose_get_string(r->pool, id_token_jwt->payload.value.json,
OIDC_CLAIM_SID, FALSE, &sid, NULL);
if (sid == NULL)
sid = id_token_jwt->payload.sub;
session->sid = oidc_make_sid_iss_unique(r, sid, provider->issuer);
}
/* store the session */
return oidc_session_save(r, session, TRUE);
}
/*
* parse the expiry for the access token
*/
static int oidc_parse_expires_in(request_rec *r, const char *expires_in) {
if (expires_in != NULL) {
char *ptr = NULL;
long number = strtol(expires_in, &ptr, 10);
if (number <= 0) {
oidc_warn(r,
"could not convert \"expires_in\" value (%s) to a number",
expires_in);
return -1;
}
return number;
}
return -1;
}
/*
* handle the different flows (hybrid, implicit, Authorization Code)
*/
static apr_byte_t oidc_handle_flows(request_rec *r, oidc_cfg *c,
oidc_proto_state_t *proto_state, oidc_provider_t *provider,
apr_table_t *params, const char *response_mode, oidc_jwt_t **jwt) {
apr_byte_t rc = FALSE;
const char *requested_response_type = oidc_proto_state_get_response_type(
proto_state);
/* handle the requested response type/mode */
if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_IDTOKEN_TOKEN)) {
rc = oidc_proto_authorization_response_code_idtoken_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_IDTOKEN)) {
rc = oidc_proto_authorization_response_code_idtoken(r, c, proto_state,
provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_TOKEN)) {
rc = oidc_proto_handle_authorization_response_code_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE)) {
rc = oidc_proto_handle_authorization_response_code(r, c, proto_state,
provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_IDTOKEN_TOKEN)) {
rc = oidc_proto_handle_authorization_response_idtoken_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_IDTOKEN)) {
rc = oidc_proto_handle_authorization_response_idtoken(r, c, proto_state,
provider, params, response_mode, jwt);
} else {
oidc_error(r, "unsupported response type: \"%s\"",
requested_response_type);
}
if ((rc == FALSE) && (*jwt != NULL)) {
oidc_jwt_destroy(*jwt);
*jwt = NULL;
}
return rc;
}
/* handle the browser back on an authorization response */
static apr_byte_t oidc_handle_browser_back(request_rec *r, const char *r_state,
oidc_session_t *session) {
/* see if we have an existing session and browser-back was used */
const char *s_state = NULL, *o_url = NULL;
if (session->remote_user != NULL) {
s_state = oidc_session_get_request_state(r, session);
o_url = oidc_session_get_original_url(r, session);
if ((r_state != NULL) && (s_state != NULL)
&& (apr_strnatcmp(r_state, s_state) == 0)) {
/* log the browser back event detection */
oidc_warn(r,
"browser back detected, redirecting to original URL: %s",
o_url);
/* go back to the URL that he originally tried to access */
oidc_util_hdr_out_location_set(r, o_url);
return TRUE;
}
}
return FALSE;
}
/*
* complete the handling of an authorization response by obtaining, parsing and verifying the
* id_token and storing the authenticated user state in the session
*/
static int oidc_handle_authorization_response(request_rec *r, oidc_cfg *c,
oidc_session_t *session, apr_table_t *params, const char *response_mode) {
oidc_debug(r, "enter, response_mode=%s", response_mode);
oidc_provider_t *provider = NULL;
oidc_proto_state_t *proto_state = NULL;
oidc_jwt_t *jwt = NULL;
/* see if this response came from a browser-back event */
if (oidc_handle_browser_back(r, apr_table_get(params, OIDC_PROTO_STATE),
session) == TRUE)
return HTTP_MOVED_TEMPORARILY;
/* match the returned state parameter against the state stored in the browser */
if (oidc_authorization_response_match_state(r, c,
apr_table_get(params, OIDC_PROTO_STATE), &provider,
&proto_state) == FALSE) {
if (c->default_sso_url != NULL) {
oidc_warn(r,
"invalid authorization response state; a default SSO URL is set, sending the user there: %s",
c->default_sso_url);
oidc_util_hdr_out_location_set(r, c->default_sso_url);
return HTTP_MOVED_TEMPORARILY;
}
oidc_error(r,
"invalid authorization response state and no default SSO URL is set, sending an error...");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if the response is an error response */
if (apr_table_get(params, OIDC_PROTO_ERROR) != NULL)
return oidc_authorization_response_error(r, c, proto_state,
apr_table_get(params, OIDC_PROTO_ERROR),
apr_table_get(params, OIDC_PROTO_ERROR_DESCRIPTION));
/* handle the code, implicit or hybrid flow */
if (oidc_handle_flows(r, c, proto_state, provider, params, response_mode,
&jwt) == FALSE)
return oidc_authorization_response_error(r, c, proto_state,
"Error in handling response type.", NULL);
if (jwt == NULL) {
oidc_error(r, "no id_token was provided");
return oidc_authorization_response_error(r, c, proto_state,
"No id_token was provided.", NULL);
}
int expires_in = oidc_parse_expires_in(r,
apr_table_get(params, OIDC_PROTO_EXPIRES_IN));
char *userinfo_jwt = NULL;
/*
* optionally resolve additional claims against the userinfo endpoint
* parsed claims are not actually used here but need to be parsed anyway for error checking purposes
*/
const char *claims = oidc_retrieve_claims_from_userinfo_endpoint(r, c,
provider, apr_table_get(params, OIDC_PROTO_ACCESS_TOKEN), NULL,
jwt->payload.sub, &userinfo_jwt);
/* restore the original protected URL that the user was trying to access */
const char *original_url = oidc_proto_state_get_original_url(proto_state);
if (original_url != NULL)
original_url = apr_pstrdup(r->pool, original_url);
const char *original_method = oidc_proto_state_get_original_method(
proto_state);
if (original_method != NULL)
original_method = apr_pstrdup(r->pool, original_method);
const char *prompt = oidc_proto_state_get_prompt(proto_state);
/* set the user */
if (oidc_set_request_user(r, c, provider, jwt, claims) == TRUE) {
/* session management: if the user in the new response is not equal to the old one, error out */
if ((prompt != NULL)
&& (apr_strnatcmp(prompt, OIDC_PROTO_PROMPT_NONE) == 0)) {
// TOOD: actually need to compare sub? (need to store it in the session separately then
//const char *sub = NULL;
//oidc_session_get(r, session, "sub", &sub);
//if (apr_strnatcmp(sub, jwt->payload.sub) != 0) {
if (apr_strnatcmp(session->remote_user, r->user) != 0) {
oidc_warn(r,
"user set from new id_token is different from current one");
oidc_jwt_destroy(jwt);
return oidc_authorization_response_error(r, c, proto_state,
"User changed!", NULL);
}
}
/* store resolved information in the session */
if (oidc_save_in_session(r, c, session, provider, r->user,
apr_table_get(params, OIDC_PROTO_ID_TOKEN), jwt, claims,
apr_table_get(params, OIDC_PROTO_ACCESS_TOKEN), expires_in,
apr_table_get(params, OIDC_PROTO_REFRESH_TOKEN),
apr_table_get(params, OIDC_PROTO_SESSION_STATE),
apr_table_get(params, OIDC_PROTO_STATE), original_url,
userinfo_jwt) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
} else {
oidc_error(r, "remote user could not be set");
return oidc_authorization_response_error(r, c, proto_state,
"Remote user could not be set: contact the website administrator",
NULL);
}
/* cleanup */
oidc_proto_state_destroy(proto_state);
oidc_jwt_destroy(jwt);
/* check that we've actually authenticated a user; functions as error handling for oidc_get_remote_user */
if (r->user == NULL)
return HTTP_UNAUTHORIZED;
/* log the successful response */
oidc_debug(r,
"session created and stored, returning to original URL: %s, original method: %s",
original_url, original_method);
/* check whether form post data was preserved; if so restore it */
if (apr_strnatcmp(original_method, OIDC_METHOD_FORM_POST) == 0) {
return oidc_request_post_preserved_restore(r, original_url);
}
/* now we've authenticated the user so go back to the URL that he originally tried to access */
oidc_util_hdr_out_location_set(r, original_url);
/* do the actual redirect to the original URL */
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle an OpenID Connect Authorization Response using the POST (+fragment->POST) response_mode
*/
static int oidc_handle_post_authorization_response(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
oidc_debug(r, "enter");
/* initialize local variables */
char *response_mode = NULL;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if we've got any POST-ed data at all */
if ((apr_table_elts(params)->nelts < 1)
|| ((apr_table_elts(params)->nelts == 1)
&& apr_table_get(params, OIDC_PROTO_RESPONSE_MODE)
&& (apr_strnatcmp(
apr_table_get(params, OIDC_PROTO_RESPONSE_MODE),
OIDC_PROTO_RESPONSE_MODE_FRAGMENT) == 0))) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"You've hit an OpenID Connect Redirect URI with no parameters, this is an invalid request; you should not open this URL in your browser directly, or have the server administrator use a different " OIDCRedirectURI " setting.",
HTTP_INTERNAL_SERVER_ERROR);
}
/* get the parameters */
response_mode = (char *) apr_table_get(params, OIDC_PROTO_RESPONSE_MODE);
/* do the actual implicit work */
return oidc_handle_authorization_response(r, c, session, params,
response_mode ? response_mode : OIDC_PROTO_RESPONSE_MODE_FORM_POST);
}
/*
* handle an OpenID Connect Authorization Response using the redirect response_mode
*/
static int oidc_handle_redirect_authorization_response(request_rec *r,
oidc_cfg *c, oidc_session_t *session) {
oidc_debug(r, "enter");
/* read the parameters from the query string */
apr_table_t *params = apr_table_make(r->pool, 8);
oidc_util_read_form_encoded_params(r, params, r->args);
/* do the actual work */
return oidc_handle_authorization_response(r, c, session, params,
OIDC_PROTO_RESPONSE_MODE_QUERY);
}
/*
* present the user with an OP selection screen
*/
static int oidc_discovery(request_rec *r, oidc_cfg *cfg) {
oidc_debug(r, "enter");
/* obtain the URL we're currently accessing, to be stored in the state/session */
char *current_url = oidc_get_current_url(r);
const char *method = oidc_original_request_method(r, cfg, FALSE);
/* generate CSRF token */
char *csrf = NULL;
if (oidc_proto_generate_nonce(r, &csrf, 8) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
char *path_scopes = oidc_dir_cfg_path_scope(r);
char *path_auth_request_params = oidc_dir_cfg_path_auth_request_params(r);
char *discover_url = oidc_cfg_dir_discover_url(r);
/* see if there's an external discovery page configured */
if (discover_url != NULL) {
/* yes, assemble the parameters for external discovery */
char *url = apr_psprintf(r->pool, "%s%s%s=%s&%s=%s&%s=%s&%s=%s",
discover_url,
strchr(discover_url, OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
OIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url),
OIDC_DISC_RM_PARAM, method,
OIDC_DISC_CB_PARAM,
oidc_util_escape_string(r, oidc_get_redirect_uri(r, cfg)),
OIDC_CSRF_NAME, oidc_util_escape_string(r, csrf));
if (path_scopes != NULL)
url = apr_psprintf(r->pool, "%s&%s=%s", url, OIDC_DISC_SC_PARAM,
oidc_util_escape_string(r, path_scopes));
if (path_auth_request_params != NULL)
url = apr_psprintf(r->pool, "%s&%s=%s", url, OIDC_DISC_AR_PARAM,
oidc_util_escape_string(r, path_auth_request_params));
/* log what we're about to do */
oidc_debug(r, "redirecting to external discovery page: %s", url);
/* set CSRF cookie */
oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1,
cfg->cookie_same_site ?
OIDC_COOKIE_EXT_SAME_SITE_STRICT :
NULL);
/* see if we need to preserve POST parameters through Javascript/HTML5 storage */
if (oidc_post_preserve_javascript(r, url, NULL, NULL) == TRUE)
return OK;
/* do the actual redirect to an external discovery page */
oidc_util_hdr_out_location_set(r, url);
return HTTP_MOVED_TEMPORARILY;
}
/* get a list of all providers configured in the metadata directory */
apr_array_header_t *arr = NULL;
if (oidc_metadata_list(r, cfg, &arr) == FALSE)
return oidc_util_html_send_error(r, cfg->error_template,
"Configuration Error",
"No configured providers found, contact your administrator",
HTTP_UNAUTHORIZED);
/* assemble a where-are-you-from IDP discovery HTML page */
const char *s = " <h3>Select your OpenID Connect Identity Provider</h3>\n";
/* list all configured providers in there */
int i;
for (i = 0; i < arr->nelts; i++) {
const char *issuer = ((const char**) arr->elts)[i];
// TODO: html escape (especially & character)
char *href = apr_psprintf(r->pool,
"%s?%s=%s&%s=%s&%s=%s&%s=%s",
oidc_get_redirect_uri(r, cfg), OIDC_DISC_OP_PARAM,
oidc_util_escape_string(r, issuer),
OIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url),
OIDC_DISC_RM_PARAM, method,
OIDC_CSRF_NAME, csrf);
if (path_scopes != NULL)
href = apr_psprintf(r->pool, "%s&%s=%s", href,
OIDC_DISC_SC_PARAM, oidc_util_escape_string(r, path_scopes));
if (path_auth_request_params != NULL)
href = apr_psprintf(r->pool, "%s&%s=%s", href,
OIDC_DISC_AR_PARAM,
oidc_util_escape_string(r, path_auth_request_params));
char *display =
(strstr(issuer, "https://") == NULL) ?
apr_pstrdup(r->pool, issuer) :
apr_pstrdup(r->pool, issuer + strlen("https://"));
/* strip port number */
//char *p = strstr(display, ":");
//if (p != NULL) *p = '\0';
/* point back to the redirect_uri, where the selection is handled, with an IDP selection and return_to URL */
s = apr_psprintf(r->pool, "%s<p><a href=\"%s\">%s</a></p>\n", s, href,
display);
}
/* add an option to enter an account or issuer name for dynamic OP discovery */
s = apr_psprintf(r->pool, "%s<form method=\"get\" action=\"%s\">\n", s,
oidc_get_redirect_uri(r, cfg));
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_RT_PARAM, current_url);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_RM_PARAM, method);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_CSRF_NAME, csrf);
if (path_scopes != NULL)
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_SC_PARAM, path_scopes);
if (path_auth_request_params != NULL)
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_AR_PARAM, path_auth_request_params);
s =
apr_psprintf(r->pool,
"%s<p>Or enter your account name (eg. "mike@seed.gluu.org", or an IDP identifier (eg. "mitreid.org"):</p>\n",
s);
s = apr_psprintf(r->pool,
"%s<p><input type=\"text\" name=\"%s\" value=\"%s\"></p>\n", s,
OIDC_DISC_OP_PARAM, "");
s = apr_psprintf(r->pool,
"%s<p><input type=\"submit\" value=\"Submit\"></p>\n", s);
s = apr_psprintf(r->pool, "%s</form>\n", s);
oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1,
cfg->cookie_same_site ? OIDC_COOKIE_EXT_SAME_SITE_STRICT : NULL);
char *javascript = NULL, *javascript_method = NULL;
char *html_head =
"<style type=\"text/css\">body {text-align: center}</style>";
if (oidc_post_preserve_javascript(r, NULL, &javascript,
&javascript_method) == TRUE)
html_head = apr_psprintf(r->pool, "%s%s", html_head, javascript);
/* now send the HTML contents to the user agent */
return oidc_util_html_send(r, "OpenID Connect Provider Discovery",
html_head, javascript_method, s, OK);
}
/*
* authenticate the user to the selected OP, if the OP is not selected yet perform discovery first
*/
static int oidc_authenticate_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, const char *original_url,
const char *login_hint, const char *id_token_hint, const char *prompt,
const char *auth_request_params, const char *path_scope) {
oidc_debug(r, "enter");
if (provider == NULL) {
// TODO: should we use an explicit redirect to the discovery endpoint (maybe a "discovery" param to the redirect_uri)?
if (c->metadata_dir != NULL)
return oidc_discovery(r, c);
/* we're not using multiple OP's configured in a metadata directory, pick the statically configured OP */
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
/* generate the random nonce value that correlates requests and responses */
char *nonce = NULL;
if (oidc_proto_generate_nonce(r, &nonce, OIDC_PROTO_NONCE_LENGTH) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
char *pkce_state = NULL;
char *code_challenge = NULL;
if ((oidc_util_spaced_string_contains(r->pool, provider->response_type,
OIDC_PROTO_CODE) == TRUE) && (provider->pkce != NULL)) {
/* generate the code verifier value that correlates authorization requests and code exchange requests */
if (provider->pkce->state(r, &pkce_state) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* generate the PKCE code challenge */
if (provider->pkce->challenge(r, pkce_state, &code_challenge) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
/* create the state between request/response */
oidc_proto_state_t *proto_state = oidc_proto_state_new();
oidc_proto_state_set_original_url(proto_state, original_url);
oidc_proto_state_set_original_method(proto_state,
oidc_original_request_method(r, c, TRUE));
oidc_proto_state_set_issuer(proto_state, provider->issuer);
oidc_proto_state_set_response_type(proto_state, provider->response_type);
oidc_proto_state_set_nonce(proto_state, nonce);
oidc_proto_state_set_timestamp_now(proto_state);
if (provider->response_mode)
oidc_proto_state_set_response_mode(proto_state,
provider->response_mode);
if (prompt)
oidc_proto_state_set_prompt(proto_state, prompt);
if (pkce_state)
oidc_proto_state_set_pkce_state(proto_state, pkce_state);
/* get a hash value that fingerprints the browser concatenated with the random input */
char *state = oidc_get_browser_state_hash(r, nonce);
/*
* create state that restores the context when the authorization response comes in
* and cryptographically bind it to the browser
*/
int rc = oidc_authorization_request_set_cookie(r, c, state, proto_state);
if (rc != HTTP_OK) {
oidc_proto_state_destroy(proto_state);
return rc;
}
/*
* printout errors if Cookie settings are not going to work
* TODO: separate this code out into its own function
*/
apr_uri_t o_uri;
memset(&o_uri, 0, sizeof(apr_uri_t));
apr_uri_t r_uri;
memset(&r_uri, 0, sizeof(apr_uri_t));
apr_uri_parse(r->pool, original_url, &o_uri);
apr_uri_parse(r->pool, oidc_get_redirect_uri(r, c), &r_uri);
if ((apr_strnatcmp(o_uri.scheme, r_uri.scheme) != 0)
&& (apr_strnatcmp(r_uri.scheme, "https") == 0)) {
oidc_error(r,
"the URL scheme (%s) of the configured " OIDCRedirectURI " does not match the URL scheme of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!",
r_uri.scheme, o_uri.scheme);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
if (c->cookie_domain == NULL) {
if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
char *p = strstr(o_uri.hostname, r_uri.hostname);
if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
oidc_error(r,
"the URL hostname (%s) of the configured " OIDCRedirectURI " does not match the URL hostname of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!",
r_uri.hostname, o_uri.hostname);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
} else {
if (!oidc_util_cookie_domain_valid(r_uri.hostname, c->cookie_domain)) {
oidc_error(r,
"the domain (%s) configured in " OIDCCookieDomain " does not match the URL hostname (%s) of the URL being accessed (%s): setting \"state\" and \"session\" cookies will not work!!",
c->cookie_domain, o_uri.hostname, original_url);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
/* send off to the OpenID Connect Provider */
// TODO: maybe show intermediate/progress screen "redirecting to"
return oidc_proto_authorization_request(r, provider, login_hint,
oidc_get_redirect_uri_iss(r, c, provider), state, proto_state,
id_token_hint, code_challenge, auth_request_params, path_scope);
}
/*
* check if the target_link_uri matches to configuration settings to prevent an open redirect
*/
static int oidc_target_link_uri_matches_configuration(request_rec *r,
oidc_cfg *cfg, const char *target_link_uri) {
apr_uri_t o_uri;
apr_uri_parse(r->pool, target_link_uri, &o_uri);
if (o_uri.hostname == NULL) {
oidc_error(r,
"could not parse the \"target_link_uri\" (%s) in to a valid URL: aborting.",
target_link_uri);
return FALSE;
}
apr_uri_t r_uri;
apr_uri_parse(r->pool, oidc_get_redirect_uri(r, cfg), &r_uri);
if (cfg->cookie_domain == NULL) {
/* cookie_domain set: see if the target_link_uri matches the redirect_uri host (because the session cookie will be set host-wide) */
if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
char *p = strstr(o_uri.hostname, r_uri.hostname);
if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
oidc_error(r,
"the URL hostname (%s) of the configured " OIDCRedirectURI " does not match the URL hostname of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
r_uri.hostname, o_uri.hostname);
return FALSE;
}
}
} else {
/* cookie_domain set: see if the target_link_uri is within the cookie_domain */
char *p = strstr(o_uri.hostname, cfg->cookie_domain);
if ((p == NULL) || (apr_strnatcmp(cfg->cookie_domain, p) != 0)) {
oidc_error(r,
"the domain (%s) configured in " OIDCCookieDomain " does not match the URL hostname (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.hostname, target_link_uri);
return FALSE;
}
}
/* see if the cookie_path setting matches the target_link_uri path */
char *cookie_path = oidc_cfg_dir_cookie_path(r);
if (cookie_path != NULL) {
char *p = (o_uri.path != NULL) ? strstr(o_uri.path, cookie_path) : NULL;
if ((p == NULL) || (p != o_uri.path)) {
oidc_error(r,
"the path (%s) configured in " OIDCCookiePath " does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.path, target_link_uri);
return FALSE;
} else if (strlen(o_uri.path) > strlen(cookie_path)) {
int n = strlen(cookie_path);
if (cookie_path[n - 1] == OIDC_CHAR_FORWARD_SLASH)
n--;
if (o_uri.path[n] != OIDC_CHAR_FORWARD_SLASH) {
oidc_error(r,
"the path (%s) configured in " OIDCCookiePath " does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.path, target_link_uri);
return FALSE;
}
}
}
return TRUE;
}
/*
* handle a response from an IDP discovery page and/or handle 3rd-party initiated SSO
*/
static int oidc_handle_discovery_response(request_rec *r, oidc_cfg *c) {
/* variables to hold the values returned in the response */
char *issuer = NULL, *target_link_uri = NULL, *login_hint = NULL,
*auth_request_params = NULL, *csrf_cookie, *csrf_query = NULL,
*user = NULL, *path_scopes;
oidc_provider_t *provider = NULL;
oidc_util_get_request_parameter(r, OIDC_DISC_OP_PARAM, &issuer);
oidc_util_get_request_parameter(r, OIDC_DISC_USER_PARAM, &user);
oidc_util_get_request_parameter(r, OIDC_DISC_RT_PARAM, &target_link_uri);
oidc_util_get_request_parameter(r, OIDC_DISC_LH_PARAM, &login_hint);
oidc_util_get_request_parameter(r, OIDC_DISC_SC_PARAM, &path_scopes);
oidc_util_get_request_parameter(r, OIDC_DISC_AR_PARAM,
&auth_request_params);
oidc_util_get_request_parameter(r, OIDC_CSRF_NAME, &csrf_query);
csrf_cookie = oidc_util_get_cookie(r, OIDC_CSRF_NAME);
/* do CSRF protection if not 3rd party initiated SSO */
if (csrf_cookie) {
/* clean CSRF cookie */
oidc_util_set_cookie(r, OIDC_CSRF_NAME, "", 0, NULL);
/* compare CSRF cookie value with query parameter value */
if ((csrf_query == NULL)
|| apr_strnatcmp(csrf_query, csrf_cookie) != 0) {
oidc_warn(r,
"CSRF protection failed, no Discovery and dynamic client registration will be allowed");
csrf_cookie = NULL;
}
}
// TODO: trim issuer/accountname/domain input and do more input validation
oidc_debug(r,
"issuer=\"%s\", target_link_uri=\"%s\", login_hint=\"%s\", user=\"%s\"",
issuer, target_link_uri, login_hint, user);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"SSO to this module without specifying a \"target_link_uri\" parameter is not possible because " OIDCDefaultURL " is not set.",
HTTP_INTERNAL_SERVER_ERROR);
}
target_link_uri = c->default_sso_url;
}
/* do open redirect prevention */
if (oidc_target_link_uri_matches_configuration(r, c,
target_link_uri) == FALSE) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"\"target_link_uri\" parameter does not match configuration settings, aborting to prevent an open redirect.",
HTTP_UNAUTHORIZED);
}
/* see if this is a static setup */
if (c->metadata_dir == NULL) {
if ((oidc_provider_static_config(r, c, &provider) == TRUE)
&& (issuer != NULL)) {
if (apr_strnatcmp(provider->issuer, issuer) != 0) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
apr_psprintf(r->pool,
"The \"iss\" value must match the configured providers' one (%s != %s).",
issuer, c->provider.issuer),
HTTP_INTERNAL_SERVER_ERROR);
}
}
return oidc_authenticate_user(r, c, NULL, target_link_uri, login_hint,
NULL, NULL, auth_request_params, path_scopes);
}
/* find out if the user entered an account name or selected an OP manually */
if (user != NULL) {
if (login_hint == NULL)
login_hint = apr_pstrdup(r->pool, user);
/* normalize the user identifier */
if (strstr(user, "https://") != user)
user = apr_psprintf(r->pool, "https://%s", user);
/* got an user identifier as input, perform OP discovery with that */
if (oidc_proto_url_based_discovery(r, c, user, &issuer) == FALSE) {
/* something did not work out, show a user facing error */
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"Could not resolve the provided user identifier to an OpenID Connect provider; check your syntax.",
HTTP_NOT_FOUND);
}
/* issuer is set now, so let's continue as planned */
} else if (strstr(issuer, OIDC_STR_AT) != NULL) {
if (login_hint == NULL) {
login_hint = apr_pstrdup(r->pool, issuer);
//char *p = strstr(issuer, OIDC_STR_AT);
//*p = '\0';
}
/* got an account name as input, perform OP discovery with that */
if (oidc_proto_account_based_discovery(r, c, issuer, &issuer) == FALSE) {
/* something did not work out, show a user facing error */
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"Could not resolve the provided account name to an OpenID Connect provider; check your syntax.",
HTTP_NOT_FOUND);
}
/* issuer is set now, so let's continue as planned */
}
/* strip trailing '/' */
int n = strlen(issuer);
if (issuer[n - 1] == OIDC_CHAR_FORWARD_SLASH)
issuer[n - 1] = '\0';
/* try and get metadata from the metadata directories for the selected OP */
if ((oidc_metadata_get(r, c, issuer, &provider, csrf_cookie != NULL) == TRUE)
&& (provider != NULL)) {
/* now we've got a selected OP, send the user there to authenticate */
return oidc_authenticate_user(r, c, provider, target_link_uri,
login_hint, NULL, NULL, auth_request_params, path_scopes);
}
/* something went wrong */
return oidc_util_html_send_error(r, c->error_template, "Invalid Request",
"Could not find valid provider metadata for the selected OpenID Connect provider; contact the administrator",
HTTP_NOT_FOUND);
}
static apr_uint32_t oidc_transparent_pixel[17] = { 0x474e5089, 0x0a1a0a0d,
0x0d000000, 0x52444849, 0x01000000, 0x01000000, 0x00000408, 0x0c1cb500,
0x00000002, 0x4144490b, 0x639c7854, 0x0000cffa, 0x02010702, 0x71311c9a,
0x00000000, 0x444e4549, 0x826042ae };
static apr_byte_t oidc_is_front_channel_logout(const char *logout_param_value) {
return ((logout_param_value != NULL)
&& ((apr_strnatcmp(logout_param_value,
OIDC_GET_STYLE_LOGOUT_PARAM_VALUE) == 0)
|| (apr_strnatcmp(logout_param_value,
OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0)));
}
static apr_byte_t oidc_is_back_channel_logout(const char *logout_param_value) {
return ((logout_param_value != NULL) && (apr_strnatcmp(logout_param_value,
OIDC_BACKCHANNEL_STYLE_LOGOUT_PARAM_VALUE) == 0));
}
/*
* revoke refresh token and access token stored in the session if the
* OP has an RFC 7009 compliant token revocation endpoint
*/
static void oidc_revoke_tokens(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *response = NULL;
char *basic_auth = NULL;
char *bearer_auth = NULL;
apr_table_t *params = NULL;
const char *token = NULL;
oidc_provider_t *provider = NULL;
oidc_debug(r, "enter");
if (oidc_get_provider_from_session(r, c, session, &provider) == FALSE)
goto out;
oidc_debug(r, "revocation_endpoint=%s",
provider->revocation_endpoint_url ?
provider->revocation_endpoint_url : "(null)");
if (provider->revocation_endpoint_url == NULL)
goto out;
params = apr_table_make(r->pool, 4);
// add the token endpoint authentication credentials to the revocation endpoint call...
if (oidc_proto_token_endpoint_auth(r, c, provider->token_endpoint_auth,
provider->client_id, provider->client_secret,
provider->client_signing_keys, provider->token_endpoint_url, params,
NULL, &basic_auth, &bearer_auth) == FALSE)
goto out;
// TODO: use oauth.ssl_validate_server ...
token = oidc_session_get_refresh_token(r, session);
if (token != NULL) {
apr_table_addn(params, "token_type_hint", "refresh_token");
apr_table_addn(params, "token", token);
if (oidc_util_http_post_form(r, provider->revocation_endpoint_url,
params, basic_auth, bearer_auth, c->oauth.ssl_validate_server,
&response, c->http_timeout_long, c->outgoing_proxy,
oidc_dir_cfg_pass_cookies(r), NULL,
NULL) == FALSE) {
oidc_warn(r, "revoking refresh token failed");
}
apr_table_clear(params);
}
token = oidc_session_get_access_token(r, session);
if (token != NULL) {
apr_table_addn(params, "token_type_hint", "access_token");
apr_table_addn(params, "token", token);
if (oidc_util_http_post_form(r, provider->revocation_endpoint_url,
params, basic_auth, bearer_auth, c->oauth.ssl_validate_server,
&response, c->http_timeout_long, c->outgoing_proxy,
oidc_dir_cfg_pass_cookies(r), NULL,
NULL) == FALSE) {
oidc_warn(r, "revoking access token failed");
}
}
out:
oidc_debug(r, "leave");
}
/*
* handle a local logout
*/
static int oidc_handle_logout_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *url) {
oidc_debug(r, "enter (url=%s)", url);
/* if there's no remote_user then there's no (stored) session to kill */
if (session->remote_user != NULL) {
oidc_revoke_tokens(r, c, session);
/* remove session state (cq. cache entry and cookie) */
oidc_session_kill(r, session);
}
/* see if this is the OP calling us */
if (oidc_is_front_channel_logout(url)) {
/* set recommended cache control headers */
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_CACHE_CONTROL,
"no-cache, no-store");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_PRAGMA, "no-cache");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_P3P, "CAO PSA OUR");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_EXPIRES, "0");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_X_FRAME_OPTIONS, "DENY");
/* see if this is PF-PA style logout in which case we return a transparent pixel */
const char *accept = oidc_util_hdr_in_accept_get(r);
if ((apr_strnatcmp(url, OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0)
|| ((accept) && strstr(accept, OIDC_CONTENT_TYPE_IMAGE_PNG))) {
return oidc_util_http_send(r,
(const char *) &oidc_transparent_pixel,
sizeof(oidc_transparent_pixel), OIDC_CONTENT_TYPE_IMAGE_PNG,
OK);
}
/* standard HTTP based logout: should be called in an iframe from the OP */
return oidc_util_html_send(r, "Logged Out", NULL, NULL,
"<p>Logged Out</p>", OK);
}
/* see if we don't need to go somewhere special after killing the session locally */
if (url == NULL)
return oidc_util_html_send(r, "Logged Out", NULL, NULL,
"<p>Logged Out</p>", OK);
/* send the user to the specified where-to-go-after-logout URL */
oidc_util_hdr_out_location_set(r, url);
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle a backchannel logout
*/
#define OIDC_EVENTS_BLOGOUT_KEY "http://schemas.openid.net/event/backchannel-logout"
static int oidc_handle_logout_backchannel(request_rec *r, oidc_cfg *cfg) {
oidc_debug(r, "enter");
const char *logout_token = NULL;
oidc_jwt_t *jwt = NULL;
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
oidc_provider_t *provider = NULL;
char *sid = NULL, *uuid = NULL;
oidc_session_t session;
int rc = HTTP_BAD_REQUEST;
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r,
"could not read POST-ed parameters to the logout endpoint");
goto out;
}
logout_token = apr_table_get(params, OIDC_PROTO_LOGOUT_TOKEN);
if (logout_token == NULL) {
oidc_error(r,
"backchannel lggout endpoint was called but could not find a parameter named \"%s\"",
OIDC_PROTO_LOGOUT_TOKEN);
goto out;
}
// TODO: jwk symmetric key based on provider
// TODO: share more code with regular id_token validation and unsolicited state
if (oidc_jwt_parse(r->pool, logout_token, &jwt,
oidc_util_merge_symmetric_key(r->pool, cfg->private_keys, NULL),
&err) == FALSE) {
oidc_error(r, "oidc_jwt_parse failed: %s", oidc_jose_e2s(r->pool, err));
goto out;
}
provider = oidc_get_provider_for_issuer(r, cfg, jwt->payload.iss, FALSE);
if (provider == NULL) {
oidc_error(r, "no provider found for issuer: %s", jwt->payload.iss);
goto out;
}
// TODO: destroy the JWK used for decryption
jwk = NULL;
if (oidc_util_create_symmetric_key(r, provider->client_secret, 0,
NULL, TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwks_uri_t jwks_uri = { provider->jwks_uri,
provider->jwks_refresh_interval, provider->ssl_validate_server };
if (oidc_proto_jwt_verify(r, cfg, jwt, &jwks_uri,
oidc_util_merge_symmetric_key(r->pool, NULL, jwk)) == FALSE) {
oidc_error(r, "id_token signature could not be validated, aborting");
goto out;
}
// oidc_proto_validate_idtoken would try and require a token binding cnf
// if the policy is set to "required", so don't use that here
if (oidc_proto_validate_jwt(r, jwt, provider->issuer, FALSE, FALSE,
provider->idtoken_iat_slack,
OIDC_TOKEN_BINDING_POLICY_DISABLED) == FALSE)
goto out;
/* verify the "aud" and "azp" values */
if (oidc_proto_validate_aud_and_azp(r, cfg, provider,
&jwt->payload) == FALSE)
goto out;
json_t *events = json_object_get(jwt->payload.value.json,
OIDC_CLAIM_EVENTS);
if (events == NULL) {
oidc_error(r, "\"%s\" claim could not be found in logout token",
OIDC_CLAIM_EVENTS);
goto out;
}
json_t *blogout = json_object_get(events, OIDC_EVENTS_BLOGOUT_KEY);
if (!json_is_object(blogout)) {
oidc_error(r, "\"%s\" object could not be found in \"%s\" claim",
OIDC_EVENTS_BLOGOUT_KEY, OIDC_CLAIM_EVENTS);
goto out;
}
char *nonce = NULL;
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_NONCE, &nonce, NULL);
if (nonce != NULL) {
oidc_error(r,
"rejecting logout request/token since it contains a \"%s\" claim",
OIDC_CLAIM_NONCE);
goto out;
}
char *jti = NULL;
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_JTI, &jti, NULL);
if (jti != NULL) {
char *replay = NULL;
oidc_cache_get_jti(r, jti, &replay);
if (replay != NULL) {
oidc_error(r,
"the \"%s\" value (%s) passed in logout token was found in the cache already; possible replay attack!?",
OIDC_CLAIM_JTI, jti);
goto out;
}
}
/* jti cache duration is the configured replay prevention window for token issuance plus 10 seconds for safety */
apr_time_t jti_cache_duration = apr_time_from_sec(
provider->idtoken_iat_slack * 2 + 10);
/* store it in the cache for the calculated duration */
oidc_cache_set_jti(r, jti, jti, apr_time_now() + jti_cache_duration);
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_EVENTS, &sid, NULL);
// TODO: by-spec we should cater for the fact that "sid" has been provided
// in the id_token returned in the authentication request, but "sub"
// is used in the logout token but that requires a 2nd entry in the
// cache and a separate session "sub" member, ugh; we'll just assume
// that is "sid" is specified in the id_token, the OP will actually use
// this for logout
// (and probably call us multiple times or the same sub if needed)
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_SID, &sid, NULL);
if (sid == NULL)
sid = jwt->payload.sub;
if (sid == NULL) {
oidc_error(r, "no \"sub\" and no \"sid\" claim found in logout token");
goto out;
}
// TODO: when dealing with sub instead of a true sid, we'll be killing all sessions for
// a specific user, across hosts that share the *same* cache backend
// if those hosts haven't been configured with a different OIDCCryptoPassphrase
// - perhaps that's even acceptable since non-memory caching is encrypted by default
// and memory-based caching doesn't suffer from this (different shm segments)?
// - it will result in 400 errors returned from backchannel logout calls to the other hosts...
sid = oidc_make_sid_iss_unique(r, sid, provider->issuer);
oidc_cache_get_sid(r, sid, &uuid);
if (uuid == NULL) {
oidc_error(r,
"could not find session based on sid/sub provided in logout token: %s",
sid);
goto out;
}
// revoke tokens if we can get a handle on those
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
if (oidc_session_load_cache_by_uuid(r, cfg, uuid, &session) != FALSE)
if (oidc_session_extract(r, &session) != FALSE)
oidc_revoke_tokens(r, cfg, &session);
}
// clear the session cache
oidc_cache_set_sid(r, sid, NULL, 0);
oidc_cache_set_session(r, uuid, NULL, 0);
rc = OK;
out:
if (jwk != NULL) {
oidc_jwk_destroy(jwk);
jwk = NULL;
}
if (jwt != NULL) {
oidc_jwt_destroy(jwt);
jwt = NULL;
}
return rc;
}
static apr_byte_t oidc_validate_post_logout_url(request_rec *r, const char *url,
char **err_str, char **err_desc) {
apr_uri_t uri;
const char *c_host = NULL;
if (apr_uri_parse(r->pool, url, &uri) != APR_SUCCESS) {
*err_str = apr_pstrdup(r->pool, "Malformed URL");
*err_desc = apr_psprintf(r->pool, "Logout URL malformed: %s", url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
c_host = oidc_get_current_url_host(r);
if ((uri.hostname != NULL)
&& ((strstr(c_host, uri.hostname) == NULL)
|| (strstr(uri.hostname, c_host) == NULL))) {
*err_str = apr_pstrdup(r->pool, "Invalid Request");
*err_desc =
apr_psprintf(r->pool,
"logout value \"%s\" does not match the hostname of the current request \"%s\"",
apr_uri_unparse(r->pool, &uri, 0), c_host);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
} else if (strstr(url, "/") != url) {
*err_str = apr_pstrdup(r->pool, "Malformed URL");
*err_desc =
apr_psprintf(r->pool,
"No hostname was parsed and it does not seem to be relative, i.e starting with '/': %s",
url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
/* validate the URL to prevent HTTP header splitting */
if (((strstr(url, "\n") != NULL) || strstr(url, "\r") != NULL)) {
*err_str = apr_pstrdup(r->pool, "Invalid Request");
*err_desc =
apr_psprintf(r->pool,
"logout value \"%s\" contains illegal \"\n\" or \"\r\" character(s)",
url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
return TRUE;
}
/*
* perform (single) logout
*/
static int oidc_handle_logout(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
oidc_provider_t *provider = NULL;
/* pickup the command or URL where the user wants to go after logout */
char *url = NULL;
char *error_str = NULL;
char *error_description = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_LOGOUT, &url);
oidc_debug(r, "enter (url=%s)", url);
if (oidc_is_front_channel_logout(url)) {
return oidc_handle_logout_request(r, c, session, url);
} else if (oidc_is_back_channel_logout(url)) {
return oidc_handle_logout_backchannel(r, c);
}
if ((url == NULL) || (apr_strnatcmp(url, "") == 0)) {
url = c->default_slo_url;
} else {
/* do input validation on the logout parameter value */
if (oidc_validate_post_logout_url(r, url, &error_str,
&error_description) == FALSE) {
return oidc_util_html_send_error(r, c->error_template, error_str,
error_description,
HTTP_BAD_REQUEST);
}
}
oidc_get_provider_from_session(r, c, session, &provider);
if ((provider != NULL) && (provider->end_session_endpoint != NULL)) {
const char *id_token_hint = oidc_session_get_idtoken(r, session);
char *logout_request = apr_pstrdup(r->pool,
provider->end_session_endpoint);
if (id_token_hint != NULL) {
logout_request = apr_psprintf(r->pool, "%s%sid_token_hint=%s",
logout_request, strchr(logout_request ? logout_request : "",
OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
oidc_util_escape_string(r, id_token_hint));
}
if (url != NULL) {
logout_request = apr_psprintf(r->pool,
"%s%spost_logout_redirect_uri=%s", logout_request,
strchr(logout_request ? logout_request : "",
OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
oidc_util_escape_string(r, url));
}
url = logout_request;
}
return oidc_handle_logout_request(r, c, session, url);
}
/*
* handle request for JWKs
*/
int oidc_handle_jwks(request_rec *r, oidc_cfg *c) {
/* pickup requested JWKs type */
// char *jwks_type = NULL;
// oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_JWKS, &jwks_type);
char *jwks = apr_pstrdup(r->pool, "{ \"keys\" : [");
apr_hash_index_t *hi = NULL;
apr_byte_t first = TRUE;
oidc_jose_error_t err;
if (c->public_keys != NULL) {
/* loop over the RSA public keys */
for (hi = apr_hash_first(r->pool, c->public_keys); hi; hi =
apr_hash_next(hi)) {
const char *s_kid = NULL;
oidc_jwk_t *jwk = NULL;
char *s_json = NULL;
apr_hash_this(hi, (const void**) &s_kid, NULL, (void**) &jwk);
if (oidc_jwk_to_json(r->pool, jwk, &s_json, &err) == TRUE) {
jwks = apr_psprintf(r->pool, "%s%s %s ", jwks, first ? "" : ",",
s_json);
first = FALSE;
} else {
oidc_error(r,
"could not convert RSA JWK to JSON using oidc_jwk_to_json: %s",
oidc_jose_e2s(r->pool, err));
}
}
}
// TODO: send stuff if first == FALSE?
jwks = apr_psprintf(r->pool, "%s ] }", jwks);
return oidc_util_http_send(r, jwks, strlen(jwks), OIDC_CONTENT_TYPE_JSON,
OK);
}
static int oidc_handle_session_management_iframe_op(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *check_session_iframe) {
oidc_debug(r, "enter");
oidc_util_hdr_out_location_set(r, check_session_iframe);
return HTTP_MOVED_TEMPORARILY;
}
static int oidc_handle_session_management_iframe_rp(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *client_id,
const char *check_session_iframe) {
oidc_debug(r, "enter");
const char *java_script =
" <script type=\"text/javascript\">\n"
" var targetOrigin = '%s';\n"
" var message = '%s' + ' ' + '%s';\n"
" var timerID;\n"
"\n"
" function checkSession() {\n"
" console.debug('checkSession: posting ' + message + ' to ' + targetOrigin);\n"
" var win = window.parent.document.getElementById('%s').contentWindow;\n"
" win.postMessage( message, targetOrigin);\n"
" }\n"
"\n"
" function setTimer() {\n"
" checkSession();\n"
" timerID = setInterval('checkSession()', %d);\n"
" }\n"
"\n"
" function receiveMessage(e) {\n"
" console.debug('receiveMessage: ' + e.data + ' from ' + e.origin);\n"
" if (e.origin !== targetOrigin ) {\n"
" console.debug('receiveMessage: cross-site scripting attack?');\n"
" return;\n"
" }\n"
" if (e.data != 'unchanged') {\n"
" clearInterval(timerID);\n"
" if (e.data == 'changed') {\n"
" window.location.href = '%s?session=check';\n"
" } else {\n"
" window.location.href = '%s?session=logout';\n"
" }\n"
" }\n"
" }\n"
"\n"
" window.addEventListener('message', receiveMessage, false);\n"
"\n"
" </script>\n";
/* determine the origin for the check_session_iframe endpoint */
char *origin = apr_pstrdup(r->pool, check_session_iframe);
apr_uri_t uri;
apr_uri_parse(r->pool, check_session_iframe, &uri);
char *p = strstr(origin, uri.path);
*p = '\0';
/* the element identifier for the OP iframe */
const char *op_iframe_id = "openidc-op";
/* restore the OP session_state from the session */
const char *session_state = oidc_session_get_session_state(r, session);
if (session_state == NULL) {
oidc_warn(r,
"no session_state found in the session; the OP does probably not support session management!?");
return OK;
}
char *s_poll_interval = NULL;
oidc_util_get_request_parameter(r, "poll", &s_poll_interval);
int poll_interval = s_poll_interval ? strtol(s_poll_interval, NULL, 10) : 0;
if ((poll_interval <= 0) || (poll_interval > 3600 * 24))
poll_interval = 3000;
const char *redirect_uri = oidc_get_redirect_uri(r, c);
java_script = apr_psprintf(r->pool, java_script, origin, client_id,
session_state, op_iframe_id, poll_interval, redirect_uri,
redirect_uri);
return oidc_util_html_send(r, NULL, java_script, "setTimer", NULL, OK);
}
/*
* handle session management request
*/
static int oidc_handle_session_management(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *cmd = NULL;
const char *id_token_hint = NULL;
oidc_provider_t *provider = NULL;
/* get the command passed to the session management handler */
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_SESSION, &cmd);
if (cmd == NULL) {
oidc_error(r, "session management handler called with no command");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if this is a local logout during session management */
if (apr_strnatcmp("logout", cmd) == 0) {
oidc_debug(r,
"[session=logout] calling oidc_handle_logout_request because of session mgmt local logout call.");
return oidc_handle_logout_request(r, c, session, c->default_slo_url);
}
oidc_get_provider_from_session(r, c, session, &provider);
/* see if this is a request for the OP iframe */
if (apr_strnatcmp("iframe_op", cmd) == 0) {
if (provider->check_session_iframe != NULL) {
return oidc_handle_session_management_iframe_op(r, c, session,
provider->check_session_iframe);
}
return HTTP_NOT_FOUND;
}
/* see if this is a request for the RP iframe */
if (apr_strnatcmp("iframe_rp", cmd) == 0) {
if ((provider->client_id != NULL)
&& (provider->check_session_iframe != NULL)) {
return oidc_handle_session_management_iframe_rp(r, c, session,
provider->client_id, provider->check_session_iframe);
}
oidc_debug(r,
"iframe_rp command issued but no client (%s) and/or no check_session_iframe (%s) set",
provider->client_id, provider->check_session_iframe);
return HTTP_NOT_FOUND;
}
/* see if this is a request check the login state with the OP */
if (apr_strnatcmp("check", cmd) == 0) {
id_token_hint = oidc_session_get_idtoken(r, session);
if ((session->remote_user != NULL) && (provider != NULL)) {
/*
* TODO: this doesn't work with per-path provided auth_request_params and scopes
* as oidc_dir_cfg_path_auth_request_params and oidc_dir_cfg_path_scope will pick
* those for the redirect_uri itself; do we need to store those as part of the
* session now?
*/
return oidc_authenticate_user(r, c, provider,
apr_psprintf(r->pool, "%s?session=iframe_rp",
oidc_get_redirect_uri_iss(r, c, provider)), NULL,
id_token_hint, "none",
oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
}
oidc_debug(r,
"[session=check] calling oidc_handle_logout_request because no session found.");
return oidc_session_redirect_parent_window_to_logout(r, c);
}
/* handle failure in fallthrough */
oidc_error(r, "unknown command: %s", cmd);
return HTTP_INTERNAL_SERVER_ERROR;
}
/*
* handle refresh token request
*/
static int oidc_handle_refresh_token_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *return_to = NULL;
char *r_access_token = NULL;
char *error_code = NULL;
/* get the command passed to the session management handler */
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_REFRESH,
&return_to);
oidc_util_get_request_parameter(r, OIDC_PROTO_ACCESS_TOKEN,
&r_access_token);
/* check the input parameters */
if (return_to == NULL) {
oidc_error(r,
"refresh token request handler called with no URL to return to");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (r_access_token == NULL) {
oidc_error(r,
"refresh token request handler called with no access_token parameter");
error_code = "no_access_token";
goto end;
}
const char *s_access_token = oidc_session_get_access_token(r, session);
if (s_access_token == NULL) {
oidc_error(r,
"no existing access_token found in the session, nothing to refresh");
error_code = "no_access_token_exists";
goto end;
}
/* compare the access_token parameter used for XSRF protection */
if (apr_strnatcmp(s_access_token, r_access_token) != 0) {
oidc_error(r,
"access_token passed in refresh request does not match the one stored in the session");
error_code = "no_access_token_match";
goto end;
}
/* get a handle to the provider configuration */
oidc_provider_t *provider = NULL;
if (oidc_get_provider_from_session(r, c, session, &provider) == FALSE) {
error_code = "session_corruption";
goto end;
}
/* execute the actual refresh grant */
if (oidc_refresh_access_token(r, c, session, provider, NULL) == FALSE) {
oidc_error(r, "access_token could not be refreshed");
error_code = "refresh_failed";
goto end;
}
/* pass the tokens to the application and save the session, possibly updating the expiry */
if (oidc_session_pass_tokens_and_save(r, c, session, TRUE) == FALSE) {
error_code = "session_corruption";
goto end;
}
end:
/* pass optional error message to the return URL */
if (error_code != NULL)
return_to = apr_psprintf(r->pool, "%s%serror_code=%s", return_to,
strchr(return_to ? return_to : "", OIDC_CHAR_QUERY) ?
OIDC_STR_AMP :
OIDC_STR_QUERY, oidc_util_escape_string(r, error_code));
/* add the redirect location header */
oidc_util_hdr_out_location_set(r, return_to);
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle request object by reference request
*/
static int oidc_handle_request_uri(request_rec *r, oidc_cfg *c) {
char *request_ref = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_REQUEST_URI,
&request_ref);
if (request_ref == NULL) {
oidc_error(r, "no \"%s\" parameter found",
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI);
return HTTP_BAD_REQUEST;
}
char *jwt = NULL;
oidc_cache_get_request_uri(r, request_ref, &jwt);
if (jwt == NULL) {
oidc_error(r, "no cached JWT found for %s reference: %s",
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI, request_ref);
return HTTP_NOT_FOUND;
}
oidc_cache_set_request_uri(r, request_ref, NULL, 0);
return oidc_util_http_send(r, jwt, strlen(jwt), OIDC_CONTENT_TYPE_JWT, OK);
}
/*
* handle a request to invalidate a cached access token introspection result
*/
int oidc_handle_remove_at_cache(request_rec *r, oidc_cfg *c) {
char *access_token = NULL;
oidc_util_get_request_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REMOVE_AT_CACHE, &access_token);
char *cache_entry = NULL;
oidc_cache_get_access_token(r, access_token, &cache_entry);
if (cache_entry == NULL) {
oidc_error(r, "no cached access token found for value: %s",
access_token);
return HTTP_NOT_FOUND;
}
oidc_cache_set_access_token(r, access_token, NULL, 0);
return OK;
}
#define OIDC_INFO_PARAM_ACCESS_TOKEN_REFRESH_INTERVAL "access_token_refresh_interval"
/*
* handle request for session info
*/
static int oidc_handle_info_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
int rc = HTTP_UNAUTHORIZED;
apr_byte_t needs_save = FALSE;
char *s_format = NULL, *s_interval = NULL, *r_value = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_INFO,
&s_format);
oidc_util_get_request_parameter(r,
OIDC_INFO_PARAM_ACCESS_TOKEN_REFRESH_INTERVAL, &s_interval);
/* see if this is a request for a format that is supported */
if ((apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_JSON, s_format) != 0)
&& (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_HTML, s_format) != 0)) {
oidc_warn(r, "request for unknown format: %s", s_format);
return HTTP_UNSUPPORTED_MEDIA_TYPE;
}
/* check that we actually have a user session and this is someone calling with a proper session cookie */
if (session->remote_user == NULL) {
oidc_warn(r, "no user session found");
return HTTP_UNAUTHORIZED;
}
/* set the user in the main request for further (incl. sub-request and authz) processing */
r->user = apr_pstrdup(r->pool, session->remote_user);
if (c->info_hook_data == NULL) {
oidc_warn(r, "no data configured to return in " OIDCInfoHook);
return HTTP_NOT_FOUND;
}
/* see if we can and need to refresh the access token */
if ((s_interval != NULL)
&& (oidc_session_get_refresh_token(r, session) != NULL)) {
apr_time_t t_interval;
if (sscanf(s_interval, "%" APR_TIME_T_FMT, &t_interval) == 1) {
t_interval = apr_time_from_sec(t_interval);
/* get the last refresh timestamp from the session info */
apr_time_t last_refresh =
oidc_session_get_access_token_last_refresh(r, session);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(last_refresh + t_interval - apr_time_now()));
/* see if we need to refresh again */
if (last_refresh + t_interval < apr_time_now()) {
/* get the current provider info */
oidc_provider_t *provider = NULL;
if (oidc_get_provider_from_session(r, c, session,
&provider) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* execute the actual refresh grant */
if (oidc_refresh_access_token(r, c, session, provider,
NULL) == FALSE)
oidc_warn(r, "access_token could not be refreshed");
else
needs_save = TRUE;
}
}
}
/* create the JSON object */
json_t *json = json_object();
/* add a timestamp of creation in there for the caller */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_TIMESTAMP,
APR_HASH_KEY_STRING)) {
json_object_set_new(json, OIDC_HOOK_INFO_TIMESTAMP,
json_integer(apr_time_sec(apr_time_now())));
}
/*
* refresh the claims from the userinfo endpoint
* side-effect is that this may refresh the access token if not already done
* note that OIDCUserInfoRefreshInterval should be set to control the refresh policy
*/
needs_save |= oidc_refresh_claims_from_userinfo_endpoint(r, c, session);
/* include the access token in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ACCES_TOKEN,
APR_HASH_KEY_STRING)) {
const char *access_token = oidc_session_get_access_token(r, session);
if (access_token != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_ACCES_TOKEN,
json_string(access_token));
}
/* include the access token expiry timestamp in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ACCES_TOKEN_EXP,
APR_HASH_KEY_STRING)) {
const char *access_token_expires =
oidc_session_get_access_token_expires(r, session);
if (access_token_expires != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_ACCES_TOKEN_EXP,
json_string(access_token_expires));
}
/* include the id_token claims in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ID_TOKEN,
APR_HASH_KEY_STRING)) {
json_t *id_token = oidc_session_get_idtoken_claims_json(r, session);
if (id_token)
json_object_set_new(json, OIDC_HOOK_INFO_ID_TOKEN, id_token);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_USER_INFO,
APR_HASH_KEY_STRING)) {
/* include the claims from the userinfo endpoint the session info */
json_t *claims = oidc_session_get_userinfo_claims_json(r, session);
if (claims)
json_object_set_new(json, OIDC_HOOK_INFO_USER_INFO, claims);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_SESSION,
APR_HASH_KEY_STRING)) {
json_t *j_session = json_object();
json_object_set(j_session, OIDC_HOOK_INFO_SESSION_STATE,
session->state);
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_UUID,
json_string(session->uuid));
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_TIMEOUT,
json_integer(apr_time_sec(session->expiry)));
apr_time_t session_expires = oidc_session_get_session_expires(r,
session);
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_EXP,
json_integer(apr_time_sec(session_expires)));
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_REMOTE_USER,
json_string(session->remote_user));
json_object_set_new(json, OIDC_HOOK_INFO_SESSION, j_session);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_REFRESH_TOKEN,
APR_HASH_KEY_STRING)) {
/* include the refresh token in the session info */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if (refresh_token != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_REFRESH_TOKEN,
json_string(refresh_token));
}
if (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_JSON, s_format) == 0) {
/* JSON-encode the result */
r_value = oidc_util_encode_json_object(r, json, 0);
/* return the stringified JSON result */
rc = oidc_util_http_send(r, r_value, strlen(r_value),
OIDC_CONTENT_TYPE_JSON, OK);
} else if (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_HTML, s_format) == 0) {
/* JSON-encode the result */
r_value = oidc_util_encode_json_object(r, json, JSON_INDENT(2));
rc = oidc_util_html_send(r, "Session Info", NULL, NULL,
apr_psprintf(r->pool, "<pre>%s</pre>", r_value), OK);
}
/* free the allocated resources */
json_decref(json);
/* pass the tokens to the application and save the session, possibly updating the expiry */
if (oidc_session_pass_tokens_and_save(r, c, session, needs_save) == FALSE) {
oidc_warn(r, "error saving session");
rc = HTTP_INTERNAL_SERVER_ERROR;
}
return rc;
}
/*
* handle all requests to the redirect_uri
*/
int oidc_handle_redirect_uri_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
if (oidc_proto_is_redirect_authorization_response(r, c)) {
/* this is an authorization response from the OP using the Basic Client profile or a Hybrid flow*/
return oidc_handle_redirect_authorization_response(r, c, session);
/*
*
* Note that we are checking for logout *before* checking for a POST authorization response
* to handle backchannel POST-based logout
*
* so any POST to the Redirect URI that does not have a logout query parameter will be handled
* as an authorization response; alternatively we could assume that a POST response has no
* parameters
*/
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_LOGOUT)) {
/* handle logout */
return oidc_handle_logout(r, c, session);
} else if (oidc_proto_is_post_authorization_response(r, c)) {
/* this is an authorization response using the fragment(+POST) response_mode with the Implicit Client profile */
return oidc_handle_post_authorization_response(r, c, session);
} else if (oidc_is_discovery_response(r, c)) {
/* this is response from the OP discovery page */
return oidc_handle_discovery_response(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_JWKS)) {
/* handle JWKs request */
return oidc_handle_jwks(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_SESSION)) {
/* handle session management request */
return oidc_handle_session_management(r, c, session);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REFRESH)) {
/* handle refresh token request */
return oidc_handle_refresh_token_request(r, c, session);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI)) {
/* handle request object by reference request */
return oidc_handle_request_uri(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REMOVE_AT_CACHE)) {
/* handle request to invalidate access token cache */
return oidc_handle_remove_at_cache(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_INFO)) {
if (session->remote_user == NULL)
return HTTP_UNAUTHORIZED;
/* set r->user, set headers/env-vars, update expiry, update userinfo + AT */
int rc = oidc_handle_existing_session(r, c, session);
if (rc != OK)
return rc;
return oidc_handle_info_request(r, c, session);
} else if ((r->args == NULL) || (apr_strnatcmp(r->args, "") == 0)) {
/* this is a "bare" request to the redirect URI, indicating implicit flow using the fragment response_mode */
return oidc_proto_javascript_implicit(r, c);
}
/* this is not an authorization response or logout request */
/* check for "error" response */
if (oidc_util_request_has_parameter(r, OIDC_PROTO_ERROR)) {
// char *error = NULL, *descr = NULL;
// oidc_util_get_request_parameter(r, "error", &error);
// oidc_util_get_request_parameter(r, "error_description", &descr);
//
// /* send user facing error to browser */
// return oidc_util_html_send_error(r, error, descr, DONE);
return oidc_handle_redirect_authorization_response(r, c, session);
}
oidc_error(r,
"The OpenID Connect callback URL received an invalid request: %s; returning HTTP_INTERNAL_SERVER_ERROR",
r->args);
/* something went wrong */
return oidc_util_html_send_error(r, c->error_template, "Invalid Request",
apr_psprintf(r->pool,
"The OpenID Connect callback URL received an invalid request"),
HTTP_INTERNAL_SERVER_ERROR);
}
#define OIDC_AUTH_TYPE_OPENID_CONNECT "openid-connect"
#define OIDC_AUTH_TYPE_OPENID_OAUTH20 "oauth20"
#define OIDC_AUTH_TYPE_OPENID_BOTH "auth-openidc"
/*
* main routine: handle OpenID Connect authentication
*/
static int oidc_check_userid_openidc(request_rec *r, oidc_cfg *c) {
if (oidc_get_redirect_uri(r, c) == NULL) {
oidc_error(r,
"configuration error: the authentication type is set to \"" OIDC_AUTH_TYPE_OPENID_CONNECT "\" but " OIDCRedirectURI " has not been set");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* check if this is a sub-request or an initial request */
if (ap_is_initial_req(r)) {
int rc = OK;
/* load the session from the request state; this will be a new "empty" session if no state exists */
oidc_session_t *session = NULL;
oidc_session_load(r, &session);
/* see if the initial request is to the redirect URI; this handles potential logout too */
if (oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, c))) {
/* handle request to the redirect_uri */
rc = oidc_handle_redirect_uri_request(r, c, session);
/* free resources allocated for the session */
oidc_session_free(r, session);
return rc;
/* initial request to non-redirect URI, check if we have an existing session */
} else if (session->remote_user != NULL) {
/* this is initial request and we already have a session */
rc = oidc_handle_existing_session(r, c, session);
/* free resources allocated for the session */
oidc_session_free(r, session);
/* strip any cookies that we need to */
oidc_strip_cookies(r);
return rc;
}
/* free resources allocated for the session */
oidc_session_free(r, session);
/*
* else: initial request, we have no session and it is not an authorization or
* discovery response: just hit the default flow for unauthenticated users
*/
} else {
/* not an initial request, try to recycle what we've already established in the main request */
if (r->main != NULL)
r->user = r->main->user;
else if (r->prev != NULL)
r->user = r->prev->user;
if (r->user != NULL) {
/* this is a sub-request and we have a session (headers will have been scrubbed and set already) */
oidc_debug(r,
"recycling user '%s' from initial request for sub-request",
r->user);
/*
* apparently request state can get lost in sub-requests, so let's see
* if we need to restore id_token and/or claims from the session cache
*/
const char *s_id_token = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_IDTOKEN);
if (s_id_token == NULL) {
oidc_session_t *session = NULL;
oidc_session_load(r, &session);
oidc_copy_tokens_to_request_state(r, session, NULL, NULL);
/* free resources allocated for the session */
oidc_session_free(r, session);
}
/* strip any cookies that we need to */
oidc_strip_cookies(r);
return OK;
}
/*
* else: not initial request, but we could not find a session, so:
* just hit the default flow for unauthenticated users
*/
}
return oidc_handle_unauthenticated_user(r, c);
}
/*
* main routine: handle "mixed" OIDC/OAuth authentication
*/
static int oidc_check_mixed_userid_oauth(request_rec *r, oidc_cfg *c) {
/* get the bearer access token from the Authorization header */
const char *access_token = NULL;
if (oidc_oauth_get_bearer_token(r, &access_token) == TRUE)
return oidc_oauth_check_userid(r, c, access_token);
/* no bearer token found: then treat this as a regular OIDC browser request */
return oidc_check_userid_openidc(r, c);
}
/*
* generic Apache authentication hook for this module: dispatches to OpenID Connect or OAuth 2.0 specific routines
*/
int oidc_check_user_id(request_rec *r) {
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
/* log some stuff about the incoming HTTP request */
oidc_debug(r, "incoming request: \"%s?%s\", ap_is_initial_req(r)=%d",
r->parsed_uri.path, r->args, ap_is_initial_req(r));
/* see if any authentication has been defined at all */
if (ap_auth_type(r) == NULL)
return DECLINED;
/* see if we've configured OpenID Connect user authentication for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_CONNECT) == 0)
return oidc_check_userid_openidc(r, c);
/* see if we've configured OAuth 2.0 access control for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0)
return oidc_oauth_check_userid(r, c, NULL);
/* see if we've configured "mixed mode" for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_BOTH) == 0)
return oidc_check_mixed_userid_oauth(r, c);
/* this is not for us but for some other handler */
return DECLINED;
}
/*
* get the claims and id_token from request state
*/
static void oidc_authz_get_claims_and_idtoken(request_rec *r, json_t **claims,
json_t **id_token) {
const char *s_claims = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_CLAIMS);
if (s_claims != NULL)
oidc_util_decode_json_object(r, s_claims, claims);
const char *s_id_token = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_IDTOKEN);
if (s_id_token != NULL)
oidc_util_decode_json_object(r, s_id_token, id_token);
}
#if MODULE_MAGIC_NUMBER_MAJOR >= 20100714
/*
* find out which action we need to take when encountering an unauthorized request
*/
static authz_status oidc_handle_unauthorized_user24(request_rec *r) {
oidc_debug(r, "enter");
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0) {
oidc_oauth_return_www_authenticate(r, "insufficient_scope",
"Different scope(s) or other claims required");
return AUTHZ_DENIED;
}
/* see if we've configured OIDCUnAutzAction for this path */
switch (oidc_dir_cfg_unautz_action(r)) {
// TODO: document that AuthzSendForbiddenOnFailure is required to return 403 FORBIDDEN
case OIDC_UNAUTZ_RETURN403:
case OIDC_UNAUTZ_RETURN401:
return AUTHZ_DENIED;
break;
case OIDC_UNAUTZ_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return AUTHZ_DENIED;
break;
}
oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
const char *location = oidc_util_hdr_out_location_get(r);
if (location != NULL) {
oidc_debug(r, "send HTML refresh with authorization redirect: %s",
location);
char *html_head = apr_psprintf(r->pool,
"<meta http-equiv=\"refresh\" content=\"0; url=%s\">",
location);
oidc_util_html_send(r, "Stepup Authentication", html_head, NULL, NULL,
HTTP_UNAUTHORIZED);
}
return AUTHZ_DENIED;
}
/*
* generic Apache >=2.4 authorization hook for this module
* handles both OpenID Connect or OAuth 2.0 in the same way, based on the claims stored in the session
*/
authz_status oidc_authz_checker(request_rec *r, const char *require_args,
const void *parsed_require_args,
oidc_authz_match_claim_fn_type match_claim_fn) {
oidc_debug(r, "enter");
/* check for anonymous access and PASS mode */
if (r->user != NULL && strlen(r->user) == 0) {
r->user = NULL;
if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS)
return AUTHZ_GRANTED;
}
/* get the set of claims from the request state (they've been set in the authentication part earlier */
json_t *claims = NULL, *id_token = NULL;
oidc_authz_get_claims_and_idtoken(r, &claims, &id_token);
/* merge id_token claims (e.g. "iss") in to claims json object */
if (claims)
oidc_util_json_merge(r, id_token, claims);
/* dispatch to the >=2.4 specific authz routine */
authz_status rc = oidc_authz_worker24(r, claims ? claims : id_token,
require_args, match_claim_fn);
/* cleanup */
if (claims)
json_decref(claims);
if (id_token)
json_decref(id_token);
if ((rc == AUTHZ_DENIED) && ap_auth_type(r))
rc = oidc_handle_unauthorized_user24(r);
return rc;
}
authz_status oidc_authz_checker_claim(request_rec *r, const char *require_args,
const void *parsed_require_args) {
return oidc_authz_checker(r, require_args, parsed_require_args,
oidc_authz_match_claim);
}
#ifdef USE_LIBJQ
authz_status oidc_authz_checker_claims_expr(request_rec *r, const char *require_args, const void *parsed_require_args) {
return oidc_authz_checker(r, require_args, parsed_require_args, oidc_authz_match_claims_expr);
}
#endif
#else
/*
* find out which action we need to take when encountering an unauthorized request
*/
static int oidc_handle_unauthorized_user22(request_rec *r) {
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
if (apr_strnatcasecmp((const char *) ap_auth_type(r), OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0) {
oidc_oauth_return_www_authenticate(r, "insufficient_scope", "Different scope(s) or other claims required");
return HTTP_UNAUTHORIZED;
}
/* see if we've configured OIDCUnAutzAction for this path */
switch (oidc_dir_cfg_unautz_action(r)) {
case OIDC_UNAUTZ_RETURN403:
return HTTP_FORBIDDEN;
case OIDC_UNAUTZ_RETURN401:
return HTTP_UNAUTHORIZED;
case OIDC_UNAUTZ_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return HTTP_UNAUTHORIZED;
}
return oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r), oidc_dir_cfg_path_scope(r));
}
/*
* generic Apache <2.4 authorization hook for this module
* handles both OpenID Connect and OAuth 2.0 in the same way, based on the claims stored in the request context
*/
int oidc_auth_checker(request_rec *r) {
/* check for anonymous access and PASS mode */
if (r->user != NULL && strlen(r->user) == 0) {
r->user = NULL;
if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS)
return OK;
}
/* get the set of claims from the request state (they've been set in the authentication part earlier */
json_t *claims = NULL, *id_token = NULL;
oidc_authz_get_claims_and_idtoken(r, &claims, &id_token);
/* get the Require statements */
const apr_array_header_t * const reqs_arr = ap_requires(r);
/* see if we have any */
const require_line * const reqs =
reqs_arr ? (require_line *) reqs_arr->elts : NULL;
if (!reqs_arr) {
oidc_debug(r,
"no require statements found, so declining to perform authorization.");
return DECLINED;
}
/* merge id_token claims (e.g. "iss") in to claims json object */
if (claims)
oidc_util_json_merge(r, id_token, claims);
/* dispatch to the <2.4 specific authz routine */
int rc = oidc_authz_worker22(r, claims ? claims : id_token, reqs,
reqs_arr->nelts);
/* cleanup */
if (claims)
json_decref(claims);
if (id_token)
json_decref(id_token);
if ((rc == HTTP_UNAUTHORIZED) && ap_auth_type(r))
rc = oidc_handle_unauthorized_user22(r);
return rc;
}
#endif
apr_byte_t oidc_enabled(request_rec *r) {
if (ap_auth_type(r) == NULL)
return FALSE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_CONNECT) == 0)
return TRUE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0)
return TRUE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_BOTH) == 0)
return TRUE;
return FALSE;
}
/*
* handle content generating requests
*/
int oidc_content_handler(request_rec *r) {
if (oidc_enabled(r) == FALSE)
return DECLINED;
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
return oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, c)) ?
OK : DECLINED;
}
extern const command_rec oidc_config_cmds[];
module AP_MODULE_DECLARE_DATA auth_openidc_module = {
STANDARD20_MODULE_STUFF,
oidc_create_dir_config,
oidc_merge_dir_config,
oidc_create_server_config,
oidc_merge_server_config,
oidc_config_cmds,
oidc_register_hooks
};
| ./CrossVul/dataset_final_sorted/CWE-601/c/bad_1002_2 |
crossvul-cpp_data_good_1002_2 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/***************************************************************************
* Copyright (C) 2017-2019 ZmartZone IAM
* Copyright (C) 2013-2017 Ping Identity Corporation
* All rights reserved.
*
* For further information please contact:
*
* Ping Identity Corporation
* 1099 18th St Suite 2950
* Denver, CO 80202
* 303.468.2900
* http://www.pingidentity.com
*
* DISCLAIMER OF WARRANTIES:
*
* THE SOFTWARE PROVIDED HEREUNDER IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
* ANY WARRANTIES OR REPRESENTATIONS EXPRESS, IMPLIED OR STATUTORY; INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF QUALITY, PERFORMANCE, NONINFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NOR ARE THERE ANY
* WARRANTIES CREATED BY A COURSE OR DEALING, COURSE OF PERFORMANCE OR TRADE
* USAGE. FURTHERMORE, THERE ARE NO WARRANTIES THAT THE SOFTWARE WILL MEET
* YOUR NEEDS OR BE FREE FROM ERRORS, OR THAT THE OPERATION OF THE SOFTWARE
* WILL BE UNINTERRUPTED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES 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.
*
* Initially based on mod_auth_cas.c:
* https://github.com/Jasig/mod_auth_cas
*
* Other code copied/borrowed/adapted:
* shared memory caching: mod_auth_mellon
*
* @Author: Hans Zandbelt - hans.zandbelt@zmartzone.eu
*
**************************************************************************/
#include "apr_hash.h"
#include "apr_strings.h"
#include "ap_config.h"
#include "ap_provider.h"
#include "apr_lib.h"
#include "apr_file_io.h"
#include "apr_sha1.h"
#include "apr_base64.h"
#include "httpd.h"
#include "http_core.h"
#include "http_config.h"
#include "http_log.h"
#include "http_protocol.h"
#include "http_request.h"
#include "mod_auth_openidc.h"
#define ERROR 2
static int oidc_handle_logout_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *url);
// TODO:
// - sort out oidc_cfg vs. oidc_dir_cfg stuff
// - rigid input checking on discovery responses
// - check self-issued support
// - README.quickstart
// - refresh metadata once-per too? (for non-signing key changes)
extern module AP_MODULE_DECLARE_DATA auth_openidc_module;
/*
* clean any suspicious headers in the HTTP request sent by the user agent
*/
static void oidc_scrub_request_headers(request_rec *r, const char *claim_prefix,
apr_hash_t *scrub) {
const int prefix_len = claim_prefix ? strlen(claim_prefix) : 0;
/* get an array representation of the incoming HTTP headers */
const apr_array_header_t * const h = apr_table_elts(r->headers_in);
/* table to keep the non-suspicious headers */
apr_table_t *clean_headers = apr_table_make(r->pool, h->nelts);
/* loop over the incoming HTTP headers */
const apr_table_entry_t * const e = (const apr_table_entry_t *) h->elts;
int i;
for (i = 0; i < h->nelts; i++) {
const char * const k = e[i].key;
/* is this header's name equivalent to a header that needs scrubbing? */
const char *hdr =
(k != NULL) && (scrub != NULL) ?
apr_hash_get(scrub, k, APR_HASH_KEY_STRING) : NULL;
const int header_matches = (hdr != NULL)
&& (oidc_strnenvcmp(k, hdr, -1) == 0);
/*
* would this header be interpreted as a mod_auth_openidc attribute? Note
* that prefix_len will be zero if no attr_prefix is defined,
* so this will always be false. Also note that we do not
* scrub headers if the prefix is empty because every header
* would match.
*/
const int prefix_matches = (k != NULL) && prefix_len
&& (oidc_strnenvcmp(k, claim_prefix, prefix_len) == 0);
/* add to the clean_headers if non-suspicious, skip and report otherwise */
if (!prefix_matches && !header_matches) {
apr_table_addn(clean_headers, k, e[i].val);
} else {
oidc_warn(r, "scrubbed suspicious request header (%s: %.32s)", k,
e[i].val);
}
}
/* overwrite the incoming headers with the cleaned result */
r->headers_in = clean_headers;
}
/*
* scrub all mod_auth_openidc related headers
*/
void oidc_scrub_headers(request_rec *r) {
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
const char *prefix = oidc_cfg_claim_prefix(r);
apr_hash_t *hdrs = apr_hash_make(r->pool);
if (apr_strnatcmp(prefix, "") == 0) {
if ((cfg->white_listed_claims != NULL)
&& (apr_hash_count(cfg->white_listed_claims) > 0))
hdrs = apr_hash_overlay(r->pool, cfg->white_listed_claims, hdrs);
else
oidc_warn(r,
"both " OIDCClaimPrefix " and " OIDCWhiteListedClaims " are empty: this renders an insecure setup!");
}
char *authn_hdr = oidc_cfg_dir_authn_header(r);
if (authn_hdr != NULL)
apr_hash_set(hdrs, authn_hdr, APR_HASH_KEY_STRING, authn_hdr);
/*
* scrub all headers starting with OIDC_ first
*/
oidc_scrub_request_headers(r, OIDC_DEFAULT_HEADER_PREFIX, hdrs);
/*
* then see if the claim headers need to be removed on top of that
* (i.e. the prefix does not start with the default OIDC_)
*/
if ((strstr(prefix, OIDC_DEFAULT_HEADER_PREFIX) != prefix)) {
oidc_scrub_request_headers(r, prefix, NULL);
}
}
/*
* strip the session cookie from the headers sent to the application/backend
*/
void oidc_strip_cookies(request_rec *r) {
char *cookie, *ctx, *result = NULL;
const char *name = NULL;
int i;
apr_array_header_t *strip = oidc_dir_cfg_strip_cookies(r);
char *cookies = apr_pstrdup(r->pool, oidc_util_hdr_in_cookie_get(r));
if ((cookies != NULL) && (strip != NULL)) {
oidc_debug(r,
"looking for the following cookies to strip from cookie header: %s",
apr_array_pstrcat(r->pool, strip, OIDC_CHAR_COMMA));
cookie = apr_strtok(cookies, OIDC_STR_SEMI_COLON, &ctx);
do {
while (cookie != NULL && *cookie == OIDC_CHAR_SPACE)
cookie++;
for (i = 0; i < strip->nelts; i++) {
name = ((const char**) strip->elts)[i];
if ((strncmp(cookie, name, strlen(name)) == 0)
&& (cookie[strlen(name)] == OIDC_CHAR_EQUAL)) {
oidc_debug(r, "stripping: %s", name);
break;
}
}
if (i == strip->nelts) {
result = result ? apr_psprintf(r->pool, "%s%s%s", result,
OIDC_STR_SEMI_COLON, cookie) :
cookie;
}
cookie = apr_strtok(NULL, OIDC_STR_SEMI_COLON, &ctx);
} while (cookie != NULL);
oidc_util_hdr_in_cookie_set(r, result);
}
}
#define OIDC_SHA1_LEN 20
/*
* calculates a hash value based on request fingerprint plus a provided nonce string.
*/
static char *oidc_get_browser_state_hash(request_rec *r, const char *nonce) {
oidc_debug(r, "enter");
/* helper to hold to header values */
const char *value = NULL;
/* the hash context */
apr_sha1_ctx_t sha1;
/* Initialize the hash context */
apr_sha1_init(&sha1);
/* get the X-FORWARDED-FOR header value */
value = oidc_util_hdr_in_x_forwarded_for_get(r);
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, strlen(value));
/* get the USER-AGENT header value */
value = oidc_util_hdr_in_user_agent_get(r);
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, strlen(value));
/* get the remote client IP address or host name */
/*
int remotehost_is_ip;
value = ap_get_remote_host(r->connection, r->per_dir_config,
REMOTE_NOLOOKUP, &remotehost_is_ip);
apr_sha1_update(&sha1, value, strlen(value));
*/
/* concat the nonce parameter to the hash input */
apr_sha1_update(&sha1, nonce, strlen(nonce));
/* concat the token binding ID if present */
value = oidc_util_get_provided_token_binding_id(r);
if (value != NULL) {
oidc_debug(r,
"Provided Token Binding ID environment variable found; adding its value to the state");
apr_sha1_update(&sha1, value, strlen(value));
}
/* finalize the hash input and calculate the resulting hash output */
unsigned char hash[OIDC_SHA1_LEN];
apr_sha1_final(hash, &sha1);
/* base64url-encode the resulting hash and return it */
char *result = NULL;
oidc_base64url_encode(r, &result, (const char *) hash, OIDC_SHA1_LEN, TRUE);
return result;
}
/*
* return the name for the state cookie
*/
static char *oidc_get_state_cookie_name(request_rec *r, const char *state) {
return apr_psprintf(r->pool, "%s%s", OIDC_STATE_COOKIE_PREFIX, state);
}
/*
* return the static provider configuration, i.e. from a metadata URL or configuration primitives
*/
static apr_byte_t oidc_provider_static_config(request_rec *r, oidc_cfg *c,
oidc_provider_t **provider) {
json_t *j_provider = NULL;
char *s_json = NULL;
/* see if we should configure a static provider based on external (cached) metadata */
if ((c->metadata_dir != NULL) || (c->provider.metadata_url == NULL)) {
*provider = &c->provider;
return TRUE;
}
oidc_cache_get_provider(r, c->provider.metadata_url, &s_json);
if (s_json == NULL) {
if (oidc_metadata_provider_retrieve(r, c, NULL,
c->provider.metadata_url, &j_provider, &s_json) == FALSE) {
oidc_error(r, "could not retrieve metadata from url: %s",
c->provider.metadata_url);
return FALSE;
}
oidc_cache_set_provider(r, c->provider.metadata_url, s_json,
apr_time_now() + (c->provider_metadata_refresh_interval <= 0 ? apr_time_from_sec( OIDC_CACHE_PROVIDER_METADATA_EXPIRY_DEFAULT) : c->provider_metadata_refresh_interval));
} else {
oidc_util_decode_json_object(r, s_json, &j_provider);
/* check to see if it is valid metadata */
if (oidc_metadata_provider_is_valid(r, c, j_provider, NULL) == FALSE) {
oidc_error(r,
"cache corruption detected: invalid metadata from url: %s",
c->provider.metadata_url);
return FALSE;
}
}
*provider = apr_pcalloc(r->pool, sizeof(oidc_provider_t));
memcpy(*provider, &c->provider, sizeof(oidc_provider_t));
if (oidc_metadata_provider_parse(r, c, j_provider, *provider) == FALSE) {
oidc_error(r, "could not parse metadata from url: %s",
c->provider.metadata_url);
if (j_provider)
json_decref(j_provider);
return FALSE;
}
json_decref(j_provider);
return TRUE;
}
/*
* return the oidc_provider_t struct for the specified issuer
*/
static oidc_provider_t *oidc_get_provider_for_issuer(request_rec *r,
oidc_cfg *c, const char *issuer, apr_byte_t allow_discovery) {
/* by default we'll assume that we're dealing with a single statically configured OP */
oidc_provider_t *provider = NULL;
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return NULL;
/* unless a metadata directory was configured, so we'll try and get the provider settings from there */
if (c->metadata_dir != NULL) {
/* try and get metadata from the metadata directory for the OP that sent this response */
if ((oidc_metadata_get(r, c, issuer, &provider, allow_discovery)
== FALSE) || (provider == NULL)) {
/* don't know nothing about this OP/issuer */
oidc_error(r, "no provider metadata found for issuer \"%s\"",
issuer);
return NULL;
}
}
return provider;
}
/*
* find out whether the request is a response from an IDP discovery page
*/
static apr_byte_t oidc_is_discovery_response(request_rec *r, oidc_cfg *cfg) {
/*
* prereq: this is a call to the configured redirect_uri, now see if:
* the OIDC_DISC_OP_PARAM is present
*/
return oidc_util_request_has_parameter(r, OIDC_DISC_OP_PARAM)
|| oidc_util_request_has_parameter(r, OIDC_DISC_USER_PARAM);
}
/*
* return the HTTP method being called: only for POST data persistence purposes
*/
static const char *oidc_original_request_method(request_rec *r, oidc_cfg *cfg,
apr_byte_t handle_discovery_response) {
const char *method = OIDC_METHOD_GET;
char *m = NULL;
if ((handle_discovery_response == TRUE)
&& (oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, cfg)))
&& (oidc_is_discovery_response(r, cfg))) {
oidc_util_get_request_parameter(r, OIDC_DISC_RM_PARAM, &m);
if (m != NULL)
method = apr_pstrdup(r->pool, m);
} else {
/*
* if POST preserve is not enabled for this location, there's no point in preserving
* the method either which would result in POSTing empty data on return;
* so we revert to legacy behavior
*/
if (oidc_cfg_dir_preserve_post(r) == 0)
return OIDC_METHOD_GET;
const char *content_type = oidc_util_hdr_in_content_type_get(r);
if ((r->method_number == M_POST) && (apr_strnatcmp(content_type,
OIDC_CONTENT_TYPE_FORM_ENCODED) == 0))
method = OIDC_METHOD_FORM_POST;
}
oidc_debug(r, "return: %s", method);
return method;
}
/*
* send an OpenID Connect authorization request to the specified provider preserving POST parameters using HTML5 storage
*/
apr_byte_t oidc_post_preserve_javascript(request_rec *r, const char *location,
char **javascript, char **javascript_method) {
if (oidc_cfg_dir_preserve_post(r) == 0)
return FALSE;
oidc_debug(r, "enter");
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
const char *method = oidc_original_request_method(r, cfg, FALSE);
if (apr_strnatcmp(method, OIDC_METHOD_FORM_POST) != 0)
return FALSE;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return FALSE;
}
const apr_array_header_t *arr = apr_table_elts(params);
const apr_table_entry_t *elts = (const apr_table_entry_t*) arr->elts;
int i;
char *json = "";
for (i = 0; i < arr->nelts; i++) {
json = apr_psprintf(r->pool, "%s'%s': '%s'%s", json,
oidc_util_escape_string(r, elts[i].key),
oidc_util_escape_string(r, elts[i].val),
i < arr->nelts - 1 ? "," : "");
}
json = apr_psprintf(r->pool, "{ %s }", json);
const char *jmethod = "preserveOnLoad";
const char *jscript =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function %s() {\n"
" sessionStorage.setItem('mod_auth_openidc_preserve_post_params', JSON.stringify(%s));\n"
" %s"
" }\n"
" </script>\n", jmethod, json,
location ?
apr_psprintf(r->pool, "window.location='%s';\n",
location) :
"");
if (location == NULL) {
if (javascript_method)
*javascript_method = apr_pstrdup(r->pool, jmethod);
if (javascript)
*javascript = apr_pstrdup(r->pool, jscript);
} else {
oidc_util_html_send(r, "Preserving...", jscript, jmethod,
"<p>Preserving...</p>", OK);
}
return TRUE;
}
/*
* restore POST parameters on original_url from HTML5 local storage
*/
static int oidc_request_post_preserved_restore(request_rec *r,
const char *original_url) {
oidc_debug(r, "enter: original_url=%s", original_url);
const char *method = "postOnLoad";
const char *script =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function str_decode(string) {\n"
" try {\n"
" result = decodeURIComponent(string);\n"
" } catch (e) {\n"
" result = unescape(string);\n"
" }\n"
" return result;\n"
" }\n"
" function %s() {\n"
" var mod_auth_openidc_preserve_post_params = JSON.parse(sessionStorage.getItem('mod_auth_openidc_preserve_post_params'));\n"
" sessionStorage.removeItem('mod_auth_openidc_preserve_post_params');\n"
" for (var key in mod_auth_openidc_preserve_post_params) {\n"
" var input = document.createElement(\"input\");\n"
" input.name = str_decode(key);\n"
" input.value = str_decode(mod_auth_openidc_preserve_post_params[key]);\n"
" input.type = \"hidden\";\n"
" document.forms[0].appendChild(input);\n"
" }\n"
" document.forms[0].action = '%s';\n"
" document.forms[0].submit();\n"
" }\n"
" </script>\n", method, original_url);
const char *body = " <p>Restoring...</p>\n"
" <form method=\"post\"></form>\n";
return oidc_util_html_send(r, "Restoring...", script, method, body,
OK);
}
/*
* parse state that was sent to us by the issuer
*/
static apr_byte_t oidc_unsolicited_proto_state(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t **proto_state) {
char *alg = NULL;
oidc_debug(r, "enter: state header=%s",
oidc_proto_peek_jwt_header(r, state, &alg));
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret,
oidc_alg2keysize(alg), OIDC_JOSE_ALG_SHA256,
TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwt_t *jwt = NULL;
if (oidc_jwt_parse(r->pool, state, &jwt,
oidc_util_merge_symmetric_key(r->pool, c->private_keys, jwk),
&err) == FALSE) {
oidc_error(r,
"could not parse JWT from state: invalid unsolicited response: %s",
oidc_jose_e2s(r->pool, err));
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully parsed JWT from state");
if (jwt->payload.iss == NULL) {
oidc_error(r, "no \"%s\" could be retrieved from JWT state, aborting",
OIDC_CLAIM_ISS);
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_provider_t *provider = oidc_get_provider_for_issuer(r, c,
jwt->payload.iss, FALSE);
if (provider == NULL) {
oidc_jwt_destroy(jwt);
return FALSE;
}
/* validate the state JWT, validating optional exp + iat */
if (oidc_proto_validate_jwt(r, jwt, provider->issuer, FALSE, FALSE,
provider->idtoken_iat_slack,
OIDC_TOKEN_BINDING_POLICY_DISABLED) == FALSE) {
oidc_jwt_destroy(jwt);
return FALSE;
}
char *rfp = NULL;
if (oidc_jose_get_string(r->pool, jwt->payload.value.json, OIDC_CLAIM_RFP,
TRUE, &rfp, &err) == FALSE) {
oidc_error(r,
"no \"%s\" claim could be retrieved from JWT state, aborting: %s",
OIDC_CLAIM_RFP, oidc_jose_e2s(r->pool, err));
oidc_jwt_destroy(jwt);
return FALSE;
}
if (apr_strnatcmp(rfp, OIDC_PROTO_ISS) != 0) {
oidc_error(r, "\"%s\" (%s) does not match \"%s\", aborting",
OIDC_CLAIM_RFP, rfp, OIDC_PROTO_ISS);
oidc_jwt_destroy(jwt);
return FALSE;
}
char *target_link_uri = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_TARGET_LINK_URI,
FALSE, &target_link_uri, NULL);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
oidc_error(r,
"no \"%s\" claim could be retrieved from JWT state and no " OIDCDefaultURL " is set, aborting",
OIDC_CLAIM_TARGET_LINK_URI);
oidc_jwt_destroy(jwt);
return FALSE;
}
target_link_uri = c->default_sso_url;
}
if (c->metadata_dir != NULL) {
if ((oidc_metadata_get(r, c, jwt->payload.iss, &provider, FALSE)
== FALSE) || (provider == NULL)) {
oidc_error(r, "no provider metadata found for provider \"%s\"",
jwt->payload.iss);
oidc_jwt_destroy(jwt);
return FALSE;
}
}
char *jti = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json, OIDC_CLAIM_JTI,
FALSE, &jti,
NULL);
if (jti == NULL) {
char *cser = oidc_jwt_serialize(r->pool, jwt, &err);
if (cser == NULL)
return FALSE;
if (oidc_util_hash_string_and_base64url_encode(r, OIDC_JOSE_ALG_SHA256,
cser, &jti) == FALSE) {
oidc_error(r,
"oidc_util_hash_string_and_base64url_encode returned an error");
return FALSE;
}
}
char *replay = NULL;
oidc_cache_get_jti(r, jti, &replay);
if (replay != NULL) {
oidc_error(r,
"the \"%s\" value (%s) passed in the browser state was found in the cache already; possible replay attack!?",
OIDC_CLAIM_JTI, jti);
oidc_jwt_destroy(jwt);
return FALSE;
}
/* jti cache duration is the configured replay prevention window for token issuance plus 10 seconds for safety */
apr_time_t jti_cache_duration = apr_time_from_sec(
provider->idtoken_iat_slack * 2 + 10);
/* store it in the cache for the calculated duration */
oidc_cache_set_jti(r, jti, jti, apr_time_now() + jti_cache_duration);
oidc_debug(r,
"jti \"%s\" validated successfully and is now cached for %" APR_TIME_T_FMT " seconds",
jti, apr_time_sec(jti_cache_duration));
jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret, 0,
NULL, TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwks_uri_t jwks_uri = { provider->jwks_uri,
provider->jwks_refresh_interval, provider->ssl_validate_server };
if (oidc_proto_jwt_verify(r, c, jwt, &jwks_uri,
oidc_util_merge_symmetric_key(r->pool, NULL, jwk)) == FALSE) {
oidc_error(r, "state JWT could not be validated, aborting");
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully verified state JWT");
*proto_state = oidc_proto_state_new();
oidc_proto_state_set_issuer(*proto_state, jwt->payload.iss);
oidc_proto_state_set_original_url(*proto_state, target_link_uri);
oidc_proto_state_set_original_method(*proto_state, OIDC_METHOD_GET);
oidc_proto_state_set_response_mode(*proto_state, provider->response_mode);
oidc_proto_state_set_response_type(*proto_state, provider->response_type);
oidc_proto_state_set_timestamp_now(*proto_state);
oidc_jwt_destroy(jwt);
return TRUE;
}
typedef struct oidc_state_cookies_t {
char *name;
apr_time_t timestamp;
struct oidc_state_cookies_t *next;
} oidc_state_cookies_t;
static int oidc_delete_oldest_state_cookies(request_rec *r,
int number_of_valid_state_cookies, int max_number_of_state_cookies,
oidc_state_cookies_t *first) {
oidc_state_cookies_t *cur = NULL, *prev = NULL, *prev_oldest = NULL,
*oldest = NULL;
while (number_of_valid_state_cookies >= max_number_of_state_cookies) {
oldest = first;
prev_oldest = NULL;
prev = first;
cur = first->next;
while (cur) {
if ((cur->timestamp < oldest->timestamp)) {
oldest = cur;
prev_oldest = prev;
}
prev = cur;
cur = cur->next;
}
oidc_warn(r,
"deleting oldest state cookie: %s (time until expiry %" APR_TIME_T_FMT " seconds)",
oldest->name, apr_time_sec(oldest->timestamp - apr_time_now()));
oidc_util_set_cookie(r, oldest->name, "", 0, NULL);
if (prev_oldest)
prev_oldest->next = oldest->next;
else
first = first->next;
number_of_valid_state_cookies--;
}
return number_of_valid_state_cookies;
}
/*
* clean state cookies that have expired i.e. for outstanding requests that will never return
* successfully and return the number of remaining valid cookies/outstanding-requests while
* doing so
*/
static int oidc_clean_expired_state_cookies(request_rec *r, oidc_cfg *c,
const char *currentCookieName, int delete_oldest) {
int number_of_valid_state_cookies = 0;
oidc_state_cookies_t *first = NULL, *last = NULL;
char *cookie, *tokenizerCtx = NULL;
char *cookies = apr_pstrdup(r->pool, oidc_util_hdr_in_cookie_get(r));
if (cookies != NULL) {
cookie = apr_strtok(cookies, OIDC_STR_SEMI_COLON, &tokenizerCtx);
while (cookie != NULL) {
while (*cookie == OIDC_CHAR_SPACE)
cookie++;
if (strstr(cookie, OIDC_STATE_COOKIE_PREFIX) == cookie) {
char *cookieName = cookie;
while (cookie != NULL && *cookie != OIDC_CHAR_EQUAL)
cookie++;
if (*cookie == OIDC_CHAR_EQUAL) {
*cookie = '\0';
cookie++;
if ((currentCookieName == NULL)
|| (apr_strnatcmp(cookieName, currentCookieName)
!= 0)) {
oidc_proto_state_t *proto_state =
oidc_proto_state_from_cookie(r, c, cookie);
if (proto_state != NULL) {
json_int_t ts = oidc_proto_state_get_timestamp(
proto_state);
if (apr_time_now() > ts + apr_time_from_sec(c->state_timeout)) {
oidc_error(r,
"state (%s) has expired (original_url=%s)",
cookieName,
oidc_proto_state_get_original_url(
proto_state));
oidc_util_set_cookie(r, cookieName, "", 0,
NULL);
} else {
if (first == NULL) {
first = apr_pcalloc(r->pool,
sizeof(oidc_state_cookies_t));
last = first;
} else {
last->next = apr_pcalloc(r->pool,
sizeof(oidc_state_cookies_t));
last = last->next;
}
last->name = cookieName;
last->timestamp = ts;
last->next = NULL;
number_of_valid_state_cookies++;
}
oidc_proto_state_destroy(proto_state);
}
}
}
}
cookie = apr_strtok(NULL, OIDC_STR_SEMI_COLON, &tokenizerCtx);
}
}
if (delete_oldest > 0)
number_of_valid_state_cookies = oidc_delete_oldest_state_cookies(r,
number_of_valid_state_cookies, c->max_number_of_state_cookies,
first);
return number_of_valid_state_cookies;
}
/*
* restore the state that was maintained between authorization request and response in an encrypted cookie
*/
static apr_byte_t oidc_restore_proto_state(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t **proto_state) {
oidc_debug(r, "enter");
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* clean expired state cookies to avoid pollution */
oidc_clean_expired_state_cookies(r, c, cookieName, FALSE);
/* get the state cookie value first */
char *cookieValue = oidc_util_get_cookie(r, cookieName);
if (cookieValue == NULL) {
oidc_error(r, "no \"%s\" state cookie found", cookieName);
return oidc_unsolicited_proto_state(r, c, state, proto_state);
}
/* clear state cookie because we don't need it anymore */
oidc_util_set_cookie(r, cookieName, "", 0, NULL);
*proto_state = oidc_proto_state_from_cookie(r, c, cookieValue);
if (*proto_state == NULL)
return FALSE;
const char *nonce = oidc_proto_state_get_nonce(*proto_state);
/* calculate the hash of the browser fingerprint concatenated with the nonce */
char *calc = oidc_get_browser_state_hash(r, nonce);
/* compare the calculated hash with the value provided in the authorization response */
if (apr_strnatcmp(calc, state) != 0) {
oidc_error(r,
"calculated state from cookie does not match state parameter passed back in URL: \"%s\" != \"%s\"",
state, calc);
oidc_proto_state_destroy(*proto_state);
return FALSE;
}
apr_time_t ts = oidc_proto_state_get_timestamp(*proto_state);
/* check that the timestamp is not beyond the valid interval */
if (apr_time_now() > ts + apr_time_from_sec(c->state_timeout)) {
oidc_error(r, "state has expired");
/*
* note that this overrides redirection to the OIDCDefaultURL as done later...
* see: https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!msg/mod_auth_openidc/L4JFBw-XCNU/BWi2Fmk2AwAJ
*/
oidc_util_html_send_error(r, c->error_template,
"Invalid Authentication Response",
apr_psprintf(r->pool,
"This is due to a timeout; please restart your authentication session by re-entering the URL/bookmark you originally wanted to access: %s",
oidc_proto_state_get_original_url(*proto_state)),
OK);
oidc_proto_state_destroy(*proto_state);
return FALSE;
}
/* add the state */
oidc_proto_state_set_state(*proto_state, state);
/* log the restored state object */
oidc_debug(r, "restored state: %s",
oidc_proto_state_to_string(r, *proto_state));
/* we've made it */
return TRUE;
}
/*
* set the state that is maintained between an authorization request and an authorization response
* in a cookie in the browser that is cryptographically bound to that state
*/
static int oidc_authorization_request_set_cookie(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t *proto_state) {
/*
* create a cookie consisting of 8 elements:
* random value, original URL, original method, issuer, response_type, response_mod, prompt and timestamp
* encoded as JSON, encrypting the resulting JSON value
*/
char *cookieValue = oidc_proto_state_to_cookie(r, c, proto_state);
if (cookieValue == NULL)
return HTTP_INTERNAL_SERVER_ERROR;
/*
* clean expired state cookies to avoid pollution and optionally
* try to avoid the number of state cookies exceeding a max
*/
int number_of_cookies = oidc_clean_expired_state_cookies(r, c, NULL,
oidc_cfg_delete_oldest_state_cookies(c));
int max_number_of_cookies = oidc_cfg_max_number_of_state_cookies(c);
if ((max_number_of_cookies > 0)
&& (number_of_cookies >= max_number_of_cookies)) {
oidc_warn(r,
"the number of existing, valid state cookies (%d) has exceeded the limit (%d), no additional authorization request + state cookie can be generated, aborting the request",
number_of_cookies, max_number_of_cookies);
/*
* TODO: the html_send code below caters for the case that there's a user behind a
* browser generating this request, rather than a piece of XHR code; how would an
* XHR client handle this?
*/
/*
* it appears that sending content with a 503 turns the HTTP status code
* into a 200 so we'll avoid that for now: the user will see Apache specific
* readable text anyway
*
return oidc_util_html_send_error(r, c->error_template,
"Too Many Outstanding Requests",
apr_psprintf(r->pool,
"No authentication request could be generated since there are too many outstanding authentication requests already; you may have to wait up to %d seconds to be able to create a new request",
c->state_timeout),
HTTP_SERVICE_UNAVAILABLE);
*/
return HTTP_SERVICE_UNAVAILABLE;
}
/* assemble the cookie name for the state cookie */
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* set it as a cookie */
oidc_util_set_cookie(r, cookieName, cookieValue, -1,
c->cookie_same_site ? OIDC_COOKIE_EXT_SAME_SITE_LAX : NULL);
return HTTP_OK;
}
/*
* get the mod_auth_openidc related context from the (userdata in the) request
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
static apr_table_t *oidc_request_state(request_rec *rr) {
/* our state is always stored in the main request */
request_rec *r = (rr->main != NULL) ? rr->main : rr;
/* our state is a table, get it */
apr_table_t *state = NULL;
apr_pool_userdata_get((void **) &state, OIDC_USERDATA_KEY, r->pool);
/* if it does not exist, we'll create a new table */
if (state == NULL) {
state = apr_table_make(r->pool, 5);
apr_pool_userdata_set(state, OIDC_USERDATA_KEY, NULL, r->pool);
}
/* return the resulting table, always non-null now */
return state;
}
/*
* set a name/value pair in the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
void oidc_request_state_set(request_rec *r, const char *key, const char *value) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* put the name/value pair in that table */
apr_table_set(state, key, value);
}
/*
* get a name/value pair from the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
const char*oidc_request_state_get(request_rec *r, const char *key) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* return the value from the table */
return apr_table_get(state, key);
}
/*
* set the claims from a JSON object (c.q. id_token or user_info response) stored
* in the session in to HTTP headers passed on to the application
*/
static apr_byte_t oidc_set_app_claims(request_rec *r,
const oidc_cfg * const cfg, oidc_session_t *session,
const char *s_claims) {
json_t *j_claims = NULL;
/* decode the string-encoded attributes in to a JSON structure */
if (s_claims != NULL) {
if (oidc_util_decode_json_object(r, s_claims, &j_claims) == FALSE)
return FALSE;
}
/* set the resolved claims a HTTP headers for the application */
if (j_claims != NULL) {
oidc_util_set_app_infos(r, j_claims, oidc_cfg_claim_prefix(r),
cfg->claim_delimiter, oidc_cfg_dir_pass_info_in_headers(r),
oidc_cfg_dir_pass_info_in_envvars(r));
/* release resources */
json_decref(j_claims);
}
return TRUE;
}
static int oidc_authenticate_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, const char *original_url,
const char *login_hint, const char *id_token_hint, const char *prompt,
const char *auth_request_params, const char *path_scope);
/*
* log message about max session duration
*/
static void oidc_log_session_expires(request_rec *r, const char *msg,
apr_time_t session_expires) {
char buf[APR_RFC822_DATE_LEN + 1];
apr_rfc822_date(buf, session_expires);
oidc_debug(r, "%s: %s (in %" APR_TIME_T_FMT " secs from now)", msg, buf,
apr_time_sec(session_expires - apr_time_now()));
}
/*
* see if this is a non-browser request
*/
static apr_byte_t oidc_is_xml_http_request(request_rec *r) {
if ((oidc_util_hdr_in_x_requested_with_get(r) != NULL)
&& (apr_strnatcasecmp(oidc_util_hdr_in_x_requested_with_get(r),
OIDC_HTTP_HDR_VAL_XML_HTTP_REQUEST) == 0))
return TRUE;
if ((oidc_util_hdr_in_accept_contains(r, OIDC_CONTENT_TYPE_TEXT_HTML)
== FALSE) && (oidc_util_hdr_in_accept_contains(r,
OIDC_CONTENT_TYPE_APP_XHTML_XML) == FALSE)
&& (oidc_util_hdr_in_accept_contains(r,
OIDC_CONTENT_TYPE_ANY) == FALSE))
return TRUE;
return FALSE;
}
/*
* find out which action we need to take when encountering an unauthenticated request
*/
static int oidc_handle_unauthenticated_user(request_rec *r, oidc_cfg *c) {
/* see if we've configured OIDCUnAuthAction for this path */
switch (oidc_dir_cfg_unauth_action(r)) {
case OIDC_UNAUTH_RETURN410:
return HTTP_GONE;
case OIDC_UNAUTH_RETURN401:
return HTTP_UNAUTHORIZED;
case OIDC_UNAUTH_PASS:
r->user = "";
/*
* we're not going to pass information about an authenticated user to the application,
* but we do need to scrub the headers that mod_auth_openidc would set for security reasons
*/
oidc_scrub_headers(r);
return OK;
case OIDC_UNAUTH_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return HTTP_UNAUTHORIZED;
}
/*
* else: no session (regardless of whether it is main or sub-request),
* and we need to authenticate the user
*/
return oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
}
/*
* check if maximum session duration was exceeded
*/
static int oidc_check_max_session_duration(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
/* get the session expiry from the session data */
apr_time_t session_expires = oidc_session_get_session_expires(r, session);
/* check the expire timestamp against the current time */
if (apr_time_now() > session_expires) {
oidc_warn(r, "maximum session duration exceeded for user: %s",
session->remote_user);
oidc_session_kill(r, session);
return oidc_handle_unauthenticated_user(r, cfg);
}
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
return OK;
}
/*
* validate received session cookie against the domain it was issued for:
*
* this handles the case where the cache configured is a the same single memcache, Redis, or file
* backend for different (virtual) hosts, or a client-side cookie protected with the same secret
*
* it also handles the case that a cookie is unexpectedly shared across multiple hosts in
* name-based virtual hosting even though the OP(s) would be the same
*/
static apr_byte_t oidc_check_cookie_domain(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
const char *c_cookie_domain =
cfg->cookie_domain ?
cfg->cookie_domain : oidc_get_current_url_host(r);
const char *s_cookie_domain = oidc_session_get_cookie_domain(r, session);
if ((s_cookie_domain == NULL)
|| (apr_strnatcmp(c_cookie_domain, s_cookie_domain) != 0)) {
oidc_warn(r,
"aborting: detected attempt to play cookie against a different domain/host than issued for! (issued=%s, current=%s)",
s_cookie_domain, c_cookie_domain);
return FALSE;
}
return TRUE;
}
/*
* get a handle to the provider configuration via the "issuer" stored in the session
*/
apr_byte_t oidc_get_provider_from_session(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t **provider) {
oidc_debug(r, "enter");
/* get the issuer value from the session state */
const char *issuer = oidc_session_get_issuer(r, session);
if (issuer == NULL) {
oidc_error(r, "session corrupted: no issuer found in session");
return FALSE;
}
/* get the provider info associated with the issuer value */
oidc_provider_t *p = oidc_get_provider_for_issuer(r, c, issuer, FALSE);
if (p == NULL) {
oidc_error(r, "session corrupted: no provider found for issuer: %s",
issuer);
return FALSE;
}
*provider = p;
return TRUE;
}
/*
* store claims resolved from the userinfo endpoint in the session
*/
static void oidc_store_userinfo_claims(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider, const char *claims,
const char *userinfo_jwt) {
oidc_debug(r, "enter");
/* see if we've resolved any claims */
if (claims != NULL) {
/*
* Successfully decoded a set claims from the response so we can store them
* (well actually the stringified representation in the response)
* in the session context safely now
*/
oidc_session_set_userinfo_claims(r, session, claims);
if (c->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* this will also clear the entry if a JWT was not returned at this point */
oidc_session_set_userinfo_jwt(r, session, userinfo_jwt);
}
} else {
/*
* clear the existing claims because we could not refresh them
*/
oidc_session_set_userinfo_claims(r, session, NULL);
oidc_session_set_userinfo_jwt(r, session, NULL);
}
/* store the last refresh time if we've configured a userinfo refresh interval */
if (provider->userinfo_refresh_interval > 0)
oidc_session_reset_userinfo_last_refresh(r, session);
}
/*
* execute refresh token grant to refresh the existing access token
*/
static apr_byte_t oidc_refresh_access_token(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider,
char **new_access_token) {
oidc_debug(r, "enter");
/* get the refresh token that was stored in the session */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if (refresh_token == NULL) {
oidc_warn(r,
"refresh token routine called but no refresh_token found in the session");
return FALSE;
}
/* elements returned in the refresh response */
char *s_id_token = NULL;
int expires_in = -1;
char *s_token_type = NULL;
char *s_access_token = NULL;
char *s_refresh_token = NULL;
/* refresh the tokens by calling the token endpoint */
if (oidc_proto_refresh_request(r, c, provider, refresh_token, &s_id_token,
&s_access_token, &s_token_type, &expires_in,
&s_refresh_token) == FALSE) {
oidc_error(r, "access_token could not be refreshed");
return FALSE;
}
/* store the new access_token in the session and discard the old one */
oidc_session_set_access_token(r, session, s_access_token);
oidc_session_set_access_token_expires(r, session, expires_in);
/* reset the access token refresh timestamp */
oidc_session_reset_access_token_last_refresh(r, session);
/* see if we need to return it as a parameter */
if (new_access_token != NULL)
*new_access_token = s_access_token;
/* if we have a new refresh token (rolling refresh), store it in the session and overwrite the old one */
if (s_refresh_token != NULL)
oidc_session_set_refresh_token(r, session, s_refresh_token);
return TRUE;
}
/*
* retrieve claims from the userinfo endpoint and return the stringified response
*/
static const char *oidc_retrieve_claims_from_userinfo_endpoint(request_rec *r,
oidc_cfg *c, oidc_provider_t *provider, const char *access_token,
oidc_session_t *session, char *id_token_sub, char **userinfo_jwt) {
oidc_debug(r, "enter");
char *result = NULL;
char *refreshed_access_token = NULL;
/* see if a userinfo endpoint is set, otherwise there's nothing to do for us */
if (provider->userinfo_endpoint_url == NULL) {
oidc_debug(r,
"not retrieving userinfo claims because userinfo_endpoint is not set");
return NULL;
}
/* see if there's an access token, otherwise we can't call the userinfo endpoint at all */
if (access_token == NULL) {
oidc_debug(r,
"not retrieving userinfo claims because access_token is not provided");
return NULL;
}
if ((id_token_sub == NULL) && (session != NULL)) {
// when refreshing claims from the userinfo endpoint
json_t *id_token_claims = oidc_session_get_idtoken_claims_json(r,
session);
if (id_token_claims == NULL) {
oidc_error(r, "no id_token_claims found in session");
return NULL;
}
oidc_jose_get_string(r->pool, id_token_claims, OIDC_CLAIM_SUB, FALSE,
&id_token_sub, NULL);
}
// TODO: return code should indicate whether the token expired or some other error occurred
// TODO: long-term: session storage should be JSON (with explicit types and less conversion, using standard routines)
/* try to get claims from the userinfo endpoint using the provided access token */
if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub, access_token,
&result, userinfo_jwt) == FALSE) {
/* see if we have an existing session and we are refreshing the user info claims */
if (session != NULL) {
/* first call to user info endpoint failed, but the access token may have just expired, so refresh it */
if (oidc_refresh_access_token(r, c, session, provider,
&refreshed_access_token) == TRUE) {
/* try again with the new access token */
if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub,
refreshed_access_token, &result, userinfo_jwt) == FALSE) {
oidc_error(r,
"resolving user info claims with the refreshed access token failed, nothing will be stored in the session");
result = NULL;
}
} else {
oidc_warn(r,
"refreshing access token failed, claims will not be retrieved/refreshed from the userinfo endpoint");
result = NULL;
}
} else {
oidc_error(r,
"resolving user info claims with the existing/provided access token failed, nothing will be stored in the session");
result = NULL;
}
}
return result;
}
/*
* get (new) claims from the userinfo endpoint
*/
static apr_byte_t oidc_refresh_claims_from_userinfo_endpoint(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session) {
oidc_provider_t *provider = NULL;
const char *claims = NULL;
const char *access_token = NULL;
char *userinfo_jwt = NULL;
/* get the current provider info */
if (oidc_get_provider_from_session(r, cfg, session, &provider) == FALSE)
return FALSE;
/* see if we can do anything here, i.e. we have a userinfo endpoint and a refresh interval is configured */
apr_time_t interval = apr_time_from_sec(
provider->userinfo_refresh_interval);
oidc_debug(r, "userinfo_endpoint=%s, interval=%d",
provider->userinfo_endpoint_url,
provider->userinfo_refresh_interval);
if ((provider->userinfo_endpoint_url != NULL) && (interval > 0)) {
/* get the last refresh timestamp from the session info */
apr_time_t last_refresh = oidc_session_get_userinfo_last_refresh(r,
session);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(last_refresh + interval - apr_time_now()));
/* see if we need to refresh again */
if (last_refresh + interval < apr_time_now()) {
/* get the current access token */
access_token = oidc_session_get_access_token(r, session);
/* retrieve the current claims */
claims = oidc_retrieve_claims_from_userinfo_endpoint(r, cfg,
provider, access_token, session, NULL, &userinfo_jwt);
/* store claims resolved from userinfo endpoint */
oidc_store_userinfo_claims(r, cfg, session, provider, claims,
userinfo_jwt);
/* indicated something changed */
return TRUE;
}
}
return FALSE;
}
/*
* copy the claims and id_token from the session to the request state and optionally return them
*/
static void oidc_copy_tokens_to_request_state(request_rec *r,
oidc_session_t *session, const char **s_id_token, const char **s_claims) {
const char *id_token = oidc_session_get_idtoken_claims(r, session);
const char *claims = oidc_session_get_userinfo_claims(r, session);
oidc_debug(r, "id_token=%s claims=%s", id_token, claims);
if (id_token != NULL) {
oidc_request_state_set(r, OIDC_REQUEST_STATE_KEY_IDTOKEN, id_token);
if (s_id_token != NULL)
*s_id_token = id_token;
}
if (claims != NULL) {
oidc_request_state_set(r, OIDC_REQUEST_STATE_KEY_CLAIMS, claims);
if (s_claims != NULL)
*s_claims = claims;
}
}
/*
* pass refresh_token, access_token and access_token_expires as headers/environment variables to the application
*/
static apr_byte_t oidc_session_pass_tokens_and_save(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session, apr_byte_t needs_save) {
apr_byte_t pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
apr_byte_t pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
/* set the refresh_token in the app headers/variables, if enabled for this location/directory */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if ((oidc_cfg_dir_pass_refresh_token(r) != 0) && (refresh_token != NULL)) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_REFRESH_TOKEN, refresh_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* set the access_token in the app headers/variables */
const char *access_token = oidc_session_get_access_token(r, session);
if (access_token != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ACCESS_TOKEN, access_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* set the expiry timestamp in the app headers/variables */
const char *access_token_expires = oidc_session_get_access_token_expires(r,
session);
if (access_token_expires != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ACCESS_TOKEN_EXP,
access_token_expires,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/*
* reset the session inactivity timer
* but only do this once per 10% of the inactivity timeout interval (with a max to 60 seconds)
* for performance reasons
*
* now there's a small chance that the session ends 10% (or a minute) earlier than configured/expected
* cq. when there's a request after a recent save (so no update) and then no activity happens until
* a request comes in just before the session should expire
* ("recent" and "just before" refer to 10%-with-a-max-of-60-seconds of the inactivity interval after
* the start/last-update and before the expiry of the session respectively)
*
* this is be deemed acceptable here because of performance gain
*/
apr_time_t interval = apr_time_from_sec(cfg->session_inactivity_timeout);
apr_time_t now = apr_time_now();
apr_time_t slack = interval / 10;
if (slack > apr_time_from_sec(60))
slack = apr_time_from_sec(60);
if (session->expiry - now < interval - slack) {
session->expiry = now + interval;
needs_save = TRUE;
}
/* log message about session expiry */
oidc_log_session_expires(r, "session inactivity timeout", session->expiry);
/* check if something was updated in the session and we need to save it again */
if (needs_save)
if (oidc_session_save(r, session, FALSE) == FALSE)
return FALSE;
return TRUE;
}
static apr_byte_t oidc_refresh_access_token_before_expiry(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session, int ttl_minimum, int logout_on_error) {
const char *s_access_token_expires = NULL;
apr_time_t t_expires = -1;
oidc_provider_t *provider = NULL;
oidc_debug(r, "ttl_minimum=%d", ttl_minimum);
if (ttl_minimum < 0)
return FALSE;
s_access_token_expires = oidc_session_get_access_token_expires(r, session);
if (s_access_token_expires == NULL) {
oidc_debug(r,
"no access token expires_in stored in the session (i.e. returned from in the authorization response), so cannot refresh the access token based on TTL requirement");
return FALSE;
}
if (oidc_session_get_refresh_token(r, session) == NULL) {
oidc_debug(r,
"no refresh token stored in the session, so cannot refresh the access token based on TTL requirement");
return FALSE;
}
if (sscanf(s_access_token_expires, "%" APR_TIME_T_FMT, &t_expires) != 1) {
oidc_error(r, "could not parse s_access_token_expires %s",
s_access_token_expires);
return FALSE;
}
t_expires = apr_time_from_sec(t_expires - ttl_minimum);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(t_expires - apr_time_now()));
if (t_expires > apr_time_now())
return FALSE;
if (oidc_get_provider_from_session(r, cfg, session, &provider) == FALSE)
return FALSE;
if (oidc_refresh_access_token(r, cfg, session, provider,
NULL) == FALSE) {
oidc_warn(r, "access_token could not be refreshed, logout=%d", logout_on_error & OIDC_LOGOUT_ON_ERROR_REFRESH);
if (logout_on_error & OIDC_LOGOUT_ON_ERROR_REFRESH)
return ERROR;
else
return FALSE;
}
return TRUE;
}
/*
* handle the case where we have identified an existing authentication session for a user
*/
static int oidc_handle_existing_session(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
oidc_debug(r, "enter");
/* track if the session needs to be updated/saved into the cache */
apr_byte_t needs_save = FALSE;
/* set the user in the main request for further (incl. sub-request) processing */
r->user = apr_pstrdup(r->pool, session->remote_user);
oidc_debug(r, "set remote_user to \"%s\"", r->user);
/* get the header name in which the remote user name needs to be passed */
char *authn_header = oidc_cfg_dir_authn_header(r);
apr_byte_t pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
apr_byte_t pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
/* verify current cookie domain against issued cookie domain */
if (oidc_check_cookie_domain(r, cfg, session) == FALSE)
return HTTP_UNAUTHORIZED;
/* check if the maximum session duration was exceeded */
int rc = oidc_check_max_session_duration(r, cfg, session);
if (rc != OK)
return rc;
/* if needed, refresh the access token */
needs_save = oidc_refresh_access_token_before_expiry(r, cfg, session,
oidc_cfg_dir_refresh_access_token_before_expiry(r),
oidc_cfg_dir_logout_on_error_refresh(r));
if (needs_save == ERROR)
return oidc_handle_logout_request(r, cfg, session, cfg->default_slo_url);
/* if needed, refresh claims from the user info endpoint */
if (oidc_refresh_claims_from_userinfo_endpoint(r, cfg, session) == TRUE)
needs_save = TRUE;
/*
* we're going to pass the information that we have to the application,
* but first we need to scrub the headers that we're going to use for security reasons
*/
oidc_scrub_headers(r);
/* set the user authentication HTTP header if set and required */
if ((r->user != NULL) && (authn_header != NULL))
oidc_util_hdr_in_set(r, authn_header, r->user);
const char *s_claims = NULL;
const char *s_id_token = NULL;
/* copy id_token and claims from session to request state and obtain their values */
oidc_copy_tokens_to_request_state(r, session, &s_id_token, &s_claims);
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_CLAIMS)) {
/* set the userinfo claims in the app headers */
if (oidc_set_app_claims(r, cfg, session, s_claims) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_JSON_OBJECT)) {
/* pass the userinfo JSON object to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_USERINFO_JSON, s_claims,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_JWT)) {
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* get the compact serialized JWT from the session */
const char *s_userinfo_jwt = oidc_session_get_userinfo_jwt(r,
session);
if (s_userinfo_jwt != NULL) {
/* pass the compact serialized JWT to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_USERINFO_JWT,
s_userinfo_jwt,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
} else {
oidc_debug(r,
"configured to pass userinfo in a JWT, but no such JWT was found in the session (probably no such JWT was returned from the userinfo endpoint)");
}
} else {
oidc_error(r,
"session type \"client-cookie\" does not allow storing/passing a userinfo JWT; use \"" OIDCSessionType " server-cache\" for that");
}
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_CLAIMS)) {
/* set the id_token in the app headers */
if (oidc_set_app_claims(r, cfg, session, s_id_token) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_PAYLOAD)) {
/* pass the id_token JSON object to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ID_TOKEN_PAYLOAD, s_id_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_SERIALIZED)) {
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* get the compact serialized JWT from the session */
const char *s_id_token = oidc_session_get_idtoken(r, session);
/* pass the compact serialized JWT to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ID_TOKEN, s_id_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
} else {
oidc_error(r,
"session type \"client-cookie\" does not allow storing/passing the id_token; use \"" OIDCSessionType " server-cache\" for that");
}
}
/* pass the at, rt and at expiry to the application, possibly update the session expiry and save the session */
if (oidc_session_pass_tokens_and_save(r, cfg, session, needs_save) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* return "user authenticated" status */
return OK;
}
/*
* helper function for basic/implicit client flows upon receiving an authorization response:
* check that it matches the state stored in the browser and return the variables associated
* with the state, such as original_url and OP oidc_provider_t pointer.
*/
static apr_byte_t oidc_authorization_response_match_state(request_rec *r,
oidc_cfg *c, const char *state, struct oidc_provider_t **provider,
oidc_proto_state_t **proto_state) {
oidc_debug(r, "enter (state=%s)", state);
if ((state == NULL) || (apr_strnatcmp(state, "") == 0)) {
oidc_error(r, "state parameter is not set");
return FALSE;
}
/* check the state parameter against what we stored in a cookie */
if (oidc_restore_proto_state(r, c, state, proto_state) == FALSE) {
oidc_error(r, "unable to restore state");
return FALSE;
}
*provider = oidc_get_provider_for_issuer(r, c,
oidc_proto_state_get_issuer(*proto_state), FALSE);
return (*provider != NULL);
}
/*
* redirect the browser to the session logout endpoint
*/
static int oidc_session_redirect_parent_window_to_logout(request_rec *r,
oidc_cfg *c) {
oidc_debug(r, "enter");
char *java_script = apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" window.top.location.href = '%s?session=logout';\n"
" </script>\n", oidc_get_redirect_uri(r, c));
return oidc_util_html_send(r, "Redirecting...", java_script, NULL, NULL,
OK);
}
/*
* handle an error returned by the OP
*/
static int oidc_authorization_response_error(request_rec *r, oidc_cfg *c,
oidc_proto_state_t *proto_state, const char *error,
const char *error_description) {
const char *prompt = oidc_proto_state_get_prompt(proto_state);
if (prompt != NULL)
prompt = apr_pstrdup(r->pool, prompt);
oidc_proto_state_destroy(proto_state);
if ((prompt != NULL)
&& (apr_strnatcmp(prompt, OIDC_PROTO_PROMPT_NONE) == 0)) {
return oidc_session_redirect_parent_window_to_logout(r, c);
}
return oidc_util_html_send_error(r, c->error_template,
apr_psprintf(r->pool, "OpenID Connect Provider error: %s", error),
error_description, OK);
}
/*
* get the r->user for this request based on the configuration for OIDC/OAuth
*/
apr_byte_t oidc_get_remote_user(request_rec *r, const char *claim_name,
const char *reg_exp, const char *replace, json_t *json,
char **request_user) {
/* get the claim value from the JSON object */
json_t *username = json_object_get(json, claim_name);
if ((username == NULL) || (!json_is_string(username))) {
oidc_warn(r, "JSON object did not contain a \"%s\" string", claim_name);
return FALSE;
}
*request_user = apr_pstrdup(r->pool, json_string_value(username));
if (reg_exp != NULL) {
char *error_str = NULL;
if (replace == NULL) {
if (oidc_util_regexp_first_match(r->pool, *request_user, reg_exp,
request_user, &error_str) == FALSE) {
oidc_error(r, "oidc_util_regexp_first_match failed: %s",
error_str);
*request_user = NULL;
return FALSE;
}
} else if (oidc_util_regexp_substitute(r->pool, *request_user, reg_exp,
replace, request_user, &error_str) == FALSE) {
oidc_error(r, "oidc_util_regexp_substitute failed: %s", error_str);
*request_user = NULL;
return FALSE;
}
}
return TRUE;
}
/*
* set the unique user identifier that will be propagated in the Apache r->user and REMOTE_USER variables
*/
static apr_byte_t oidc_set_request_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, oidc_jwt_t *jwt, const char *s_claims) {
char *issuer = provider->issuer;
char *claim_name = apr_pstrdup(r->pool, c->remote_user_claim.claim_name);
int n = strlen(claim_name);
apr_byte_t post_fix_with_issuer = (claim_name[n - 1] == OIDC_CHAR_AT);
if (post_fix_with_issuer == TRUE) {
claim_name[n - 1] = '\0';
issuer =
(strstr(issuer, "https://") == NULL) ?
apr_pstrdup(r->pool, issuer) :
apr_pstrdup(r->pool, issuer + strlen("https://"));
}
/* extract the username claim (default: "sub") from the id_token payload or user claims */
apr_byte_t rc = FALSE;
char *remote_user = NULL;
json_t *claims = NULL;
oidc_util_decode_json_object(r, s_claims, &claims);
if (claims == NULL) {
rc = oidc_get_remote_user(r, claim_name, c->remote_user_claim.reg_exp,
c->remote_user_claim.replace, jwt->payload.value.json,
&remote_user);
} else {
oidc_util_json_merge(r, jwt->payload.value.json, claims);
rc = oidc_get_remote_user(r, claim_name, c->remote_user_claim.reg_exp,
c->remote_user_claim.replace, claims, &remote_user);
json_decref(claims);
}
if ((rc == FALSE) || (remote_user == NULL)) {
oidc_error(r,
"" OIDCRemoteUserClaim "is set to \"%s\", but could not set the remote user based on the requested claim \"%s\" and the available claims for the user",
c->remote_user_claim.claim_name, claim_name);
return FALSE;
}
if (post_fix_with_issuer == TRUE)
remote_user = apr_psprintf(r->pool, "%s%s%s", remote_user, OIDC_STR_AT,
issuer);
r->user = apr_pstrdup(r->pool, remote_user);
oidc_debug(r, "set remote_user to \"%s\" based on claim: \"%s\"%s", r->user,
c->remote_user_claim.claim_name,
c->remote_user_claim.reg_exp ?
apr_psprintf(r->pool,
" and expression: \"%s\" and replace string: \"%s\"",
c->remote_user_claim.reg_exp,
c->remote_user_claim.replace) :
"");
return TRUE;
}
static char *oidc_make_sid_iss_unique(request_rec *r, const char *sid,
const char *issuer) {
return apr_psprintf(r->pool, "%s@%s", sid, issuer);
}
/*
* store resolved information in the session
*/
static apr_byte_t oidc_save_in_session(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider,
const char *remoteUser, const char *id_token, oidc_jwt_t *id_token_jwt,
const char *claims, const char *access_token, const int expires_in,
const char *refresh_token, const char *session_state, const char *state,
const char *original_url, const char *userinfo_jwt) {
/* store the user in the session */
session->remote_user = remoteUser;
/* set the session expiry to the inactivity timeout */
session->expiry =
apr_time_now() + apr_time_from_sec(c->session_inactivity_timeout);
/* store the claims payload in the id_token for later reference */
oidc_session_set_idtoken_claims(r, session,
id_token_jwt->payload.value.str);
if (c->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* store the compact serialized representation of the id_token for later reference */
oidc_session_set_idtoken(r, session, id_token);
}
/* store the issuer in the session (at least needed for session mgmt and token refresh */
oidc_session_set_issuer(r, session, provider->issuer);
/* store the state and original URL in the session for handling browser-back more elegantly */
oidc_session_set_request_state(r, session, state);
oidc_session_set_original_url(r, session, original_url);
if ((session_state != NULL) && (provider->check_session_iframe != NULL)) {
/* store the session state and required parameters session management */
oidc_session_set_session_state(r, session, session_state);
oidc_debug(r,
"session management enabled: stored session_state (%s), check_session_iframe (%s) and client_id (%s) in the session",
session_state, provider->check_session_iframe,
provider->client_id);
} else if (provider->check_session_iframe == NULL) {
oidc_debug(r,
"session management disabled: \"check_session_iframe\" is not set in provider configuration");
} else {
oidc_debug(r,
"session management disabled: no \"session_state\" value is provided in the authentication response even though \"check_session_iframe\" (%s) is set in the provider configuration",
provider->check_session_iframe);
}
/* store claims resolved from userinfo endpoint */
oidc_store_userinfo_claims(r, c, session, provider, claims, userinfo_jwt);
/* see if we have an access_token */
if (access_token != NULL) {
/* store the access_token in the session context */
oidc_session_set_access_token(r, session, access_token);
/* store the associated expires_in value */
oidc_session_set_access_token_expires(r, session, expires_in);
/* reset the access token refresh timestamp */
oidc_session_reset_access_token_last_refresh(r, session);
}
/* see if we have a refresh_token */
if (refresh_token != NULL) {
/* store the refresh_token in the session context */
oidc_session_set_refresh_token(r, session, refresh_token);
}
/* store max session duration in the session as a hard cut-off expiry timestamp */
apr_time_t session_expires =
(provider->session_max_duration == 0) ?
apr_time_from_sec(id_token_jwt->payload.exp) :
(apr_time_now()
+ apr_time_from_sec(provider->session_max_duration));
oidc_session_set_session_expires(r, session, session_expires);
oidc_debug(r,
"provider->session_max_duration = %d, session_expires=%" APR_TIME_T_FMT,
provider->session_max_duration, session_expires);
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
/* store the domain for which this session is valid */
oidc_session_set_cookie_domain(r, session,
c->cookie_domain ? c->cookie_domain : oidc_get_current_url_host(r));
char *sid = NULL;
oidc_debug(r, "provider->backchannel_logout_supported=%d",
provider->backchannel_logout_supported);
if (provider->backchannel_logout_supported > 0) {
oidc_jose_get_string(r->pool, id_token_jwt->payload.value.json,
OIDC_CLAIM_SID, FALSE, &sid, NULL);
if (sid == NULL)
sid = id_token_jwt->payload.sub;
session->sid = oidc_make_sid_iss_unique(r, sid, provider->issuer);
}
/* store the session */
return oidc_session_save(r, session, TRUE);
}
/*
* parse the expiry for the access token
*/
static int oidc_parse_expires_in(request_rec *r, const char *expires_in) {
if (expires_in != NULL) {
char *ptr = NULL;
long number = strtol(expires_in, &ptr, 10);
if (number <= 0) {
oidc_warn(r,
"could not convert \"expires_in\" value (%s) to a number",
expires_in);
return -1;
}
return number;
}
return -1;
}
/*
* handle the different flows (hybrid, implicit, Authorization Code)
*/
static apr_byte_t oidc_handle_flows(request_rec *r, oidc_cfg *c,
oidc_proto_state_t *proto_state, oidc_provider_t *provider,
apr_table_t *params, const char *response_mode, oidc_jwt_t **jwt) {
apr_byte_t rc = FALSE;
const char *requested_response_type = oidc_proto_state_get_response_type(
proto_state);
/* handle the requested response type/mode */
if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_IDTOKEN_TOKEN)) {
rc = oidc_proto_authorization_response_code_idtoken_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_IDTOKEN)) {
rc = oidc_proto_authorization_response_code_idtoken(r, c, proto_state,
provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_TOKEN)) {
rc = oidc_proto_handle_authorization_response_code_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE)) {
rc = oidc_proto_handle_authorization_response_code(r, c, proto_state,
provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_IDTOKEN_TOKEN)) {
rc = oidc_proto_handle_authorization_response_idtoken_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_IDTOKEN)) {
rc = oidc_proto_handle_authorization_response_idtoken(r, c, proto_state,
provider, params, response_mode, jwt);
} else {
oidc_error(r, "unsupported response type: \"%s\"",
requested_response_type);
}
if ((rc == FALSE) && (*jwt != NULL)) {
oidc_jwt_destroy(*jwt);
*jwt = NULL;
}
return rc;
}
/* handle the browser back on an authorization response */
static apr_byte_t oidc_handle_browser_back(request_rec *r, const char *r_state,
oidc_session_t *session) {
/* see if we have an existing session and browser-back was used */
const char *s_state = NULL, *o_url = NULL;
if (session->remote_user != NULL) {
s_state = oidc_session_get_request_state(r, session);
o_url = oidc_session_get_original_url(r, session);
if ((r_state != NULL) && (s_state != NULL)
&& (apr_strnatcmp(r_state, s_state) == 0)) {
/* log the browser back event detection */
oidc_warn(r,
"browser back detected, redirecting to original URL: %s",
o_url);
/* go back to the URL that he originally tried to access */
oidc_util_hdr_out_location_set(r, o_url);
return TRUE;
}
}
return FALSE;
}
/*
* complete the handling of an authorization response by obtaining, parsing and verifying the
* id_token and storing the authenticated user state in the session
*/
static int oidc_handle_authorization_response(request_rec *r, oidc_cfg *c,
oidc_session_t *session, apr_table_t *params, const char *response_mode) {
oidc_debug(r, "enter, response_mode=%s", response_mode);
oidc_provider_t *provider = NULL;
oidc_proto_state_t *proto_state = NULL;
oidc_jwt_t *jwt = NULL;
/* see if this response came from a browser-back event */
if (oidc_handle_browser_back(r, apr_table_get(params, OIDC_PROTO_STATE),
session) == TRUE)
return HTTP_MOVED_TEMPORARILY;
/* match the returned state parameter against the state stored in the browser */
if (oidc_authorization_response_match_state(r, c,
apr_table_get(params, OIDC_PROTO_STATE), &provider,
&proto_state) == FALSE) {
if (c->default_sso_url != NULL) {
oidc_warn(r,
"invalid authorization response state; a default SSO URL is set, sending the user there: %s",
c->default_sso_url);
oidc_util_hdr_out_location_set(r, c->default_sso_url);
return HTTP_MOVED_TEMPORARILY;
}
oidc_error(r,
"invalid authorization response state and no default SSO URL is set, sending an error...");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if the response is an error response */
if (apr_table_get(params, OIDC_PROTO_ERROR) != NULL)
return oidc_authorization_response_error(r, c, proto_state,
apr_table_get(params, OIDC_PROTO_ERROR),
apr_table_get(params, OIDC_PROTO_ERROR_DESCRIPTION));
/* handle the code, implicit or hybrid flow */
if (oidc_handle_flows(r, c, proto_state, provider, params, response_mode,
&jwt) == FALSE)
return oidc_authorization_response_error(r, c, proto_state,
"Error in handling response type.", NULL);
if (jwt == NULL) {
oidc_error(r, "no id_token was provided");
return oidc_authorization_response_error(r, c, proto_state,
"No id_token was provided.", NULL);
}
int expires_in = oidc_parse_expires_in(r,
apr_table_get(params, OIDC_PROTO_EXPIRES_IN));
char *userinfo_jwt = NULL;
/*
* optionally resolve additional claims against the userinfo endpoint
* parsed claims are not actually used here but need to be parsed anyway for error checking purposes
*/
const char *claims = oidc_retrieve_claims_from_userinfo_endpoint(r, c,
provider, apr_table_get(params, OIDC_PROTO_ACCESS_TOKEN), NULL,
jwt->payload.sub, &userinfo_jwt);
/* restore the original protected URL that the user was trying to access */
const char *original_url = oidc_proto_state_get_original_url(proto_state);
if (original_url != NULL)
original_url = apr_pstrdup(r->pool, original_url);
const char *original_method = oidc_proto_state_get_original_method(
proto_state);
if (original_method != NULL)
original_method = apr_pstrdup(r->pool, original_method);
const char *prompt = oidc_proto_state_get_prompt(proto_state);
/* set the user */
if (oidc_set_request_user(r, c, provider, jwt, claims) == TRUE) {
/* session management: if the user in the new response is not equal to the old one, error out */
if ((prompt != NULL)
&& (apr_strnatcmp(prompt, OIDC_PROTO_PROMPT_NONE) == 0)) {
// TOOD: actually need to compare sub? (need to store it in the session separately then
//const char *sub = NULL;
//oidc_session_get(r, session, "sub", &sub);
//if (apr_strnatcmp(sub, jwt->payload.sub) != 0) {
if (apr_strnatcmp(session->remote_user, r->user) != 0) {
oidc_warn(r,
"user set from new id_token is different from current one");
oidc_jwt_destroy(jwt);
return oidc_authorization_response_error(r, c, proto_state,
"User changed!", NULL);
}
}
/* store resolved information in the session */
if (oidc_save_in_session(r, c, session, provider, r->user,
apr_table_get(params, OIDC_PROTO_ID_TOKEN), jwt, claims,
apr_table_get(params, OIDC_PROTO_ACCESS_TOKEN), expires_in,
apr_table_get(params, OIDC_PROTO_REFRESH_TOKEN),
apr_table_get(params, OIDC_PROTO_SESSION_STATE),
apr_table_get(params, OIDC_PROTO_STATE), original_url,
userinfo_jwt) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
} else {
oidc_error(r, "remote user could not be set");
return oidc_authorization_response_error(r, c, proto_state,
"Remote user could not be set: contact the website administrator",
NULL);
}
/* cleanup */
oidc_proto_state_destroy(proto_state);
oidc_jwt_destroy(jwt);
/* check that we've actually authenticated a user; functions as error handling for oidc_get_remote_user */
if (r->user == NULL)
return HTTP_UNAUTHORIZED;
/* log the successful response */
oidc_debug(r,
"session created and stored, returning to original URL: %s, original method: %s",
original_url, original_method);
/* check whether form post data was preserved; if so restore it */
if (apr_strnatcmp(original_method, OIDC_METHOD_FORM_POST) == 0) {
return oidc_request_post_preserved_restore(r, original_url);
}
/* now we've authenticated the user so go back to the URL that he originally tried to access */
oidc_util_hdr_out_location_set(r, original_url);
/* do the actual redirect to the original URL */
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle an OpenID Connect Authorization Response using the POST (+fragment->POST) response_mode
*/
static int oidc_handle_post_authorization_response(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
oidc_debug(r, "enter");
/* initialize local variables */
char *response_mode = NULL;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if we've got any POST-ed data at all */
if ((apr_table_elts(params)->nelts < 1)
|| ((apr_table_elts(params)->nelts == 1)
&& apr_table_get(params, OIDC_PROTO_RESPONSE_MODE)
&& (apr_strnatcmp(
apr_table_get(params, OIDC_PROTO_RESPONSE_MODE),
OIDC_PROTO_RESPONSE_MODE_FRAGMENT) == 0))) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"You've hit an OpenID Connect Redirect URI with no parameters, this is an invalid request; you should not open this URL in your browser directly, or have the server administrator use a different " OIDCRedirectURI " setting.",
HTTP_INTERNAL_SERVER_ERROR);
}
/* get the parameters */
response_mode = (char *) apr_table_get(params, OIDC_PROTO_RESPONSE_MODE);
/* do the actual implicit work */
return oidc_handle_authorization_response(r, c, session, params,
response_mode ? response_mode : OIDC_PROTO_RESPONSE_MODE_FORM_POST);
}
/*
* handle an OpenID Connect Authorization Response using the redirect response_mode
*/
static int oidc_handle_redirect_authorization_response(request_rec *r,
oidc_cfg *c, oidc_session_t *session) {
oidc_debug(r, "enter");
/* read the parameters from the query string */
apr_table_t *params = apr_table_make(r->pool, 8);
oidc_util_read_form_encoded_params(r, params, r->args);
/* do the actual work */
return oidc_handle_authorization_response(r, c, session, params,
OIDC_PROTO_RESPONSE_MODE_QUERY);
}
/*
* present the user with an OP selection screen
*/
static int oidc_discovery(request_rec *r, oidc_cfg *cfg) {
oidc_debug(r, "enter");
/* obtain the URL we're currently accessing, to be stored in the state/session */
char *current_url = oidc_get_current_url(r);
const char *method = oidc_original_request_method(r, cfg, FALSE);
/* generate CSRF token */
char *csrf = NULL;
if (oidc_proto_generate_nonce(r, &csrf, 8) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
char *path_scopes = oidc_dir_cfg_path_scope(r);
char *path_auth_request_params = oidc_dir_cfg_path_auth_request_params(r);
char *discover_url = oidc_cfg_dir_discover_url(r);
/* see if there's an external discovery page configured */
if (discover_url != NULL) {
/* yes, assemble the parameters for external discovery */
char *url = apr_psprintf(r->pool, "%s%s%s=%s&%s=%s&%s=%s&%s=%s",
discover_url,
strchr(discover_url, OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
OIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url),
OIDC_DISC_RM_PARAM, method,
OIDC_DISC_CB_PARAM,
oidc_util_escape_string(r, oidc_get_redirect_uri(r, cfg)),
OIDC_CSRF_NAME, oidc_util_escape_string(r, csrf));
if (path_scopes != NULL)
url = apr_psprintf(r->pool, "%s&%s=%s", url, OIDC_DISC_SC_PARAM,
oidc_util_escape_string(r, path_scopes));
if (path_auth_request_params != NULL)
url = apr_psprintf(r->pool, "%s&%s=%s", url, OIDC_DISC_AR_PARAM,
oidc_util_escape_string(r, path_auth_request_params));
/* log what we're about to do */
oidc_debug(r, "redirecting to external discovery page: %s", url);
/* set CSRF cookie */
oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1,
cfg->cookie_same_site ?
OIDC_COOKIE_EXT_SAME_SITE_STRICT :
NULL);
/* see if we need to preserve POST parameters through Javascript/HTML5 storage */
if (oidc_post_preserve_javascript(r, url, NULL, NULL) == TRUE)
return OK;
/* do the actual redirect to an external discovery page */
oidc_util_hdr_out_location_set(r, url);
return HTTP_MOVED_TEMPORARILY;
}
/* get a list of all providers configured in the metadata directory */
apr_array_header_t *arr = NULL;
if (oidc_metadata_list(r, cfg, &arr) == FALSE)
return oidc_util_html_send_error(r, cfg->error_template,
"Configuration Error",
"No configured providers found, contact your administrator",
HTTP_UNAUTHORIZED);
/* assemble a where-are-you-from IDP discovery HTML page */
const char *s = " <h3>Select your OpenID Connect Identity Provider</h3>\n";
/* list all configured providers in there */
int i;
for (i = 0; i < arr->nelts; i++) {
const char *issuer = ((const char**) arr->elts)[i];
// TODO: html escape (especially & character)
char *href = apr_psprintf(r->pool,
"%s?%s=%s&%s=%s&%s=%s&%s=%s",
oidc_get_redirect_uri(r, cfg), OIDC_DISC_OP_PARAM,
oidc_util_escape_string(r, issuer),
OIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url),
OIDC_DISC_RM_PARAM, method,
OIDC_CSRF_NAME, csrf);
if (path_scopes != NULL)
href = apr_psprintf(r->pool, "%s&%s=%s", href,
OIDC_DISC_SC_PARAM, oidc_util_escape_string(r, path_scopes));
if (path_auth_request_params != NULL)
href = apr_psprintf(r->pool, "%s&%s=%s", href,
OIDC_DISC_AR_PARAM,
oidc_util_escape_string(r, path_auth_request_params));
char *display =
(strstr(issuer, "https://") == NULL) ?
apr_pstrdup(r->pool, issuer) :
apr_pstrdup(r->pool, issuer + strlen("https://"));
/* strip port number */
//char *p = strstr(display, ":");
//if (p != NULL) *p = '\0';
/* point back to the redirect_uri, where the selection is handled, with an IDP selection and return_to URL */
s = apr_psprintf(r->pool, "%s<p><a href=\"%s\">%s</a></p>\n", s, href,
display);
}
/* add an option to enter an account or issuer name for dynamic OP discovery */
s = apr_psprintf(r->pool, "%s<form method=\"get\" action=\"%s\">\n", s,
oidc_get_redirect_uri(r, cfg));
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_RT_PARAM, current_url);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_RM_PARAM, method);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_CSRF_NAME, csrf);
if (path_scopes != NULL)
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_SC_PARAM, path_scopes);
if (path_auth_request_params != NULL)
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_AR_PARAM, path_auth_request_params);
s =
apr_psprintf(r->pool,
"%s<p>Or enter your account name (eg. "mike@seed.gluu.org", or an IDP identifier (eg. "mitreid.org"):</p>\n",
s);
s = apr_psprintf(r->pool,
"%s<p><input type=\"text\" name=\"%s\" value=\"%s\"></p>\n", s,
OIDC_DISC_OP_PARAM, "");
s = apr_psprintf(r->pool,
"%s<p><input type=\"submit\" value=\"Submit\"></p>\n", s);
s = apr_psprintf(r->pool, "%s</form>\n", s);
oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1,
cfg->cookie_same_site ? OIDC_COOKIE_EXT_SAME_SITE_STRICT : NULL);
char *javascript = NULL, *javascript_method = NULL;
char *html_head =
"<style type=\"text/css\">body {text-align: center}</style>";
if (oidc_post_preserve_javascript(r, NULL, &javascript,
&javascript_method) == TRUE)
html_head = apr_psprintf(r->pool, "%s%s", html_head, javascript);
/* now send the HTML contents to the user agent */
return oidc_util_html_send(r, "OpenID Connect Provider Discovery",
html_head, javascript_method, s, OK);
}
/*
* authenticate the user to the selected OP, if the OP is not selected yet perform discovery first
*/
static int oidc_authenticate_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, const char *original_url,
const char *login_hint, const char *id_token_hint, const char *prompt,
const char *auth_request_params, const char *path_scope) {
oidc_debug(r, "enter");
if (provider == NULL) {
// TODO: should we use an explicit redirect to the discovery endpoint (maybe a "discovery" param to the redirect_uri)?
if (c->metadata_dir != NULL)
return oidc_discovery(r, c);
/* we're not using multiple OP's configured in a metadata directory, pick the statically configured OP */
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
/* generate the random nonce value that correlates requests and responses */
char *nonce = NULL;
if (oidc_proto_generate_nonce(r, &nonce, OIDC_PROTO_NONCE_LENGTH) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
char *pkce_state = NULL;
char *code_challenge = NULL;
if ((oidc_util_spaced_string_contains(r->pool, provider->response_type,
OIDC_PROTO_CODE) == TRUE) && (provider->pkce != NULL)) {
/* generate the code verifier value that correlates authorization requests and code exchange requests */
if (provider->pkce->state(r, &pkce_state) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* generate the PKCE code challenge */
if (provider->pkce->challenge(r, pkce_state, &code_challenge) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
/* create the state between request/response */
oidc_proto_state_t *proto_state = oidc_proto_state_new();
oidc_proto_state_set_original_url(proto_state, original_url);
oidc_proto_state_set_original_method(proto_state,
oidc_original_request_method(r, c, TRUE));
oidc_proto_state_set_issuer(proto_state, provider->issuer);
oidc_proto_state_set_response_type(proto_state, provider->response_type);
oidc_proto_state_set_nonce(proto_state, nonce);
oidc_proto_state_set_timestamp_now(proto_state);
if (provider->response_mode)
oidc_proto_state_set_response_mode(proto_state,
provider->response_mode);
if (prompt)
oidc_proto_state_set_prompt(proto_state, prompt);
if (pkce_state)
oidc_proto_state_set_pkce_state(proto_state, pkce_state);
/* get a hash value that fingerprints the browser concatenated with the random input */
char *state = oidc_get_browser_state_hash(r, nonce);
/*
* create state that restores the context when the authorization response comes in
* and cryptographically bind it to the browser
*/
int rc = oidc_authorization_request_set_cookie(r, c, state, proto_state);
if (rc != HTTP_OK) {
oidc_proto_state_destroy(proto_state);
return rc;
}
/*
* printout errors if Cookie settings are not going to work
* TODO: separate this code out into its own function
*/
apr_uri_t o_uri;
memset(&o_uri, 0, sizeof(apr_uri_t));
apr_uri_t r_uri;
memset(&r_uri, 0, sizeof(apr_uri_t));
apr_uri_parse(r->pool, original_url, &o_uri);
apr_uri_parse(r->pool, oidc_get_redirect_uri(r, c), &r_uri);
if ((apr_strnatcmp(o_uri.scheme, r_uri.scheme) != 0)
&& (apr_strnatcmp(r_uri.scheme, "https") == 0)) {
oidc_error(r,
"the URL scheme (%s) of the configured " OIDCRedirectURI " does not match the URL scheme of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!",
r_uri.scheme, o_uri.scheme);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
if (c->cookie_domain == NULL) {
if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
char *p = strstr(o_uri.hostname, r_uri.hostname);
if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
oidc_error(r,
"the URL hostname (%s) of the configured " OIDCRedirectURI " does not match the URL hostname of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!",
r_uri.hostname, o_uri.hostname);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
} else {
if (!oidc_util_cookie_domain_valid(r_uri.hostname, c->cookie_domain)) {
oidc_error(r,
"the domain (%s) configured in " OIDCCookieDomain " does not match the URL hostname (%s) of the URL being accessed (%s): setting \"state\" and \"session\" cookies will not work!!",
c->cookie_domain, o_uri.hostname, original_url);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
/* send off to the OpenID Connect Provider */
// TODO: maybe show intermediate/progress screen "redirecting to"
return oidc_proto_authorization_request(r, provider, login_hint,
oidc_get_redirect_uri_iss(r, c, provider), state, proto_state,
id_token_hint, code_challenge, auth_request_params, path_scope);
}
/*
* check if the target_link_uri matches to configuration settings to prevent an open redirect
*/
static int oidc_target_link_uri_matches_configuration(request_rec *r,
oidc_cfg *cfg, const char *target_link_uri) {
apr_uri_t o_uri;
apr_uri_parse(r->pool, target_link_uri, &o_uri);
if (o_uri.hostname == NULL) {
oidc_error(r,
"could not parse the \"target_link_uri\" (%s) in to a valid URL: aborting.",
target_link_uri);
return FALSE;
}
apr_uri_t r_uri;
apr_uri_parse(r->pool, oidc_get_redirect_uri(r, cfg), &r_uri);
if (cfg->cookie_domain == NULL) {
/* cookie_domain set: see if the target_link_uri matches the redirect_uri host (because the session cookie will be set host-wide) */
if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
char *p = strstr(o_uri.hostname, r_uri.hostname);
if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
oidc_error(r,
"the URL hostname (%s) of the configured " OIDCRedirectURI " does not match the URL hostname of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
r_uri.hostname, o_uri.hostname);
return FALSE;
}
}
} else {
/* cookie_domain set: see if the target_link_uri is within the cookie_domain */
char *p = strstr(o_uri.hostname, cfg->cookie_domain);
if ((p == NULL) || (apr_strnatcmp(cfg->cookie_domain, p) != 0)) {
oidc_error(r,
"the domain (%s) configured in " OIDCCookieDomain " does not match the URL hostname (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.hostname, target_link_uri);
return FALSE;
}
}
/* see if the cookie_path setting matches the target_link_uri path */
char *cookie_path = oidc_cfg_dir_cookie_path(r);
if (cookie_path != NULL) {
char *p = (o_uri.path != NULL) ? strstr(o_uri.path, cookie_path) : NULL;
if ((p == NULL) || (p != o_uri.path)) {
oidc_error(r,
"the path (%s) configured in " OIDCCookiePath " does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.path, target_link_uri);
return FALSE;
} else if (strlen(o_uri.path) > strlen(cookie_path)) {
int n = strlen(cookie_path);
if (cookie_path[n - 1] == OIDC_CHAR_FORWARD_SLASH)
n--;
if (o_uri.path[n] != OIDC_CHAR_FORWARD_SLASH) {
oidc_error(r,
"the path (%s) configured in " OIDCCookiePath " does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.path, target_link_uri);
return FALSE;
}
}
}
return TRUE;
}
/*
* handle a response from an IDP discovery page and/or handle 3rd-party initiated SSO
*/
static int oidc_handle_discovery_response(request_rec *r, oidc_cfg *c) {
/* variables to hold the values returned in the response */
char *issuer = NULL, *target_link_uri = NULL, *login_hint = NULL,
*auth_request_params = NULL, *csrf_cookie, *csrf_query = NULL,
*user = NULL, *path_scopes;
oidc_provider_t *provider = NULL;
oidc_util_get_request_parameter(r, OIDC_DISC_OP_PARAM, &issuer);
oidc_util_get_request_parameter(r, OIDC_DISC_USER_PARAM, &user);
oidc_util_get_request_parameter(r, OIDC_DISC_RT_PARAM, &target_link_uri);
oidc_util_get_request_parameter(r, OIDC_DISC_LH_PARAM, &login_hint);
oidc_util_get_request_parameter(r, OIDC_DISC_SC_PARAM, &path_scopes);
oidc_util_get_request_parameter(r, OIDC_DISC_AR_PARAM,
&auth_request_params);
oidc_util_get_request_parameter(r, OIDC_CSRF_NAME, &csrf_query);
csrf_cookie = oidc_util_get_cookie(r, OIDC_CSRF_NAME);
/* do CSRF protection if not 3rd party initiated SSO */
if (csrf_cookie) {
/* clean CSRF cookie */
oidc_util_set_cookie(r, OIDC_CSRF_NAME, "", 0, NULL);
/* compare CSRF cookie value with query parameter value */
if ((csrf_query == NULL)
|| apr_strnatcmp(csrf_query, csrf_cookie) != 0) {
oidc_warn(r,
"CSRF protection failed, no Discovery and dynamic client registration will be allowed");
csrf_cookie = NULL;
}
}
// TODO: trim issuer/accountname/domain input and do more input validation
oidc_debug(r,
"issuer=\"%s\", target_link_uri=\"%s\", login_hint=\"%s\", user=\"%s\"",
issuer, target_link_uri, login_hint, user);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"SSO to this module without specifying a \"target_link_uri\" parameter is not possible because " OIDCDefaultURL " is not set.",
HTTP_INTERNAL_SERVER_ERROR);
}
target_link_uri = c->default_sso_url;
}
/* do open redirect prevention */
if (oidc_target_link_uri_matches_configuration(r, c,
target_link_uri) == FALSE) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"\"target_link_uri\" parameter does not match configuration settings, aborting to prevent an open redirect.",
HTTP_UNAUTHORIZED);
}
/* see if this is a static setup */
if (c->metadata_dir == NULL) {
if ((oidc_provider_static_config(r, c, &provider) == TRUE)
&& (issuer != NULL)) {
if (apr_strnatcmp(provider->issuer, issuer) != 0) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
apr_psprintf(r->pool,
"The \"iss\" value must match the configured providers' one (%s != %s).",
issuer, c->provider.issuer),
HTTP_INTERNAL_SERVER_ERROR);
}
}
return oidc_authenticate_user(r, c, NULL, target_link_uri, login_hint,
NULL, NULL, auth_request_params, path_scopes);
}
/* find out if the user entered an account name or selected an OP manually */
if (user != NULL) {
if (login_hint == NULL)
login_hint = apr_pstrdup(r->pool, user);
/* normalize the user identifier */
if (strstr(user, "https://") != user)
user = apr_psprintf(r->pool, "https://%s", user);
/* got an user identifier as input, perform OP discovery with that */
if (oidc_proto_url_based_discovery(r, c, user, &issuer) == FALSE) {
/* something did not work out, show a user facing error */
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"Could not resolve the provided user identifier to an OpenID Connect provider; check your syntax.",
HTTP_NOT_FOUND);
}
/* issuer is set now, so let's continue as planned */
} else if (strstr(issuer, OIDC_STR_AT) != NULL) {
if (login_hint == NULL) {
login_hint = apr_pstrdup(r->pool, issuer);
//char *p = strstr(issuer, OIDC_STR_AT);
//*p = '\0';
}
/* got an account name as input, perform OP discovery with that */
if (oidc_proto_account_based_discovery(r, c, issuer, &issuer) == FALSE) {
/* something did not work out, show a user facing error */
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"Could not resolve the provided account name to an OpenID Connect provider; check your syntax.",
HTTP_NOT_FOUND);
}
/* issuer is set now, so let's continue as planned */
}
/* strip trailing '/' */
int n = strlen(issuer);
if (issuer[n - 1] == OIDC_CHAR_FORWARD_SLASH)
issuer[n - 1] = '\0';
/* try and get metadata from the metadata directories for the selected OP */
if ((oidc_metadata_get(r, c, issuer, &provider, csrf_cookie != NULL) == TRUE)
&& (provider != NULL)) {
/* now we've got a selected OP, send the user there to authenticate */
return oidc_authenticate_user(r, c, provider, target_link_uri,
login_hint, NULL, NULL, auth_request_params, path_scopes);
}
/* something went wrong */
return oidc_util_html_send_error(r, c->error_template, "Invalid Request",
"Could not find valid provider metadata for the selected OpenID Connect provider; contact the administrator",
HTTP_NOT_FOUND);
}
static apr_uint32_t oidc_transparent_pixel[17] = { 0x474e5089, 0x0a1a0a0d,
0x0d000000, 0x52444849, 0x01000000, 0x01000000, 0x00000408, 0x0c1cb500,
0x00000002, 0x4144490b, 0x639c7854, 0x0000cffa, 0x02010702, 0x71311c9a,
0x00000000, 0x444e4549, 0x826042ae };
static apr_byte_t oidc_is_front_channel_logout(const char *logout_param_value) {
return ((logout_param_value != NULL)
&& ((apr_strnatcmp(logout_param_value,
OIDC_GET_STYLE_LOGOUT_PARAM_VALUE) == 0)
|| (apr_strnatcmp(logout_param_value,
OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0)));
}
static apr_byte_t oidc_is_back_channel_logout(const char *logout_param_value) {
return ((logout_param_value != NULL) && (apr_strnatcmp(logout_param_value,
OIDC_BACKCHANNEL_STYLE_LOGOUT_PARAM_VALUE) == 0));
}
/*
* revoke refresh token and access token stored in the session if the
* OP has an RFC 7009 compliant token revocation endpoint
*/
static void oidc_revoke_tokens(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *response = NULL;
char *basic_auth = NULL;
char *bearer_auth = NULL;
apr_table_t *params = NULL;
const char *token = NULL;
oidc_provider_t *provider = NULL;
oidc_debug(r, "enter");
if (oidc_get_provider_from_session(r, c, session, &provider) == FALSE)
goto out;
oidc_debug(r, "revocation_endpoint=%s",
provider->revocation_endpoint_url ?
provider->revocation_endpoint_url : "(null)");
if (provider->revocation_endpoint_url == NULL)
goto out;
params = apr_table_make(r->pool, 4);
// add the token endpoint authentication credentials to the revocation endpoint call...
if (oidc_proto_token_endpoint_auth(r, c, provider->token_endpoint_auth,
provider->client_id, provider->client_secret,
provider->client_signing_keys, provider->token_endpoint_url, params,
NULL, &basic_auth, &bearer_auth) == FALSE)
goto out;
// TODO: use oauth.ssl_validate_server ...
token = oidc_session_get_refresh_token(r, session);
if (token != NULL) {
apr_table_addn(params, "token_type_hint", "refresh_token");
apr_table_addn(params, "token", token);
if (oidc_util_http_post_form(r, provider->revocation_endpoint_url,
params, basic_auth, bearer_auth, c->oauth.ssl_validate_server,
&response, c->http_timeout_long, c->outgoing_proxy,
oidc_dir_cfg_pass_cookies(r), NULL,
NULL) == FALSE) {
oidc_warn(r, "revoking refresh token failed");
}
apr_table_clear(params);
}
token = oidc_session_get_access_token(r, session);
if (token != NULL) {
apr_table_addn(params, "token_type_hint", "access_token");
apr_table_addn(params, "token", token);
if (oidc_util_http_post_form(r, provider->revocation_endpoint_url,
params, basic_auth, bearer_auth, c->oauth.ssl_validate_server,
&response, c->http_timeout_long, c->outgoing_proxy,
oidc_dir_cfg_pass_cookies(r), NULL,
NULL) == FALSE) {
oidc_warn(r, "revoking access token failed");
}
}
out:
oidc_debug(r, "leave");
}
/*
* handle a local logout
*/
static int oidc_handle_logout_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *url) {
oidc_debug(r, "enter (url=%s)", url);
/* if there's no remote_user then there's no (stored) session to kill */
if (session->remote_user != NULL) {
oidc_revoke_tokens(r, c, session);
/* remove session state (cq. cache entry and cookie) */
oidc_session_kill(r, session);
}
/* see if this is the OP calling us */
if (oidc_is_front_channel_logout(url)) {
/* set recommended cache control headers */
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_CACHE_CONTROL,
"no-cache, no-store");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_PRAGMA, "no-cache");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_P3P, "CAO PSA OUR");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_EXPIRES, "0");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_X_FRAME_OPTIONS, "DENY");
/* see if this is PF-PA style logout in which case we return a transparent pixel */
const char *accept = oidc_util_hdr_in_accept_get(r);
if ((apr_strnatcmp(url, OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0)
|| ((accept) && strstr(accept, OIDC_CONTENT_TYPE_IMAGE_PNG))) {
return oidc_util_http_send(r,
(const char *) &oidc_transparent_pixel,
sizeof(oidc_transparent_pixel), OIDC_CONTENT_TYPE_IMAGE_PNG,
OK);
}
/* standard HTTP based logout: should be called in an iframe from the OP */
return oidc_util_html_send(r, "Logged Out", NULL, NULL,
"<p>Logged Out</p>", OK);
}
/* see if we don't need to go somewhere special after killing the session locally */
if (url == NULL)
return oidc_util_html_send(r, "Logged Out", NULL, NULL,
"<p>Logged Out</p>", OK);
/* send the user to the specified where-to-go-after-logout URL */
oidc_util_hdr_out_location_set(r, url);
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle a backchannel logout
*/
#define OIDC_EVENTS_BLOGOUT_KEY "http://schemas.openid.net/event/backchannel-logout"
static int oidc_handle_logout_backchannel(request_rec *r, oidc_cfg *cfg) {
oidc_debug(r, "enter");
const char *logout_token = NULL;
oidc_jwt_t *jwt = NULL;
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
oidc_provider_t *provider = NULL;
char *sid = NULL, *uuid = NULL;
oidc_session_t session;
int rc = HTTP_BAD_REQUEST;
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r,
"could not read POST-ed parameters to the logout endpoint");
goto out;
}
logout_token = apr_table_get(params, OIDC_PROTO_LOGOUT_TOKEN);
if (logout_token == NULL) {
oidc_error(r,
"backchannel lggout endpoint was called but could not find a parameter named \"%s\"",
OIDC_PROTO_LOGOUT_TOKEN);
goto out;
}
// TODO: jwk symmetric key based on provider
// TODO: share more code with regular id_token validation and unsolicited state
if (oidc_jwt_parse(r->pool, logout_token, &jwt,
oidc_util_merge_symmetric_key(r->pool, cfg->private_keys, NULL),
&err) == FALSE) {
oidc_error(r, "oidc_jwt_parse failed: %s", oidc_jose_e2s(r->pool, err));
goto out;
}
provider = oidc_get_provider_for_issuer(r, cfg, jwt->payload.iss, FALSE);
if (provider == NULL) {
oidc_error(r, "no provider found for issuer: %s", jwt->payload.iss);
goto out;
}
// TODO: destroy the JWK used for decryption
jwk = NULL;
if (oidc_util_create_symmetric_key(r, provider->client_secret, 0,
NULL, TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwks_uri_t jwks_uri = { provider->jwks_uri,
provider->jwks_refresh_interval, provider->ssl_validate_server };
if (oidc_proto_jwt_verify(r, cfg, jwt, &jwks_uri,
oidc_util_merge_symmetric_key(r->pool, NULL, jwk)) == FALSE) {
oidc_error(r, "id_token signature could not be validated, aborting");
goto out;
}
// oidc_proto_validate_idtoken would try and require a token binding cnf
// if the policy is set to "required", so don't use that here
if (oidc_proto_validate_jwt(r, jwt, provider->issuer, FALSE, FALSE,
provider->idtoken_iat_slack,
OIDC_TOKEN_BINDING_POLICY_DISABLED) == FALSE)
goto out;
/* verify the "aud" and "azp" values */
if (oidc_proto_validate_aud_and_azp(r, cfg, provider,
&jwt->payload) == FALSE)
goto out;
json_t *events = json_object_get(jwt->payload.value.json,
OIDC_CLAIM_EVENTS);
if (events == NULL) {
oidc_error(r, "\"%s\" claim could not be found in logout token",
OIDC_CLAIM_EVENTS);
goto out;
}
json_t *blogout = json_object_get(events, OIDC_EVENTS_BLOGOUT_KEY);
if (!json_is_object(blogout)) {
oidc_error(r, "\"%s\" object could not be found in \"%s\" claim",
OIDC_EVENTS_BLOGOUT_KEY, OIDC_CLAIM_EVENTS);
goto out;
}
char *nonce = NULL;
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_NONCE, &nonce, NULL);
if (nonce != NULL) {
oidc_error(r,
"rejecting logout request/token since it contains a \"%s\" claim",
OIDC_CLAIM_NONCE);
goto out;
}
char *jti = NULL;
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_JTI, &jti, NULL);
if (jti != NULL) {
char *replay = NULL;
oidc_cache_get_jti(r, jti, &replay);
if (replay != NULL) {
oidc_error(r,
"the \"%s\" value (%s) passed in logout token was found in the cache already; possible replay attack!?",
OIDC_CLAIM_JTI, jti);
goto out;
}
}
/* jti cache duration is the configured replay prevention window for token issuance plus 10 seconds for safety */
apr_time_t jti_cache_duration = apr_time_from_sec(
provider->idtoken_iat_slack * 2 + 10);
/* store it in the cache for the calculated duration */
oidc_cache_set_jti(r, jti, jti, apr_time_now() + jti_cache_duration);
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_EVENTS, &sid, NULL);
// TODO: by-spec we should cater for the fact that "sid" has been provided
// in the id_token returned in the authentication request, but "sub"
// is used in the logout token but that requires a 2nd entry in the
// cache and a separate session "sub" member, ugh; we'll just assume
// that is "sid" is specified in the id_token, the OP will actually use
// this for logout
// (and probably call us multiple times or the same sub if needed)
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_SID, &sid, NULL);
if (sid == NULL)
sid = jwt->payload.sub;
if (sid == NULL) {
oidc_error(r, "no \"sub\" and no \"sid\" claim found in logout token");
goto out;
}
// TODO: when dealing with sub instead of a true sid, we'll be killing all sessions for
// a specific user, across hosts that share the *same* cache backend
// if those hosts haven't been configured with a different OIDCCryptoPassphrase
// - perhaps that's even acceptable since non-memory caching is encrypted by default
// and memory-based caching doesn't suffer from this (different shm segments)?
// - it will result in 400 errors returned from backchannel logout calls to the other hosts...
sid = oidc_make_sid_iss_unique(r, sid, provider->issuer);
oidc_cache_get_sid(r, sid, &uuid);
if (uuid == NULL) {
oidc_error(r,
"could not find session based on sid/sub provided in logout token: %s",
sid);
goto out;
}
// revoke tokens if we can get a handle on those
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
if (oidc_session_load_cache_by_uuid(r, cfg, uuid, &session) != FALSE)
if (oidc_session_extract(r, &session) != FALSE)
oidc_revoke_tokens(r, cfg, &session);
}
// clear the session cache
oidc_cache_set_sid(r, sid, NULL, 0);
oidc_cache_set_session(r, uuid, NULL, 0);
rc = OK;
out:
if (jwk != NULL) {
oidc_jwk_destroy(jwk);
jwk = NULL;
}
if (jwt != NULL) {
oidc_jwt_destroy(jwt);
jwt = NULL;
}
return rc;
}
static apr_byte_t oidc_validate_post_logout_url(request_rec *r, const char *url,
char **err_str, char **err_desc) {
apr_uri_t uri;
const char *c_host = NULL;
if (apr_uri_parse(r->pool, url, &uri) != APR_SUCCESS) {
*err_str = apr_pstrdup(r->pool, "Malformed URL");
*err_desc = apr_psprintf(r->pool, "Logout URL malformed: %s", url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
c_host = oidc_get_current_url_host(r);
if ((uri.hostname != NULL)
&& ((strstr(c_host, uri.hostname) == NULL)
|| (strstr(uri.hostname, c_host) == NULL))) {
*err_str = apr_pstrdup(r->pool, "Invalid Request");
*err_desc =
apr_psprintf(r->pool,
"logout value \"%s\" does not match the hostname of the current request \"%s\"",
apr_uri_unparse(r->pool, &uri, 0), c_host);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
} else if ((uri.hostname == NULL) && (strstr(url, "/") != url)) {
*err_str = apr_pstrdup(r->pool, "Malformed URL");
*err_desc =
apr_psprintf(r->pool,
"No hostname was parsed and it does not seem to be relative, i.e starting with '/': %s",
url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
/* validate the URL to prevent HTTP header splitting */
if (((strstr(url, "\n") != NULL) || strstr(url, "\r") != NULL)) {
*err_str = apr_pstrdup(r->pool, "Invalid Request");
*err_desc =
apr_psprintf(r->pool,
"logout value \"%s\" contains illegal \"\n\" or \"\r\" character(s)",
url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
return TRUE;
}
/*
* perform (single) logout
*/
static int oidc_handle_logout(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
oidc_provider_t *provider = NULL;
/* pickup the command or URL where the user wants to go after logout */
char *url = NULL;
char *error_str = NULL;
char *error_description = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_LOGOUT, &url);
oidc_debug(r, "enter (url=%s)", url);
if (oidc_is_front_channel_logout(url)) {
return oidc_handle_logout_request(r, c, session, url);
} else if (oidc_is_back_channel_logout(url)) {
return oidc_handle_logout_backchannel(r, c);
}
if ((url == NULL) || (apr_strnatcmp(url, "") == 0)) {
url = c->default_slo_url;
} else {
/* do input validation on the logout parameter value */
if (oidc_validate_post_logout_url(r, url, &error_str,
&error_description) == FALSE) {
return oidc_util_html_send_error(r, c->error_template, error_str,
error_description,
HTTP_BAD_REQUEST);
}
}
oidc_get_provider_from_session(r, c, session, &provider);
if ((provider != NULL) && (provider->end_session_endpoint != NULL)) {
const char *id_token_hint = oidc_session_get_idtoken(r, session);
char *logout_request = apr_pstrdup(r->pool,
provider->end_session_endpoint);
if (id_token_hint != NULL) {
logout_request = apr_psprintf(r->pool, "%s%sid_token_hint=%s",
logout_request, strchr(logout_request ? logout_request : "",
OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
oidc_util_escape_string(r, id_token_hint));
}
if (url != NULL) {
logout_request = apr_psprintf(r->pool,
"%s%spost_logout_redirect_uri=%s", logout_request,
strchr(logout_request ? logout_request : "",
OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
oidc_util_escape_string(r, url));
}
url = logout_request;
}
return oidc_handle_logout_request(r, c, session, url);
}
/*
* handle request for JWKs
*/
int oidc_handle_jwks(request_rec *r, oidc_cfg *c) {
/* pickup requested JWKs type */
// char *jwks_type = NULL;
// oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_JWKS, &jwks_type);
char *jwks = apr_pstrdup(r->pool, "{ \"keys\" : [");
apr_hash_index_t *hi = NULL;
apr_byte_t first = TRUE;
oidc_jose_error_t err;
if (c->public_keys != NULL) {
/* loop over the RSA public keys */
for (hi = apr_hash_first(r->pool, c->public_keys); hi; hi =
apr_hash_next(hi)) {
const char *s_kid = NULL;
oidc_jwk_t *jwk = NULL;
char *s_json = NULL;
apr_hash_this(hi, (const void**) &s_kid, NULL, (void**) &jwk);
if (oidc_jwk_to_json(r->pool, jwk, &s_json, &err) == TRUE) {
jwks = apr_psprintf(r->pool, "%s%s %s ", jwks, first ? "" : ",",
s_json);
first = FALSE;
} else {
oidc_error(r,
"could not convert RSA JWK to JSON using oidc_jwk_to_json: %s",
oidc_jose_e2s(r->pool, err));
}
}
}
// TODO: send stuff if first == FALSE?
jwks = apr_psprintf(r->pool, "%s ] }", jwks);
return oidc_util_http_send(r, jwks, strlen(jwks), OIDC_CONTENT_TYPE_JSON,
OK);
}
static int oidc_handle_session_management_iframe_op(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *check_session_iframe) {
oidc_debug(r, "enter");
oidc_util_hdr_out_location_set(r, check_session_iframe);
return HTTP_MOVED_TEMPORARILY;
}
static int oidc_handle_session_management_iframe_rp(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *client_id,
const char *check_session_iframe) {
oidc_debug(r, "enter");
const char *java_script =
" <script type=\"text/javascript\">\n"
" var targetOrigin = '%s';\n"
" var message = '%s' + ' ' + '%s';\n"
" var timerID;\n"
"\n"
" function checkSession() {\n"
" console.debug('checkSession: posting ' + message + ' to ' + targetOrigin);\n"
" var win = window.parent.document.getElementById('%s').contentWindow;\n"
" win.postMessage( message, targetOrigin);\n"
" }\n"
"\n"
" function setTimer() {\n"
" checkSession();\n"
" timerID = setInterval('checkSession()', %d);\n"
" }\n"
"\n"
" function receiveMessage(e) {\n"
" console.debug('receiveMessage: ' + e.data + ' from ' + e.origin);\n"
" if (e.origin !== targetOrigin ) {\n"
" console.debug('receiveMessage: cross-site scripting attack?');\n"
" return;\n"
" }\n"
" if (e.data != 'unchanged') {\n"
" clearInterval(timerID);\n"
" if (e.data == 'changed') {\n"
" window.location.href = '%s?session=check';\n"
" } else {\n"
" window.location.href = '%s?session=logout';\n"
" }\n"
" }\n"
" }\n"
"\n"
" window.addEventListener('message', receiveMessage, false);\n"
"\n"
" </script>\n";
/* determine the origin for the check_session_iframe endpoint */
char *origin = apr_pstrdup(r->pool, check_session_iframe);
apr_uri_t uri;
apr_uri_parse(r->pool, check_session_iframe, &uri);
char *p = strstr(origin, uri.path);
*p = '\0';
/* the element identifier for the OP iframe */
const char *op_iframe_id = "openidc-op";
/* restore the OP session_state from the session */
const char *session_state = oidc_session_get_session_state(r, session);
if (session_state == NULL) {
oidc_warn(r,
"no session_state found in the session; the OP does probably not support session management!?");
return OK;
}
char *s_poll_interval = NULL;
oidc_util_get_request_parameter(r, "poll", &s_poll_interval);
int poll_interval = s_poll_interval ? strtol(s_poll_interval, NULL, 10) : 0;
if ((poll_interval <= 0) || (poll_interval > 3600 * 24))
poll_interval = 3000;
const char *redirect_uri = oidc_get_redirect_uri(r, c);
java_script = apr_psprintf(r->pool, java_script, origin, client_id,
session_state, op_iframe_id, poll_interval, redirect_uri,
redirect_uri);
return oidc_util_html_send(r, NULL, java_script, "setTimer", NULL, OK);
}
/*
* handle session management request
*/
static int oidc_handle_session_management(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *cmd = NULL;
const char *id_token_hint = NULL;
oidc_provider_t *provider = NULL;
/* get the command passed to the session management handler */
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_SESSION, &cmd);
if (cmd == NULL) {
oidc_error(r, "session management handler called with no command");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if this is a local logout during session management */
if (apr_strnatcmp("logout", cmd) == 0) {
oidc_debug(r,
"[session=logout] calling oidc_handle_logout_request because of session mgmt local logout call.");
return oidc_handle_logout_request(r, c, session, c->default_slo_url);
}
oidc_get_provider_from_session(r, c, session, &provider);
/* see if this is a request for the OP iframe */
if (apr_strnatcmp("iframe_op", cmd) == 0) {
if (provider->check_session_iframe != NULL) {
return oidc_handle_session_management_iframe_op(r, c, session,
provider->check_session_iframe);
}
return HTTP_NOT_FOUND;
}
/* see if this is a request for the RP iframe */
if (apr_strnatcmp("iframe_rp", cmd) == 0) {
if ((provider->client_id != NULL)
&& (provider->check_session_iframe != NULL)) {
return oidc_handle_session_management_iframe_rp(r, c, session,
provider->client_id, provider->check_session_iframe);
}
oidc_debug(r,
"iframe_rp command issued but no client (%s) and/or no check_session_iframe (%s) set",
provider->client_id, provider->check_session_iframe);
return HTTP_NOT_FOUND;
}
/* see if this is a request check the login state with the OP */
if (apr_strnatcmp("check", cmd) == 0) {
id_token_hint = oidc_session_get_idtoken(r, session);
if ((session->remote_user != NULL) && (provider != NULL)) {
/*
* TODO: this doesn't work with per-path provided auth_request_params and scopes
* as oidc_dir_cfg_path_auth_request_params and oidc_dir_cfg_path_scope will pick
* those for the redirect_uri itself; do we need to store those as part of the
* session now?
*/
return oidc_authenticate_user(r, c, provider,
apr_psprintf(r->pool, "%s?session=iframe_rp",
oidc_get_redirect_uri_iss(r, c, provider)), NULL,
id_token_hint, "none",
oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
}
oidc_debug(r,
"[session=check] calling oidc_handle_logout_request because no session found.");
return oidc_session_redirect_parent_window_to_logout(r, c);
}
/* handle failure in fallthrough */
oidc_error(r, "unknown command: %s", cmd);
return HTTP_INTERNAL_SERVER_ERROR;
}
/*
* handle refresh token request
*/
static int oidc_handle_refresh_token_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *return_to = NULL;
char *r_access_token = NULL;
char *error_code = NULL;
/* get the command passed to the session management handler */
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_REFRESH,
&return_to);
oidc_util_get_request_parameter(r, OIDC_PROTO_ACCESS_TOKEN,
&r_access_token);
/* check the input parameters */
if (return_to == NULL) {
oidc_error(r,
"refresh token request handler called with no URL to return to");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (r_access_token == NULL) {
oidc_error(r,
"refresh token request handler called with no access_token parameter");
error_code = "no_access_token";
goto end;
}
const char *s_access_token = oidc_session_get_access_token(r, session);
if (s_access_token == NULL) {
oidc_error(r,
"no existing access_token found in the session, nothing to refresh");
error_code = "no_access_token_exists";
goto end;
}
/* compare the access_token parameter used for XSRF protection */
if (apr_strnatcmp(s_access_token, r_access_token) != 0) {
oidc_error(r,
"access_token passed in refresh request does not match the one stored in the session");
error_code = "no_access_token_match";
goto end;
}
/* get a handle to the provider configuration */
oidc_provider_t *provider = NULL;
if (oidc_get_provider_from_session(r, c, session, &provider) == FALSE) {
error_code = "session_corruption";
goto end;
}
/* execute the actual refresh grant */
if (oidc_refresh_access_token(r, c, session, provider, NULL) == FALSE) {
oidc_error(r, "access_token could not be refreshed");
error_code = "refresh_failed";
goto end;
}
/* pass the tokens to the application and save the session, possibly updating the expiry */
if (oidc_session_pass_tokens_and_save(r, c, session, TRUE) == FALSE) {
error_code = "session_corruption";
goto end;
}
end:
/* pass optional error message to the return URL */
if (error_code != NULL)
return_to = apr_psprintf(r->pool, "%s%serror_code=%s", return_to,
strchr(return_to ? return_to : "", OIDC_CHAR_QUERY) ?
OIDC_STR_AMP :
OIDC_STR_QUERY, oidc_util_escape_string(r, error_code));
/* add the redirect location header */
oidc_util_hdr_out_location_set(r, return_to);
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle request object by reference request
*/
static int oidc_handle_request_uri(request_rec *r, oidc_cfg *c) {
char *request_ref = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_REQUEST_URI,
&request_ref);
if (request_ref == NULL) {
oidc_error(r, "no \"%s\" parameter found",
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI);
return HTTP_BAD_REQUEST;
}
char *jwt = NULL;
oidc_cache_get_request_uri(r, request_ref, &jwt);
if (jwt == NULL) {
oidc_error(r, "no cached JWT found for %s reference: %s",
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI, request_ref);
return HTTP_NOT_FOUND;
}
oidc_cache_set_request_uri(r, request_ref, NULL, 0);
return oidc_util_http_send(r, jwt, strlen(jwt), OIDC_CONTENT_TYPE_JWT, OK);
}
/*
* handle a request to invalidate a cached access token introspection result
*/
int oidc_handle_remove_at_cache(request_rec *r, oidc_cfg *c) {
char *access_token = NULL;
oidc_util_get_request_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REMOVE_AT_CACHE, &access_token);
char *cache_entry = NULL;
oidc_cache_get_access_token(r, access_token, &cache_entry);
if (cache_entry == NULL) {
oidc_error(r, "no cached access token found for value: %s",
access_token);
return HTTP_NOT_FOUND;
}
oidc_cache_set_access_token(r, access_token, NULL, 0);
return OK;
}
#define OIDC_INFO_PARAM_ACCESS_TOKEN_REFRESH_INTERVAL "access_token_refresh_interval"
/*
* handle request for session info
*/
static int oidc_handle_info_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
int rc = HTTP_UNAUTHORIZED;
apr_byte_t needs_save = FALSE;
char *s_format = NULL, *s_interval = NULL, *r_value = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_INFO,
&s_format);
oidc_util_get_request_parameter(r,
OIDC_INFO_PARAM_ACCESS_TOKEN_REFRESH_INTERVAL, &s_interval);
/* see if this is a request for a format that is supported */
if ((apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_JSON, s_format) != 0)
&& (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_HTML, s_format) != 0)) {
oidc_warn(r, "request for unknown format: %s", s_format);
return HTTP_UNSUPPORTED_MEDIA_TYPE;
}
/* check that we actually have a user session and this is someone calling with a proper session cookie */
if (session->remote_user == NULL) {
oidc_warn(r, "no user session found");
return HTTP_UNAUTHORIZED;
}
/* set the user in the main request for further (incl. sub-request and authz) processing */
r->user = apr_pstrdup(r->pool, session->remote_user);
if (c->info_hook_data == NULL) {
oidc_warn(r, "no data configured to return in " OIDCInfoHook);
return HTTP_NOT_FOUND;
}
/* see if we can and need to refresh the access token */
if ((s_interval != NULL)
&& (oidc_session_get_refresh_token(r, session) != NULL)) {
apr_time_t t_interval;
if (sscanf(s_interval, "%" APR_TIME_T_FMT, &t_interval) == 1) {
t_interval = apr_time_from_sec(t_interval);
/* get the last refresh timestamp from the session info */
apr_time_t last_refresh =
oidc_session_get_access_token_last_refresh(r, session);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(last_refresh + t_interval - apr_time_now()));
/* see if we need to refresh again */
if (last_refresh + t_interval < apr_time_now()) {
/* get the current provider info */
oidc_provider_t *provider = NULL;
if (oidc_get_provider_from_session(r, c, session,
&provider) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* execute the actual refresh grant */
if (oidc_refresh_access_token(r, c, session, provider,
NULL) == FALSE)
oidc_warn(r, "access_token could not be refreshed");
else
needs_save = TRUE;
}
}
}
/* create the JSON object */
json_t *json = json_object();
/* add a timestamp of creation in there for the caller */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_TIMESTAMP,
APR_HASH_KEY_STRING)) {
json_object_set_new(json, OIDC_HOOK_INFO_TIMESTAMP,
json_integer(apr_time_sec(apr_time_now())));
}
/*
* refresh the claims from the userinfo endpoint
* side-effect is that this may refresh the access token if not already done
* note that OIDCUserInfoRefreshInterval should be set to control the refresh policy
*/
needs_save |= oidc_refresh_claims_from_userinfo_endpoint(r, c, session);
/* include the access token in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ACCES_TOKEN,
APR_HASH_KEY_STRING)) {
const char *access_token = oidc_session_get_access_token(r, session);
if (access_token != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_ACCES_TOKEN,
json_string(access_token));
}
/* include the access token expiry timestamp in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ACCES_TOKEN_EXP,
APR_HASH_KEY_STRING)) {
const char *access_token_expires =
oidc_session_get_access_token_expires(r, session);
if (access_token_expires != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_ACCES_TOKEN_EXP,
json_string(access_token_expires));
}
/* include the id_token claims in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ID_TOKEN,
APR_HASH_KEY_STRING)) {
json_t *id_token = oidc_session_get_idtoken_claims_json(r, session);
if (id_token)
json_object_set_new(json, OIDC_HOOK_INFO_ID_TOKEN, id_token);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_USER_INFO,
APR_HASH_KEY_STRING)) {
/* include the claims from the userinfo endpoint the session info */
json_t *claims = oidc_session_get_userinfo_claims_json(r, session);
if (claims)
json_object_set_new(json, OIDC_HOOK_INFO_USER_INFO, claims);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_SESSION,
APR_HASH_KEY_STRING)) {
json_t *j_session = json_object();
json_object_set(j_session, OIDC_HOOK_INFO_SESSION_STATE,
session->state);
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_UUID,
json_string(session->uuid));
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_TIMEOUT,
json_integer(apr_time_sec(session->expiry)));
apr_time_t session_expires = oidc_session_get_session_expires(r,
session);
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_EXP,
json_integer(apr_time_sec(session_expires)));
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_REMOTE_USER,
json_string(session->remote_user));
json_object_set_new(json, OIDC_HOOK_INFO_SESSION, j_session);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_REFRESH_TOKEN,
APR_HASH_KEY_STRING)) {
/* include the refresh token in the session info */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if (refresh_token != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_REFRESH_TOKEN,
json_string(refresh_token));
}
if (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_JSON, s_format) == 0) {
/* JSON-encode the result */
r_value = oidc_util_encode_json_object(r, json, 0);
/* return the stringified JSON result */
rc = oidc_util_http_send(r, r_value, strlen(r_value),
OIDC_CONTENT_TYPE_JSON, OK);
} else if (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_HTML, s_format) == 0) {
/* JSON-encode the result */
r_value = oidc_util_encode_json_object(r, json, JSON_INDENT(2));
rc = oidc_util_html_send(r, "Session Info", NULL, NULL,
apr_psprintf(r->pool, "<pre>%s</pre>", r_value), OK);
}
/* free the allocated resources */
json_decref(json);
/* pass the tokens to the application and save the session, possibly updating the expiry */
if (oidc_session_pass_tokens_and_save(r, c, session, needs_save) == FALSE) {
oidc_warn(r, "error saving session");
rc = HTTP_INTERNAL_SERVER_ERROR;
}
return rc;
}
/*
* handle all requests to the redirect_uri
*/
int oidc_handle_redirect_uri_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
if (oidc_proto_is_redirect_authorization_response(r, c)) {
/* this is an authorization response from the OP using the Basic Client profile or a Hybrid flow*/
return oidc_handle_redirect_authorization_response(r, c, session);
/*
*
* Note that we are checking for logout *before* checking for a POST authorization response
* to handle backchannel POST-based logout
*
* so any POST to the Redirect URI that does not have a logout query parameter will be handled
* as an authorization response; alternatively we could assume that a POST response has no
* parameters
*/
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_LOGOUT)) {
/* handle logout */
return oidc_handle_logout(r, c, session);
} else if (oidc_proto_is_post_authorization_response(r, c)) {
/* this is an authorization response using the fragment(+POST) response_mode with the Implicit Client profile */
return oidc_handle_post_authorization_response(r, c, session);
} else if (oidc_is_discovery_response(r, c)) {
/* this is response from the OP discovery page */
return oidc_handle_discovery_response(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_JWKS)) {
/* handle JWKs request */
return oidc_handle_jwks(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_SESSION)) {
/* handle session management request */
return oidc_handle_session_management(r, c, session);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REFRESH)) {
/* handle refresh token request */
return oidc_handle_refresh_token_request(r, c, session);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI)) {
/* handle request object by reference request */
return oidc_handle_request_uri(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REMOVE_AT_CACHE)) {
/* handle request to invalidate access token cache */
return oidc_handle_remove_at_cache(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_INFO)) {
if (session->remote_user == NULL)
return HTTP_UNAUTHORIZED;
/* set r->user, set headers/env-vars, update expiry, update userinfo + AT */
int rc = oidc_handle_existing_session(r, c, session);
if (rc != OK)
return rc;
return oidc_handle_info_request(r, c, session);
} else if ((r->args == NULL) || (apr_strnatcmp(r->args, "") == 0)) {
/* this is a "bare" request to the redirect URI, indicating implicit flow using the fragment response_mode */
return oidc_proto_javascript_implicit(r, c);
}
/* this is not an authorization response or logout request */
/* check for "error" response */
if (oidc_util_request_has_parameter(r, OIDC_PROTO_ERROR)) {
// char *error = NULL, *descr = NULL;
// oidc_util_get_request_parameter(r, "error", &error);
// oidc_util_get_request_parameter(r, "error_description", &descr);
//
// /* send user facing error to browser */
// return oidc_util_html_send_error(r, error, descr, DONE);
return oidc_handle_redirect_authorization_response(r, c, session);
}
oidc_error(r,
"The OpenID Connect callback URL received an invalid request: %s; returning HTTP_INTERNAL_SERVER_ERROR",
r->args);
/* something went wrong */
return oidc_util_html_send_error(r, c->error_template, "Invalid Request",
apr_psprintf(r->pool,
"The OpenID Connect callback URL received an invalid request"),
HTTP_INTERNAL_SERVER_ERROR);
}
#define OIDC_AUTH_TYPE_OPENID_CONNECT "openid-connect"
#define OIDC_AUTH_TYPE_OPENID_OAUTH20 "oauth20"
#define OIDC_AUTH_TYPE_OPENID_BOTH "auth-openidc"
/*
* main routine: handle OpenID Connect authentication
*/
static int oidc_check_userid_openidc(request_rec *r, oidc_cfg *c) {
if (oidc_get_redirect_uri(r, c) == NULL) {
oidc_error(r,
"configuration error: the authentication type is set to \"" OIDC_AUTH_TYPE_OPENID_CONNECT "\" but " OIDCRedirectURI " has not been set");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* check if this is a sub-request or an initial request */
if (ap_is_initial_req(r)) {
int rc = OK;
/* load the session from the request state; this will be a new "empty" session if no state exists */
oidc_session_t *session = NULL;
oidc_session_load(r, &session);
/* see if the initial request is to the redirect URI; this handles potential logout too */
if (oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, c))) {
/* handle request to the redirect_uri */
rc = oidc_handle_redirect_uri_request(r, c, session);
/* free resources allocated for the session */
oidc_session_free(r, session);
return rc;
/* initial request to non-redirect URI, check if we have an existing session */
} else if (session->remote_user != NULL) {
/* this is initial request and we already have a session */
rc = oidc_handle_existing_session(r, c, session);
/* free resources allocated for the session */
oidc_session_free(r, session);
/* strip any cookies that we need to */
oidc_strip_cookies(r);
return rc;
}
/* free resources allocated for the session */
oidc_session_free(r, session);
/*
* else: initial request, we have no session and it is not an authorization or
* discovery response: just hit the default flow for unauthenticated users
*/
} else {
/* not an initial request, try to recycle what we've already established in the main request */
if (r->main != NULL)
r->user = r->main->user;
else if (r->prev != NULL)
r->user = r->prev->user;
if (r->user != NULL) {
/* this is a sub-request and we have a session (headers will have been scrubbed and set already) */
oidc_debug(r,
"recycling user '%s' from initial request for sub-request",
r->user);
/*
* apparently request state can get lost in sub-requests, so let's see
* if we need to restore id_token and/or claims from the session cache
*/
const char *s_id_token = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_IDTOKEN);
if (s_id_token == NULL) {
oidc_session_t *session = NULL;
oidc_session_load(r, &session);
oidc_copy_tokens_to_request_state(r, session, NULL, NULL);
/* free resources allocated for the session */
oidc_session_free(r, session);
}
/* strip any cookies that we need to */
oidc_strip_cookies(r);
return OK;
}
/*
* else: not initial request, but we could not find a session, so:
* just hit the default flow for unauthenticated users
*/
}
return oidc_handle_unauthenticated_user(r, c);
}
/*
* main routine: handle "mixed" OIDC/OAuth authentication
*/
static int oidc_check_mixed_userid_oauth(request_rec *r, oidc_cfg *c) {
/* get the bearer access token from the Authorization header */
const char *access_token = NULL;
if (oidc_oauth_get_bearer_token(r, &access_token) == TRUE)
return oidc_oauth_check_userid(r, c, access_token);
/* no bearer token found: then treat this as a regular OIDC browser request */
return oidc_check_userid_openidc(r, c);
}
/*
* generic Apache authentication hook for this module: dispatches to OpenID Connect or OAuth 2.0 specific routines
*/
int oidc_check_user_id(request_rec *r) {
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
/* log some stuff about the incoming HTTP request */
oidc_debug(r, "incoming request: \"%s?%s\", ap_is_initial_req(r)=%d",
r->parsed_uri.path, r->args, ap_is_initial_req(r));
/* see if any authentication has been defined at all */
if (ap_auth_type(r) == NULL)
return DECLINED;
/* see if we've configured OpenID Connect user authentication for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_CONNECT) == 0)
return oidc_check_userid_openidc(r, c);
/* see if we've configured OAuth 2.0 access control for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0)
return oidc_oauth_check_userid(r, c, NULL);
/* see if we've configured "mixed mode" for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_BOTH) == 0)
return oidc_check_mixed_userid_oauth(r, c);
/* this is not for us but for some other handler */
return DECLINED;
}
/*
* get the claims and id_token from request state
*/
static void oidc_authz_get_claims_and_idtoken(request_rec *r, json_t **claims,
json_t **id_token) {
const char *s_claims = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_CLAIMS);
if (s_claims != NULL)
oidc_util_decode_json_object(r, s_claims, claims);
const char *s_id_token = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_IDTOKEN);
if (s_id_token != NULL)
oidc_util_decode_json_object(r, s_id_token, id_token);
}
#if MODULE_MAGIC_NUMBER_MAJOR >= 20100714
/*
* find out which action we need to take when encountering an unauthorized request
*/
static authz_status oidc_handle_unauthorized_user24(request_rec *r) {
oidc_debug(r, "enter");
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0) {
oidc_oauth_return_www_authenticate(r, "insufficient_scope",
"Different scope(s) or other claims required");
return AUTHZ_DENIED;
}
/* see if we've configured OIDCUnAutzAction for this path */
switch (oidc_dir_cfg_unautz_action(r)) {
// TODO: document that AuthzSendForbiddenOnFailure is required to return 403 FORBIDDEN
case OIDC_UNAUTZ_RETURN403:
case OIDC_UNAUTZ_RETURN401:
return AUTHZ_DENIED;
break;
case OIDC_UNAUTZ_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return AUTHZ_DENIED;
break;
}
oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
const char *location = oidc_util_hdr_out_location_get(r);
if (location != NULL) {
oidc_debug(r, "send HTML refresh with authorization redirect: %s",
location);
char *html_head = apr_psprintf(r->pool,
"<meta http-equiv=\"refresh\" content=\"0; url=%s\">",
location);
oidc_util_html_send(r, "Stepup Authentication", html_head, NULL, NULL,
HTTP_UNAUTHORIZED);
}
return AUTHZ_DENIED;
}
/*
* generic Apache >=2.4 authorization hook for this module
* handles both OpenID Connect or OAuth 2.0 in the same way, based on the claims stored in the session
*/
authz_status oidc_authz_checker(request_rec *r, const char *require_args,
const void *parsed_require_args,
oidc_authz_match_claim_fn_type match_claim_fn) {
oidc_debug(r, "enter");
/* check for anonymous access and PASS mode */
if (r->user != NULL && strlen(r->user) == 0) {
r->user = NULL;
if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS)
return AUTHZ_GRANTED;
}
/* get the set of claims from the request state (they've been set in the authentication part earlier */
json_t *claims = NULL, *id_token = NULL;
oidc_authz_get_claims_and_idtoken(r, &claims, &id_token);
/* merge id_token claims (e.g. "iss") in to claims json object */
if (claims)
oidc_util_json_merge(r, id_token, claims);
/* dispatch to the >=2.4 specific authz routine */
authz_status rc = oidc_authz_worker24(r, claims ? claims : id_token,
require_args, match_claim_fn);
/* cleanup */
if (claims)
json_decref(claims);
if (id_token)
json_decref(id_token);
if ((rc == AUTHZ_DENIED) && ap_auth_type(r))
rc = oidc_handle_unauthorized_user24(r);
return rc;
}
authz_status oidc_authz_checker_claim(request_rec *r, const char *require_args,
const void *parsed_require_args) {
return oidc_authz_checker(r, require_args, parsed_require_args,
oidc_authz_match_claim);
}
#ifdef USE_LIBJQ
authz_status oidc_authz_checker_claims_expr(request_rec *r, const char *require_args, const void *parsed_require_args) {
return oidc_authz_checker(r, require_args, parsed_require_args, oidc_authz_match_claims_expr);
}
#endif
#else
/*
* find out which action we need to take when encountering an unauthorized request
*/
static int oidc_handle_unauthorized_user22(request_rec *r) {
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
if (apr_strnatcasecmp((const char *) ap_auth_type(r), OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0) {
oidc_oauth_return_www_authenticate(r, "insufficient_scope", "Different scope(s) or other claims required");
return HTTP_UNAUTHORIZED;
}
/* see if we've configured OIDCUnAutzAction for this path */
switch (oidc_dir_cfg_unautz_action(r)) {
case OIDC_UNAUTZ_RETURN403:
return HTTP_FORBIDDEN;
case OIDC_UNAUTZ_RETURN401:
return HTTP_UNAUTHORIZED;
case OIDC_UNAUTZ_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return HTTP_UNAUTHORIZED;
}
return oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r), oidc_dir_cfg_path_scope(r));
}
/*
* generic Apache <2.4 authorization hook for this module
* handles both OpenID Connect and OAuth 2.0 in the same way, based on the claims stored in the request context
*/
int oidc_auth_checker(request_rec *r) {
/* check for anonymous access and PASS mode */
if (r->user != NULL && strlen(r->user) == 0) {
r->user = NULL;
if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS)
return OK;
}
/* get the set of claims from the request state (they've been set in the authentication part earlier */
json_t *claims = NULL, *id_token = NULL;
oidc_authz_get_claims_and_idtoken(r, &claims, &id_token);
/* get the Require statements */
const apr_array_header_t * const reqs_arr = ap_requires(r);
/* see if we have any */
const require_line * const reqs =
reqs_arr ? (require_line *) reqs_arr->elts : NULL;
if (!reqs_arr) {
oidc_debug(r,
"no require statements found, so declining to perform authorization.");
return DECLINED;
}
/* merge id_token claims (e.g. "iss") in to claims json object */
if (claims)
oidc_util_json_merge(r, id_token, claims);
/* dispatch to the <2.4 specific authz routine */
int rc = oidc_authz_worker22(r, claims ? claims : id_token, reqs,
reqs_arr->nelts);
/* cleanup */
if (claims)
json_decref(claims);
if (id_token)
json_decref(id_token);
if ((rc == HTTP_UNAUTHORIZED) && ap_auth_type(r))
rc = oidc_handle_unauthorized_user22(r);
return rc;
}
#endif
apr_byte_t oidc_enabled(request_rec *r) {
if (ap_auth_type(r) == NULL)
return FALSE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_CONNECT) == 0)
return TRUE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0)
return TRUE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_BOTH) == 0)
return TRUE;
return FALSE;
}
/*
* handle content generating requests
*/
int oidc_content_handler(request_rec *r) {
if (oidc_enabled(r) == FALSE)
return DECLINED;
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
return oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, c)) ?
OK : DECLINED;
}
extern const command_rec oidc_config_cmds[];
module AP_MODULE_DECLARE_DATA auth_openidc_module = {
STANDARD20_MODULE_STUFF,
oidc_create_dir_config,
oidc_merge_dir_config,
oidc_create_server_config,
oidc_merge_server_config,
oidc_config_cmds,
oidc_register_hooks
};
| ./CrossVul/dataset_final_sorted/CWE-601/c/good_1002_2 |
crossvul-cpp_data_good_1001_3 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/***************************************************************************
* Copyright (C) 2017-2019 ZmartZone IAM
* Copyright (C) 2013-2017 Ping Identity Corporation
* All rights reserved.
*
* For further information please contact:
*
* Ping Identity Corporation
* 1099 18th St Suite 2950
* Denver, CO 80202
* 303.468.2900
* http://www.pingidentity.com
*
* DISCLAIMER OF WARRANTIES:
*
* THE SOFTWARE PROVIDED HEREUNDER IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
* ANY WARRANTIES OR REPRESENTATIONS EXPRESS, IMPLIED OR STATUTORY; INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF QUALITY, PERFORMANCE, NONINFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NOR ARE THERE ANY
* WARRANTIES CREATED BY A COURSE OR DEALING, COURSE OF PERFORMANCE OR TRADE
* USAGE. FURTHERMORE, THERE ARE NO WARRANTIES THAT THE SOFTWARE WILL MEET
* YOUR NEEDS OR BE FREE FROM ERRORS, OR THAT THE OPERATION OF THE SOFTWARE
* WILL BE UNINTERRUPTED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES 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.
*
* Initially based on mod_auth_cas.c:
* https://github.com/Jasig/mod_auth_cas
*
* Other code copied/borrowed/adapted:
* shared memory caching: mod_auth_mellon
*
* @Author: Hans Zandbelt - hans.zandbelt@zmartzone.eu
*
**************************************************************************/
#include "apr_hash.h"
#include "apr_strings.h"
#include "ap_config.h"
#include "ap_provider.h"
#include "apr_lib.h"
#include "apr_file_io.h"
#include "apr_sha1.h"
#include "apr_base64.h"
#include "httpd.h"
#include "http_core.h"
#include "http_config.h"
#include "http_log.h"
#include "http_protocol.h"
#include "http_request.h"
#include "mod_auth_openidc.h"
#define ERROR 2
static int oidc_handle_logout_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *url);
// TODO:
// - sort out oidc_cfg vs. oidc_dir_cfg stuff
// - rigid input checking on discovery responses
// - check self-issued support
// - README.quickstart
// - refresh metadata once-per too? (for non-signing key changes)
extern module AP_MODULE_DECLARE_DATA auth_openidc_module;
/*
* clean any suspicious headers in the HTTP request sent by the user agent
*/
static void oidc_scrub_request_headers(request_rec *r, const char *claim_prefix,
apr_hash_t *scrub) {
const int prefix_len = claim_prefix ? strlen(claim_prefix) : 0;
/* get an array representation of the incoming HTTP headers */
const apr_array_header_t * const h = apr_table_elts(r->headers_in);
/* table to keep the non-suspicious headers */
apr_table_t *clean_headers = apr_table_make(r->pool, h->nelts);
/* loop over the incoming HTTP headers */
const apr_table_entry_t * const e = (const apr_table_entry_t *) h->elts;
int i;
for (i = 0; i < h->nelts; i++) {
const char * const k = e[i].key;
/* is this header's name equivalent to a header that needs scrubbing? */
const char *hdr =
(k != NULL) && (scrub != NULL) ?
apr_hash_get(scrub, k, APR_HASH_KEY_STRING) : NULL;
const int header_matches = (hdr != NULL)
&& (oidc_strnenvcmp(k, hdr, -1) == 0);
/*
* would this header be interpreted as a mod_auth_openidc attribute? Note
* that prefix_len will be zero if no attr_prefix is defined,
* so this will always be false. Also note that we do not
* scrub headers if the prefix is empty because every header
* would match.
*/
const int prefix_matches = (k != NULL) && prefix_len
&& (oidc_strnenvcmp(k, claim_prefix, prefix_len) == 0);
/* add to the clean_headers if non-suspicious, skip and report otherwise */
if (!prefix_matches && !header_matches) {
apr_table_addn(clean_headers, k, e[i].val);
} else {
oidc_warn(r, "scrubbed suspicious request header (%s: %.32s)", k,
e[i].val);
}
}
/* overwrite the incoming headers with the cleaned result */
r->headers_in = clean_headers;
}
/*
* scrub all mod_auth_openidc related headers
*/
void oidc_scrub_headers(request_rec *r) {
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
const char *prefix = oidc_cfg_claim_prefix(r);
apr_hash_t *hdrs = apr_hash_make(r->pool);
if (apr_strnatcmp(prefix, "") == 0) {
if ((cfg->white_listed_claims != NULL)
&& (apr_hash_count(cfg->white_listed_claims) > 0))
hdrs = apr_hash_overlay(r->pool, cfg->white_listed_claims, hdrs);
else
oidc_warn(r,
"both " OIDCClaimPrefix " and " OIDCWhiteListedClaims " are empty: this renders an insecure setup!");
}
char *authn_hdr = oidc_cfg_dir_authn_header(r);
if (authn_hdr != NULL)
apr_hash_set(hdrs, authn_hdr, APR_HASH_KEY_STRING, authn_hdr);
/*
* scrub all headers starting with OIDC_ first
*/
oidc_scrub_request_headers(r, OIDC_DEFAULT_HEADER_PREFIX, hdrs);
/*
* then see if the claim headers need to be removed on top of that
* (i.e. the prefix does not start with the default OIDC_)
*/
if ((strstr(prefix, OIDC_DEFAULT_HEADER_PREFIX) != prefix)) {
oidc_scrub_request_headers(r, prefix, NULL);
}
}
/*
* strip the session cookie from the headers sent to the application/backend
*/
void oidc_strip_cookies(request_rec *r) {
char *cookie, *ctx, *result = NULL;
const char *name = NULL;
int i;
apr_array_header_t *strip = oidc_dir_cfg_strip_cookies(r);
char *cookies = apr_pstrdup(r->pool, oidc_util_hdr_in_cookie_get(r));
if ((cookies != NULL) && (strip != NULL)) {
oidc_debug(r,
"looking for the following cookies to strip from cookie header: %s",
apr_array_pstrcat(r->pool, strip, OIDC_CHAR_COMMA));
cookie = apr_strtok(cookies, OIDC_STR_SEMI_COLON, &ctx);
do {
while (cookie != NULL && *cookie == OIDC_CHAR_SPACE)
cookie++;
for (i = 0; i < strip->nelts; i++) {
name = ((const char**) strip->elts)[i];
if ((strncmp(cookie, name, strlen(name)) == 0)
&& (cookie[strlen(name)] == OIDC_CHAR_EQUAL)) {
oidc_debug(r, "stripping: %s", name);
break;
}
}
if (i == strip->nelts) {
result = result ? apr_psprintf(r->pool, "%s%s%s", result,
OIDC_STR_SEMI_COLON, cookie) :
cookie;
}
cookie = apr_strtok(NULL, OIDC_STR_SEMI_COLON, &ctx);
} while (cookie != NULL);
oidc_util_hdr_in_cookie_set(r, result);
}
}
#define OIDC_SHA1_LEN 20
/*
* calculates a hash value based on request fingerprint plus a provided nonce string.
*/
static char *oidc_get_browser_state_hash(request_rec *r, const char *nonce) {
oidc_debug(r, "enter");
/* helper to hold to header values */
const char *value = NULL;
/* the hash context */
apr_sha1_ctx_t sha1;
/* Initialize the hash context */
apr_sha1_init(&sha1);
/* get the X-FORWARDED-FOR header value */
value = oidc_util_hdr_in_x_forwarded_for_get(r);
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, strlen(value));
/* get the USER-AGENT header value */
value = oidc_util_hdr_in_user_agent_get(r);
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, strlen(value));
/* get the remote client IP address or host name */
/*
int remotehost_is_ip;
value = ap_get_remote_host(r->connection, r->per_dir_config,
REMOTE_NOLOOKUP, &remotehost_is_ip);
apr_sha1_update(&sha1, value, strlen(value));
*/
/* concat the nonce parameter to the hash input */
apr_sha1_update(&sha1, nonce, strlen(nonce));
/* concat the token binding ID if present */
value = oidc_util_get_provided_token_binding_id(r);
if (value != NULL) {
oidc_debug(r,
"Provided Token Binding ID environment variable found; adding its value to the state");
apr_sha1_update(&sha1, value, strlen(value));
}
/* finalize the hash input and calculate the resulting hash output */
unsigned char hash[OIDC_SHA1_LEN];
apr_sha1_final(hash, &sha1);
/* base64url-encode the resulting hash and return it */
char *result = NULL;
oidc_base64url_encode(r, &result, (const char *) hash, OIDC_SHA1_LEN, TRUE);
return result;
}
/*
* return the name for the state cookie
*/
static char *oidc_get_state_cookie_name(request_rec *r, const char *state) {
return apr_psprintf(r->pool, "%s%s", OIDC_STATE_COOKIE_PREFIX, state);
}
/*
* return the static provider configuration, i.e. from a metadata URL or configuration primitives
*/
static apr_byte_t oidc_provider_static_config(request_rec *r, oidc_cfg *c,
oidc_provider_t **provider) {
json_t *j_provider = NULL;
char *s_json = NULL;
/* see if we should configure a static provider based on external (cached) metadata */
if ((c->metadata_dir != NULL) || (c->provider.metadata_url == NULL)) {
*provider = &c->provider;
return TRUE;
}
oidc_cache_get_provider(r, c->provider.metadata_url, &s_json);
if (s_json == NULL) {
if (oidc_metadata_provider_retrieve(r, c, NULL,
c->provider.metadata_url, &j_provider, &s_json) == FALSE) {
oidc_error(r, "could not retrieve metadata from url: %s",
c->provider.metadata_url);
return FALSE;
}
oidc_cache_set_provider(r, c->provider.metadata_url, s_json,
apr_time_now() + (c->provider_metadata_refresh_interval <= 0 ? apr_time_from_sec( OIDC_CACHE_PROVIDER_METADATA_EXPIRY_DEFAULT) : c->provider_metadata_refresh_interval));
} else {
oidc_util_decode_json_object(r, s_json, &j_provider);
/* check to see if it is valid metadata */
if (oidc_metadata_provider_is_valid(r, c, j_provider, NULL) == FALSE) {
oidc_error(r,
"cache corruption detected: invalid metadata from url: %s",
c->provider.metadata_url);
return FALSE;
}
}
*provider = apr_pcalloc(r->pool, sizeof(oidc_provider_t));
memcpy(*provider, &c->provider, sizeof(oidc_provider_t));
if (oidc_metadata_provider_parse(r, c, j_provider, *provider) == FALSE) {
oidc_error(r, "could not parse metadata from url: %s",
c->provider.metadata_url);
if (j_provider)
json_decref(j_provider);
return FALSE;
}
json_decref(j_provider);
return TRUE;
}
/*
* return the oidc_provider_t struct for the specified issuer
*/
static oidc_provider_t *oidc_get_provider_for_issuer(request_rec *r,
oidc_cfg *c, const char *issuer, apr_byte_t allow_discovery) {
/* by default we'll assume that we're dealing with a single statically configured OP */
oidc_provider_t *provider = NULL;
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return NULL;
/* unless a metadata directory was configured, so we'll try and get the provider settings from there */
if (c->metadata_dir != NULL) {
/* try and get metadata from the metadata directory for the OP that sent this response */
if ((oidc_metadata_get(r, c, issuer, &provider, allow_discovery)
== FALSE) || (provider == NULL)) {
/* don't know nothing about this OP/issuer */
oidc_error(r, "no provider metadata found for issuer \"%s\"",
issuer);
return NULL;
}
}
return provider;
}
/*
* find out whether the request is a response from an IDP discovery page
*/
static apr_byte_t oidc_is_discovery_response(request_rec *r, oidc_cfg *cfg) {
/*
* prereq: this is a call to the configured redirect_uri, now see if:
* the OIDC_DISC_OP_PARAM is present
*/
return oidc_util_request_has_parameter(r, OIDC_DISC_OP_PARAM)
|| oidc_util_request_has_parameter(r, OIDC_DISC_USER_PARAM);
}
/*
* return the HTTP method being called: only for POST data persistence purposes
*/
static const char *oidc_original_request_method(request_rec *r, oidc_cfg *cfg,
apr_byte_t handle_discovery_response) {
const char *method = OIDC_METHOD_GET;
char *m = NULL;
if ((handle_discovery_response == TRUE)
&& (oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, cfg)))
&& (oidc_is_discovery_response(r, cfg))) {
oidc_util_get_request_parameter(r, OIDC_DISC_RM_PARAM, &m);
if (m != NULL)
method = apr_pstrdup(r->pool, m);
} else {
/*
* if POST preserve is not enabled for this location, there's no point in preserving
* the method either which would result in POSTing empty data on return;
* so we revert to legacy behavior
*/
if (oidc_cfg_dir_preserve_post(r) == 0)
return OIDC_METHOD_GET;
const char *content_type = oidc_util_hdr_in_content_type_get(r);
if ((r->method_number == M_POST) && (apr_strnatcmp(content_type,
OIDC_CONTENT_TYPE_FORM_ENCODED) == 0))
method = OIDC_METHOD_FORM_POST;
}
oidc_debug(r, "return: %s", method);
return method;
}
/*
* send an OpenID Connect authorization request to the specified provider preserving POST parameters using HTML5 storage
*/
apr_byte_t oidc_post_preserve_javascript(request_rec *r, const char *location,
char **javascript, char **javascript_method) {
if (oidc_cfg_dir_preserve_post(r) == 0)
return FALSE;
oidc_debug(r, "enter");
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
const char *method = oidc_original_request_method(r, cfg, FALSE);
if (apr_strnatcmp(method, OIDC_METHOD_FORM_POST) != 0)
return FALSE;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return FALSE;
}
const apr_array_header_t *arr = apr_table_elts(params);
const apr_table_entry_t *elts = (const apr_table_entry_t*) arr->elts;
int i;
char *json = "";
for (i = 0; i < arr->nelts; i++) {
json = apr_psprintf(r->pool, "%s'%s': '%s'%s", json,
oidc_util_escape_string(r, elts[i].key),
oidc_util_escape_string(r, elts[i].val),
i < arr->nelts - 1 ? "," : "");
}
json = apr_psprintf(r->pool, "{ %s }", json);
const char *jmethod = "preserveOnLoad";
const char *jscript =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function %s() {\n"
" sessionStorage.setItem('mod_auth_openidc_preserve_post_params', JSON.stringify(%s));\n"
" %s"
" }\n"
" </script>\n", jmethod, json,
location ?
apr_psprintf(r->pool, "window.location='%s';\n",
location) :
"");
if (location == NULL) {
if (javascript_method)
*javascript_method = apr_pstrdup(r->pool, jmethod);
if (javascript)
*javascript = apr_pstrdup(r->pool, jscript);
} else {
oidc_util_html_send(r, "Preserving...", jscript, jmethod,
"<p>Preserving...</p>", OK);
}
return TRUE;
}
/*
* restore POST parameters on original_url from HTML5 local storage
*/
static int oidc_request_post_preserved_restore(request_rec *r,
const char *original_url) {
oidc_debug(r, "enter: original_url=%s", original_url);
const char *method = "postOnLoad";
const char *script =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function str_decode(string) {\n"
" try {\n"
" result = decodeURIComponent(string);\n"
" } catch (e) {\n"
" result = unescape(string);\n"
" }\n"
" return result;\n"
" }\n"
" function %s() {\n"
" var mod_auth_openidc_preserve_post_params = JSON.parse(sessionStorage.getItem('mod_auth_openidc_preserve_post_params'));\n"
" sessionStorage.removeItem('mod_auth_openidc_preserve_post_params');\n"
" for (var key in mod_auth_openidc_preserve_post_params) {\n"
" var input = document.createElement(\"input\");\n"
" input.name = str_decode(key);\n"
" input.value = str_decode(mod_auth_openidc_preserve_post_params[key]);\n"
" input.type = \"hidden\";\n"
" document.forms[0].appendChild(input);\n"
" }\n"
" document.forms[0].action = '%s';\n"
" document.forms[0].submit();\n"
" }\n"
" </script>\n", method, original_url);
const char *body = " <p>Restoring...</p>\n"
" <form method=\"post\"></form>\n";
return oidc_util_html_send(r, "Restoring...", script, method, body,
OK);
}
/*
* parse state that was sent to us by the issuer
*/
static apr_byte_t oidc_unsolicited_proto_state(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t **proto_state) {
char *alg = NULL;
oidc_debug(r, "enter: state header=%s",
oidc_proto_peek_jwt_header(r, state, &alg));
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret,
oidc_alg2keysize(alg), OIDC_JOSE_ALG_SHA256,
TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwt_t *jwt = NULL;
if (oidc_jwt_parse(r->pool, state, &jwt,
oidc_util_merge_symmetric_key(r->pool, c->private_keys, jwk),
&err) == FALSE) {
oidc_error(r,
"could not parse JWT from state: invalid unsolicited response: %s",
oidc_jose_e2s(r->pool, err));
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully parsed JWT from state");
if (jwt->payload.iss == NULL) {
oidc_error(r, "no \"%s\" could be retrieved from JWT state, aborting",
OIDC_CLAIM_ISS);
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_provider_t *provider = oidc_get_provider_for_issuer(r, c,
jwt->payload.iss, FALSE);
if (provider == NULL) {
oidc_jwt_destroy(jwt);
return FALSE;
}
/* validate the state JWT, validating optional exp + iat */
if (oidc_proto_validate_jwt(r, jwt, provider->issuer, FALSE, FALSE,
provider->idtoken_iat_slack,
OIDC_TOKEN_BINDING_POLICY_DISABLED) == FALSE) {
oidc_jwt_destroy(jwt);
return FALSE;
}
char *rfp = NULL;
if (oidc_jose_get_string(r->pool, jwt->payload.value.json, OIDC_CLAIM_RFP,
TRUE, &rfp, &err) == FALSE) {
oidc_error(r,
"no \"%s\" claim could be retrieved from JWT state, aborting: %s",
OIDC_CLAIM_RFP, oidc_jose_e2s(r->pool, err));
oidc_jwt_destroy(jwt);
return FALSE;
}
if (apr_strnatcmp(rfp, OIDC_PROTO_ISS) != 0) {
oidc_error(r, "\"%s\" (%s) does not match \"%s\", aborting",
OIDC_CLAIM_RFP, rfp, OIDC_PROTO_ISS);
oidc_jwt_destroy(jwt);
return FALSE;
}
char *target_link_uri = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_TARGET_LINK_URI,
FALSE, &target_link_uri, NULL);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
oidc_error(r,
"no \"%s\" claim could be retrieved from JWT state and no " OIDCDefaultURL " is set, aborting",
OIDC_CLAIM_TARGET_LINK_URI);
oidc_jwt_destroy(jwt);
return FALSE;
}
target_link_uri = c->default_sso_url;
}
if (c->metadata_dir != NULL) {
if ((oidc_metadata_get(r, c, jwt->payload.iss, &provider, FALSE)
== FALSE) || (provider == NULL)) {
oidc_error(r, "no provider metadata found for provider \"%s\"",
jwt->payload.iss);
oidc_jwt_destroy(jwt);
return FALSE;
}
}
char *jti = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json, OIDC_CLAIM_JTI,
FALSE, &jti,
NULL);
if (jti == NULL) {
char *cser = oidc_jwt_serialize(r->pool, jwt, &err);
if (cser == NULL)
return FALSE;
if (oidc_util_hash_string_and_base64url_encode(r, OIDC_JOSE_ALG_SHA256,
cser, &jti) == FALSE) {
oidc_error(r,
"oidc_util_hash_string_and_base64url_encode returned an error");
return FALSE;
}
}
char *replay = NULL;
oidc_cache_get_jti(r, jti, &replay);
if (replay != NULL) {
oidc_error(r,
"the \"%s\" value (%s) passed in the browser state was found in the cache already; possible replay attack!?",
OIDC_CLAIM_JTI, jti);
oidc_jwt_destroy(jwt);
return FALSE;
}
/* jti cache duration is the configured replay prevention window for token issuance plus 10 seconds for safety */
apr_time_t jti_cache_duration = apr_time_from_sec(
provider->idtoken_iat_slack * 2 + 10);
/* store it in the cache for the calculated duration */
oidc_cache_set_jti(r, jti, jti, apr_time_now() + jti_cache_duration);
oidc_debug(r,
"jti \"%s\" validated successfully and is now cached for %" APR_TIME_T_FMT " seconds",
jti, apr_time_sec(jti_cache_duration));
jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret, 0,
NULL, TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwks_uri_t jwks_uri = { provider->jwks_uri,
provider->jwks_refresh_interval, provider->ssl_validate_server };
if (oidc_proto_jwt_verify(r, c, jwt, &jwks_uri,
oidc_util_merge_symmetric_key(r->pool, NULL, jwk)) == FALSE) {
oidc_error(r, "state JWT could not be validated, aborting");
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully verified state JWT");
*proto_state = oidc_proto_state_new();
oidc_proto_state_set_issuer(*proto_state, jwt->payload.iss);
oidc_proto_state_set_original_url(*proto_state, target_link_uri);
oidc_proto_state_set_original_method(*proto_state, OIDC_METHOD_GET);
oidc_proto_state_set_response_mode(*proto_state, provider->response_mode);
oidc_proto_state_set_response_type(*proto_state, provider->response_type);
oidc_proto_state_set_timestamp_now(*proto_state);
oidc_jwt_destroy(jwt);
return TRUE;
}
typedef struct oidc_state_cookies_t {
char *name;
apr_time_t timestamp;
struct oidc_state_cookies_t *next;
} oidc_state_cookies_t;
static int oidc_delete_oldest_state_cookies(request_rec *r,
int number_of_valid_state_cookies, int max_number_of_state_cookies,
oidc_state_cookies_t *first) {
oidc_state_cookies_t *cur = NULL, *prev = NULL, *prev_oldest = NULL,
*oldest = NULL;
while (number_of_valid_state_cookies >= max_number_of_state_cookies) {
oldest = first;
prev_oldest = NULL;
prev = first;
cur = first->next;
while (cur) {
if ((cur->timestamp < oldest->timestamp)) {
oldest = cur;
prev_oldest = prev;
}
prev = cur;
cur = cur->next;
}
oidc_warn(r,
"deleting oldest state cookie: %s (time until expiry %" APR_TIME_T_FMT " seconds)",
oldest->name, apr_time_sec(oldest->timestamp - apr_time_now()));
oidc_util_set_cookie(r, oldest->name, "", 0, NULL);
if (prev_oldest)
prev_oldest->next = oldest->next;
else
first = first->next;
number_of_valid_state_cookies--;
}
return number_of_valid_state_cookies;
}
/*
* clean state cookies that have expired i.e. for outstanding requests that will never return
* successfully and return the number of remaining valid cookies/outstanding-requests while
* doing so
*/
static int oidc_clean_expired_state_cookies(request_rec *r, oidc_cfg *c,
const char *currentCookieName, int delete_oldest) {
int number_of_valid_state_cookies = 0;
oidc_state_cookies_t *first = NULL, *last = NULL;
char *cookie, *tokenizerCtx = NULL;
char *cookies = apr_pstrdup(r->pool, oidc_util_hdr_in_cookie_get(r));
if (cookies != NULL) {
cookie = apr_strtok(cookies, OIDC_STR_SEMI_COLON, &tokenizerCtx);
while (cookie != NULL) {
while (*cookie == OIDC_CHAR_SPACE)
cookie++;
if (strstr(cookie, OIDC_STATE_COOKIE_PREFIX) == cookie) {
char *cookieName = cookie;
while (cookie != NULL && *cookie != OIDC_CHAR_EQUAL)
cookie++;
if (*cookie == OIDC_CHAR_EQUAL) {
*cookie = '\0';
cookie++;
if ((currentCookieName == NULL)
|| (apr_strnatcmp(cookieName, currentCookieName)
!= 0)) {
oidc_proto_state_t *proto_state =
oidc_proto_state_from_cookie(r, c, cookie);
if (proto_state != NULL) {
json_int_t ts = oidc_proto_state_get_timestamp(
proto_state);
if (apr_time_now() > ts + apr_time_from_sec(c->state_timeout)) {
oidc_error(r,
"state (%s) has expired (original_url=%s)",
cookieName,
oidc_proto_state_get_original_url(
proto_state));
oidc_util_set_cookie(r, cookieName, "", 0,
NULL);
} else {
if (first == NULL) {
first = apr_pcalloc(r->pool,
sizeof(oidc_state_cookies_t));
last = first;
} else {
last->next = apr_pcalloc(r->pool,
sizeof(oidc_state_cookies_t));
last = last->next;
}
last->name = cookieName;
last->timestamp = ts;
last->next = NULL;
number_of_valid_state_cookies++;
}
oidc_proto_state_destroy(proto_state);
}
}
}
}
cookie = apr_strtok(NULL, OIDC_STR_SEMI_COLON, &tokenizerCtx);
}
}
if (delete_oldest > 0)
number_of_valid_state_cookies = oidc_delete_oldest_state_cookies(r,
number_of_valid_state_cookies, c->max_number_of_state_cookies,
first);
return number_of_valid_state_cookies;
}
/*
* restore the state that was maintained between authorization request and response in an encrypted cookie
*/
static apr_byte_t oidc_restore_proto_state(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t **proto_state) {
oidc_debug(r, "enter");
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* clean expired state cookies to avoid pollution */
oidc_clean_expired_state_cookies(r, c, cookieName, FALSE);
/* get the state cookie value first */
char *cookieValue = oidc_util_get_cookie(r, cookieName);
if (cookieValue == NULL) {
oidc_error(r, "no \"%s\" state cookie found", cookieName);
return oidc_unsolicited_proto_state(r, c, state, proto_state);
}
/* clear state cookie because we don't need it anymore */
oidc_util_set_cookie(r, cookieName, "", 0, NULL);
*proto_state = oidc_proto_state_from_cookie(r, c, cookieValue);
if (*proto_state == NULL)
return FALSE;
const char *nonce = oidc_proto_state_get_nonce(*proto_state);
/* calculate the hash of the browser fingerprint concatenated with the nonce */
char *calc = oidc_get_browser_state_hash(r, nonce);
/* compare the calculated hash with the value provided in the authorization response */
if (apr_strnatcmp(calc, state) != 0) {
oidc_error(r,
"calculated state from cookie does not match state parameter passed back in URL: \"%s\" != \"%s\"",
state, calc);
oidc_proto_state_destroy(*proto_state);
return FALSE;
}
apr_time_t ts = oidc_proto_state_get_timestamp(*proto_state);
/* check that the timestamp is not beyond the valid interval */
if (apr_time_now() > ts + apr_time_from_sec(c->state_timeout)) {
oidc_error(r, "state has expired");
/*
* note that this overrides redirection to the OIDCDefaultURL as done later...
* see: https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!msg/mod_auth_openidc/L4JFBw-XCNU/BWi2Fmk2AwAJ
*/
oidc_util_html_send_error(r, c->error_template,
"Invalid Authentication Response",
apr_psprintf(r->pool,
"This is due to a timeout; please restart your authentication session by re-entering the URL/bookmark you originally wanted to access: %s",
oidc_proto_state_get_original_url(*proto_state)),
OK);
oidc_proto_state_destroy(*proto_state);
return FALSE;
}
/* add the state */
oidc_proto_state_set_state(*proto_state, state);
/* log the restored state object */
oidc_debug(r, "restored state: %s",
oidc_proto_state_to_string(r, *proto_state));
/* we've made it */
return TRUE;
}
/*
* set the state that is maintained between an authorization request and an authorization response
* in a cookie in the browser that is cryptographically bound to that state
*/
static int oidc_authorization_request_set_cookie(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t *proto_state) {
/*
* create a cookie consisting of 8 elements:
* random value, original URL, original method, issuer, response_type, response_mod, prompt and timestamp
* encoded as JSON, encrypting the resulting JSON value
*/
char *cookieValue = oidc_proto_state_to_cookie(r, c, proto_state);
if (cookieValue == NULL)
return HTTP_INTERNAL_SERVER_ERROR;
/*
* clean expired state cookies to avoid pollution and optionally
* try to avoid the number of state cookies exceeding a max
*/
int number_of_cookies = oidc_clean_expired_state_cookies(r, c, NULL,
oidc_cfg_delete_oldest_state_cookies(c));
int max_number_of_cookies = oidc_cfg_max_number_of_state_cookies(c);
if ((max_number_of_cookies > 0)
&& (number_of_cookies >= max_number_of_cookies)) {
oidc_warn(r,
"the number of existing, valid state cookies (%d) has exceeded the limit (%d), no additional authorization request + state cookie can be generated, aborting the request",
number_of_cookies, max_number_of_cookies);
/*
* TODO: the html_send code below caters for the case that there's a user behind a
* browser generating this request, rather than a piece of XHR code; how would an
* XHR client handle this?
*/
/*
* it appears that sending content with a 503 turns the HTTP status code
* into a 200 so we'll avoid that for now: the user will see Apache specific
* readable text anyway
*
return oidc_util_html_send_error(r, c->error_template,
"Too Many Outstanding Requests",
apr_psprintf(r->pool,
"No authentication request could be generated since there are too many outstanding authentication requests already; you may have to wait up to %d seconds to be able to create a new request",
c->state_timeout),
HTTP_SERVICE_UNAVAILABLE);
*/
return HTTP_SERVICE_UNAVAILABLE;
}
/* assemble the cookie name for the state cookie */
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* set it as a cookie */
oidc_util_set_cookie(r, cookieName, cookieValue, -1,
c->cookie_same_site ? OIDC_COOKIE_EXT_SAME_SITE_LAX : NULL);
return HTTP_OK;
}
/*
* get the mod_auth_openidc related context from the (userdata in the) request
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
static apr_table_t *oidc_request_state(request_rec *rr) {
/* our state is always stored in the main request */
request_rec *r = (rr->main != NULL) ? rr->main : rr;
/* our state is a table, get it */
apr_table_t *state = NULL;
apr_pool_userdata_get((void **) &state, OIDC_USERDATA_KEY, r->pool);
/* if it does not exist, we'll create a new table */
if (state == NULL) {
state = apr_table_make(r->pool, 5);
apr_pool_userdata_set(state, OIDC_USERDATA_KEY, NULL, r->pool);
}
/* return the resulting table, always non-null now */
return state;
}
/*
* set a name/value pair in the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
void oidc_request_state_set(request_rec *r, const char *key, const char *value) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* put the name/value pair in that table */
apr_table_set(state, key, value);
}
/*
* get a name/value pair from the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
const char*oidc_request_state_get(request_rec *r, const char *key) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* return the value from the table */
return apr_table_get(state, key);
}
/*
* set the claims from a JSON object (c.q. id_token or user_info response) stored
* in the session in to HTTP headers passed on to the application
*/
static apr_byte_t oidc_set_app_claims(request_rec *r,
const oidc_cfg * const cfg, oidc_session_t *session,
const char *s_claims) {
json_t *j_claims = NULL;
/* decode the string-encoded attributes in to a JSON structure */
if (s_claims != NULL) {
if (oidc_util_decode_json_object(r, s_claims, &j_claims) == FALSE)
return FALSE;
}
/* set the resolved claims a HTTP headers for the application */
if (j_claims != NULL) {
oidc_util_set_app_infos(r, j_claims, oidc_cfg_claim_prefix(r),
cfg->claim_delimiter, oidc_cfg_dir_pass_info_in_headers(r),
oidc_cfg_dir_pass_info_in_envvars(r));
/* release resources */
json_decref(j_claims);
}
return TRUE;
}
static int oidc_authenticate_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, const char *original_url,
const char *login_hint, const char *id_token_hint, const char *prompt,
const char *auth_request_params, const char *path_scope);
/*
* log message about max session duration
*/
static void oidc_log_session_expires(request_rec *r, const char *msg,
apr_time_t session_expires) {
char buf[APR_RFC822_DATE_LEN + 1];
apr_rfc822_date(buf, session_expires);
oidc_debug(r, "%s: %s (in %" APR_TIME_T_FMT " secs from now)", msg, buf,
apr_time_sec(session_expires - apr_time_now()));
}
/*
* see if this is a non-browser request
*/
static apr_byte_t oidc_is_xml_http_request(request_rec *r) {
if ((oidc_util_hdr_in_x_requested_with_get(r) != NULL)
&& (apr_strnatcasecmp(oidc_util_hdr_in_x_requested_with_get(r),
OIDC_HTTP_HDR_VAL_XML_HTTP_REQUEST) == 0))
return TRUE;
if ((oidc_util_hdr_in_accept_contains(r, OIDC_CONTENT_TYPE_TEXT_HTML)
== FALSE) && (oidc_util_hdr_in_accept_contains(r,
OIDC_CONTENT_TYPE_APP_XHTML_XML) == FALSE)
&& (oidc_util_hdr_in_accept_contains(r,
OIDC_CONTENT_TYPE_ANY) == FALSE))
return TRUE;
return FALSE;
}
/*
* find out which action we need to take when encountering an unauthenticated request
*/
static int oidc_handle_unauthenticated_user(request_rec *r, oidc_cfg *c) {
/* see if we've configured OIDCUnAuthAction for this path */
switch (oidc_dir_cfg_unauth_action(r)) {
case OIDC_UNAUTH_RETURN410:
return HTTP_GONE;
case OIDC_UNAUTH_RETURN401:
return HTTP_UNAUTHORIZED;
case OIDC_UNAUTH_PASS:
r->user = "";
/*
* we're not going to pass information about an authenticated user to the application,
* but we do need to scrub the headers that mod_auth_openidc would set for security reasons
*/
oidc_scrub_headers(r);
return OK;
case OIDC_UNAUTH_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return HTTP_UNAUTHORIZED;
}
/*
* else: no session (regardless of whether it is main or sub-request),
* and we need to authenticate the user
*/
return oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
}
/*
* check if maximum session duration was exceeded
*/
static int oidc_check_max_session_duration(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
/* get the session expiry from the session data */
apr_time_t session_expires = oidc_session_get_session_expires(r, session);
/* check the expire timestamp against the current time */
if (apr_time_now() > session_expires) {
oidc_warn(r, "maximum session duration exceeded for user: %s",
session->remote_user);
oidc_session_kill(r, session);
return oidc_handle_unauthenticated_user(r, cfg);
}
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
return OK;
}
/*
* validate received session cookie against the domain it was issued for:
*
* this handles the case where the cache configured is a the same single memcache, Redis, or file
* backend for different (virtual) hosts, or a client-side cookie protected with the same secret
*
* it also handles the case that a cookie is unexpectedly shared across multiple hosts in
* name-based virtual hosting even though the OP(s) would be the same
*/
static apr_byte_t oidc_check_cookie_domain(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
const char *c_cookie_domain =
cfg->cookie_domain ?
cfg->cookie_domain : oidc_get_current_url_host(r);
const char *s_cookie_domain = oidc_session_get_cookie_domain(r, session);
if ((s_cookie_domain == NULL)
|| (apr_strnatcmp(c_cookie_domain, s_cookie_domain) != 0)) {
oidc_warn(r,
"aborting: detected attempt to play cookie against a different domain/host than issued for! (issued=%s, current=%s)",
s_cookie_domain, c_cookie_domain);
return FALSE;
}
return TRUE;
}
/*
* get a handle to the provider configuration via the "issuer" stored in the session
*/
apr_byte_t oidc_get_provider_from_session(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t **provider) {
oidc_debug(r, "enter");
/* get the issuer value from the session state */
const char *issuer = oidc_session_get_issuer(r, session);
if (issuer == NULL) {
oidc_error(r, "session corrupted: no issuer found in session");
return FALSE;
}
/* get the provider info associated with the issuer value */
oidc_provider_t *p = oidc_get_provider_for_issuer(r, c, issuer, FALSE);
if (p == NULL) {
oidc_error(r, "session corrupted: no provider found for issuer: %s",
issuer);
return FALSE;
}
*provider = p;
return TRUE;
}
/*
* store claims resolved from the userinfo endpoint in the session
*/
static void oidc_store_userinfo_claims(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider, const char *claims,
const char *userinfo_jwt) {
oidc_debug(r, "enter");
/* see if we've resolved any claims */
if (claims != NULL) {
/*
* Successfully decoded a set claims from the response so we can store them
* (well actually the stringified representation in the response)
* in the session context safely now
*/
oidc_session_set_userinfo_claims(r, session, claims);
if (c->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* this will also clear the entry if a JWT was not returned at this point */
oidc_session_set_userinfo_jwt(r, session, userinfo_jwt);
}
} else {
/*
* clear the existing claims because we could not refresh them
*/
oidc_session_set_userinfo_claims(r, session, NULL);
oidc_session_set_userinfo_jwt(r, session, NULL);
}
/* store the last refresh time if we've configured a userinfo refresh interval */
if (provider->userinfo_refresh_interval > 0)
oidc_session_reset_userinfo_last_refresh(r, session);
}
/*
* execute refresh token grant to refresh the existing access token
*/
static apr_byte_t oidc_refresh_access_token(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider,
char **new_access_token) {
oidc_debug(r, "enter");
/* get the refresh token that was stored in the session */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if (refresh_token == NULL) {
oidc_warn(r,
"refresh token routine called but no refresh_token found in the session");
return FALSE;
}
/* elements returned in the refresh response */
char *s_id_token = NULL;
int expires_in = -1;
char *s_token_type = NULL;
char *s_access_token = NULL;
char *s_refresh_token = NULL;
/* refresh the tokens by calling the token endpoint */
if (oidc_proto_refresh_request(r, c, provider, refresh_token, &s_id_token,
&s_access_token, &s_token_type, &expires_in,
&s_refresh_token) == FALSE) {
oidc_error(r, "access_token could not be refreshed");
return FALSE;
}
/* store the new access_token in the session and discard the old one */
oidc_session_set_access_token(r, session, s_access_token);
oidc_session_set_access_token_expires(r, session, expires_in);
/* reset the access token refresh timestamp */
oidc_session_reset_access_token_last_refresh(r, session);
/* see if we need to return it as a parameter */
if (new_access_token != NULL)
*new_access_token = s_access_token;
/* if we have a new refresh token (rolling refresh), store it in the session and overwrite the old one */
if (s_refresh_token != NULL)
oidc_session_set_refresh_token(r, session, s_refresh_token);
return TRUE;
}
/*
* retrieve claims from the userinfo endpoint and return the stringified response
*/
static const char *oidc_retrieve_claims_from_userinfo_endpoint(request_rec *r,
oidc_cfg *c, oidc_provider_t *provider, const char *access_token,
oidc_session_t *session, char *id_token_sub, char **userinfo_jwt) {
oidc_debug(r, "enter");
char *result = NULL;
char *refreshed_access_token = NULL;
/* see if a userinfo endpoint is set, otherwise there's nothing to do for us */
if (provider->userinfo_endpoint_url == NULL) {
oidc_debug(r,
"not retrieving userinfo claims because userinfo_endpoint is not set");
return NULL;
}
/* see if there's an access token, otherwise we can't call the userinfo endpoint at all */
if (access_token == NULL) {
oidc_debug(r,
"not retrieving userinfo claims because access_token is not provided");
return NULL;
}
if ((id_token_sub == NULL) && (session != NULL)) {
// when refreshing claims from the userinfo endpoint
json_t *id_token_claims = oidc_session_get_idtoken_claims_json(r,
session);
if (id_token_claims == NULL) {
oidc_error(r, "no id_token_claims found in session");
return NULL;
}
oidc_jose_get_string(r->pool, id_token_claims, OIDC_CLAIM_SUB, FALSE,
&id_token_sub, NULL);
}
// TODO: return code should indicate whether the token expired or some other error occurred
// TODO: long-term: session storage should be JSON (with explicit types and less conversion, using standard routines)
/* try to get claims from the userinfo endpoint using the provided access token */
if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub, access_token,
&result, userinfo_jwt) == FALSE) {
/* see if we have an existing session and we are refreshing the user info claims */
if (session != NULL) {
/* first call to user info endpoint failed, but the access token may have just expired, so refresh it */
if (oidc_refresh_access_token(r, c, session, provider,
&refreshed_access_token) == TRUE) {
/* try again with the new access token */
if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub,
refreshed_access_token, &result, userinfo_jwt) == FALSE) {
oidc_error(r,
"resolving user info claims with the refreshed access token failed, nothing will be stored in the session");
result = NULL;
}
} else {
oidc_warn(r,
"refreshing access token failed, claims will not be retrieved/refreshed from the userinfo endpoint");
result = NULL;
}
} else {
oidc_error(r,
"resolving user info claims with the existing/provided access token failed, nothing will be stored in the session");
result = NULL;
}
}
return result;
}
/*
* get (new) claims from the userinfo endpoint
*/
static apr_byte_t oidc_refresh_claims_from_userinfo_endpoint(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session) {
oidc_provider_t *provider = NULL;
const char *claims = NULL;
const char *access_token = NULL;
char *userinfo_jwt = NULL;
/* get the current provider info */
if (oidc_get_provider_from_session(r, cfg, session, &provider) == FALSE)
return FALSE;
/* see if we can do anything here, i.e. we have a userinfo endpoint and a refresh interval is configured */
apr_time_t interval = apr_time_from_sec(
provider->userinfo_refresh_interval);
oidc_debug(r, "userinfo_endpoint=%s, interval=%d",
provider->userinfo_endpoint_url,
provider->userinfo_refresh_interval);
if ((provider->userinfo_endpoint_url != NULL) && (interval > 0)) {
/* get the last refresh timestamp from the session info */
apr_time_t last_refresh = oidc_session_get_userinfo_last_refresh(r,
session);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(last_refresh + interval - apr_time_now()));
/* see if we need to refresh again */
if (last_refresh + interval < apr_time_now()) {
/* get the current access token */
access_token = oidc_session_get_access_token(r, session);
/* retrieve the current claims */
claims = oidc_retrieve_claims_from_userinfo_endpoint(r, cfg,
provider, access_token, session, NULL, &userinfo_jwt);
/* store claims resolved from userinfo endpoint */
oidc_store_userinfo_claims(r, cfg, session, provider, claims,
userinfo_jwt);
/* indicated something changed */
return TRUE;
}
}
return FALSE;
}
/*
* copy the claims and id_token from the session to the request state and optionally return them
*/
static void oidc_copy_tokens_to_request_state(request_rec *r,
oidc_session_t *session, const char **s_id_token, const char **s_claims) {
const char *id_token = oidc_session_get_idtoken_claims(r, session);
const char *claims = oidc_session_get_userinfo_claims(r, session);
oidc_debug(r, "id_token=%s claims=%s", id_token, claims);
if (id_token != NULL) {
oidc_request_state_set(r, OIDC_REQUEST_STATE_KEY_IDTOKEN, id_token);
if (s_id_token != NULL)
*s_id_token = id_token;
}
if (claims != NULL) {
oidc_request_state_set(r, OIDC_REQUEST_STATE_KEY_CLAIMS, claims);
if (s_claims != NULL)
*s_claims = claims;
}
}
/*
* pass refresh_token, access_token and access_token_expires as headers/environment variables to the application
*/
static apr_byte_t oidc_session_pass_tokens_and_save(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session, apr_byte_t needs_save) {
apr_byte_t pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
apr_byte_t pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
/* set the refresh_token in the app headers/variables, if enabled for this location/directory */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if ((oidc_cfg_dir_pass_refresh_token(r) != 0) && (refresh_token != NULL)) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_REFRESH_TOKEN, refresh_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* set the access_token in the app headers/variables */
const char *access_token = oidc_session_get_access_token(r, session);
if (access_token != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ACCESS_TOKEN, access_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* set the expiry timestamp in the app headers/variables */
const char *access_token_expires = oidc_session_get_access_token_expires(r,
session);
if (access_token_expires != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ACCESS_TOKEN_EXP,
access_token_expires,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/*
* reset the session inactivity timer
* but only do this once per 10% of the inactivity timeout interval (with a max to 60 seconds)
* for performance reasons
*
* now there's a small chance that the session ends 10% (or a minute) earlier than configured/expected
* cq. when there's a request after a recent save (so no update) and then no activity happens until
* a request comes in just before the session should expire
* ("recent" and "just before" refer to 10%-with-a-max-of-60-seconds of the inactivity interval after
* the start/last-update and before the expiry of the session respectively)
*
* this is be deemed acceptable here because of performance gain
*/
apr_time_t interval = apr_time_from_sec(cfg->session_inactivity_timeout);
apr_time_t now = apr_time_now();
apr_time_t slack = interval / 10;
if (slack > apr_time_from_sec(60))
slack = apr_time_from_sec(60);
if (session->expiry - now < interval - slack) {
session->expiry = now + interval;
needs_save = TRUE;
}
/* log message about session expiry */
oidc_log_session_expires(r, "session inactivity timeout", session->expiry);
/* check if something was updated in the session and we need to save it again */
if (needs_save)
if (oidc_session_save(r, session, FALSE) == FALSE)
return FALSE;
return TRUE;
}
static apr_byte_t oidc_refresh_access_token_before_expiry(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session, int ttl_minimum, int logout_on_error) {
const char *s_access_token_expires = NULL;
apr_time_t t_expires = -1;
oidc_provider_t *provider = NULL;
oidc_debug(r, "ttl_minimum=%d", ttl_minimum);
if (ttl_minimum < 0)
return FALSE;
s_access_token_expires = oidc_session_get_access_token_expires(r, session);
if (s_access_token_expires == NULL) {
oidc_debug(r,
"no access token expires_in stored in the session (i.e. returned from in the authorization response), so cannot refresh the access token based on TTL requirement");
return FALSE;
}
if (oidc_session_get_refresh_token(r, session) == NULL) {
oidc_debug(r,
"no refresh token stored in the session, so cannot refresh the access token based on TTL requirement");
return FALSE;
}
if (sscanf(s_access_token_expires, "%" APR_TIME_T_FMT, &t_expires) != 1) {
oidc_error(r, "could not parse s_access_token_expires %s",
s_access_token_expires);
return FALSE;
}
t_expires = apr_time_from_sec(t_expires - ttl_minimum);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(t_expires - apr_time_now()));
if (t_expires > apr_time_now())
return FALSE;
if (oidc_get_provider_from_session(r, cfg, session, &provider) == FALSE)
return FALSE;
if (oidc_refresh_access_token(r, cfg, session, provider,
NULL) == FALSE) {
oidc_warn(r, "access_token could not be refreshed, logout=%d", logout_on_error & OIDC_LOGOUT_ON_ERROR_REFRESH);
if (logout_on_error & OIDC_LOGOUT_ON_ERROR_REFRESH)
return ERROR;
else
return FALSE;
}
return TRUE;
}
/*
* handle the case where we have identified an existing authentication session for a user
*/
static int oidc_handle_existing_session(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
oidc_debug(r, "enter");
/* track if the session needs to be updated/saved into the cache */
apr_byte_t needs_save = FALSE;
/* set the user in the main request for further (incl. sub-request) processing */
r->user = apr_pstrdup(r->pool, session->remote_user);
oidc_debug(r, "set remote_user to \"%s\"", r->user);
/* get the header name in which the remote user name needs to be passed */
char *authn_header = oidc_cfg_dir_authn_header(r);
apr_byte_t pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
apr_byte_t pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
/* verify current cookie domain against issued cookie domain */
if (oidc_check_cookie_domain(r, cfg, session) == FALSE)
return HTTP_UNAUTHORIZED;
/* check if the maximum session duration was exceeded */
int rc = oidc_check_max_session_duration(r, cfg, session);
if (rc != OK)
return rc;
/* if needed, refresh the access token */
needs_save = oidc_refresh_access_token_before_expiry(r, cfg, session,
oidc_cfg_dir_refresh_access_token_before_expiry(r),
oidc_cfg_dir_logout_on_error_refresh(r));
if (needs_save == ERROR)
return oidc_handle_logout_request(r, cfg, session, cfg->default_slo_url);
/* if needed, refresh claims from the user info endpoint */
if (oidc_refresh_claims_from_userinfo_endpoint(r, cfg, session) == TRUE)
needs_save = TRUE;
/*
* we're going to pass the information that we have to the application,
* but first we need to scrub the headers that we're going to use for security reasons
*/
oidc_scrub_headers(r);
/* set the user authentication HTTP header if set and required */
if ((r->user != NULL) && (authn_header != NULL))
oidc_util_hdr_in_set(r, authn_header, r->user);
const char *s_claims = NULL;
const char *s_id_token = NULL;
/* copy id_token and claims from session to request state and obtain their values */
oidc_copy_tokens_to_request_state(r, session, &s_id_token, &s_claims);
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_CLAIMS)) {
/* set the userinfo claims in the app headers */
if (oidc_set_app_claims(r, cfg, session, s_claims) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_JSON_OBJECT)) {
/* pass the userinfo JSON object to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_USERINFO_JSON, s_claims,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_JWT)) {
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* get the compact serialized JWT from the session */
const char *s_userinfo_jwt = oidc_session_get_userinfo_jwt(r,
session);
if (s_userinfo_jwt != NULL) {
/* pass the compact serialized JWT to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_USERINFO_JWT,
s_userinfo_jwt,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
} else {
oidc_debug(r,
"configured to pass userinfo in a JWT, but no such JWT was found in the session (probably no such JWT was returned from the userinfo endpoint)");
}
} else {
oidc_error(r,
"session type \"client-cookie\" does not allow storing/passing a userinfo JWT; use \"" OIDCSessionType " server-cache\" for that");
}
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_CLAIMS)) {
/* set the id_token in the app headers */
if (oidc_set_app_claims(r, cfg, session, s_id_token) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_PAYLOAD)) {
/* pass the id_token JSON object to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ID_TOKEN_PAYLOAD, s_id_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_SERIALIZED)) {
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* get the compact serialized JWT from the session */
const char *s_id_token = oidc_session_get_idtoken(r, session);
/* pass the compact serialized JWT to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ID_TOKEN, s_id_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
} else {
oidc_error(r,
"session type \"client-cookie\" does not allow storing/passing the id_token; use \"" OIDCSessionType " server-cache\" for that");
}
}
/* pass the at, rt and at expiry to the application, possibly update the session expiry and save the session */
if (oidc_session_pass_tokens_and_save(r, cfg, session, needs_save) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* return "user authenticated" status */
return OK;
}
/*
* helper function for basic/implicit client flows upon receiving an authorization response:
* check that it matches the state stored in the browser and return the variables associated
* with the state, such as original_url and OP oidc_provider_t pointer.
*/
static apr_byte_t oidc_authorization_response_match_state(request_rec *r,
oidc_cfg *c, const char *state, struct oidc_provider_t **provider,
oidc_proto_state_t **proto_state) {
oidc_debug(r, "enter (state=%s)", state);
if ((state == NULL) || (apr_strnatcmp(state, "") == 0)) {
oidc_error(r, "state parameter is not set");
return FALSE;
}
/* check the state parameter against what we stored in a cookie */
if (oidc_restore_proto_state(r, c, state, proto_state) == FALSE) {
oidc_error(r, "unable to restore state");
return FALSE;
}
*provider = oidc_get_provider_for_issuer(r, c,
oidc_proto_state_get_issuer(*proto_state), FALSE);
return (*provider != NULL);
}
/*
* redirect the browser to the session logout endpoint
*/
static int oidc_session_redirect_parent_window_to_logout(request_rec *r,
oidc_cfg *c) {
oidc_debug(r, "enter");
char *java_script = apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" window.top.location.href = '%s?session=logout';\n"
" </script>\n", oidc_get_redirect_uri(r, c));
return oidc_util_html_send(r, "Redirecting...", java_script, NULL, NULL,
OK);
}
/*
* handle an error returned by the OP
*/
static int oidc_authorization_response_error(request_rec *r, oidc_cfg *c,
oidc_proto_state_t *proto_state, const char *error,
const char *error_description) {
const char *prompt = oidc_proto_state_get_prompt(proto_state);
if (prompt != NULL)
prompt = apr_pstrdup(r->pool, prompt);
oidc_proto_state_destroy(proto_state);
if ((prompt != NULL)
&& (apr_strnatcmp(prompt, OIDC_PROTO_PROMPT_NONE) == 0)) {
return oidc_session_redirect_parent_window_to_logout(r, c);
}
return oidc_util_html_send_error(r, c->error_template,
apr_psprintf(r->pool, "OpenID Connect Provider error: %s", error),
error_description, OK);
}
/*
* get the r->user for this request based on the configuration for OIDC/OAuth
*/
apr_byte_t oidc_get_remote_user(request_rec *r, const char *claim_name,
const char *reg_exp, const char *replace, json_t *json,
char **request_user) {
/* get the claim value from the JSON object */
json_t *username = json_object_get(json, claim_name);
if ((username == NULL) || (!json_is_string(username))) {
oidc_warn(r, "JSON object did not contain a \"%s\" string", claim_name);
return FALSE;
}
*request_user = apr_pstrdup(r->pool, json_string_value(username));
if (reg_exp != NULL) {
char *error_str = NULL;
if (replace == NULL) {
if (oidc_util_regexp_first_match(r->pool, *request_user, reg_exp,
request_user, &error_str) == FALSE) {
oidc_error(r, "oidc_util_regexp_first_match failed: %s",
error_str);
*request_user = NULL;
return FALSE;
}
} else if (oidc_util_regexp_substitute(r->pool, *request_user, reg_exp,
replace, request_user, &error_str) == FALSE) {
oidc_error(r, "oidc_util_regexp_substitute failed: %s", error_str);
*request_user = NULL;
return FALSE;
}
}
return TRUE;
}
/*
* set the unique user identifier that will be propagated in the Apache r->user and REMOTE_USER variables
*/
static apr_byte_t oidc_set_request_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, oidc_jwt_t *jwt, const char *s_claims) {
char *issuer = provider->issuer;
char *claim_name = apr_pstrdup(r->pool, c->remote_user_claim.claim_name);
int n = strlen(claim_name);
apr_byte_t post_fix_with_issuer = (claim_name[n - 1] == OIDC_CHAR_AT);
if (post_fix_with_issuer == TRUE) {
claim_name[n - 1] = '\0';
issuer =
(strstr(issuer, "https://") == NULL) ?
apr_pstrdup(r->pool, issuer) :
apr_pstrdup(r->pool, issuer + strlen("https://"));
}
/* extract the username claim (default: "sub") from the id_token payload or user claims */
apr_byte_t rc = FALSE;
char *remote_user = NULL;
json_t *claims = NULL;
oidc_util_decode_json_object(r, s_claims, &claims);
if (claims == NULL) {
rc = oidc_get_remote_user(r, claim_name, c->remote_user_claim.reg_exp,
c->remote_user_claim.replace, jwt->payload.value.json,
&remote_user);
} else {
oidc_util_json_merge(r, jwt->payload.value.json, claims);
rc = oidc_get_remote_user(r, claim_name, c->remote_user_claim.reg_exp,
c->remote_user_claim.replace, claims, &remote_user);
json_decref(claims);
}
if ((rc == FALSE) || (remote_user == NULL)) {
oidc_error(r,
"" OIDCRemoteUserClaim "is set to \"%s\", but could not set the remote user based on the requested claim \"%s\" and the available claims for the user",
c->remote_user_claim.claim_name, claim_name);
return FALSE;
}
if (post_fix_with_issuer == TRUE)
remote_user = apr_psprintf(r->pool, "%s%s%s", remote_user, OIDC_STR_AT,
issuer);
r->user = apr_pstrdup(r->pool, remote_user);
oidc_debug(r, "set remote_user to \"%s\" based on claim: \"%s\"%s", r->user,
c->remote_user_claim.claim_name,
c->remote_user_claim.reg_exp ?
apr_psprintf(r->pool,
" and expression: \"%s\" and replace string: \"%s\"",
c->remote_user_claim.reg_exp,
c->remote_user_claim.replace) :
"");
return TRUE;
}
static char *oidc_make_sid_iss_unique(request_rec *r, const char *sid,
const char *issuer) {
return apr_psprintf(r->pool, "%s@%s", sid, issuer);
}
/*
* store resolved information in the session
*/
static apr_byte_t oidc_save_in_session(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider,
const char *remoteUser, const char *id_token, oidc_jwt_t *id_token_jwt,
const char *claims, const char *access_token, const int expires_in,
const char *refresh_token, const char *session_state, const char *state,
const char *original_url, const char *userinfo_jwt) {
/* store the user in the session */
session->remote_user = remoteUser;
/* set the session expiry to the inactivity timeout */
session->expiry =
apr_time_now() + apr_time_from_sec(c->session_inactivity_timeout);
/* store the claims payload in the id_token for later reference */
oidc_session_set_idtoken_claims(r, session,
id_token_jwt->payload.value.str);
if (c->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* store the compact serialized representation of the id_token for later reference */
oidc_session_set_idtoken(r, session, id_token);
}
/* store the issuer in the session (at least needed for session mgmt and token refresh */
oidc_session_set_issuer(r, session, provider->issuer);
/* store the state and original URL in the session for handling browser-back more elegantly */
oidc_session_set_request_state(r, session, state);
oidc_session_set_original_url(r, session, original_url);
if ((session_state != NULL) && (provider->check_session_iframe != NULL)) {
/* store the session state and required parameters session management */
oidc_session_set_session_state(r, session, session_state);
oidc_debug(r,
"session management enabled: stored session_state (%s), check_session_iframe (%s) and client_id (%s) in the session",
session_state, provider->check_session_iframe,
provider->client_id);
} else if (provider->check_session_iframe == NULL) {
oidc_debug(r,
"session management disabled: \"check_session_iframe\" is not set in provider configuration");
} else {
oidc_debug(r,
"session management disabled: no \"session_state\" value is provided in the authentication response even though \"check_session_iframe\" (%s) is set in the provider configuration",
provider->check_session_iframe);
}
/* store claims resolved from userinfo endpoint */
oidc_store_userinfo_claims(r, c, session, provider, claims, userinfo_jwt);
/* see if we have an access_token */
if (access_token != NULL) {
/* store the access_token in the session context */
oidc_session_set_access_token(r, session, access_token);
/* store the associated expires_in value */
oidc_session_set_access_token_expires(r, session, expires_in);
/* reset the access token refresh timestamp */
oidc_session_reset_access_token_last_refresh(r, session);
}
/* see if we have a refresh_token */
if (refresh_token != NULL) {
/* store the refresh_token in the session context */
oidc_session_set_refresh_token(r, session, refresh_token);
}
/* store max session duration in the session as a hard cut-off expiry timestamp */
apr_time_t session_expires =
(provider->session_max_duration == 0) ?
apr_time_from_sec(id_token_jwt->payload.exp) :
(apr_time_now()
+ apr_time_from_sec(provider->session_max_duration));
oidc_session_set_session_expires(r, session, session_expires);
oidc_debug(r,
"provider->session_max_duration = %d, session_expires=%" APR_TIME_T_FMT,
provider->session_max_duration, session_expires);
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
/* store the domain for which this session is valid */
oidc_session_set_cookie_domain(r, session,
c->cookie_domain ? c->cookie_domain : oidc_get_current_url_host(r));
char *sid = NULL;
oidc_debug(r, "provider->backchannel_logout_supported=%d",
provider->backchannel_logout_supported);
if (provider->backchannel_logout_supported > 0) {
oidc_jose_get_string(r->pool, id_token_jwt->payload.value.json,
OIDC_CLAIM_SID, FALSE, &sid, NULL);
if (sid == NULL)
sid = id_token_jwt->payload.sub;
session->sid = oidc_make_sid_iss_unique(r, sid, provider->issuer);
}
/* store the session */
return oidc_session_save(r, session, TRUE);
}
/*
* parse the expiry for the access token
*/
static int oidc_parse_expires_in(request_rec *r, const char *expires_in) {
if (expires_in != NULL) {
char *ptr = NULL;
long number = strtol(expires_in, &ptr, 10);
if (number <= 0) {
oidc_warn(r,
"could not convert \"expires_in\" value (%s) to a number",
expires_in);
return -1;
}
return number;
}
return -1;
}
/*
* handle the different flows (hybrid, implicit, Authorization Code)
*/
static apr_byte_t oidc_handle_flows(request_rec *r, oidc_cfg *c,
oidc_proto_state_t *proto_state, oidc_provider_t *provider,
apr_table_t *params, const char *response_mode, oidc_jwt_t **jwt) {
apr_byte_t rc = FALSE;
const char *requested_response_type = oidc_proto_state_get_response_type(
proto_state);
/* handle the requested response type/mode */
if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_IDTOKEN_TOKEN)) {
rc = oidc_proto_authorization_response_code_idtoken_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_IDTOKEN)) {
rc = oidc_proto_authorization_response_code_idtoken(r, c, proto_state,
provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_TOKEN)) {
rc = oidc_proto_handle_authorization_response_code_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE)) {
rc = oidc_proto_handle_authorization_response_code(r, c, proto_state,
provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_IDTOKEN_TOKEN)) {
rc = oidc_proto_handle_authorization_response_idtoken_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_IDTOKEN)) {
rc = oidc_proto_handle_authorization_response_idtoken(r, c, proto_state,
provider, params, response_mode, jwt);
} else {
oidc_error(r, "unsupported response type: \"%s\"",
requested_response_type);
}
if ((rc == FALSE) && (*jwt != NULL)) {
oidc_jwt_destroy(*jwt);
*jwt = NULL;
}
return rc;
}
/* handle the browser back on an authorization response */
static apr_byte_t oidc_handle_browser_back(request_rec *r, const char *r_state,
oidc_session_t *session) {
/* see if we have an existing session and browser-back was used */
const char *s_state = NULL, *o_url = NULL;
if (session->remote_user != NULL) {
s_state = oidc_session_get_request_state(r, session);
o_url = oidc_session_get_original_url(r, session);
if ((r_state != NULL) && (s_state != NULL)
&& (apr_strnatcmp(r_state, s_state) == 0)) {
/* log the browser back event detection */
oidc_warn(r,
"browser back detected, redirecting to original URL: %s",
o_url);
/* go back to the URL that he originally tried to access */
oidc_util_hdr_out_location_set(r, o_url);
return TRUE;
}
}
return FALSE;
}
/*
* complete the handling of an authorization response by obtaining, parsing and verifying the
* id_token and storing the authenticated user state in the session
*/
static int oidc_handle_authorization_response(request_rec *r, oidc_cfg *c,
oidc_session_t *session, apr_table_t *params, const char *response_mode) {
oidc_debug(r, "enter, response_mode=%s", response_mode);
oidc_provider_t *provider = NULL;
oidc_proto_state_t *proto_state = NULL;
oidc_jwt_t *jwt = NULL;
/* see if this response came from a browser-back event */
if (oidc_handle_browser_back(r, apr_table_get(params, OIDC_PROTO_STATE),
session) == TRUE)
return HTTP_MOVED_TEMPORARILY;
/* match the returned state parameter against the state stored in the browser */
if (oidc_authorization_response_match_state(r, c,
apr_table_get(params, OIDC_PROTO_STATE), &provider,
&proto_state) == FALSE) {
if (c->default_sso_url != NULL) {
oidc_warn(r,
"invalid authorization response state; a default SSO URL is set, sending the user there: %s",
c->default_sso_url);
oidc_util_hdr_out_location_set(r, c->default_sso_url);
return HTTP_MOVED_TEMPORARILY;
}
oidc_error(r,
"invalid authorization response state and no default SSO URL is set, sending an error...");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if the response is an error response */
if (apr_table_get(params, OIDC_PROTO_ERROR) != NULL)
return oidc_authorization_response_error(r, c, proto_state,
apr_table_get(params, OIDC_PROTO_ERROR),
apr_table_get(params, OIDC_PROTO_ERROR_DESCRIPTION));
/* handle the code, implicit or hybrid flow */
if (oidc_handle_flows(r, c, proto_state, provider, params, response_mode,
&jwt) == FALSE)
return oidc_authorization_response_error(r, c, proto_state,
"Error in handling response type.", NULL);
if (jwt == NULL) {
oidc_error(r, "no id_token was provided");
return oidc_authorization_response_error(r, c, proto_state,
"No id_token was provided.", NULL);
}
int expires_in = oidc_parse_expires_in(r,
apr_table_get(params, OIDC_PROTO_EXPIRES_IN));
char *userinfo_jwt = NULL;
/*
* optionally resolve additional claims against the userinfo endpoint
* parsed claims are not actually used here but need to be parsed anyway for error checking purposes
*/
const char *claims = oidc_retrieve_claims_from_userinfo_endpoint(r, c,
provider, apr_table_get(params, OIDC_PROTO_ACCESS_TOKEN), NULL,
jwt->payload.sub, &userinfo_jwt);
/* restore the original protected URL that the user was trying to access */
const char *original_url = oidc_proto_state_get_original_url(proto_state);
if (original_url != NULL)
original_url = apr_pstrdup(r->pool, original_url);
const char *original_method = oidc_proto_state_get_original_method(
proto_state);
if (original_method != NULL)
original_method = apr_pstrdup(r->pool, original_method);
const char *prompt = oidc_proto_state_get_prompt(proto_state);
/* set the user */
if (oidc_set_request_user(r, c, provider, jwt, claims) == TRUE) {
/* session management: if the user in the new response is not equal to the old one, error out */
if ((prompt != NULL)
&& (apr_strnatcmp(prompt, OIDC_PROTO_PROMPT_NONE) == 0)) {
// TOOD: actually need to compare sub? (need to store it in the session separately then
//const char *sub = NULL;
//oidc_session_get(r, session, "sub", &sub);
//if (apr_strnatcmp(sub, jwt->payload.sub) != 0) {
if (apr_strnatcmp(session->remote_user, r->user) != 0) {
oidc_warn(r,
"user set from new id_token is different from current one");
oidc_jwt_destroy(jwt);
return oidc_authorization_response_error(r, c, proto_state,
"User changed!", NULL);
}
}
/* store resolved information in the session */
if (oidc_save_in_session(r, c, session, provider, r->user,
apr_table_get(params, OIDC_PROTO_ID_TOKEN), jwt, claims,
apr_table_get(params, OIDC_PROTO_ACCESS_TOKEN), expires_in,
apr_table_get(params, OIDC_PROTO_REFRESH_TOKEN),
apr_table_get(params, OIDC_PROTO_SESSION_STATE),
apr_table_get(params, OIDC_PROTO_STATE), original_url,
userinfo_jwt) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
} else {
oidc_error(r, "remote user could not be set");
return oidc_authorization_response_error(r, c, proto_state,
"Remote user could not be set: contact the website administrator",
NULL);
}
/* cleanup */
oidc_proto_state_destroy(proto_state);
oidc_jwt_destroy(jwt);
/* check that we've actually authenticated a user; functions as error handling for oidc_get_remote_user */
if (r->user == NULL)
return HTTP_UNAUTHORIZED;
/* log the successful response */
oidc_debug(r,
"session created and stored, returning to original URL: %s, original method: %s",
original_url, original_method);
/* check whether form post data was preserved; if so restore it */
if (apr_strnatcmp(original_method, OIDC_METHOD_FORM_POST) == 0) {
return oidc_request_post_preserved_restore(r, original_url);
}
/* now we've authenticated the user so go back to the URL that he originally tried to access */
oidc_util_hdr_out_location_set(r, original_url);
/* do the actual redirect to the original URL */
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle an OpenID Connect Authorization Response using the POST (+fragment->POST) response_mode
*/
static int oidc_handle_post_authorization_response(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
oidc_debug(r, "enter");
/* initialize local variables */
char *response_mode = NULL;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if we've got any POST-ed data at all */
if ((apr_table_elts(params)->nelts < 1)
|| ((apr_table_elts(params)->nelts == 1)
&& apr_table_get(params, OIDC_PROTO_RESPONSE_MODE)
&& (apr_strnatcmp(
apr_table_get(params, OIDC_PROTO_RESPONSE_MODE),
OIDC_PROTO_RESPONSE_MODE_FRAGMENT) == 0))) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"You've hit an OpenID Connect Redirect URI with no parameters, this is an invalid request; you should not open this URL in your browser directly, or have the server administrator use a different " OIDCRedirectURI " setting.",
HTTP_INTERNAL_SERVER_ERROR);
}
/* get the parameters */
response_mode = (char *) apr_table_get(params, OIDC_PROTO_RESPONSE_MODE);
/* do the actual implicit work */
return oidc_handle_authorization_response(r, c, session, params,
response_mode ? response_mode : OIDC_PROTO_RESPONSE_MODE_FORM_POST);
}
/*
* handle an OpenID Connect Authorization Response using the redirect response_mode
*/
static int oidc_handle_redirect_authorization_response(request_rec *r,
oidc_cfg *c, oidc_session_t *session) {
oidc_debug(r, "enter");
/* read the parameters from the query string */
apr_table_t *params = apr_table_make(r->pool, 8);
oidc_util_read_form_encoded_params(r, params, r->args);
/* do the actual work */
return oidc_handle_authorization_response(r, c, session, params,
OIDC_PROTO_RESPONSE_MODE_QUERY);
}
/*
* present the user with an OP selection screen
*/
static int oidc_discovery(request_rec *r, oidc_cfg *cfg) {
oidc_debug(r, "enter");
/* obtain the URL we're currently accessing, to be stored in the state/session */
char *current_url = oidc_get_current_url(r);
const char *method = oidc_original_request_method(r, cfg, FALSE);
/* generate CSRF token */
char *csrf = NULL;
if (oidc_proto_generate_nonce(r, &csrf, 8) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
char *path_scopes = oidc_dir_cfg_path_scope(r);
char *path_auth_request_params = oidc_dir_cfg_path_auth_request_params(r);
char *discover_url = oidc_cfg_dir_discover_url(r);
/* see if there's an external discovery page configured */
if (discover_url != NULL) {
/* yes, assemble the parameters for external discovery */
char *url = apr_psprintf(r->pool, "%s%s%s=%s&%s=%s&%s=%s&%s=%s",
discover_url,
strchr(discover_url, OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
OIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url),
OIDC_DISC_RM_PARAM, method,
OIDC_DISC_CB_PARAM,
oidc_util_escape_string(r, oidc_get_redirect_uri(r, cfg)),
OIDC_CSRF_NAME, oidc_util_escape_string(r, csrf));
if (path_scopes != NULL)
url = apr_psprintf(r->pool, "%s&%s=%s", url, OIDC_DISC_SC_PARAM,
oidc_util_escape_string(r, path_scopes));
if (path_auth_request_params != NULL)
url = apr_psprintf(r->pool, "%s&%s=%s", url, OIDC_DISC_AR_PARAM,
oidc_util_escape_string(r, path_auth_request_params));
/* log what we're about to do */
oidc_debug(r, "redirecting to external discovery page: %s", url);
/* set CSRF cookie */
oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1,
cfg->cookie_same_site ?
OIDC_COOKIE_EXT_SAME_SITE_STRICT :
NULL);
/* see if we need to preserve POST parameters through Javascript/HTML5 storage */
if (oidc_post_preserve_javascript(r, url, NULL, NULL) == TRUE)
return OK;
/* do the actual redirect to an external discovery page */
oidc_util_hdr_out_location_set(r, url);
return HTTP_MOVED_TEMPORARILY;
}
/* get a list of all providers configured in the metadata directory */
apr_array_header_t *arr = NULL;
if (oidc_metadata_list(r, cfg, &arr) == FALSE)
return oidc_util_html_send_error(r, cfg->error_template,
"Configuration Error",
"No configured providers found, contact your administrator",
HTTP_UNAUTHORIZED);
/* assemble a where-are-you-from IDP discovery HTML page */
const char *s = " <h3>Select your OpenID Connect Identity Provider</h3>\n";
/* list all configured providers in there */
int i;
for (i = 0; i < arr->nelts; i++) {
const char *issuer = ((const char**) arr->elts)[i];
// TODO: html escape (especially & character)
char *href = apr_psprintf(r->pool,
"%s?%s=%s&%s=%s&%s=%s&%s=%s",
oidc_get_redirect_uri(r, cfg), OIDC_DISC_OP_PARAM,
oidc_util_escape_string(r, issuer),
OIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url),
OIDC_DISC_RM_PARAM, method,
OIDC_CSRF_NAME, csrf);
if (path_scopes != NULL)
href = apr_psprintf(r->pool, "%s&%s=%s", href,
OIDC_DISC_SC_PARAM, oidc_util_escape_string(r, path_scopes));
if (path_auth_request_params != NULL)
href = apr_psprintf(r->pool, "%s&%s=%s", href,
OIDC_DISC_AR_PARAM,
oidc_util_escape_string(r, path_auth_request_params));
char *display =
(strstr(issuer, "https://") == NULL) ?
apr_pstrdup(r->pool, issuer) :
apr_pstrdup(r->pool, issuer + strlen("https://"));
/* strip port number */
//char *p = strstr(display, ":");
//if (p != NULL) *p = '\0';
/* point back to the redirect_uri, where the selection is handled, with an IDP selection and return_to URL */
s = apr_psprintf(r->pool, "%s<p><a href=\"%s\">%s</a></p>\n", s, href,
display);
}
/* add an option to enter an account or issuer name for dynamic OP discovery */
s = apr_psprintf(r->pool, "%s<form method=\"get\" action=\"%s\">\n", s,
oidc_get_redirect_uri(r, cfg));
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_RT_PARAM, current_url);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_RM_PARAM, method);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_CSRF_NAME, csrf);
if (path_scopes != NULL)
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_SC_PARAM, path_scopes);
if (path_auth_request_params != NULL)
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_AR_PARAM, path_auth_request_params);
s =
apr_psprintf(r->pool,
"%s<p>Or enter your account name (eg. "mike@seed.gluu.org", or an IDP identifier (eg. "mitreid.org"):</p>\n",
s);
s = apr_psprintf(r->pool,
"%s<p><input type=\"text\" name=\"%s\" value=\"%s\"></p>\n", s,
OIDC_DISC_OP_PARAM, "");
s = apr_psprintf(r->pool,
"%s<p><input type=\"submit\" value=\"Submit\"></p>\n", s);
s = apr_psprintf(r->pool, "%s</form>\n", s);
oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1,
cfg->cookie_same_site ? OIDC_COOKIE_EXT_SAME_SITE_STRICT : NULL);
char *javascript = NULL, *javascript_method = NULL;
char *html_head =
"<style type=\"text/css\">body {text-align: center}</style>";
if (oidc_post_preserve_javascript(r, NULL, &javascript,
&javascript_method) == TRUE)
html_head = apr_psprintf(r->pool, "%s%s", html_head, javascript);
/* now send the HTML contents to the user agent */
return oidc_util_html_send(r, "OpenID Connect Provider Discovery",
html_head, javascript_method, s, OK);
}
/*
* authenticate the user to the selected OP, if the OP is not selected yet perform discovery first
*/
static int oidc_authenticate_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, const char *original_url,
const char *login_hint, const char *id_token_hint, const char *prompt,
const char *auth_request_params, const char *path_scope) {
oidc_debug(r, "enter");
if (provider == NULL) {
// TODO: should we use an explicit redirect to the discovery endpoint (maybe a "discovery" param to the redirect_uri)?
if (c->metadata_dir != NULL)
return oidc_discovery(r, c);
/* we're not using multiple OP's configured in a metadata directory, pick the statically configured OP */
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
/* generate the random nonce value that correlates requests and responses */
char *nonce = NULL;
if (oidc_proto_generate_nonce(r, &nonce, OIDC_PROTO_NONCE_LENGTH) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
char *pkce_state = NULL;
char *code_challenge = NULL;
if ((oidc_util_spaced_string_contains(r->pool, provider->response_type,
OIDC_PROTO_CODE) == TRUE) && (provider->pkce != NULL)) {
/* generate the code verifier value that correlates authorization requests and code exchange requests */
if (provider->pkce->state(r, &pkce_state) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* generate the PKCE code challenge */
if (provider->pkce->challenge(r, pkce_state, &code_challenge) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
/* create the state between request/response */
oidc_proto_state_t *proto_state = oidc_proto_state_new();
oidc_proto_state_set_original_url(proto_state, original_url);
oidc_proto_state_set_original_method(proto_state,
oidc_original_request_method(r, c, TRUE));
oidc_proto_state_set_issuer(proto_state, provider->issuer);
oidc_proto_state_set_response_type(proto_state, provider->response_type);
oidc_proto_state_set_nonce(proto_state, nonce);
oidc_proto_state_set_timestamp_now(proto_state);
if (provider->response_mode)
oidc_proto_state_set_response_mode(proto_state,
provider->response_mode);
if (prompt)
oidc_proto_state_set_prompt(proto_state, prompt);
if (pkce_state)
oidc_proto_state_set_pkce_state(proto_state, pkce_state);
/* get a hash value that fingerprints the browser concatenated with the random input */
char *state = oidc_get_browser_state_hash(r, nonce);
/*
* create state that restores the context when the authorization response comes in
* and cryptographically bind it to the browser
*/
int rc = oidc_authorization_request_set_cookie(r, c, state, proto_state);
if (rc != HTTP_OK) {
oidc_proto_state_destroy(proto_state);
return rc;
}
/*
* printout errors if Cookie settings are not going to work
* TODO: separate this code out into its own function
*/
apr_uri_t o_uri;
memset(&o_uri, 0, sizeof(apr_uri_t));
apr_uri_t r_uri;
memset(&r_uri, 0, sizeof(apr_uri_t));
apr_uri_parse(r->pool, original_url, &o_uri);
apr_uri_parse(r->pool, oidc_get_redirect_uri(r, c), &r_uri);
if ((apr_strnatcmp(o_uri.scheme, r_uri.scheme) != 0)
&& (apr_strnatcmp(r_uri.scheme, "https") == 0)) {
oidc_error(r,
"the URL scheme (%s) of the configured " OIDCRedirectURI " does not match the URL scheme of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!",
r_uri.scheme, o_uri.scheme);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
if (c->cookie_domain == NULL) {
if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
char *p = strstr(o_uri.hostname, r_uri.hostname);
if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
oidc_error(r,
"the URL hostname (%s) of the configured " OIDCRedirectURI " does not match the URL hostname of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!",
r_uri.hostname, o_uri.hostname);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
} else {
if (!oidc_util_cookie_domain_valid(r_uri.hostname, c->cookie_domain)) {
oidc_error(r,
"the domain (%s) configured in " OIDCCookieDomain " does not match the URL hostname (%s) of the URL being accessed (%s): setting \"state\" and \"session\" cookies will not work!!",
c->cookie_domain, o_uri.hostname, original_url);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
/* send off to the OpenID Connect Provider */
// TODO: maybe show intermediate/progress screen "redirecting to"
return oidc_proto_authorization_request(r, provider, login_hint,
oidc_get_redirect_uri_iss(r, c, provider), state, proto_state,
id_token_hint, code_challenge, auth_request_params, path_scope);
}
/*
* check if the target_link_uri matches to configuration settings to prevent an open redirect
*/
static int oidc_target_link_uri_matches_configuration(request_rec *r,
oidc_cfg *cfg, const char *target_link_uri) {
apr_uri_t o_uri;
apr_uri_parse(r->pool, target_link_uri, &o_uri);
if (o_uri.hostname == NULL) {
oidc_error(r,
"could not parse the \"target_link_uri\" (%s) in to a valid URL: aborting.",
target_link_uri);
return FALSE;
}
apr_uri_t r_uri;
apr_uri_parse(r->pool, oidc_get_redirect_uri(r, cfg), &r_uri);
if (cfg->cookie_domain == NULL) {
/* cookie_domain set: see if the target_link_uri matches the redirect_uri host (because the session cookie will be set host-wide) */
if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
char *p = strstr(o_uri.hostname, r_uri.hostname);
if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
oidc_error(r,
"the URL hostname (%s) of the configured " OIDCRedirectURI " does not match the URL hostname of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
r_uri.hostname, o_uri.hostname);
return FALSE;
}
}
} else {
/* cookie_domain set: see if the target_link_uri is within the cookie_domain */
char *p = strstr(o_uri.hostname, cfg->cookie_domain);
if ((p == NULL) || (apr_strnatcmp(cfg->cookie_domain, p) != 0)) {
oidc_error(r,
"the domain (%s) configured in " OIDCCookieDomain " does not match the URL hostname (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.hostname, target_link_uri);
return FALSE;
}
}
/* see if the cookie_path setting matches the target_link_uri path */
char *cookie_path = oidc_cfg_dir_cookie_path(r);
if (cookie_path != NULL) {
char *p = (o_uri.path != NULL) ? strstr(o_uri.path, cookie_path) : NULL;
if ((p == NULL) || (p != o_uri.path)) {
oidc_error(r,
"the path (%s) configured in " OIDCCookiePath " does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.path, target_link_uri);
return FALSE;
} else if (strlen(o_uri.path) > strlen(cookie_path)) {
int n = strlen(cookie_path);
if (cookie_path[n - 1] == OIDC_CHAR_FORWARD_SLASH)
n--;
if (o_uri.path[n] != OIDC_CHAR_FORWARD_SLASH) {
oidc_error(r,
"the path (%s) configured in " OIDCCookiePath " does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.path, target_link_uri);
return FALSE;
}
}
}
return TRUE;
}
/*
* handle a response from an IDP discovery page and/or handle 3rd-party initiated SSO
*/
static int oidc_handle_discovery_response(request_rec *r, oidc_cfg *c) {
/* variables to hold the values returned in the response */
char *issuer = NULL, *target_link_uri = NULL, *login_hint = NULL,
*auth_request_params = NULL, *csrf_cookie, *csrf_query = NULL,
*user = NULL, *path_scopes;
oidc_provider_t *provider = NULL;
oidc_util_get_request_parameter(r, OIDC_DISC_OP_PARAM, &issuer);
oidc_util_get_request_parameter(r, OIDC_DISC_USER_PARAM, &user);
oidc_util_get_request_parameter(r, OIDC_DISC_RT_PARAM, &target_link_uri);
oidc_util_get_request_parameter(r, OIDC_DISC_LH_PARAM, &login_hint);
oidc_util_get_request_parameter(r, OIDC_DISC_SC_PARAM, &path_scopes);
oidc_util_get_request_parameter(r, OIDC_DISC_AR_PARAM,
&auth_request_params);
oidc_util_get_request_parameter(r, OIDC_CSRF_NAME, &csrf_query);
csrf_cookie = oidc_util_get_cookie(r, OIDC_CSRF_NAME);
/* do CSRF protection if not 3rd party initiated SSO */
if (csrf_cookie) {
/* clean CSRF cookie */
oidc_util_set_cookie(r, OIDC_CSRF_NAME, "", 0, NULL);
/* compare CSRF cookie value with query parameter value */
if ((csrf_query == NULL)
|| apr_strnatcmp(csrf_query, csrf_cookie) != 0) {
oidc_warn(r,
"CSRF protection failed, no Discovery and dynamic client registration will be allowed");
csrf_cookie = NULL;
}
}
// TODO: trim issuer/accountname/domain input and do more input validation
oidc_debug(r,
"issuer=\"%s\", target_link_uri=\"%s\", login_hint=\"%s\", user=\"%s\"",
issuer, target_link_uri, login_hint, user);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"SSO to this module without specifying a \"target_link_uri\" parameter is not possible because " OIDCDefaultURL " is not set.",
HTTP_INTERNAL_SERVER_ERROR);
}
target_link_uri = c->default_sso_url;
}
/* do open redirect prevention */
if (oidc_target_link_uri_matches_configuration(r, c,
target_link_uri) == FALSE) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"\"target_link_uri\" parameter does not match configuration settings, aborting to prevent an open redirect.",
HTTP_UNAUTHORIZED);
}
/* see if this is a static setup */
if (c->metadata_dir == NULL) {
if ((oidc_provider_static_config(r, c, &provider) == TRUE)
&& (issuer != NULL)) {
if (apr_strnatcmp(provider->issuer, issuer) != 0) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
apr_psprintf(r->pool,
"The \"iss\" value must match the configured providers' one (%s != %s).",
issuer, c->provider.issuer),
HTTP_INTERNAL_SERVER_ERROR);
}
}
return oidc_authenticate_user(r, c, NULL, target_link_uri, login_hint,
NULL, NULL, auth_request_params, path_scopes);
}
/* find out if the user entered an account name or selected an OP manually */
if (user != NULL) {
if (login_hint == NULL)
login_hint = apr_pstrdup(r->pool, user);
/* normalize the user identifier */
if (strstr(user, "https://") != user)
user = apr_psprintf(r->pool, "https://%s", user);
/* got an user identifier as input, perform OP discovery with that */
if (oidc_proto_url_based_discovery(r, c, user, &issuer) == FALSE) {
/* something did not work out, show a user facing error */
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"Could not resolve the provided user identifier to an OpenID Connect provider; check your syntax.",
HTTP_NOT_FOUND);
}
/* issuer is set now, so let's continue as planned */
} else if (strstr(issuer, OIDC_STR_AT) != NULL) {
if (login_hint == NULL) {
login_hint = apr_pstrdup(r->pool, issuer);
//char *p = strstr(issuer, OIDC_STR_AT);
//*p = '\0';
}
/* got an account name as input, perform OP discovery with that */
if (oidc_proto_account_based_discovery(r, c, issuer, &issuer) == FALSE) {
/* something did not work out, show a user facing error */
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"Could not resolve the provided account name to an OpenID Connect provider; check your syntax.",
HTTP_NOT_FOUND);
}
/* issuer is set now, so let's continue as planned */
}
/* strip trailing '/' */
int n = strlen(issuer);
if (issuer[n - 1] == OIDC_CHAR_FORWARD_SLASH)
issuer[n - 1] = '\0';
/* try and get metadata from the metadata directories for the selected OP */
if ((oidc_metadata_get(r, c, issuer, &provider, csrf_cookie != NULL) == TRUE)
&& (provider != NULL)) {
/* now we've got a selected OP, send the user there to authenticate */
return oidc_authenticate_user(r, c, provider, target_link_uri,
login_hint, NULL, NULL, auth_request_params, path_scopes);
}
/* something went wrong */
return oidc_util_html_send_error(r, c->error_template, "Invalid Request",
"Could not find valid provider metadata for the selected OpenID Connect provider; contact the administrator",
HTTP_NOT_FOUND);
}
static apr_uint32_t oidc_transparent_pixel[17] = { 0x474e5089, 0x0a1a0a0d,
0x0d000000, 0x52444849, 0x01000000, 0x01000000, 0x00000408, 0x0c1cb500,
0x00000002, 0x4144490b, 0x639c7854, 0x0000cffa, 0x02010702, 0x71311c9a,
0x00000000, 0x444e4549, 0x826042ae };
static apr_byte_t oidc_is_front_channel_logout(const char *logout_param_value) {
return ((logout_param_value != NULL)
&& ((apr_strnatcmp(logout_param_value,
OIDC_GET_STYLE_LOGOUT_PARAM_VALUE) == 0)
|| (apr_strnatcmp(logout_param_value,
OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0)));
}
static apr_byte_t oidc_is_back_channel_logout(const char *logout_param_value) {
return ((logout_param_value != NULL) && (apr_strnatcmp(logout_param_value,
OIDC_BACKCHANNEL_STYLE_LOGOUT_PARAM_VALUE) == 0));
}
/*
* revoke refresh token and access token stored in the session if the
* OP has an RFC 7009 compliant token revocation endpoint
*/
static void oidc_revoke_tokens(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *response = NULL;
char *basic_auth = NULL;
char *bearer_auth = NULL;
apr_table_t *params = NULL;
const char *token = NULL;
oidc_provider_t *provider = NULL;
oidc_debug(r, "enter");
if (oidc_get_provider_from_session(r, c, session, &provider) == FALSE)
goto out;
oidc_debug(r, "revocation_endpoint=%s",
provider->revocation_endpoint_url ?
provider->revocation_endpoint_url : "(null)");
if (provider->revocation_endpoint_url == NULL)
goto out;
params = apr_table_make(r->pool, 4);
// add the token endpoint authentication credentials to the revocation endpoint call...
if (oidc_proto_token_endpoint_auth(r, c, provider->token_endpoint_auth,
provider->client_id, provider->client_secret,
provider->client_signing_keys, provider->token_endpoint_url, params,
NULL, &basic_auth, &bearer_auth) == FALSE)
goto out;
// TODO: use oauth.ssl_validate_server ...
token = oidc_session_get_refresh_token(r, session);
if (token != NULL) {
apr_table_addn(params, "token_type_hint", "refresh_token");
apr_table_addn(params, "token", token);
if (oidc_util_http_post_form(r, provider->revocation_endpoint_url,
params, basic_auth, bearer_auth, c->oauth.ssl_validate_server,
&response, c->http_timeout_long, c->outgoing_proxy,
oidc_dir_cfg_pass_cookies(r), NULL,
NULL) == FALSE) {
oidc_warn(r, "revoking refresh token failed");
}
apr_table_clear(params);
}
token = oidc_session_get_access_token(r, session);
if (token != NULL) {
apr_table_addn(params, "token_type_hint", "access_token");
apr_table_addn(params, "token", token);
if (oidc_util_http_post_form(r, provider->revocation_endpoint_url,
params, basic_auth, bearer_auth, c->oauth.ssl_validate_server,
&response, c->http_timeout_long, c->outgoing_proxy,
oidc_dir_cfg_pass_cookies(r), NULL,
NULL) == FALSE) {
oidc_warn(r, "revoking access token failed");
}
}
out:
oidc_debug(r, "leave");
}
/*
* handle a local logout
*/
static int oidc_handle_logout_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *url) {
oidc_debug(r, "enter (url=%s)", url);
/* if there's no remote_user then there's no (stored) session to kill */
if (session->remote_user != NULL) {
oidc_revoke_tokens(r, c, session);
/* remove session state (cq. cache entry and cookie) */
oidc_session_kill(r, session);
}
/* see if this is the OP calling us */
if (oidc_is_front_channel_logout(url)) {
/* set recommended cache control headers */
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_CACHE_CONTROL,
"no-cache, no-store");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_PRAGMA, "no-cache");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_P3P, "CAO PSA OUR");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_EXPIRES, "0");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_X_FRAME_OPTIONS, "DENY");
/* see if this is PF-PA style logout in which case we return a transparent pixel */
const char *accept = oidc_util_hdr_in_accept_get(r);
if ((apr_strnatcmp(url, OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0)
|| ((accept) && strstr(accept, OIDC_CONTENT_TYPE_IMAGE_PNG))) {
return oidc_util_http_send(r,
(const char *) &oidc_transparent_pixel,
sizeof(oidc_transparent_pixel), OIDC_CONTENT_TYPE_IMAGE_PNG,
OK);
}
/* standard HTTP based logout: should be called in an iframe from the OP */
return oidc_util_html_send(r, "Logged Out", NULL, NULL,
"<p>Logged Out</p>", OK);
}
/* see if we don't need to go somewhere special after killing the session locally */
if (url == NULL)
return oidc_util_html_send(r, "Logged Out", NULL, NULL,
"<p>Logged Out</p>", OK);
/* send the user to the specified where-to-go-after-logout URL */
oidc_util_hdr_out_location_set(r, url);
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle a backchannel logout
*/
#define OIDC_EVENTS_BLOGOUT_KEY "http://schemas.openid.net/event/backchannel-logout"
static int oidc_handle_logout_backchannel(request_rec *r, oidc_cfg *cfg) {
oidc_debug(r, "enter");
const char *logout_token = NULL;
oidc_jwt_t *jwt = NULL;
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
oidc_provider_t *provider = NULL;
char *sid = NULL, *uuid = NULL;
oidc_session_t session;
int rc = HTTP_BAD_REQUEST;
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r,
"could not read POST-ed parameters to the logout endpoint");
goto out;
}
logout_token = apr_table_get(params, OIDC_PROTO_LOGOUT_TOKEN);
if (logout_token == NULL) {
oidc_error(r,
"backchannel lggout endpoint was called but could not find a parameter named \"%s\"",
OIDC_PROTO_LOGOUT_TOKEN);
goto out;
}
// TODO: jwk symmetric key based on provider
// TODO: share more code with regular id_token validation and unsolicited state
if (oidc_jwt_parse(r->pool, logout_token, &jwt,
oidc_util_merge_symmetric_key(r->pool, cfg->private_keys, NULL),
&err) == FALSE) {
oidc_error(r, "oidc_jwt_parse failed: %s", oidc_jose_e2s(r->pool, err));
goto out;
}
provider = oidc_get_provider_for_issuer(r, cfg, jwt->payload.iss, FALSE);
if (provider == NULL) {
oidc_error(r, "no provider found for issuer: %s", jwt->payload.iss);
goto out;
}
// TODO: destroy the JWK used for decryption
jwk = NULL;
if (oidc_util_create_symmetric_key(r, provider->client_secret, 0,
NULL, TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwks_uri_t jwks_uri = { provider->jwks_uri,
provider->jwks_refresh_interval, provider->ssl_validate_server };
if (oidc_proto_jwt_verify(r, cfg, jwt, &jwks_uri,
oidc_util_merge_symmetric_key(r->pool, NULL, jwk)) == FALSE) {
oidc_error(r, "id_token signature could not be validated, aborting");
goto out;
}
// oidc_proto_validate_idtoken would try and require a token binding cnf
// if the policy is set to "required", so don't use that here
if (oidc_proto_validate_jwt(r, jwt, provider->issuer, FALSE, FALSE,
provider->idtoken_iat_slack,
OIDC_TOKEN_BINDING_POLICY_DISABLED) == FALSE)
goto out;
/* verify the "aud" and "azp" values */
if (oidc_proto_validate_aud_and_azp(r, cfg, provider,
&jwt->payload) == FALSE)
goto out;
json_t *events = json_object_get(jwt->payload.value.json,
OIDC_CLAIM_EVENTS);
if (events == NULL) {
oidc_error(r, "\"%s\" claim could not be found in logout token",
OIDC_CLAIM_EVENTS);
goto out;
}
json_t *blogout = json_object_get(events, OIDC_EVENTS_BLOGOUT_KEY);
if (!json_is_object(blogout)) {
oidc_error(r, "\"%s\" object could not be found in \"%s\" claim",
OIDC_EVENTS_BLOGOUT_KEY, OIDC_CLAIM_EVENTS);
goto out;
}
char *nonce = NULL;
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_NONCE, &nonce, NULL);
if (nonce != NULL) {
oidc_error(r,
"rejecting logout request/token since it contains a \"%s\" claim",
OIDC_CLAIM_NONCE);
goto out;
}
char *jti = NULL;
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_JTI, &jti, NULL);
if (jti != NULL) {
char *replay = NULL;
oidc_cache_get_jti(r, jti, &replay);
if (replay != NULL) {
oidc_error(r,
"the \"%s\" value (%s) passed in logout token was found in the cache already; possible replay attack!?",
OIDC_CLAIM_JTI, jti);
goto out;
}
}
/* jti cache duration is the configured replay prevention window for token issuance plus 10 seconds for safety */
apr_time_t jti_cache_duration = apr_time_from_sec(
provider->idtoken_iat_slack * 2 + 10);
/* store it in the cache for the calculated duration */
oidc_cache_set_jti(r, jti, jti, apr_time_now() + jti_cache_duration);
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_EVENTS, &sid, NULL);
// TODO: by-spec we should cater for the fact that "sid" has been provided
// in the id_token returned in the authentication request, but "sub"
// is used in the logout token but that requires a 2nd entry in the
// cache and a separate session "sub" member, ugh; we'll just assume
// that is "sid" is specified in the id_token, the OP will actually use
// this for logout
// (and probably call us multiple times or the same sub if needed)
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_SID, &sid, NULL);
if (sid == NULL)
sid = jwt->payload.sub;
if (sid == NULL) {
oidc_error(r, "no \"sub\" and no \"sid\" claim found in logout token");
goto out;
}
// TODO: when dealing with sub instead of a true sid, we'll be killing all sessions for
// a specific user, across hosts that share the *same* cache backend
// if those hosts haven't been configured with a different OIDCCryptoPassphrase
// - perhaps that's even acceptable since non-memory caching is encrypted by default
// and memory-based caching doesn't suffer from this (different shm segments)?
// - it will result in 400 errors returned from backchannel logout calls to the other hosts...
sid = oidc_make_sid_iss_unique(r, sid, provider->issuer);
oidc_cache_get_sid(r, sid, &uuid);
if (uuid == NULL) {
oidc_error(r,
"could not find session based on sid/sub provided in logout token: %s",
sid);
goto out;
}
// revoke tokens if we can get a handle on those
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
if (oidc_session_load_cache_by_uuid(r, cfg, uuid, &session) != FALSE)
if (oidc_session_extract(r, &session) != FALSE)
oidc_revoke_tokens(r, cfg, &session);
}
// clear the session cache
oidc_cache_set_sid(r, sid, NULL, 0);
oidc_cache_set_session(r, uuid, NULL, 0);
rc = OK;
out:
if (jwk != NULL) {
oidc_jwk_destroy(jwk);
jwk = NULL;
}
if (jwt != NULL) {
oidc_jwt_destroy(jwt);
jwt = NULL;
}
return rc;
}
static apr_byte_t oidc_validate_post_logout_url(request_rec *r, const char *url,
char **err_str, char **err_desc) {
apr_uri_t uri;
const char *c_host = NULL;
if (apr_uri_parse(r->pool, url, &uri) != APR_SUCCESS) {
*err_str = apr_pstrdup(r->pool, "Malformed URL");
*err_desc = apr_psprintf(r->pool, "Logout URL malformed: %s", url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
c_host = oidc_get_current_url_host(r);
if ((uri.hostname != NULL)
&& ((strstr(c_host, uri.hostname) == NULL)
|| (strstr(uri.hostname, c_host) == NULL))) {
*err_str = apr_pstrdup(r->pool, "Invalid Request");
*err_desc =
apr_psprintf(r->pool,
"logout value \"%s\" does not match the hostname of the current request \"%s\"",
apr_uri_unparse(r->pool, &uri, 0), c_host);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
} else if (strstr(url, "/") != url) {
*err_str = apr_pstrdup(r->pool, "Malformed URL");
*err_desc =
apr_psprintf(r->pool,
"No hostname was parsed and it does not seem to be relative, i.e starting with '/': %s",
url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
/* validate the URL to prevent HTTP header splitting */
if (((strstr(url, "\n") != NULL) || strstr(url, "\r") != NULL)) {
*err_str = apr_pstrdup(r->pool, "Invalid Request");
*err_desc =
apr_psprintf(r->pool,
"logout value \"%s\" contains illegal \"\n\" or \"\r\" character(s)",
url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
return TRUE;
}
/*
* perform (single) logout
*/
static int oidc_handle_logout(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
oidc_provider_t *provider = NULL;
/* pickup the command or URL where the user wants to go after logout */
char *url = NULL;
char *error_str = NULL;
char *error_description = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_LOGOUT, &url);
oidc_debug(r, "enter (url=%s)", url);
if (oidc_is_front_channel_logout(url)) {
return oidc_handle_logout_request(r, c, session, url);
} else if (oidc_is_back_channel_logout(url)) {
return oidc_handle_logout_backchannel(r, c);
}
if ((url == NULL) || (apr_strnatcmp(url, "") == 0)) {
url = c->default_slo_url;
} else {
/* do input validation on the logout parameter value */
if (oidc_validate_post_logout_url(r, url, &error_str,
&error_description) == FALSE) {
return oidc_util_html_send_error(r, c->error_template, error_str,
error_description,
HTTP_BAD_REQUEST);
}
}
oidc_get_provider_from_session(r, c, session, &provider);
if ((provider != NULL) && (provider->end_session_endpoint != NULL)) {
const char *id_token_hint = oidc_session_get_idtoken(r, session);
char *logout_request = apr_pstrdup(r->pool,
provider->end_session_endpoint);
if (id_token_hint != NULL) {
logout_request = apr_psprintf(r->pool, "%s%sid_token_hint=%s",
logout_request, strchr(logout_request ? logout_request : "",
OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
oidc_util_escape_string(r, id_token_hint));
}
if (url != NULL) {
logout_request = apr_psprintf(r->pool,
"%s%spost_logout_redirect_uri=%s", logout_request,
strchr(logout_request ? logout_request : "",
OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
oidc_util_escape_string(r, url));
}
url = logout_request;
}
return oidc_handle_logout_request(r, c, session, url);
}
/*
* handle request for JWKs
*/
int oidc_handle_jwks(request_rec *r, oidc_cfg *c) {
/* pickup requested JWKs type */
// char *jwks_type = NULL;
// oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_JWKS, &jwks_type);
char *jwks = apr_pstrdup(r->pool, "{ \"keys\" : [");
apr_hash_index_t *hi = NULL;
apr_byte_t first = TRUE;
oidc_jose_error_t err;
if (c->public_keys != NULL) {
/* loop over the RSA public keys */
for (hi = apr_hash_first(r->pool, c->public_keys); hi; hi =
apr_hash_next(hi)) {
const char *s_kid = NULL;
oidc_jwk_t *jwk = NULL;
char *s_json = NULL;
apr_hash_this(hi, (const void**) &s_kid, NULL, (void**) &jwk);
if (oidc_jwk_to_json(r->pool, jwk, &s_json, &err) == TRUE) {
jwks = apr_psprintf(r->pool, "%s%s %s ", jwks, first ? "" : ",",
s_json);
first = FALSE;
} else {
oidc_error(r,
"could not convert RSA JWK to JSON using oidc_jwk_to_json: %s",
oidc_jose_e2s(r->pool, err));
}
}
}
// TODO: send stuff if first == FALSE?
jwks = apr_psprintf(r->pool, "%s ] }", jwks);
return oidc_util_http_send(r, jwks, strlen(jwks), OIDC_CONTENT_TYPE_JSON,
OK);
}
static int oidc_handle_session_management_iframe_op(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *check_session_iframe) {
oidc_debug(r, "enter");
oidc_util_hdr_out_location_set(r, check_session_iframe);
return HTTP_MOVED_TEMPORARILY;
}
static int oidc_handle_session_management_iframe_rp(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *client_id,
const char *check_session_iframe) {
oidc_debug(r, "enter");
const char *java_script =
" <script type=\"text/javascript\">\n"
" var targetOrigin = '%s';\n"
" var message = '%s' + ' ' + '%s';\n"
" var timerID;\n"
"\n"
" function checkSession() {\n"
" console.debug('checkSession: posting ' + message + ' to ' + targetOrigin);\n"
" var win = window.parent.document.getElementById('%s').contentWindow;\n"
" win.postMessage( message, targetOrigin);\n"
" }\n"
"\n"
" function setTimer() {\n"
" checkSession();\n"
" timerID = setInterval('checkSession()', %d);\n"
" }\n"
"\n"
" function receiveMessage(e) {\n"
" console.debug('receiveMessage: ' + e.data + ' from ' + e.origin);\n"
" if (e.origin !== targetOrigin ) {\n"
" console.debug('receiveMessage: cross-site scripting attack?');\n"
" return;\n"
" }\n"
" if (e.data != 'unchanged') {\n"
" clearInterval(timerID);\n"
" if (e.data == 'changed') {\n"
" window.location.href = '%s?session=check';\n"
" } else {\n"
" window.location.href = '%s?session=logout';\n"
" }\n"
" }\n"
" }\n"
"\n"
" window.addEventListener('message', receiveMessage, false);\n"
"\n"
" </script>\n";
/* determine the origin for the check_session_iframe endpoint */
char *origin = apr_pstrdup(r->pool, check_session_iframe);
apr_uri_t uri;
apr_uri_parse(r->pool, check_session_iframe, &uri);
char *p = strstr(origin, uri.path);
*p = '\0';
/* the element identifier for the OP iframe */
const char *op_iframe_id = "openidc-op";
/* restore the OP session_state from the session */
const char *session_state = oidc_session_get_session_state(r, session);
if (session_state == NULL) {
oidc_warn(r,
"no session_state found in the session; the OP does probably not support session management!?");
return OK;
}
char *s_poll_interval = NULL;
oidc_util_get_request_parameter(r, "poll", &s_poll_interval);
int poll_interval = s_poll_interval ? strtol(s_poll_interval, NULL, 10) : 0;
if ((poll_interval <= 0) || (poll_interval > 3600 * 24))
poll_interval = 3000;
const char *redirect_uri = oidc_get_redirect_uri(r, c);
java_script = apr_psprintf(r->pool, java_script, origin, client_id,
session_state, op_iframe_id, poll_interval, redirect_uri,
redirect_uri);
return oidc_util_html_send(r, NULL, java_script, "setTimer", NULL, OK);
}
/*
* handle session management request
*/
static int oidc_handle_session_management(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *cmd = NULL;
const char *id_token_hint = NULL;
oidc_provider_t *provider = NULL;
/* get the command passed to the session management handler */
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_SESSION, &cmd);
if (cmd == NULL) {
oidc_error(r, "session management handler called with no command");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if this is a local logout during session management */
if (apr_strnatcmp("logout", cmd) == 0) {
oidc_debug(r,
"[session=logout] calling oidc_handle_logout_request because of session mgmt local logout call.");
return oidc_handle_logout_request(r, c, session, c->default_slo_url);
}
oidc_get_provider_from_session(r, c, session, &provider);
/* see if this is a request for the OP iframe */
if (apr_strnatcmp("iframe_op", cmd) == 0) {
if (provider->check_session_iframe != NULL) {
return oidc_handle_session_management_iframe_op(r, c, session,
provider->check_session_iframe);
}
return HTTP_NOT_FOUND;
}
/* see if this is a request for the RP iframe */
if (apr_strnatcmp("iframe_rp", cmd) == 0) {
if ((provider->client_id != NULL)
&& (provider->check_session_iframe != NULL)) {
return oidc_handle_session_management_iframe_rp(r, c, session,
provider->client_id, provider->check_session_iframe);
}
oidc_debug(r,
"iframe_rp command issued but no client (%s) and/or no check_session_iframe (%s) set",
provider->client_id, provider->check_session_iframe);
return HTTP_NOT_FOUND;
}
/* see if this is a request check the login state with the OP */
if (apr_strnatcmp("check", cmd) == 0) {
id_token_hint = oidc_session_get_idtoken(r, session);
if ((session->remote_user != NULL) && (provider != NULL)) {
/*
* TODO: this doesn't work with per-path provided auth_request_params and scopes
* as oidc_dir_cfg_path_auth_request_params and oidc_dir_cfg_path_scope will pick
* those for the redirect_uri itself; do we need to store those as part of the
* session now?
*/
return oidc_authenticate_user(r, c, provider,
apr_psprintf(r->pool, "%s?session=iframe_rp",
oidc_get_redirect_uri_iss(r, c, provider)), NULL,
id_token_hint, "none",
oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
}
oidc_debug(r,
"[session=check] calling oidc_handle_logout_request because no session found.");
return oidc_session_redirect_parent_window_to_logout(r, c);
}
/* handle failure in fallthrough */
oidc_error(r, "unknown command: %s", cmd);
return HTTP_INTERNAL_SERVER_ERROR;
}
/*
* handle refresh token request
*/
static int oidc_handle_refresh_token_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *return_to = NULL;
char *r_access_token = NULL;
char *error_code = NULL;
/* get the command passed to the session management handler */
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_REFRESH,
&return_to);
oidc_util_get_request_parameter(r, OIDC_PROTO_ACCESS_TOKEN,
&r_access_token);
/* check the input parameters */
if (return_to == NULL) {
oidc_error(r,
"refresh token request handler called with no URL to return to");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (r_access_token == NULL) {
oidc_error(r,
"refresh token request handler called with no access_token parameter");
error_code = "no_access_token";
goto end;
}
const char *s_access_token = oidc_session_get_access_token(r, session);
if (s_access_token == NULL) {
oidc_error(r,
"no existing access_token found in the session, nothing to refresh");
error_code = "no_access_token_exists";
goto end;
}
/* compare the access_token parameter used for XSRF protection */
if (apr_strnatcmp(s_access_token, r_access_token) != 0) {
oidc_error(r,
"access_token passed in refresh request does not match the one stored in the session");
error_code = "no_access_token_match";
goto end;
}
/* get a handle to the provider configuration */
oidc_provider_t *provider = NULL;
if (oidc_get_provider_from_session(r, c, session, &provider) == FALSE) {
error_code = "session_corruption";
goto end;
}
/* execute the actual refresh grant */
if (oidc_refresh_access_token(r, c, session, provider, NULL) == FALSE) {
oidc_error(r, "access_token could not be refreshed");
error_code = "refresh_failed";
goto end;
}
/* pass the tokens to the application and save the session, possibly updating the expiry */
if (oidc_session_pass_tokens_and_save(r, c, session, TRUE) == FALSE) {
error_code = "session_corruption";
goto end;
}
end:
/* pass optional error message to the return URL */
if (error_code != NULL)
return_to = apr_psprintf(r->pool, "%s%serror_code=%s", return_to,
strchr(return_to ? return_to : "", OIDC_CHAR_QUERY) ?
OIDC_STR_AMP :
OIDC_STR_QUERY, oidc_util_escape_string(r, error_code));
/* add the redirect location header */
oidc_util_hdr_out_location_set(r, return_to);
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle request object by reference request
*/
static int oidc_handle_request_uri(request_rec *r, oidc_cfg *c) {
char *request_ref = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_REQUEST_URI,
&request_ref);
if (request_ref == NULL) {
oidc_error(r, "no \"%s\" parameter found",
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI);
return HTTP_BAD_REQUEST;
}
char *jwt = NULL;
oidc_cache_get_request_uri(r, request_ref, &jwt);
if (jwt == NULL) {
oidc_error(r, "no cached JWT found for %s reference: %s",
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI, request_ref);
return HTTP_NOT_FOUND;
}
oidc_cache_set_request_uri(r, request_ref, NULL, 0);
return oidc_util_http_send(r, jwt, strlen(jwt), OIDC_CONTENT_TYPE_JWT, OK);
}
/*
* handle a request to invalidate a cached access token introspection result
*/
int oidc_handle_remove_at_cache(request_rec *r, oidc_cfg *c) {
char *access_token = NULL;
oidc_util_get_request_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REMOVE_AT_CACHE, &access_token);
char *cache_entry = NULL;
oidc_cache_get_access_token(r, access_token, &cache_entry);
if (cache_entry == NULL) {
oidc_error(r, "no cached access token found for value: %s",
access_token);
return HTTP_NOT_FOUND;
}
oidc_cache_set_access_token(r, access_token, NULL, 0);
return OK;
}
#define OIDC_INFO_PARAM_ACCESS_TOKEN_REFRESH_INTERVAL "access_token_refresh_interval"
/*
* handle request for session info
*/
static int oidc_handle_info_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
int rc = HTTP_UNAUTHORIZED;
apr_byte_t needs_save = FALSE;
char *s_format = NULL, *s_interval = NULL, *r_value = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_INFO,
&s_format);
oidc_util_get_request_parameter(r,
OIDC_INFO_PARAM_ACCESS_TOKEN_REFRESH_INTERVAL, &s_interval);
/* see if this is a request for a format that is supported */
if ((apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_JSON, s_format) != 0)
&& (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_HTML, s_format) != 0)) {
oidc_warn(r, "request for unknown format: %s", s_format);
return HTTP_UNSUPPORTED_MEDIA_TYPE;
}
/* check that we actually have a user session and this is someone calling with a proper session cookie */
if (session->remote_user == NULL) {
oidc_warn(r, "no user session found");
return HTTP_UNAUTHORIZED;
}
/* set the user in the main request for further (incl. sub-request and authz) processing */
r->user = apr_pstrdup(r->pool, session->remote_user);
if (c->info_hook_data == NULL) {
oidc_warn(r, "no data configured to return in " OIDCInfoHook);
return HTTP_NOT_FOUND;
}
/* see if we can and need to refresh the access token */
if ((s_interval != NULL)
&& (oidc_session_get_refresh_token(r, session) != NULL)) {
apr_time_t t_interval;
if (sscanf(s_interval, "%" APR_TIME_T_FMT, &t_interval) == 1) {
t_interval = apr_time_from_sec(t_interval);
/* get the last refresh timestamp from the session info */
apr_time_t last_refresh =
oidc_session_get_access_token_last_refresh(r, session);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(last_refresh + t_interval - apr_time_now()));
/* see if we need to refresh again */
if (last_refresh + t_interval < apr_time_now()) {
/* get the current provider info */
oidc_provider_t *provider = NULL;
if (oidc_get_provider_from_session(r, c, session,
&provider) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* execute the actual refresh grant */
if (oidc_refresh_access_token(r, c, session, provider,
NULL) == FALSE)
oidc_warn(r, "access_token could not be refreshed");
else
needs_save = TRUE;
}
}
}
/* create the JSON object */
json_t *json = json_object();
/* add a timestamp of creation in there for the caller */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_TIMESTAMP,
APR_HASH_KEY_STRING)) {
json_object_set_new(json, OIDC_HOOK_INFO_TIMESTAMP,
json_integer(apr_time_sec(apr_time_now())));
}
/*
* refresh the claims from the userinfo endpoint
* side-effect is that this may refresh the access token if not already done
* note that OIDCUserInfoRefreshInterval should be set to control the refresh policy
*/
needs_save |= oidc_refresh_claims_from_userinfo_endpoint(r, c, session);
/* include the access token in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ACCES_TOKEN,
APR_HASH_KEY_STRING)) {
const char *access_token = oidc_session_get_access_token(r, session);
if (access_token != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_ACCES_TOKEN,
json_string(access_token));
}
/* include the access token expiry timestamp in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ACCES_TOKEN_EXP,
APR_HASH_KEY_STRING)) {
const char *access_token_expires =
oidc_session_get_access_token_expires(r, session);
if (access_token_expires != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_ACCES_TOKEN_EXP,
json_string(access_token_expires));
}
/* include the id_token claims in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ID_TOKEN,
APR_HASH_KEY_STRING)) {
json_t *id_token = oidc_session_get_idtoken_claims_json(r, session);
if (id_token)
json_object_set_new(json, OIDC_HOOK_INFO_ID_TOKEN, id_token);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_USER_INFO,
APR_HASH_KEY_STRING)) {
/* include the claims from the userinfo endpoint the session info */
json_t *claims = oidc_session_get_userinfo_claims_json(r, session);
if (claims)
json_object_set_new(json, OIDC_HOOK_INFO_USER_INFO, claims);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_SESSION,
APR_HASH_KEY_STRING)) {
json_t *j_session = json_object();
json_object_set(j_session, OIDC_HOOK_INFO_SESSION_STATE,
session->state);
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_UUID,
json_string(session->uuid));
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_TIMEOUT,
json_integer(apr_time_sec(session->expiry)));
apr_time_t session_expires = oidc_session_get_session_expires(r,
session);
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_EXP,
json_integer(apr_time_sec(session_expires)));
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_REMOTE_USER,
json_string(session->remote_user));
json_object_set_new(json, OIDC_HOOK_INFO_SESSION, j_session);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_REFRESH_TOKEN,
APR_HASH_KEY_STRING)) {
/* include the refresh token in the session info */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if (refresh_token != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_REFRESH_TOKEN,
json_string(refresh_token));
}
if (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_JSON, s_format) == 0) {
/* JSON-encode the result */
r_value = oidc_util_encode_json_object(r, json, 0);
/* return the stringified JSON result */
rc = oidc_util_http_send(r, r_value, strlen(r_value),
OIDC_CONTENT_TYPE_JSON, OK);
} else if (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_HTML, s_format) == 0) {
/* JSON-encode the result */
r_value = oidc_util_encode_json_object(r, json, JSON_INDENT(2));
rc = oidc_util_html_send(r, "Session Info", NULL, NULL,
apr_psprintf(r->pool, "<pre>%s</pre>", r_value), OK);
}
/* free the allocated resources */
json_decref(json);
/* pass the tokens to the application and save the session, possibly updating the expiry */
if (oidc_session_pass_tokens_and_save(r, c, session, needs_save) == FALSE) {
oidc_warn(r, "error saving session");
rc = HTTP_INTERNAL_SERVER_ERROR;
}
return rc;
}
/*
* handle all requests to the redirect_uri
*/
int oidc_handle_redirect_uri_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
if (oidc_proto_is_redirect_authorization_response(r, c)) {
/* this is an authorization response from the OP using the Basic Client profile or a Hybrid flow*/
return oidc_handle_redirect_authorization_response(r, c, session);
/*
*
* Note that we are checking for logout *before* checking for a POST authorization response
* to handle backchannel POST-based logout
*
* so any POST to the Redirect URI that does not have a logout query parameter will be handled
* as an authorization response; alternatively we could assume that a POST response has no
* parameters
*/
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_LOGOUT)) {
/* handle logout */
return oidc_handle_logout(r, c, session);
} else if (oidc_proto_is_post_authorization_response(r, c)) {
/* this is an authorization response using the fragment(+POST) response_mode with the Implicit Client profile */
return oidc_handle_post_authorization_response(r, c, session);
} else if (oidc_is_discovery_response(r, c)) {
/* this is response from the OP discovery page */
return oidc_handle_discovery_response(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_JWKS)) {
/* handle JWKs request */
return oidc_handle_jwks(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_SESSION)) {
/* handle session management request */
return oidc_handle_session_management(r, c, session);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REFRESH)) {
/* handle refresh token request */
return oidc_handle_refresh_token_request(r, c, session);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI)) {
/* handle request object by reference request */
return oidc_handle_request_uri(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REMOVE_AT_CACHE)) {
/* handle request to invalidate access token cache */
return oidc_handle_remove_at_cache(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_INFO)) {
if (session->remote_user == NULL)
return HTTP_UNAUTHORIZED;
/* set r->user, set headers/env-vars, update expiry, update userinfo + AT */
int rc = oidc_handle_existing_session(r, c, session);
if (rc != OK)
return rc;
return oidc_handle_info_request(r, c, session);
} else if ((r->args == NULL) || (apr_strnatcmp(r->args, "") == 0)) {
/* this is a "bare" request to the redirect URI, indicating implicit flow using the fragment response_mode */
return oidc_proto_javascript_implicit(r, c);
}
/* this is not an authorization response or logout request */
/* check for "error" response */
if (oidc_util_request_has_parameter(r, OIDC_PROTO_ERROR)) {
// char *error = NULL, *descr = NULL;
// oidc_util_get_request_parameter(r, "error", &error);
// oidc_util_get_request_parameter(r, "error_description", &descr);
//
// /* send user facing error to browser */
// return oidc_util_html_send_error(r, error, descr, DONE);
return oidc_handle_redirect_authorization_response(r, c, session);
}
oidc_error(r,
"The OpenID Connect callback URL received an invalid request: %s; returning HTTP_INTERNAL_SERVER_ERROR",
r->args);
/* something went wrong */
return oidc_util_html_send_error(r, c->error_template, "Invalid Request",
apr_psprintf(r->pool,
"The OpenID Connect callback URL received an invalid request"),
HTTP_INTERNAL_SERVER_ERROR);
}
#define OIDC_AUTH_TYPE_OPENID_CONNECT "openid-connect"
#define OIDC_AUTH_TYPE_OPENID_OAUTH20 "oauth20"
#define OIDC_AUTH_TYPE_OPENID_BOTH "auth-openidc"
/*
* main routine: handle OpenID Connect authentication
*/
static int oidc_check_userid_openidc(request_rec *r, oidc_cfg *c) {
if (oidc_get_redirect_uri(r, c) == NULL) {
oidc_error(r,
"configuration error: the authentication type is set to \"" OIDC_AUTH_TYPE_OPENID_CONNECT "\" but " OIDCRedirectURI " has not been set");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* check if this is a sub-request or an initial request */
if (ap_is_initial_req(r)) {
int rc = OK;
/* load the session from the request state; this will be a new "empty" session if no state exists */
oidc_session_t *session = NULL;
oidc_session_load(r, &session);
/* see if the initial request is to the redirect URI; this handles potential logout too */
if (oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, c))) {
/* handle request to the redirect_uri */
rc = oidc_handle_redirect_uri_request(r, c, session);
/* free resources allocated for the session */
oidc_session_free(r, session);
return rc;
/* initial request to non-redirect URI, check if we have an existing session */
} else if (session->remote_user != NULL) {
/* this is initial request and we already have a session */
rc = oidc_handle_existing_session(r, c, session);
/* free resources allocated for the session */
oidc_session_free(r, session);
/* strip any cookies that we need to */
oidc_strip_cookies(r);
return rc;
}
/* free resources allocated for the session */
oidc_session_free(r, session);
/*
* else: initial request, we have no session and it is not an authorization or
* discovery response: just hit the default flow for unauthenticated users
*/
} else {
/* not an initial request, try to recycle what we've already established in the main request */
if (r->main != NULL)
r->user = r->main->user;
else if (r->prev != NULL)
r->user = r->prev->user;
if (r->user != NULL) {
/* this is a sub-request and we have a session (headers will have been scrubbed and set already) */
oidc_debug(r,
"recycling user '%s' from initial request for sub-request",
r->user);
/*
* apparently request state can get lost in sub-requests, so let's see
* if we need to restore id_token and/or claims from the session cache
*/
const char *s_id_token = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_IDTOKEN);
if (s_id_token == NULL) {
oidc_session_t *session = NULL;
oidc_session_load(r, &session);
oidc_copy_tokens_to_request_state(r, session, NULL, NULL);
/* free resources allocated for the session */
oidc_session_free(r, session);
}
/* strip any cookies that we need to */
oidc_strip_cookies(r);
return OK;
}
/*
* else: not initial request, but we could not find a session, so:
* just hit the default flow for unauthenticated users
*/
}
return oidc_handle_unauthenticated_user(r, c);
}
/*
* main routine: handle "mixed" OIDC/OAuth authentication
*/
static int oidc_check_mixed_userid_oauth(request_rec *r, oidc_cfg *c) {
/* get the bearer access token from the Authorization header */
const char *access_token = NULL;
if (oidc_oauth_get_bearer_token(r, &access_token) == TRUE)
return oidc_oauth_check_userid(r, c, access_token);
/* no bearer token found: then treat this as a regular OIDC browser request */
return oidc_check_userid_openidc(r, c);
}
/*
* generic Apache authentication hook for this module: dispatches to OpenID Connect or OAuth 2.0 specific routines
*/
int oidc_check_user_id(request_rec *r) {
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
/* log some stuff about the incoming HTTP request */
oidc_debug(r, "incoming request: \"%s?%s\", ap_is_initial_req(r)=%d",
r->parsed_uri.path, r->args, ap_is_initial_req(r));
/* see if any authentication has been defined at all */
if (ap_auth_type(r) == NULL)
return DECLINED;
/* see if we've configured OpenID Connect user authentication for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_CONNECT) == 0)
return oidc_check_userid_openidc(r, c);
/* see if we've configured OAuth 2.0 access control for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0)
return oidc_oauth_check_userid(r, c, NULL);
/* see if we've configured "mixed mode" for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_BOTH) == 0)
return oidc_check_mixed_userid_oauth(r, c);
/* this is not for us but for some other handler */
return DECLINED;
}
/*
* get the claims and id_token from request state
*/
static void oidc_authz_get_claims_and_idtoken(request_rec *r, json_t **claims,
json_t **id_token) {
const char *s_claims = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_CLAIMS);
if (s_claims != NULL)
oidc_util_decode_json_object(r, s_claims, claims);
const char *s_id_token = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_IDTOKEN);
if (s_id_token != NULL)
oidc_util_decode_json_object(r, s_id_token, id_token);
}
#if MODULE_MAGIC_NUMBER_MAJOR >= 20100714
/*
* find out which action we need to take when encountering an unauthorized request
*/
static authz_status oidc_handle_unauthorized_user24(request_rec *r) {
oidc_debug(r, "enter");
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0) {
oidc_oauth_return_www_authenticate(r, "insufficient_scope",
"Different scope(s) or other claims required");
return AUTHZ_DENIED;
}
/* see if we've configured OIDCUnAutzAction for this path */
switch (oidc_dir_cfg_unautz_action(r)) {
// TODO: document that AuthzSendForbiddenOnFailure is required to return 403 FORBIDDEN
case OIDC_UNAUTZ_RETURN403:
case OIDC_UNAUTZ_RETURN401:
return AUTHZ_DENIED;
break;
case OIDC_UNAUTZ_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return AUTHZ_DENIED;
break;
}
oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
const char *location = oidc_util_hdr_out_location_get(r);
if (location != NULL) {
oidc_debug(r, "send HTML refresh with authorization redirect: %s",
location);
char *html_head = apr_psprintf(r->pool,
"<meta http-equiv=\"refresh\" content=\"0; url=%s\">",
location);
oidc_util_html_send(r, "Stepup Authentication", html_head, NULL, NULL,
HTTP_UNAUTHORIZED);
}
return AUTHZ_DENIED;
}
/*
* generic Apache >=2.4 authorization hook for this module
* handles both OpenID Connect or OAuth 2.0 in the same way, based on the claims stored in the session
*/
authz_status oidc_authz_checker(request_rec *r, const char *require_args,
const void *parsed_require_args,
oidc_authz_match_claim_fn_type match_claim_fn) {
oidc_debug(r, "enter");
/* check for anonymous access and PASS mode */
if (r->user != NULL && strlen(r->user) == 0) {
r->user = NULL;
if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS)
return AUTHZ_GRANTED;
}
/* get the set of claims from the request state (they've been set in the authentication part earlier */
json_t *claims = NULL, *id_token = NULL;
oidc_authz_get_claims_and_idtoken(r, &claims, &id_token);
/* merge id_token claims (e.g. "iss") in to claims json object */
if (claims)
oidc_util_json_merge(r, id_token, claims);
/* dispatch to the >=2.4 specific authz routine */
authz_status rc = oidc_authz_worker24(r, claims ? claims : id_token,
require_args, match_claim_fn);
/* cleanup */
if (claims)
json_decref(claims);
if (id_token)
json_decref(id_token);
if ((rc == AUTHZ_DENIED) && ap_auth_type(r))
rc = oidc_handle_unauthorized_user24(r);
return rc;
}
authz_status oidc_authz_checker_claim(request_rec *r, const char *require_args,
const void *parsed_require_args) {
return oidc_authz_checker(r, require_args, parsed_require_args,
oidc_authz_match_claim);
}
#ifdef USE_LIBJQ
authz_status oidc_authz_checker_claims_expr(request_rec *r, const char *require_args, const void *parsed_require_args) {
return oidc_authz_checker(r, require_args, parsed_require_args, oidc_authz_match_claims_expr);
}
#endif
#else
/*
* find out which action we need to take when encountering an unauthorized request
*/
static int oidc_handle_unauthorized_user22(request_rec *r) {
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
if (apr_strnatcasecmp((const char *) ap_auth_type(r), OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0) {
oidc_oauth_return_www_authenticate(r, "insufficient_scope", "Different scope(s) or other claims required");
return HTTP_UNAUTHORIZED;
}
/* see if we've configured OIDCUnAutzAction for this path */
switch (oidc_dir_cfg_unautz_action(r)) {
case OIDC_UNAUTZ_RETURN403:
return HTTP_FORBIDDEN;
case OIDC_UNAUTZ_RETURN401:
return HTTP_UNAUTHORIZED;
case OIDC_UNAUTZ_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return HTTP_UNAUTHORIZED;
}
return oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r), oidc_dir_cfg_path_scope(r));
}
/*
* generic Apache <2.4 authorization hook for this module
* handles both OpenID Connect and OAuth 2.0 in the same way, based on the claims stored in the request context
*/
int oidc_auth_checker(request_rec *r) {
/* check for anonymous access and PASS mode */
if (r->user != NULL && strlen(r->user) == 0) {
r->user = NULL;
if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS)
return OK;
}
/* get the set of claims from the request state (they've been set in the authentication part earlier */
json_t *claims = NULL, *id_token = NULL;
oidc_authz_get_claims_and_idtoken(r, &claims, &id_token);
/* get the Require statements */
const apr_array_header_t * const reqs_arr = ap_requires(r);
/* see if we have any */
const require_line * const reqs =
reqs_arr ? (require_line *) reqs_arr->elts : NULL;
if (!reqs_arr) {
oidc_debug(r,
"no require statements found, so declining to perform authorization.");
return DECLINED;
}
/* merge id_token claims (e.g. "iss") in to claims json object */
if (claims)
oidc_util_json_merge(r, id_token, claims);
/* dispatch to the <2.4 specific authz routine */
int rc = oidc_authz_worker22(r, claims ? claims : id_token, reqs,
reqs_arr->nelts);
/* cleanup */
if (claims)
json_decref(claims);
if (id_token)
json_decref(id_token);
if ((rc == HTTP_UNAUTHORIZED) && ap_auth_type(r))
rc = oidc_handle_unauthorized_user22(r);
return rc;
}
#endif
apr_byte_t oidc_enabled(request_rec *r) {
if (ap_auth_type(r) == NULL)
return FALSE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_CONNECT) == 0)
return TRUE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0)
return TRUE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_BOTH) == 0)
return TRUE;
return FALSE;
}
/*
* handle content generating requests
*/
int oidc_content_handler(request_rec *r) {
if (oidc_enabled(r) == FALSE)
return DECLINED;
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
return oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, c)) ?
OK : DECLINED;
}
extern const command_rec oidc_config_cmds[];
module AP_MODULE_DECLARE_DATA auth_openidc_module = {
STANDARD20_MODULE_STUFF,
oidc_create_dir_config,
oidc_merge_dir_config,
oidc_create_server_config,
oidc_merge_server_config,
oidc_config_cmds,
oidc_register_hooks
};
| ./CrossVul/dataset_final_sorted/CWE-601/c/good_1001_3 |
crossvul-cpp_data_bad_1392_0 | /*
*
* auth_mellon_util.c: an authentication apache module
* Copyright © 2003-2007 UNINETT (http://www.uninett.no/)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <assert.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include "auth_mellon.h"
#ifdef APLOG_USE_MODULE
APLOG_USE_MODULE(auth_mellon);
#endif
/* This function is used to get the url of the current request.
*
* Parameters:
* request_rec *r The current request.
*
* Returns:
* A string containing the full url of the current request.
* The string is allocated from r->pool.
*/
char *am_reconstruct_url(request_rec *r)
{
char *url;
/* This function will construct an full url for a given path relative to
* the root of the web site. To configure what hostname and port this
* function will use, see the UseCanonicalName configuration directive.
*/
url = ap_construct_url(r->pool, r->unparsed_uri, r);
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"reconstruct_url: url==\"%s\", unparsed_uri==\"%s\"", url,
r->unparsed_uri);
return url;
}
/* Get the hostname of the current request.
*
* Parameters:
* request_rec *r The current request.
*
* Returns:
* The hostname of the current request.
*/
static const char *am_request_hostname(request_rec *r)
{
const char *url;
apr_uri_t uri;
int ret;
url = am_reconstruct_url(r);
ret = apr_uri_parse(r->pool, url, &uri);
if (ret != APR_SUCCESS) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Failed to parse request URL: %s", url);
return NULL;
}
if (uri.hostname == NULL) {
/* This shouldn't happen, since the request URL is built with a hostname,
* but log a message to make any debuggin around this code easier.
*/
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"No hostname in request URL: %s", url);
return NULL;
}
return uri.hostname;
}
/* Validate the redirect URL.
*
* Checks that the redirect URL is to a trusted domain & scheme.
*
* Parameters:
* request_rec *r The current request.
* const char *url The redirect URL to validate.
*
* Returns:
* OK if the URL is valid, HTTP_BAD_REQUEST if not.
*/
int am_validate_redirect_url(request_rec *r, const char *url)
{
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
apr_uri_t uri;
int ret;
ret = apr_uri_parse(r->pool, url, &uri);
if (ret != APR_SUCCESS) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid redirect URL: %s", url);
return HTTP_BAD_REQUEST;
}
/* Sanity check of the scheme of the domain. We only allow http and https. */
if (uri.scheme) {
if (strcasecmp(uri.scheme, "http")
&& strcasecmp(uri.scheme, "https")) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Only http or https scheme allowed in redirect URL: %s (%s)",
url, uri.scheme);
return HTTP_BAD_REQUEST;
}
}
if (!uri.hostname) {
return OK; /* No hostname to check. */
}
for (int i = 0; cfg->redirect_domains[i] != NULL; i++) {
const char *redirect_domain = cfg->redirect_domains[i];
if (!strcasecmp(redirect_domain, "[self]")) {
if (!strcasecmp(uri.hostname, am_request_hostname(r))) {
return OK;
}
} else if (apr_fnmatch(redirect_domain, uri.hostname,
APR_FNM_PERIOD | APR_FNM_CASE_BLIND) ==
APR_SUCCESS) {
return OK;
}
}
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Untrusted hostname (%s) in redirect URL: %s",
uri.hostname, url);
return HTTP_BAD_REQUEST;
}
/* This function builds an array of regexp backreferences
*
* Parameters:
* request_rec *r The current request.
* const am_cond_t *ce The condition
* const char *value Attribute value
* const ap_regmatch_t *regmatch regmatch_t from ap_regexec()
*
* Returns:
* An array of collected backreference strings
*/
const apr_array_header_t *am_cond_backrefs(request_rec *r,
const am_cond_t *ce,
const char *value,
const ap_regmatch_t *regmatch)
{
apr_array_header_t *backrefs;
const char **ref;
int nsub;
int i;
nsub = ce->regex->re_nsub + 1; /* +1 for %0 */
backrefs = apr_array_make(r->pool, nsub, sizeof(const char *));
backrefs->nelts = nsub;
ref = (const char **)(backrefs->elts);
for (i = 0; i < nsub; i++) {
if ((regmatch[i].rm_so == -1) || (regmatch[i].rm_eo == -1)) {
ref[i] = "";
} else {
int len = regmatch[i].rm_eo - regmatch[i].rm_so;
int off = regmatch[i].rm_so;
ref[i] = apr_pstrndup(r->pool, value + off, len);
}
}
return (const apr_array_header_t *)backrefs;
}
/* This function clones an am_cond_t and substitute value to
* match (both regexp and string) with backreferences from
* a previous regex match.
*
* Parameters:
* request_rec *r The current request.
* const am_cond_t *cond The am_cond_t to clone and substiture
* const apr_array_header_t *backrefs Collected backreferences
*
* Returns:
* The cloned am_cond_t
*/
const am_cond_t *am_cond_substitue(request_rec *r, const am_cond_t *ce,
const apr_array_header_t *backrefs)
{
am_cond_t *c;
const char *instr = ce->str;
apr_size_t inlen = strlen(instr);
const char *outstr = "";
size_t last;
size_t i;
c = (am_cond_t *)apr_pmemdup(r->pool, ce, sizeof(*ce));
last = 0;
for (i = strcspn(instr, "%"); i < inlen; i += strcspn(instr + i, "%")) {
const char *fstr;
const char *ns;
const char *name;
const char *value;
apr_size_t flen;
apr_size_t pad;
apr_size_t nslen;
/*
* Make sure we got a %
*/
assert(instr[i] == '%');
/*
* Copy the format string in fstr. It can be a single
* digit (e.g.: %1) , or a curly-brace enclosed text
* (e.g.: %{12})
*/
fstr = instr + i + 1;
if (*fstr == '{') { /* Curly-brace enclosed text */
pad = 3; /* 3 for %{} */
fstr++;
flen = strcspn(fstr, "}");
/* If there is no closing }, we do not substitute */
if (fstr[flen] == '\0') {
pad = 2; /* 2 for %{ */
i += flen + pad;
break;
}
} else if (*fstr == '\0') { /* String ending by a % */
break;
} else { /* Single digit */
pad = 1; /* 1 for % */
flen = 1;
}
/*
* Try to extract a namespace (ns) and a name, e.g: %{ENV:foo}
*/
fstr = apr_pstrndup(r->pool, fstr, flen);
if ((nslen = strcspn(fstr, ":")) != flen) {
ns = apr_pstrndup(r->pool, fstr, nslen);
name = fstr + nslen + 1; /* +1 for : */
} else {
nslen = 0;
ns = "";
name = fstr;
}
value = NULL;
if ((*ns == '\0') && (strspn(fstr, "0123456789") == flen) && (backrefs != NULL)) {
/*
* If fstr has only digits, this is a regexp backreference
*/
int d = (int)apr_atoi64(fstr);
if ((d >= 0) && (d < backrefs->nelts))
value = ((const char **)(backrefs->elts))[d];
} else if ((*ns == '\0') && (strcmp(fstr, "%") == 0)) {
/*
* %-escape
*/
value = fstr;
} else if (strcmp(ns, "ENV") == 0) {
/*
* ENV namespace. Get value from apache environment.
* This is akin to how Apache itself does it during expression evaluation.
*/
value = apr_table_get(r->subprocess_env, name);
if (value == NULL) {
value = apr_table_get(r->notes, name);
}
if (value == NULL) {
value = getenv(name);
}
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Resolving \"%s\" from ENV to \"%s\"",
name, value == NULL ? "(nothing)" : value);
}
/*
* If we did not find a value, substitue the
* format string with an empty string.
*/
if (value == NULL)
value = "";
/*
* Concatenate the value with leading text, and * keep track
* of the last location we copied in source string
*/
outstr = apr_pstrcat(r->pool, outstr,
apr_pstrndup(r->pool, instr + last, i - last),
value, NULL);
last = i + flen + pad;
/*
* Move index to the end of the format string
*/
i += flen + pad;
}
/*
* Copy text remaining after the last format string.
*/
outstr = apr_pstrcat(r->pool, outstr,
apr_pstrndup(r->pool, instr + last, i - last),
NULL);
c->str = outstr;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Directive %s, \"%s\" substituted into \"%s\"",
ce->directive, instr, outstr);
/*
* If this was a regexp, recompile it.
*/
if (ce->flags & AM_COND_FLAG_REG) {
int regex_flags = AP_REG_EXTENDED|AP_REG_NOSUB;
if (ce->flags & AM_COND_FLAG_NC)
regex_flags |= AP_REG_ICASE;
c->regex = ap_pregcomp(r->pool, outstr, regex_flags);
if (c->regex == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"Invalid regular expression \"%s\"", outstr);
return ce;
}
}
return (const am_cond_t *)c;
}
/* This function checks if the user has access according
* to the MellonRequire and MellonCond directives.
*
* Parameters:
* request_rec *r The current request.
* am_cache_entry_t *session The current session.
*
* Returns:
* OK if the user has access and HTTP_FORBIDDEN if he doesn't.
*/
int am_check_permissions(request_rec *r, am_cache_entry_t *session)
{
am_dir_cfg_rec *dir_cfg;
int i, j;
int skip_or = 0;
const apr_array_header_t *backrefs = NULL;
dir_cfg = am_get_dir_cfg(r);
/* Iterate over all cond-directives */
for (i = 0; i < dir_cfg->cond->nelts; i++) {
const am_cond_t *ce;
const char *value = NULL;
int match = 0;
ce = &((am_cond_t *)(dir_cfg->cond->elts))[i];
am_diag_printf(r, "%s processing condition %d of %d: %s ",
__func__, i, dir_cfg->cond->nelts,
am_diag_cond_str(r, ce));
/*
* Rule with ignore flog?
*/
if (ce->flags & AM_COND_FLAG_IGN)
continue;
/*
* We matched a [OR] rule, skip the next rules
* until we have one without [OR].
*/
if (skip_or) {
if (!(ce->flags & AM_COND_FLAG_OR))
skip_or = 0;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Skip %s, [OR] rule matched previously",
ce->directive);
am_diag_printf(r, "Skip, [OR] rule matched previously\n");
continue;
}
/*
* look for a match on each value for this attribute,
* stop on first match.
*/
for (j = 0; (j < session->size) && !match; j++) {
const char *varname = NULL;
am_envattr_conf_t *envattr_conf = NULL;
/*
* if MAP flag is set, check for remapped
* attribute name with mellonSetEnv
*/
if (ce->flags & AM_COND_FLAG_MAP) {
envattr_conf = (am_envattr_conf_t *)apr_hash_get(dir_cfg->envattr,
am_cache_entry_get_string(session,&session->env[j].varname),
APR_HASH_KEY_STRING);
if (envattr_conf != NULL)
varname = envattr_conf->name;
}
/*
* Otherwise or if not found, use the attribute name
* sent by the IdP.
*/
if (varname == NULL)
varname = am_cache_entry_get_string(session,
&session->env[j].varname);
if (strcmp(varname, ce->varname) != 0)
continue;
value = am_cache_entry_get_string(session, &session->env[j].value);
/*
* Substiture backrefs if available
*/
if (ce->flags & AM_COND_FLAG_FSTR)
ce = am_cond_substitue(r, ce, backrefs);
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Evaluate %s vs \"%s\"",
ce->directive, value);
am_diag_printf(r, "evaluate value \"%s\" ", value);
if (value == NULL) {
match = 0; /* can not happen */
} else if (ce->flags & (AM_COND_FLAG_REG|AM_COND_FLAG_REF)) {
int nsub = ce->regex->re_nsub + 1;
ap_regmatch_t *regmatch;
regmatch = (ap_regmatch_t *)apr_palloc(r->pool,
nsub * sizeof(*regmatch));
match = !ap_regexec(ce->regex, value, nsub, regmatch, 0);
if (match)
backrefs = am_cond_backrefs(r, ce, value, regmatch);
} else if (ce->flags & AM_COND_FLAG_REG) {
match = !ap_regexec(ce->regex, value, 0, NULL, 0);
} else if (ce->flags & (AM_COND_FLAG_SUB|AM_COND_FLAG_NC)) {
match = (ap_strcasestr(ce->str, value) != NULL);
} else if (ce->flags & AM_COND_FLAG_SUB) {
match = (strstr(ce->str, value) != NULL);
} else if (ce->flags & AM_COND_FLAG_NC) {
match = !strcasecmp(ce->str, value);
} else {
match = !strcmp(ce->str, value);
}
am_diag_printf(r, "match=%s, ", match ? "yes" : "no");
}
if (ce->flags & AM_COND_FLAG_NOT) {
match = !match;
am_diag_printf(r, "negating now match=%s ", match ? "yes" : "no");
}
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"%s: %smatch", ce->directive,
(match == 0) ? "no ": "");
/*
* If no match, we stop here, except if it is an [OR] condition
*/
if (!match & !(ce->flags & AM_COND_FLAG_OR)) {
ap_log_rerror(APLOG_MARK, APLOG_NOTICE, 0, r,
"Client failed to match %s",
ce->directive);
am_diag_printf(r, "failed (no OR condition)"
" returning HTTP_FORBIDDEN\n");
return HTTP_FORBIDDEN;
}
/*
* Match on [OR] condition means we skip until a rule
* without [OR],
*/
if (match && (ce->flags & AM_COND_FLAG_OR))
skip_or = 1;
am_diag_printf(r, "\n");
}
am_diag_printf(r, "%s succeeds\n", __func__);
return OK;
}
/* This function sets default Cache-Control headers.
*
* Parameters:
* request_rec *r The request we are handling.
*
* Returns:
* Nothing.
*/
void am_set_cache_control_headers(request_rec *r)
{
/* Send Cache-Control header to ensure that:
* - no proxy in the path caches content inside this location (private),
* - user agent have to revalidate content on server (must-revalidate).
* - content is always stale as the session login status can change at any
* time synchronously (Redirect logout, session cookie is removed) or
* asynchronously (SOAP logout, session cookie still exists but is
* invalid),
*
* But never prohibit specifically any user agent to cache or store content
*
* Setting the headers in err_headers_out ensures that they will be
* sent for all responses.
*/
apr_table_setn(r->err_headers_out,
"Cache-Control", "private, max-age=0, must-revalidate");
}
/* This function reads the post data for a request.
*
* The data is stored in a buffer allocated from the request pool.
* After successful operation *data contains a pointer to the data and
* *length contains the length of the data.
* The data will always be null-terminated.
*
* Parameters:
* request_rec *r The request we read the form data from.
* char **data Pointer to where we will store the pointer
* to the data we read.
* apr_size_t *length Pointer to where we will store the length
* of the data we read. Pass NULL if you don't
* need to know the length of the data.
*
* Returns:
* OK if we successfully read the POST data.
* An error if we fail to read the data.
*/
int am_read_post_data(request_rec *r, char **data, apr_size_t *length)
{
apr_size_t bytes_read;
apr_size_t bytes_left;
apr_size_t len;
long read_length;
int rc;
/* Prepare to receive data from the client. We request that apache
* dechunks data if it is chunked.
*/
rc = ap_setup_client_block(r, REQUEST_CHUNKED_DECHUNK);
if (rc != OK) {
return rc;
}
/* This function will send a 100 Continue response if the client is
* waiting for that. If the client isn't going to send data, then this
* function will return 0.
*/
if (!ap_should_client_block(r)) {
len = 0;
} else {
len = r->remaining;
}
if (len >= 1024*1024) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Too large POST data payload (%lu bytes).",
(unsigned long)len);
return HTTP_BAD_REQUEST;
}
if (length != NULL) {
*length = len;
}
*data = (char *)apr_palloc(r->pool, len + 1);
if (*data == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Failed to allocate memory for %lu bytes of POST data.",
(unsigned long)len);
return HTTP_INTERNAL_SERVER_ERROR;
}
/* Make sure that the data is null-terminated. */
(*data)[len] = '\0';
bytes_read = 0;
bytes_left = len;
while (bytes_left > 0) {
/* Read data from the client. Returns 0 on EOF and -1 on
* error, the number of bytes otherwise.
*/
read_length = ap_get_client_block(r, &(*data)[bytes_read],
bytes_left);
if (read_length == 0) {
/* got the EOF */
(*data)[bytes_read] = '\0';
if (length != NULL) {
*length = bytes_read;
}
break;
}
else if (read_length < 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Failed to read POST data from client.");
return HTTP_INTERNAL_SERVER_ERROR;
}
bytes_read += read_length;
bytes_left -= read_length;
}
am_diag_printf(r, "POST data: %s\n", *data);
return OK;
}
/* extract_query_parameter is a function which extracts the value of
* a given parameter in a query string. The query string can be the
* query_string parameter of a GET request, or it can be the data
* passed to the web server in a POST request.
*
* Parameters:
* apr_pool_t *pool The memory pool which the memory for
* the value will be allocated from.
* const char *query_string Either the query_string from a GET
* request, or the data from a POST
* request.
* const char *name The name of the parameter to extract.
* Note that the search for this name is
* case sensitive.
*
* Returns:
* The value of the parameter or NULL if we don't find the parameter.
*/
char *am_extract_query_parameter(apr_pool_t *pool,
const char *query_string,
const char *name)
{
const char *ip;
const char *value_end;
apr_size_t namelen;
if (query_string == NULL) {
return NULL;
}
ip = query_string;
namelen = strlen(name);
/* Find parameter. Searches for /[^&]<name>[&=$]/.
* Moves ip to the first character after the name (either '&', '='
* or '\0').
*/
for (;;) {
/* First we find the name of the parameter. */
ip = strstr(ip, name);
if (ip == NULL) {
/* Parameter not found. */
return NULL;
}
/* Then we check what is before the parameter name. */
if (ip != query_string && ip[-1] != '&') {
/* Name not preceded by [^&]. */
ip++;
continue;
}
/* And last we check what follows the parameter name. */
if (ip[namelen] != '=' && ip[namelen] != '&'
&& ip[namelen] != '\0') {
/* Name not followed by [&=$]. */
ip++;
continue;
}
/* We have found the pattern. */
ip += namelen;
break;
}
/* Now ip points to the first character after the name. If this
* character is '&' or '\0', then this field doesn't have a value.
* If this character is '=', then this field has a value.
*/
if (ip[0] == '=') {
ip += 1;
}
/* The value is from ip to '&' or to the end of the string, whichever
* comes first. */
value_end = strchr(ip, '&');
if (value_end != NULL) {
/* '&' comes first. */
return apr_pstrndup(pool, ip, value_end - ip);
} else {
/* Value continues until the end of the string. */
return apr_pstrdup(pool, ip);
}
}
/* Convert a hexadecimal digit to an integer.
*
* Parameters:
* char c The digit we should convert.
*
* Returns:
* The digit as an integer, or -1 if it isn't a hex digit.
*/
static int am_unhex_digit(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return c - 'a' + 0xa;
} else if (c >= 'A' && c <= 'F') {
return c - 'A' + 0xa;
} else {
return -1;
}
}
/* This function urldecodes a string in-place.
*
* Parameters:
* char *data The string to urldecode.
*
* Returns:
* OK if successful or HTTP_BAD_REQUEST if any escape sequence decodes to a
* null-byte ('\0'), or if an invalid escape sequence is found.
*/
int am_urldecode(char *data)
{
char *ip;
char *op;
int c1, c2;
if (data == NULL) {
return HTTP_BAD_REQUEST;
}
ip = data;
op = data;
while (*ip) {
switch (*ip) {
case '+':
*op = ' ';
ip++;
op++;
break;
case '%':
/* Decode the hex digits. Note that we need to check the
* result of the first conversion before attempting the
* second conversion -- otherwise we may read past the end
* of the string.
*/
c1 = am_unhex_digit(ip[1]);
if (c1 < 0) {
return HTTP_BAD_REQUEST;
}
c2 = am_unhex_digit(ip[2]);
if (c2 < 0) {
return HTTP_BAD_REQUEST;
}
*op = (c1 << 4) | c2;
if (*op == '\0') {
/* null-byte. */
return HTTP_BAD_REQUEST;
}
ip += 3;
op++;
break;
default:
*op = *ip;
ip++;
op++;
}
}
*op = '\0';
return OK;
}
/* This function urlencodes a string. It will escape all characters
* except a-z, A-Z, 0-9, '_' and '.'.
*
* Parameters:
* apr_pool_t *pool The pool we should allocate memory from.
* const char *str The string we should urlencode.
*
* Returns:
* The urlencoded string, or NULL if str == NULL.
*/
char *am_urlencode(apr_pool_t *pool, const char *str)
{
const char *ip;
apr_size_t length;
char *ret;
char *op;
int hi, low;
/* Return NULL if str is NULL. */
if(str == NULL) {
return NULL;
}
/* Find the length of the output string. */
length = 0;
for(ip = str; *ip; ip++) {
if(*ip >= 'a' && *ip <= 'z') {
length++;
} else if(*ip >= 'A' && *ip <= 'Z') {
length++;
} else if(*ip >= '0' && *ip <= '9') {
length++;
} else if(*ip == '_' || *ip == '.') {
length++;
} else {
length += 3;
}
}
/* Add space for null-terminator. */
length++;
/* Allocate memory for string. */
ret = (char *)apr_palloc(pool, length);
/* Encode string. */
for(ip = str, op = ret; *ip; ip++, op++) {
if(*ip >= 'a' && *ip <= 'z') {
*op = *ip;
} else if(*ip >= 'A' && *ip <= 'Z') {
*op = *ip;
} else if(*ip >= '0' && *ip <= '9') {
*op = *ip;
} else if(*ip == '_' || *ip == '.') {
*op = *ip;
} else {
*op = '%';
op++;
hi = (*ip & 0xf0) >> 4;
if(hi < 0xa) {
*op = '0' + hi;
} else {
*op = 'A' + hi - 0xa;
}
op++;
low = *ip & 0x0f;
if(low < 0xa) {
*op = '0' + low;
} else {
*op = 'A' + low - 0xa;
}
}
}
/* Make output string null-terminated. */
*op = '\0';
return ret;
}
/*
* Check that a URL is safe for redirect.
*
* Parameters:
* request_rec *r The request we are processing.
* const char *url The URL we should check.
*
* Returns:
* OK on success, HTTP_BAD_REQUEST otherwise.
*/
int am_check_url(request_rec *r, const char *url)
{
const char *i;
for (i = url; *i; i++) {
if (*i >= 0 && *i < ' ') {
/* Deny all control-characters. */
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, HTTP_BAD_REQUEST, r,
"Control character detected in URL.");
return HTTP_BAD_REQUEST;
}
}
return OK;
}
/* This function generates a given number of (pseudo)random bytes.
* The current implementation uses OpenSSL's RAND_*-functions.
*
* Parameters:
* request_rec *r The request we are generating random bytes for.
* The request is used for configuration and
* error/warning reporting.
* void *dest The address if the buffer we should fill with data.
* apr_size_t count The number of random bytes to create.
*
* Returns:
* OK on success, or HTTP_INTERNAL_SERVER on failure.
*/
int am_generate_random_bytes(request_rec *r, void *dest, apr_size_t count)
{
int rc;
rc = RAND_bytes((unsigned char *)dest, (int)count);
if(rc != 1) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error generating random data: %lu",
ERR_get_error());
return HTTP_INTERNAL_SERVER_ERROR;
}
return OK;
}
/* This function generates an id which is AM_ID_LENGTH characters long.
* The id will consist of hexadecimal characters.
*
* Parameters:
* request_rec *r The request we associate allocated memory with.
*
* Returns:
* The session id, made up of AM_ID_LENGTH hexadecimal characters,
* terminated by a null-byte.
*/
char *am_generate_id(request_rec *r)
{
int rc;
char *ret;
int rand_data_len;
unsigned char *rand_data;
int i;
unsigned char b;
int hi, low;
ret = (char *)apr_palloc(r->pool, AM_ID_LENGTH + 1);
/* We need to round the length of the random data _up_, in case the
* length of the session id isn't even.
*/
rand_data_len = (AM_ID_LENGTH + 1) / 2;
/* Fill the last rand_data_len bytes of the string with
* random bytes. This allows us to overwrite from the beginning of
* the string.
*/
rand_data = (unsigned char *)&ret[AM_ID_LENGTH - rand_data_len];
/* Generate random numbers. */
rc = am_generate_random_bytes(r, rand_data, rand_data_len);
if(rc != OK) {
return NULL;
}
/* Convert the random bytes to hexadecimal. Note that we will write
* AM_ID_LENGTH+1 characters if we have a non-even length of the
* session id. This is OK - we will simply overwrite the last character
* with the null-terminator afterwards.
*/
for(i = 0; i < AM_ID_LENGTH; i += 2) {
b = rand_data[i / 2];
hi = (b >> 4) & 0xf;
low = b & 0xf;
if(hi >= 0xa) {
ret[i] = 'a' + hi - 0xa;
} else {
ret[i] = '0' + hi;
}
if(low >= 0xa) {
ret[i+1] = 'a' + low - 0xa;
} else {
ret[i+1] = '0' + low;
}
}
/* Add null-terminator- */
ret[AM_ID_LENGTH] = '\0';
return ret;
}
/* This returns the directroy part of a path, a la dirname(3)
*
* Parameters:
* apr_pool_t p Pool to allocate memory from
* const char *path Path to extract directory from
*
* Returns:
* The directory part of path
*/
const char *am_filepath_dirname(apr_pool_t *p, const char *path)
{
char *cp;
/*
* Try Unix and then Windows style. Borrowed from
* apr_match_glob(), it seems it cannot be made more
* portable.
*/
if (((cp = strrchr(path, (int)'/')) == NULL) &&
((cp = strrchr(path, (int)'\\')) == NULL))
return ".";
return apr_pstrndup(p, path, cp - path);
}
/*
* Allocate and initialize a am_file_data_t
*
* Parameters:
* apr_pool_t *pool Allocation pool.
* const char *path If non-NULL initialize file_data->path to copy of path
*
* Returns:
* Newly allocated & initialized file_data_t
*/
am_file_data_t *am_file_data_new(apr_pool_t *pool, const char *path)
{
am_file_data_t *file_data = NULL;
if ((file_data = apr_pcalloc(pool, sizeof(am_file_data_t))) == NULL) {
return NULL;
}
file_data->pool = pool;
file_data->rv = APR_EINIT;
if (path) {
file_data->path = apr_pstrdup(file_data->pool, path);
}
return file_data;
}
/*
* Allocate a new am_file_data_t and copy
*
* Parameters:
* apr_pool_t *pool Allocation pool.
* am_file_data_t *src_file_data The src being copied.
*
* Returns:
* Newly allocated & initialized from src_file_data
*/
am_file_data_t *am_file_data_copy(apr_pool_t *pool,
am_file_data_t *src_file_data)
{
am_file_data_t *dst_file_data = NULL;
if ((dst_file_data = am_file_data_new(pool, src_file_data->path)) == NULL) {
return NULL;
}
dst_file_data->path = apr_pstrdup(pool, src_file_data->path);
dst_file_data->stat_time = src_file_data->stat_time;
dst_file_data->finfo = src_file_data->finfo;
dst_file_data->contents = apr_pstrdup(pool, src_file_data->contents);
dst_file_data->read_time = src_file_data->read_time;
dst_file_data->rv = src_file_data->rv;
dst_file_data->strerror = apr_pstrdup(pool, src_file_data->strerror);
dst_file_data->generated = src_file_data->generated;
return dst_file_data;
}
/*
* Peform a stat on a file to get it's properties
*
* A stat is performed on the file. If there was an error the
* result value is left in file_data->rv and an error description
* string is formatted and left in file_data->strerror and function
* returns the rv value. If the stat was successful the stat
* information is left in file_data->finfo and APR_SUCCESS
* set set as file_data->rv and returned as the function result.
*
* The file_data->stat_time indicates if and when the stat was
* performed, a zero time value indicates the operation has not yet
* been performed.
*
* Parameters:
* am_file_data_t *file_data Struct containing file information
*
* Returns:
* APR status code, same value as file_data->rv
*/
apr_status_t am_file_stat(am_file_data_t *file_data)
{
char buffer[512];
if (file_data == NULL) {
return APR_EINVAL;
}
file_data->strerror = NULL;
file_data->stat_time = apr_time_now();
file_data->rv = apr_stat(&file_data->finfo, file_data->path,
APR_FINFO_SIZE, file_data->pool);
if (file_data->rv != APR_SUCCESS) {
file_data->strerror =
apr_psprintf(file_data->pool,
"apr_stat: Error opening \"%s\" [%d] \"%s\"",
file_data->path, file_data->rv,
apr_strerror(file_data->rv, buffer, sizeof(buffer)));
}
return file_data->rv;
}
/*
* Read file into dynamically allocated buffer
*
* First a stat is performed on the file. If there was an error the
* result value is left in file_data->rv and an error description
* string is formatted and left in file_data->strerror and function
* returns the rv value. If the stat was successful the stat
* information is left in file_data->finfo.
*
* A buffer is dynamically allocated and the contents of the file is
* read into file_data->contents. If there was an error the result
* value is left in file_data->rv and an error description string is
* formatted and left in file_data->strerror and the function returns
* the rv value.
*
* The file_data->stat_time and file_data->read_time indicate if and
* when those operations were performed, a zero time value indicates
* the operation has not yet been performed.
*
* Parameters:
* am_file_data_t *file_data Struct containing file information
*
* Returns:
* APR status code, same value as file_data->rv
*/
apr_status_t am_file_read(am_file_data_t *file_data)
{
char buffer[512];
apr_file_t *fd;
apr_size_t nbytes;
if (file_data == NULL) {
return APR_EINVAL;
}
file_data->rv = APR_SUCCESS;
file_data->strerror = NULL;
am_file_stat(file_data);
if (file_data->rv != APR_SUCCESS) {
return file_data->rv;
}
if ((file_data->rv = apr_file_open(&fd, file_data->path,
APR_READ, 0, file_data->pool)) != 0) {
file_data->strerror =
apr_psprintf(file_data->pool,
"apr_file_open: Error opening \"%s\" [%d] \"%s\"",
file_data->path, file_data->rv,
apr_strerror(file_data->rv, buffer, sizeof(buffer)));
return file_data->rv;
}
file_data->read_time = apr_time_now();
nbytes = file_data->finfo.size;
file_data->contents = (char *)apr_palloc(file_data->pool, nbytes + 1);
file_data->rv = apr_file_read_full(fd, file_data->contents, nbytes, NULL);
if (file_data->rv != 0) {
file_data->strerror =
apr_psprintf(file_data->pool,
"apr_file_read_full: Error reading \"%s\" [%d] \"%s\"",
file_data->path, file_data->rv,
apr_strerror(file_data->rv, buffer, sizeof(buffer)));
(void)apr_file_close(fd);
return file_data->rv;
}
file_data->contents[nbytes] = '\0';
(void)apr_file_close(fd);
return file_data->rv;
}
/*
* Purge outdated saved POST requests.
*
* Parameters:
* request_rec *r The current request
*
* Returns:
* OK on success, or HTTP_INTERNAL_SERVER on failure.
*/
int am_postdir_cleanup(request_rec *r)
{
am_mod_cfg_rec *mod_cfg;
apr_dir_t *postdir;
apr_status_t rv;
char error_buffer[64];
apr_finfo_t afi;
char *fname;
int count;
apr_time_t expire_before;
mod_cfg = am_get_mod_cfg(r->server);
/* The oldes file we should keep. Delete files that are older. */
expire_before = apr_time_now() - mod_cfg->post_ttl * APR_USEC_PER_SEC;
/*
* Open our POST directory or create it.
*/
rv = apr_dir_open(&postdir, mod_cfg->post_dir, r->pool);
if (rv != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Unable to open MellonPostDirectory \"%s\": %s",
mod_cfg->post_dir,
apr_strerror(rv, error_buffer, sizeof(error_buffer)));
return HTTP_INTERNAL_SERVER_ERROR;
}
/*
* Purge outdated items
*/
count = 0;
do {
rv = apr_dir_read(&afi, APR_FINFO_NAME|APR_FINFO_CTIME, postdir);
if (rv != OK)
break;
/* Skip dot_files */
if (afi.name[0] == '.')
continue;
if (afi.ctime < expire_before) {
fname = apr_psprintf(r->pool, "%s/%s", mod_cfg->post_dir, afi.name);
(void)apr_file_remove(fname , r->pool);
} else {
count++;
}
} while (1 /* CONSTCOND */);
(void)apr_dir_close(postdir);
if (count >= mod_cfg->post_count) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Too many saved POST sessions. "
"Increase MellonPostCount directive.");
return HTTP_INTERNAL_SERVER_ERROR;
}
return OK;
}
/*
* HTML-encode a string
*
* Parameters:
* request_rec *r The current request
* const char *str The string to encode
*
* Returns:
* The encoded string
*/
char *am_htmlencode(request_rec *r, const char *str)
{
const char *cp;
char *output;
apr_size_t outputlen;
int i;
outputlen = 0;
for (cp = str; *cp; cp++) {
switch (*cp) {
case '&':
outputlen += 5;
break;
case '"':
outputlen += 6;
break;
default:
outputlen += 1;
break;
}
}
i = 0;
output = apr_palloc(r->pool, outputlen + 1);
for (cp = str; *cp; cp++) {
switch (*cp) {
case '&':
(void)strcpy(&output[i], "&");
i += 5;
break;
case '"':
(void)strcpy(&output[i], """);
i += 6;
break;
default:
output[i] = *cp;
i += 1;
break;
}
}
output[i] = '\0';
return output;
}
/* This function produces the endpoint URL
*
* Parameters:
* request_rec *r The request we received.
*
* Returns:
* the endpoint URL
*/
char *am_get_endpoint_url(request_rec *r)
{
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
return ap_construct_url(r->pool, cfg->endpoint_path, r);
}
/*
* This function saves a POST request for later replay and updates
* the return URL.
*
* Parameters:
* request_rec *r The current request.
* const char **relay_state The returl URL
*
* Returns:
* OK on success, HTTP_INTERNAL_SERVER_ERROR otherwise
*/
int am_save_post(request_rec *r, const char **relay_state)
{
am_mod_cfg_rec *mod_cfg;
const char *content_type;
const char *charset;
const char *psf_id;
char *psf_name;
char *post_data;
apr_size_t post_data_len;
apr_size_t written;
apr_file_t *psf;
mod_cfg = am_get_mod_cfg(r->server);
if (mod_cfg->post_dir == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"MellonPostReplay enabled but MellonPostDirectory not set "
"-- cannot save post data");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (am_postdir_cleanup(r) != OK)
return HTTP_INTERNAL_SERVER_ERROR;
/* Check Content-Type */
content_type = apr_table_get(r->headers_in, "Content-Type");
if (content_type == NULL) {
content_type = "urlencoded";
charset = NULL;
} else {
if (am_has_header(r, content_type,
"application/x-www-form-urlencoded")) {
content_type = "urlencoded";
} else if (am_has_header(r, content_type,
"multipart/form-data")) {
content_type = "multipart";
} else {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Unknown POST Content-Type \"%s\"", content_type);
return HTTP_INTERNAL_SERVER_ERROR;
}
charset = am_get_header_attr(r, content_type, NULL, "charset");
}
if ((psf_id = am_generate_id(r)) == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r, "cannot generate id");
return HTTP_INTERNAL_SERVER_ERROR;
}
psf_name = apr_psprintf(r->pool, "%s/%s", mod_cfg->post_dir, psf_id);
if (apr_file_open(&psf, psf_name,
APR_WRITE|APR_CREATE|APR_BINARY,
APR_FPROT_UREAD|APR_FPROT_UWRITE,
r->pool) != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"cannot create POST session file");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (am_read_post_data(r, &post_data, &post_data_len) != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r, "cannot read POST data");
(void)apr_file_close(psf);
return HTTP_INTERNAL_SERVER_ERROR;
}
if (post_data_len > mod_cfg->post_size) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"POST data size %" APR_SIZE_T_FMT
" exceeds maximum %" APR_SIZE_T_FMT ". "
"Increase MellonPostSize directive.",
post_data_len, mod_cfg->post_size);
(void)apr_file_close(psf);
return HTTP_INTERNAL_SERVER_ERROR;
}
written = post_data_len;
if ((apr_file_write(psf, post_data, &written) != OK) ||
(written != post_data_len)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"cannot write to POST session file");
(void)apr_file_close(psf);
return HTTP_INTERNAL_SERVER_ERROR;
}
if (apr_file_close(psf) != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"cannot close POST session file");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (charset != NULL)
charset = apr_psprintf(r->pool, "&charset=%s",
am_urlencode(r->pool, charset));
else
charset = "";
*relay_state = apr_psprintf(r->pool,
"%srepost?id=%s&ReturnTo=%s&enctype=%s%s",
am_get_endpoint_url(r), psf_id,
am_urlencode(r->pool, *relay_state),
content_type, charset);
return OK;
}
/*
* This function replaces CRLF by LF in a string
*
* Parameters:
* request_rec *r The current request
* const char *str The string
*
* Returns:
* Output string
*/
const char *am_strip_cr(request_rec *r, const char *str)
{
char *output;
const char *cp;
apr_size_t i;
output = apr_palloc(r->pool, strlen(str) + 1);
i = 0;
for (cp = str; *cp; cp++) {
if ((*cp == '\r') && (*(cp + 1) == '\n'))
continue;
output[i++] = *cp;
}
output[i++] = '\0';
return (const char *)output;
}
/*
* This function replaces LF by CRLF in a string
*
* Parameters:
* request_rec *r The current request
* const char *str The string
*
* Returns:
* Output string
*/
const char *am_add_cr(request_rec *r, const char *str)
{
char *output;
const char *cp;
apr_size_t xlen;
apr_size_t i;
xlen = 0;
for (cp = str; *cp; cp++)
if (*cp == '\n')
xlen++;
output = apr_palloc(r->pool, strlen(str) + xlen + 1);
i = 0;
for (cp = str; *cp; cp++) {
if (*cp == '\n')
output[i++] = '\r';
output[i++] = *cp;
}
output[i++] = '\0';
return (const char *)output;
}
/*
* This function tokenize a string, just like strtok_r, except that
* the separator is a string instead of a character set.
*
* Parameters:
* const char *str The string to tokenize
* const char *sep The separator string
* char **last Pointer to state (char *)
*
* Returns:
* OK on success, HTTP_INTERNAL_SERVER_ERROR otherwise
*/
const char *am_xstrtok(request_rec *r, const char *str,
const char *sep, char **last)
{
char *s;
char *np;
/* Resume */
if (str != NULL)
s = apr_pstrdup(r->pool, str);
else
s = *last;
/* End of string */
if (*s == '\0')
return NULL;
/* Next sep exists? */
if ((np = strstr(s, sep)) == NULL) {
*last = s + strlen(s);
} else {
*last = np + strlen(sep);
memset(np, 0, strlen(sep));
}
return s;
}
/* This function strips leading spaces and tabs from a string
*
* Parameters:
* const char **s Pointer to the string
*
*/
void am_strip_blank(const char **s)
{
while ((**s == ' ') || (**s == '\t'))
(*s)++;
return;
}
/* This function extracts a MIME header from a MIME section
*
* Parameters:
* request_rec *r The request
* const char *m The MIME section
* const char *h The header to extract (case insensitive)
*
* Returns:
* The header value, or NULL on failure.
*/
const char *am_get_mime_header(request_rec *r, const char *m, const char *h)
{
const char *line;
char *l1;
const char *value;
char *l2;
for (line = am_xstrtok(r, m, "\n", &l1); line && *line;
line = am_xstrtok(r, NULL, "\n", &l1)) {
am_strip_blank(&line);
if (((value = am_xstrtok(r, line, ":", &l2)) != NULL) &&
(strcasecmp(value, h) == 0)) {
if ((value = am_xstrtok(r, NULL, ":", &l2)) != NULL)
am_strip_blank(&value);
return value;
}
}
return NULL;
}
/* This function extracts an attribute from a header
*
* Parameters:
* request_rec *r The request
* const char *h The header
* const char *v Optional header value to check (case insensitive)
* const char *a Optional attribute to extract (case insensitive)
*
* Returns:
* if i was provided, item value, or NULL on failure.
* if i is NULL, the whole header, or NULL on failure. This is
* useful for testing v.
*/
const char *am_get_header_attr(request_rec *r, const char *h,
const char *v, const char *a)
{
const char *value;
const char *attr;
char *l1;
const char *attr_value = NULL;
/* Looking for
* header-value; item_name="item_value"\n
*/
if ((value = am_xstrtok(r, h, ";", &l1)) == NULL)
return NULL;
am_strip_blank(&value);
/* If a header value was provided, check it */
if ((v != NULL) && (strcasecmp(value, v) != 0))
return NULL;
/* If no attribute name is provided, return everything */
if (a == NULL)
return h;
while ((attr = am_xstrtok(r, NULL, ";", &l1)) != NULL) {
const char *attr_name = NULL;
char *l2;
am_strip_blank(&attr);
attr_name = am_xstrtok(r, attr, "=", &l2);
if ((attr_name != NULL) && (strcasecmp(attr_name, a) == 0)) {
if ((attr_value = am_xstrtok(r, NULL, "=", &l2)) != NULL)
am_strip_blank(&attr_value);
break;
}
}
/* Remove leading and trailing quotes */
if (attr_value != NULL) {
apr_size_t len;
len = strlen(attr_value);
if ((len > 1) && (attr_value[len - 1] == '\"'))
attr_value = apr_pstrndup(r->pool, attr_value, len - 1);
if (attr_value[0] == '\"')
attr_value++;
}
return attr_value;
}
/* This function checks for a header name/value existence
*
* Parameters:
* request_rec *r The request
* const char *h The header (case insensitive)
* const char *v Optional header value to check (case insensitive)
*
* Returns:
* 0 if header does not exists or does not has the value, 1 otherwise
*/
int am_has_header(request_rec *r, const char *h, const char *v)
{
return (am_get_header_attr(r, h, v, NULL) != NULL);
}
/* This function extracts the body from a MIME section
*
* Parameters:
* request_rec *r The request
* const char *mime The MIME section
*
* Returns:
* The MIME section body, or NULL on failure.
*/
const char *am_get_mime_body(request_rec *r, const char *mime)
{
const char lflf[] = "\n\n";
const char *body;
apr_size_t body_len;
if ((body = strstr(mime, lflf)) == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r, "No MIME body");
return NULL;
}
body += strlen(lflf);
/* Strip tralling \n */
if ((body_len = strlen(body)) >= 1) {
if (body[body_len - 1] == '\n')
body = apr_pstrmemdup(r->pool, body, body_len - 1);
}
/* Turn back LF into CRLF */
return am_add_cr(r, body);
}
/* This function returns the URL for a given provider service (type + method)
*
* Parameters:
* request_rec *r The request
* LassoProfile *profile Login profile
* char *endpoint_name Service and method as specified in metadata
* e.g.: "SingleSignOnService HTTP-Redirect"
* Returns:
* The endpoint URL that must be freed by caller, or NULL on failure.
*/
char *
am_get_service_url(request_rec *r, LassoProfile *profile, char *service_name)
{
LassoProvider *provider;
gchar *url;
provider = lasso_server_get_provider(profile->server,
profile->remote_providerID);
if (LASSO_IS_PROVIDER(provider) == FALSE) {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"Cannot find provider service %s, no provider.",
service_name);
return NULL;
}
url = lasso_provider_get_metadata_one(provider, service_name);
if (url == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"Cannot find provider service %s from metadata.",
service_name);
return NULL;
}
return url;
}
/*------------------------ Begin Token Parsing Code --------------------------*/
typedef enum {
TOKEN_WHITESPACE = 1,
TOKEN_SEMICOLON,
TOKEN_COMMA,
TOKEN_EQUAL,
TOKEN_IDENTIFIER,
TOKEN_DBL_QUOTE_STRING,
} TokenType;
typedef struct {
TokenType type; /* The type of this token */
char *str; /* The string value of the token */
apr_size_t len; /* The number of characters in the token */
apr_size_t offset; /* The offset from the beginning of
the string to the start of the token */
} Token;
#ifdef DEBUG
/* Return string representation of TokenType enumeration
*
* Parameters:
* token_type A TokenType enumeration
* Returns: String name of token_type
*/
static const char *
token_type_str(TokenType token_type)
{
switch(token_type) {
case TOKEN_WHITESPACE: return "WHITESPACE";
case TOKEN_SEMICOLON: return "SEMICOLON";
case TOKEN_COMMA: return "COMMA";
case TOKEN_EQUAL: return "EQUAL";
case TOKEN_IDENTIFIER: return "IDENTIFIER";
case TOKEN_DBL_QUOTE_STRING: return "DBL_QUOTE_STRING";
default: return "unknown";
}
}
static void dump_tokens(request_rec *r, apr_array_header_t *tokens)
{
apr_size_t i;
for (i = 0; i < tokens->nelts; i++) {
Token token = APR_ARRAY_IDX(tokens, i, Token);
AM_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r,
"token[%2zd] %s \"%s\" offset=%lu len=%lu ", i,
token_type_str(token.type), token.str,
token.offset, token.len);
}
}
#endif
/* Initialize token and add to list of tokens
*
* Utility to assist tokenize function.
*
* A token object is created and added to the end of the list of
* tokens. It is initialized with the type of token, a copy of the
* string, it's length, and it's offset from the beginning of the
* string where it was found.
*
* Tokens with special processing needs are also handled here.
*
* A double quoted string will:
*
* * Have it's delimiting quotes removed.
* * Will unescape escaped characters.
*
* Parameters:
* tokens Array of Token objects.
* type The type of the token (e.g. TokenType).
* str The string the token was parsed from, used to compute
* the position of the token in the original string.
* start The first character in the token.
* end the last character in the token.
*/
static inline void
push_token(apr_array_header_t *tokens, TokenType type, const char *str,
const char *start, const char *end)
{
apr_size_t offset = start - str;
Token *token = apr_array_push(tokens);
if (type == TOKEN_DBL_QUOTE_STRING) {
/* do not include quotes in token value */
start++; end--;
}
token->type = type;
token->len = end - start;
token->offset = offset;
token->str = apr_pstrmemdup(tokens->pool, start, token->len);
if (type == TOKEN_DBL_QUOTE_STRING) {
/*
* The original HTTP 1.1 spec was ambiguous with respect to
* backslash quoting inside double quoted strings. This has since
* been resolved in this errata:
*
* http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p1-messaging-16.html#rfc.section.3.2.3
*
* Which states:
*
* Recipients that process the value of the quoted-string MUST
* handle a quoted-pair as if it were replaced by the octet
* following the backslash.
*
* Senders SHOULD NOT escape octets in quoted-strings that do not
* require escaping (i.e., other than DQUOTE and the backslash
* octet).
*/
char *p, *t;
for (p = token->str; *p; p++) {
if (p[0] == '\\' && p[1]) {
/*
* Found backslash with following character.
* Move rest of string down 1 character.
*/
for (t = p; *t; t++) {
t[0] = t[1];
}
token->len--;
}
}
}
}
/* Break a string into a series of tokens
*
* Given a string return an array of tokens. If the string cannot be
* successfully parsed an error string is returned at the location
* specified by the error parameter, if error is NULL then the parsing
* was successful. If an error occured the returned array of tokens
* will include all tokens parsed up until where the unrecognized
* input occurred. The input str is never modified.
*
* Parameters:
* pool memory allocation pool
* str input string to be parsed.
* ignore_whitespace if True whitespace tokens are not returned
* error location where error string is returned
* if NULL no error occurred
* Returns: array of Token objects
*/
static apr_array_header_t *
tokenize(apr_pool_t *pool, const char *str, bool ignore_whitespace,
char **error)
{
apr_array_header_t *tokens = apr_array_make(pool, 10, sizeof(Token));
const char *p, *start;
*error = NULL;
p = start = str;
while(*p) {
if (apr_isspace(*p)) { /* whitespace */
p++;
while(*p && apr_isspace(*p)) p++;
if (!ignore_whitespace) {
push_token(tokens, TOKEN_WHITESPACE, str, start, p);
}
start = p;
}
else if (apr_isalpha(*p)) { /* identifier: must begin with
alpha then any alphanumeric or
underscore */
p++;
while(*p && (apr_isalnum(*p) || *p == '_')) p++;
push_token(tokens, TOKEN_IDENTIFIER, str, start, p);
start = p;
}
else if (*p == '"') { /* double quoted string */
p++; /* step over double quote */
while(*p) {
if (*p == '\\') { /* backslash escape */
p++; /* step over backslash */
if (*p) {
p++; /* step over escaped character */
} else {
break; /* backslash at end of string, stop */
}
}
if (*p == '\"') break; /* terminating quote delimiter */
p++; /* keep scanning */
}
if (*p != '\"') {
*error = apr_psprintf(pool,
"unterminated string beginning at "
"position %" APR_SIZE_T_FMT " in \"%s\"",
start-str, str);
break;
}
p++;
push_token(tokens, TOKEN_DBL_QUOTE_STRING, str, start, p);
start = p;
}
else if (*p == '=') { /* equals */
p++;
push_token(tokens, TOKEN_EQUAL, str, start, p);
start = p;
}
else if (*p == ',') { /* comma */
p++;
push_token(tokens, TOKEN_COMMA, str, start, p);
start = p;
}
else if (*p == ';') { /* semicolon */
p++;
push_token(tokens, TOKEN_SEMICOLON, str, start, p);
start = p;
}
else { /* unrecognized token */
*error = apr_psprintf(pool,
"unknown token at "
"position %" APR_SIZE_T_FMT " in string \"%s\"",
p-str, str);
break;
}
}
return tokens;
}
/* Test if the token is what we're looking for
*
* Given an index into the tokens array determine if the token type
* matches. If the value parameter is non-NULL then the token's value
* must also match. If the array index is beyond the last array item
* false is returned.
*
* Parameters:
* tokens Array of Token objects
* index Index used to select the Token object from the Tokens array.
* If the index is beyond the last array item False is returned.
* type The token type which must match
* value If non-NULL then the token string value must be equal to this.
* Returns: True if the token matches, False otherwise.
*/
static bool
is_token(apr_array_header_t *tokens, apr_size_t index, TokenType type, const char *value)
{
if (index >= tokens->nelts) {
return false;
}
Token token = APR_ARRAY_IDX(tokens, index, Token);
if (token.type != type) {
return false;
}
if (value) {
if (!g_str_equal(token.str, value)) {
return false;
}
}
return true;
}
/*------------------------- End Token Parsing Code ---------------------------*/
/* Return message describing position an error when parsing.
*
* When parsing we expect tokens to appear in a certain sequence. We
* report the contents of the unexpected token and it's position in
* the string. However if the parsing error is due to the fact we've
* exhausted all tokens but are still expecting another token then our
* error message indicates we reached the end of the string.
*
* Parameters:
* tokens Array of Token objects.
* index Index in tokens array where bad token was found
*/
static inline const char *
parse_error_msg(apr_array_header_t *tokens, apr_size_t index)
{
if (index >= tokens->nelts) {
return "end of string";
}
return apr_psprintf(tokens->pool, "\"%s\" at position %" APR_SIZE_T_FMT,
APR_ARRAY_IDX(tokens, index, Token).str,
APR_ARRAY_IDX(tokens, index, Token).offset);
}
/* This function checks if an HTTP PAOS header is valid and
* returns any service options which may have been specified.
*
* A PAOS header is composed of a mandatory PAOS version and service
* values. A semicolon separates the version from the service values.
*
* Service values are delimited by semicolons, and options are
* comma-delimited from the service value and each other.
*
* The PAOS version must be in the form ver="xxx" (note the version
* string must be in double quotes).
*
* The ECP service must be specified, it MAY be followed by optional
* comma seperated options, all values must be in double quotes.
*
* ECP Service
* "urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp"
*
* Recognized Options:
*
* Support for channel bindings
* urn:oasis:names:tc:SAML:protocol:ext:channel-binding
*
* Support for Holder-of-Key subject confirmation
* urn:oasis:names:tc:SAML:2.0:cm:holder-of-key
*
* Request for signed SAML request
* urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp:2.0:WantAuthnRequestsSigned
*
* Request to delegate credentials to the service provider
* urn:oasis:names:tc:SAML:2.0:conditions:delegation
*
*
* Example PAOS HTTP header::
*
* PAOS: ver="urn:liberty:paos:2003-08";
* "urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp",
* "urn:oasis:names:tc:SAML:protocol:ext:channel-binding",
* "urn:oasis:names:tc:SAML:2.0:cm:holder-of-key"
*
* Parameters:
* request_rec *r The request
* const char *header The PAOS header value
* ECPServiceOptions *options_return
* Pointer to location to receive options,
* may be NULL. Bitmask of option flags.
*
* Returns:
* true if the PAOS header is valid, false otherwise. If options is non-NULL
* then the set of option flags is returned there.
*
*/
bool am_parse_paos_header(request_rec *r, const char *header,
ECPServiceOptions *options_return)
{
bool result = false;
ECPServiceOptions options = 0;
apr_array_header_t *tokens;
apr_size_t i;
char *error;
AM_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r,
"PAOS header: \"%s\"", header);
tokens = tokenize(r->pool, header, true, &error);
#ifdef DEBUG
dump_tokens(r, tokens);
#endif
if (error) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r, "%s", error);
goto cleanup;
}
/* Header must begin with "ver=xxx" where xxx is paos version */
if (!is_token(tokens, 0, TOKEN_IDENTIFIER, "ver") ||
!is_token(tokens, 1, TOKEN_EQUAL, NULL) ||
!is_token(tokens, 2, TOKEN_DBL_QUOTE_STRING, LASSO_PAOS_HREF)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"invalid PAOS header, "
"expected header to begin with ver=\"%s\", "
"actual header=\"%s\"",
LASSO_PAOS_HREF, header);
goto cleanup;
}
/* Next is the service value, separated from the version by a semicolon */
if (!is_token(tokens, 3, TOKEN_SEMICOLON, NULL)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"invalid PAOS header, "
"expected semicolon after PAOS version "
"but found %s in header=\"%s\"",
parse_error_msg(tokens, 3),
header);
goto cleanup;
}
if (!is_token(tokens, 4, TOKEN_DBL_QUOTE_STRING, LASSO_ECP_HREF)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"invalid PAOS header, "
"expected service token to be \"%s\", "
"but found %s in header=\"%s\"",
LASSO_ECP_HREF,
parse_error_msg(tokens, 4),
header);
goto cleanup;
}
/* After the service value there may be optional flags separated by commas */
if (tokens->nelts == 5) { /* no options */
result = true;
goto cleanup;
}
/* More tokens after the service value, must be options, iterate over them */
for (i = 5; i < tokens->nelts; i++) {
if (!is_token(tokens, i, TOKEN_COMMA, NULL)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"invalid PAOS header, "
"expected comma after PAOS service "
"but found %s in header=\"%s\"",
parse_error_msg(tokens, i),
header);
goto cleanup;
}
if (++i > tokens->nelts) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"invalid PAOS header, "
"expected option after comma "
"in header=\"%s\"",
header);
goto cleanup;
}
Token token = APR_ARRAY_IDX(tokens, i, Token);
if (token.type != TOKEN_DBL_QUOTE_STRING) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"invalid PAOS header, "
"expected quoted string after comma "
"but found %s in header=\"%s\"",
parse_error_msg(tokens, i),
header);
goto cleanup;
}
/* Have an option string, convert it to a bit flag */
const char *value = token.str;
if (g_str_equal(value, LASSO_SAML_EXT_CHANNEL_BINDING)) {
options |= ECP_SERVICE_OPTION_CHANNEL_BINDING;
} else if (g_str_equal(value, LASSO_SAML2_CONFIRMATION_METHOD_HOLDER_OF_KEY)) {
options |= ECP_SERVICE_OPTION_HOLDER_OF_KEY;
} else if (g_str_equal(value, LASSO_SAML2_ECP_PROFILE_WANT_AUTHN_SIGNED)) {
options |= ECP_SERVICE_OPTION_WANT_AUTHN_SIGNED;
} else if (g_str_equal(value, LASSO_SAML2_CONDITIONS_DELEGATION)) {
options |= ECP_SERVICE_OPTION_DELEGATION;
} else {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"Unknown PAOS service option = \"%s\"",
value);
goto cleanup;
}
}
result = true;
cleanup:
if (options_return) {
*options_return = options;
}
return result;
}
/* This function checks if Accept header has a media type
*
* Given an Accept header value like this:
*
* "text/html,application/xhtml+xml,application/xml;q=0.9"
*
* Parse the string and find name of each media type, ignore any parameters
* bound to the name. Test to see if the name matches the input media_type.
*
* Parameters:
* request_rec *r The request
* const char *header The header value
* const char *media_type media type header value to check (case insensitive)
*
* Returns:
* true if media type is in header, false otherwise
*/
bool am_header_has_media_type(request_rec *r, const char *header, const char *media_type)
{
bool result = false;
char **comma_tokens = NULL;
char **media_ranges = NULL;
char *media_range = NULL;
if (header == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"invalid Accept header, NULL");
goto cleanup;
}
/*
* Split the header into a list of media_range tokens separated by
* a comma and iterate over the list.
*/
comma_tokens = g_strsplit(header, ",", 0);
for (media_ranges = comma_tokens, media_range = *media_ranges;
media_range;
media_range = *(++media_ranges)) {
char **semicolon_tokens = NULL;
char *name = NULL;
/*
* Split the media_range into a name and parameters, each
* separated by a semicolon. The first element in the list is
* the media_type name, subsequent params are optional and ignored.
*/
media_range = g_strstrip(media_range);
semicolon_tokens = g_strsplit(media_range, ";", 0);
/*
* Does the media_type match our required media_type?
* If so clean up and return success.
*/
name = g_strstrip(semicolon_tokens[0]);
if (name && g_str_equal(name, media_type)) {
result = true;
g_strfreev(semicolon_tokens);
goto cleanup;
}
g_strfreev(semicolon_tokens);
}
cleanup:
g_strfreev(comma_tokens);
return result;
}
/*
* Lookup a config string in a specific language. If lang is NULL and
* the config string had been defined without a language qualifier
* return the unqualified value. If not found NULL is returned.
*/
const char *am_get_config_langstring(apr_hash_t *h, const char *lang)
{
char *string;
if (lang == NULL) {
lang = "";
}
string = (char *)apr_hash_get(h, lang, APR_HASH_KEY_STRING);
return string;
}
/*
* Get the value of boolean query parameter.
*
* Parameters:
* request_rec *r The request
* const char *name The name of the query parameter
* int *return_value The address of the variable to receive
* the boolean value
* int default_value The value returned if parameter is absent or
* in event of an error
*
* Returns:
* OK on success, HTTP error otherwise
*
* Looks for the named parameter in the query parameters, if found
* parses the value which must be one of:
*
* * true
* * false
*
* If value cannot be parsed HTTP_BAD_REQUEST is returned.
*
* If not found, or if there is an error, the returned value is set to
* default_value.
*/
int am_get_boolean_query_parameter(request_rec *r, const char *name,
int *return_value, int default_value)
{
char *value_str;
int ret = OK;
*return_value = default_value;
value_str = am_extract_query_parameter(r->pool, r->args, name);
if (value_str != NULL) {
ret = am_urldecode(value_str);
if (ret != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error urldecoding \"%s\" boolean query parameter, "
"value=\"%s\"", name, value_str);
return ret;
}
if(!strcmp(value_str, "true")) {
*return_value = TRUE;
} else if(!strcmp(value_str, "false")) {
*return_value = FALSE;
} else {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid value for \"%s\" boolean query parameter, "
"value=\"%s\"", name, value_str);
ret = HTTP_BAD_REQUEST;
}
}
return ret;
}
/*
* Get the URL of the AssertionConsumerServer having specific protocol
* binding.
*
* Parameters:
* LassoProvider *provider The provider whose endpoints will be scanned.
* const char *binding The required binding short name.
*
* Returns:
* The endpoint URL or NULL if not found. Must be freed with g_free().
*
* Lasso does not provide a public API to select a provider endpoint
* by binding. The best we can do is iterate over a list of endpoint
* descriptors and select a matching descriptor.
*
* Lasso does not document the format of these descriptor names but
* essentially a descriptor is a space separated concatenation of the
* endpoint properties. For SAML2 one can assume it is the endpoint
* type, optionally followed by the protocol binding name, optionally
* followd by the index (if the endpoint type is indexed). If the
* endpoint is a response location then "ResponseLocation" will be
* appended as the final token. For example here is a list of
* descriptors returned for a service provider (note they are
* unordered).
*
* "AssertionConsumerService HTTP-POST 0"
* "AuthnRequestsSigned"
* "AssertionConsumerService PAOS 2"
* "SingleLogoutService HTTP-Redirect"
* "SingleLogoutService SOAP"
* "AssertionConsumerService HTTP-Artifact 1"
* "NameIDFormat"
* "SingleLogoutService HTTP-POST ResponseLocation"
*
* The possible binding names are:
*
* "SOAP"
* "HTTP-Redirect"
* "HTTP-POST"
* "HTTP-Artifact"
* "PAOS"
* "URI"
*
* We know the AssertionConsumerService is indexed. If there is more
* than one endpoint with the required binding we select the one with
* the lowest index assuming it is preferred.
*/
char *am_get_assertion_consumer_service_by_binding(LassoProvider *provider, const char *binding)
{
GList *descriptors;
char *url;
char *selected_descriptor;
char *descriptor;
char **tokens;
guint n_tokens;
GList *i;
char *endptr;
long descriptor_index, min_index;
url = NULL;
selected_descriptor = NULL;
min_index = LONG_MAX;
/* The descriptor list is unordered */
descriptors = lasso_provider_get_metadata_keys_for_role(provider,
LASSO_PROVIDER_ROLE_SP);
for (i = g_list_first(descriptors), tokens=NULL;
i;
i = g_list_next(i), g_strfreev(tokens)) {
descriptor = i->data;
descriptor_index = LONG_MAX;
/*
* Split the descriptor into tokens, only consider descriptors
* which have at least 3 tokens and whose first token is
* AssertionConsumerService
*/
tokens = g_strsplit(descriptor, " ", 0);
n_tokens = g_strv_length(tokens);
if (n_tokens < 3) continue;
if (!g_str_equal(tokens[0], "AssertionConsumerService")) continue;
if (!g_str_equal(tokens[1], binding)) continue;
descriptor_index = strtol(tokens[2], &endptr, 10);
if (tokens[2] == endptr) continue; /* could not parse int */
if (descriptor_index < min_index) {
selected_descriptor = descriptor;
min_index = descriptor_index;
}
}
if (selected_descriptor) {
url = lasso_provider_get_metadata_one_for_role(provider,
LASSO_PROVIDER_ROLE_SP,
selected_descriptor);
}
lasso_release_list_of_strings(descriptors);
return url;
}
#ifdef HAVE_ECP
/* String representation of ECPServiceOptions bitmask
*
* ECPServiceOptions is a bitmask of flags. Return a comma separated string
* of all the flags. If any bit in the bitmask is unaccounted for an
* extra string will be appended of the form "(unknown bits = x)".
*
* Parameters:
* pool memory allocation pool
* options bitmask of PAOS options
*/
char *am_ecp_service_options_str(apr_pool_t *pool, ECPServiceOptions options)
{
apr_array_header_t *names = apr_array_make(pool, 4, sizeof(const char *));
if (options & ECP_SERVICE_OPTION_CHANNEL_BINDING) {
APR_ARRAY_PUSH(names, const char *) = "channel-binding";
options &= ~ECP_SERVICE_OPTION_CHANNEL_BINDING;
}
if (options & ECP_SERVICE_OPTION_HOLDER_OF_KEY) {
APR_ARRAY_PUSH(names, const char *) = "holder-of-key";
options &= ~ECP_SERVICE_OPTION_HOLDER_OF_KEY;
}
if (options & ECP_SERVICE_OPTION_WANT_AUTHN_SIGNED) {
APR_ARRAY_PUSH(names, const char *) = "want-authn-signed";
options &= ~ECP_SERVICE_OPTION_WANT_AUTHN_SIGNED;
}
if (options & ECP_SERVICE_OPTION_DELEGATION) {
APR_ARRAY_PUSH(names, const char *) = "delegation";
options &= ~ECP_SERVICE_OPTION_DELEGATION;
}
if (options) {
APR_ARRAY_PUSH(names, const char *) =
apr_psprintf(pool, "(unknown bits = %#x)", options);
}
return apr_array_pstrcat(pool, names, ',');
}
/* Determine if request is compatible with PAOS, decode headers
*
* To indicate support for the ECP profile, and the PAOS binding, the
* request MUST include the following HTTP header fields:
*
* 1. An Accept header indicating acceptance of the MIME type
* "application/vnd.paos+xml"
*
* 2. A PAOS header specifying the PAOS version with a value, at minimum, of
* "urn:liberty:paos:2003-08" and a supported service value of
* "urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp". The service value MAY
* contain option values.
*
* This function validates the Accept header the the PAOS header, if
* all condidtions are met it returns true, false otherwise. If the
* validation succeeds any ECP options specified along with the
* ECP service are parsed and stored in req_cfg->ecp_service_options
*
* Any error discovered during processing are returned in the
* error_code parameter, zero indicates success. This function never
* returns true if an error occurred.
*
* Parameters:
* request_rec *r The current request.
* int * error_code Return error code here
*
*/
bool am_is_paos_request(request_rec *r, int *error_code)
{
const char *accept_header = NULL;
const char *paos_header = NULL;
bool have_paos_media_type = false;
bool valid_paos_header = false;
bool is_paos = false;
ECPServiceOptions ecp_service_options = 0;
*error_code = 0;
accept_header = apr_table_get(r->headers_in, "Accept");
paos_header = apr_table_get(r->headers_in, "PAOS");
if (accept_header) {
if (am_header_has_media_type(r, accept_header, MEDIA_TYPE_PAOS)) {
have_paos_media_type = true;
}
}
if (paos_header) {
if (am_parse_paos_header(r, paos_header, &ecp_service_options)) {
valid_paos_header = true;
} else {
if (*error_code == 0)
*error_code = AM_ERROR_INVALID_PAOS_HEADER;
}
}
if (have_paos_media_type) {
if (valid_paos_header) {
is_paos = true;
} else {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"request supplied PAOS media type in Accept header "
"but omitted valid PAOS header");
if (*error_code == 0)
*error_code = AM_ERROR_MISSING_PAOS_HEADER;
}
} else {
if (valid_paos_header) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"request supplied valid PAOS header "
"but omitted PAOS media type in Accept header");
if (*error_code == 0)
*error_code = AM_ERROR_MISSING_PAOS_MEDIA_TYPE;
}
}
AM_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r,
"have_paos_media_type=%s valid_paos_header=%s is_paos=%s "
"error_code=%d ecp options=[%s]",
have_paos_media_type ? "True" : "False",
valid_paos_header ? "True" : "False",
is_paos ? "True" : "False",
*error_code,
am_ecp_service_options_str(r->pool, ecp_service_options));
if (is_paos) {
am_req_cfg_rec *req_cfg;
req_cfg = am_get_req_cfg(r);
req_cfg->ecp_service_options = ecp_service_options;
}
return is_paos;
}
#endif /* HAVE_ECP */
char *
am_saml_response_status_str(request_rec *r, LassoNode *node)
{
LassoSamlp2StatusResponse *response = (LassoSamlp2StatusResponse*)node;
LassoSamlp2Status *status = NULL;
const char *status_code1 = NULL;
const char *status_code2 = NULL;
if (!LASSO_IS_SAMLP2_STATUS_RESPONSE(response)) {
return apr_psprintf(r->pool,
"error, expected LassoSamlp2StatusResponse "
"but got %s",
lasso_node_get_name((LassoNode*)response));
}
status = response->Status;
if (status == NULL ||
!LASSO_IS_SAMLP2_STATUS(status) ||
status->StatusCode == NULL ||
status->StatusCode->Value == NULL) {
return apr_psprintf(r->pool, "Status missing");
}
status_code1 = status->StatusCode->Value;
if (status->StatusCode->StatusCode) {
status_code2 = status->StatusCode->StatusCode->Value;
}
return apr_psprintf(r->pool,
"StatusCode1=\"%s\", StatusCode2=\"%s\", "
"StatusMessage=\"%s\"",
status_code1, status_code2, status->StatusMessage);
}
| ./CrossVul/dataset_final_sorted/CWE-601/c/bad_1392_0 |
crossvul-cpp_data_good_1392_0 | /*
*
* auth_mellon_util.c: an authentication apache module
* Copyright © 2003-2007 UNINETT (http://www.uninett.no/)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <assert.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include "auth_mellon.h"
#ifdef APLOG_USE_MODULE
APLOG_USE_MODULE(auth_mellon);
#endif
/* This function is used to get the url of the current request.
*
* Parameters:
* request_rec *r The current request.
*
* Returns:
* A string containing the full url of the current request.
* The string is allocated from r->pool.
*/
char *am_reconstruct_url(request_rec *r)
{
char *url;
/* This function will construct an full url for a given path relative to
* the root of the web site. To configure what hostname and port this
* function will use, see the UseCanonicalName configuration directive.
*/
url = ap_construct_url(r->pool, r->unparsed_uri, r);
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"reconstruct_url: url==\"%s\", unparsed_uri==\"%s\"", url,
r->unparsed_uri);
return url;
}
/* Get the hostname of the current request.
*
* Parameters:
* request_rec *r The current request.
*
* Returns:
* The hostname of the current request.
*/
static const char *am_request_hostname(request_rec *r)
{
const char *url;
apr_uri_t uri;
int ret;
url = am_reconstruct_url(r);
ret = apr_uri_parse(r->pool, url, &uri);
if (ret != APR_SUCCESS) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Failed to parse request URL: %s", url);
return NULL;
}
if (uri.hostname == NULL) {
/* This shouldn't happen, since the request URL is built with a hostname,
* but log a message to make any debuggin around this code easier.
*/
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"No hostname in request URL: %s", url);
return NULL;
}
return uri.hostname;
}
/* Validate the redirect URL.
*
* Checks that the redirect URL is to a trusted domain & scheme.
*
* Parameters:
* request_rec *r The current request.
* const char *url The redirect URL to validate.
*
* Returns:
* OK if the URL is valid, HTTP_BAD_REQUEST if not.
*/
int am_validate_redirect_url(request_rec *r, const char *url)
{
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
apr_uri_t uri;
int ret;
ret = apr_uri_parse(r->pool, url, &uri);
if (ret != APR_SUCCESS) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid redirect URL: %s", url);
return HTTP_BAD_REQUEST;
}
/* Sanity check of the scheme of the domain. We only allow http and https. */
if (uri.scheme) {
if (strcasecmp(uri.scheme, "http")
&& strcasecmp(uri.scheme, "https")) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Only http or https scheme allowed in redirect URL: %s (%s)",
url, uri.scheme);
return HTTP_BAD_REQUEST;
}
}
if (!uri.hostname) {
return OK; /* No hostname to check. */
}
for (int i = 0; cfg->redirect_domains[i] != NULL; i++) {
const char *redirect_domain = cfg->redirect_domains[i];
if (!strcasecmp(redirect_domain, "[self]")) {
if (!strcasecmp(uri.hostname, am_request_hostname(r))) {
return OK;
}
} else if (apr_fnmatch(redirect_domain, uri.hostname,
APR_FNM_PERIOD | APR_FNM_CASE_BLIND) ==
APR_SUCCESS) {
return OK;
}
}
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Untrusted hostname (%s) in redirect URL: %s",
uri.hostname, url);
return HTTP_BAD_REQUEST;
}
/* This function builds an array of regexp backreferences
*
* Parameters:
* request_rec *r The current request.
* const am_cond_t *ce The condition
* const char *value Attribute value
* const ap_regmatch_t *regmatch regmatch_t from ap_regexec()
*
* Returns:
* An array of collected backreference strings
*/
const apr_array_header_t *am_cond_backrefs(request_rec *r,
const am_cond_t *ce,
const char *value,
const ap_regmatch_t *regmatch)
{
apr_array_header_t *backrefs;
const char **ref;
int nsub;
int i;
nsub = ce->regex->re_nsub + 1; /* +1 for %0 */
backrefs = apr_array_make(r->pool, nsub, sizeof(const char *));
backrefs->nelts = nsub;
ref = (const char **)(backrefs->elts);
for (i = 0; i < nsub; i++) {
if ((regmatch[i].rm_so == -1) || (regmatch[i].rm_eo == -1)) {
ref[i] = "";
} else {
int len = regmatch[i].rm_eo - regmatch[i].rm_so;
int off = regmatch[i].rm_so;
ref[i] = apr_pstrndup(r->pool, value + off, len);
}
}
return (const apr_array_header_t *)backrefs;
}
/* This function clones an am_cond_t and substitute value to
* match (both regexp and string) with backreferences from
* a previous regex match.
*
* Parameters:
* request_rec *r The current request.
* const am_cond_t *cond The am_cond_t to clone and substiture
* const apr_array_header_t *backrefs Collected backreferences
*
* Returns:
* The cloned am_cond_t
*/
const am_cond_t *am_cond_substitue(request_rec *r, const am_cond_t *ce,
const apr_array_header_t *backrefs)
{
am_cond_t *c;
const char *instr = ce->str;
apr_size_t inlen = strlen(instr);
const char *outstr = "";
size_t last;
size_t i;
c = (am_cond_t *)apr_pmemdup(r->pool, ce, sizeof(*ce));
last = 0;
for (i = strcspn(instr, "%"); i < inlen; i += strcspn(instr + i, "%")) {
const char *fstr;
const char *ns;
const char *name;
const char *value;
apr_size_t flen;
apr_size_t pad;
apr_size_t nslen;
/*
* Make sure we got a %
*/
assert(instr[i] == '%');
/*
* Copy the format string in fstr. It can be a single
* digit (e.g.: %1) , or a curly-brace enclosed text
* (e.g.: %{12})
*/
fstr = instr + i + 1;
if (*fstr == '{') { /* Curly-brace enclosed text */
pad = 3; /* 3 for %{} */
fstr++;
flen = strcspn(fstr, "}");
/* If there is no closing }, we do not substitute */
if (fstr[flen] == '\0') {
pad = 2; /* 2 for %{ */
i += flen + pad;
break;
}
} else if (*fstr == '\0') { /* String ending by a % */
break;
} else { /* Single digit */
pad = 1; /* 1 for % */
flen = 1;
}
/*
* Try to extract a namespace (ns) and a name, e.g: %{ENV:foo}
*/
fstr = apr_pstrndup(r->pool, fstr, flen);
if ((nslen = strcspn(fstr, ":")) != flen) {
ns = apr_pstrndup(r->pool, fstr, nslen);
name = fstr + nslen + 1; /* +1 for : */
} else {
nslen = 0;
ns = "";
name = fstr;
}
value = NULL;
if ((*ns == '\0') && (strspn(fstr, "0123456789") == flen) && (backrefs != NULL)) {
/*
* If fstr has only digits, this is a regexp backreference
*/
int d = (int)apr_atoi64(fstr);
if ((d >= 0) && (d < backrefs->nelts))
value = ((const char **)(backrefs->elts))[d];
} else if ((*ns == '\0') && (strcmp(fstr, "%") == 0)) {
/*
* %-escape
*/
value = fstr;
} else if (strcmp(ns, "ENV") == 0) {
/*
* ENV namespace. Get value from apache environment.
* This is akin to how Apache itself does it during expression evaluation.
*/
value = apr_table_get(r->subprocess_env, name);
if (value == NULL) {
value = apr_table_get(r->notes, name);
}
if (value == NULL) {
value = getenv(name);
}
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Resolving \"%s\" from ENV to \"%s\"",
name, value == NULL ? "(nothing)" : value);
}
/*
* If we did not find a value, substitue the
* format string with an empty string.
*/
if (value == NULL)
value = "";
/*
* Concatenate the value with leading text, and * keep track
* of the last location we copied in source string
*/
outstr = apr_pstrcat(r->pool, outstr,
apr_pstrndup(r->pool, instr + last, i - last),
value, NULL);
last = i + flen + pad;
/*
* Move index to the end of the format string
*/
i += flen + pad;
}
/*
* Copy text remaining after the last format string.
*/
outstr = apr_pstrcat(r->pool, outstr,
apr_pstrndup(r->pool, instr + last, i - last),
NULL);
c->str = outstr;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Directive %s, \"%s\" substituted into \"%s\"",
ce->directive, instr, outstr);
/*
* If this was a regexp, recompile it.
*/
if (ce->flags & AM_COND_FLAG_REG) {
int regex_flags = AP_REG_EXTENDED|AP_REG_NOSUB;
if (ce->flags & AM_COND_FLAG_NC)
regex_flags |= AP_REG_ICASE;
c->regex = ap_pregcomp(r->pool, outstr, regex_flags);
if (c->regex == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"Invalid regular expression \"%s\"", outstr);
return ce;
}
}
return (const am_cond_t *)c;
}
/* This function checks if the user has access according
* to the MellonRequire and MellonCond directives.
*
* Parameters:
* request_rec *r The current request.
* am_cache_entry_t *session The current session.
*
* Returns:
* OK if the user has access and HTTP_FORBIDDEN if he doesn't.
*/
int am_check_permissions(request_rec *r, am_cache_entry_t *session)
{
am_dir_cfg_rec *dir_cfg;
int i, j;
int skip_or = 0;
const apr_array_header_t *backrefs = NULL;
dir_cfg = am_get_dir_cfg(r);
/* Iterate over all cond-directives */
for (i = 0; i < dir_cfg->cond->nelts; i++) {
const am_cond_t *ce;
const char *value = NULL;
int match = 0;
ce = &((am_cond_t *)(dir_cfg->cond->elts))[i];
am_diag_printf(r, "%s processing condition %d of %d: %s ",
__func__, i, dir_cfg->cond->nelts,
am_diag_cond_str(r, ce));
/*
* Rule with ignore flog?
*/
if (ce->flags & AM_COND_FLAG_IGN)
continue;
/*
* We matched a [OR] rule, skip the next rules
* until we have one without [OR].
*/
if (skip_or) {
if (!(ce->flags & AM_COND_FLAG_OR))
skip_or = 0;
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Skip %s, [OR] rule matched previously",
ce->directive);
am_diag_printf(r, "Skip, [OR] rule matched previously\n");
continue;
}
/*
* look for a match on each value for this attribute,
* stop on first match.
*/
for (j = 0; (j < session->size) && !match; j++) {
const char *varname = NULL;
am_envattr_conf_t *envattr_conf = NULL;
/*
* if MAP flag is set, check for remapped
* attribute name with mellonSetEnv
*/
if (ce->flags & AM_COND_FLAG_MAP) {
envattr_conf = (am_envattr_conf_t *)apr_hash_get(dir_cfg->envattr,
am_cache_entry_get_string(session,&session->env[j].varname),
APR_HASH_KEY_STRING);
if (envattr_conf != NULL)
varname = envattr_conf->name;
}
/*
* Otherwise or if not found, use the attribute name
* sent by the IdP.
*/
if (varname == NULL)
varname = am_cache_entry_get_string(session,
&session->env[j].varname);
if (strcmp(varname, ce->varname) != 0)
continue;
value = am_cache_entry_get_string(session, &session->env[j].value);
/*
* Substiture backrefs if available
*/
if (ce->flags & AM_COND_FLAG_FSTR)
ce = am_cond_substitue(r, ce, backrefs);
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Evaluate %s vs \"%s\"",
ce->directive, value);
am_diag_printf(r, "evaluate value \"%s\" ", value);
if (value == NULL) {
match = 0; /* can not happen */
} else if (ce->flags & (AM_COND_FLAG_REG|AM_COND_FLAG_REF)) {
int nsub = ce->regex->re_nsub + 1;
ap_regmatch_t *regmatch;
regmatch = (ap_regmatch_t *)apr_palloc(r->pool,
nsub * sizeof(*regmatch));
match = !ap_regexec(ce->regex, value, nsub, regmatch, 0);
if (match)
backrefs = am_cond_backrefs(r, ce, value, regmatch);
} else if (ce->flags & AM_COND_FLAG_REG) {
match = !ap_regexec(ce->regex, value, 0, NULL, 0);
} else if (ce->flags & (AM_COND_FLAG_SUB|AM_COND_FLAG_NC)) {
match = (ap_strcasestr(ce->str, value) != NULL);
} else if (ce->flags & AM_COND_FLAG_SUB) {
match = (strstr(ce->str, value) != NULL);
} else if (ce->flags & AM_COND_FLAG_NC) {
match = !strcasecmp(ce->str, value);
} else {
match = !strcmp(ce->str, value);
}
am_diag_printf(r, "match=%s, ", match ? "yes" : "no");
}
if (ce->flags & AM_COND_FLAG_NOT) {
match = !match;
am_diag_printf(r, "negating now match=%s ", match ? "yes" : "no");
}
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"%s: %smatch", ce->directive,
(match == 0) ? "no ": "");
/*
* If no match, we stop here, except if it is an [OR] condition
*/
if (!match & !(ce->flags & AM_COND_FLAG_OR)) {
ap_log_rerror(APLOG_MARK, APLOG_NOTICE, 0, r,
"Client failed to match %s",
ce->directive);
am_diag_printf(r, "failed (no OR condition)"
" returning HTTP_FORBIDDEN\n");
return HTTP_FORBIDDEN;
}
/*
* Match on [OR] condition means we skip until a rule
* without [OR],
*/
if (match && (ce->flags & AM_COND_FLAG_OR))
skip_or = 1;
am_diag_printf(r, "\n");
}
am_diag_printf(r, "%s succeeds\n", __func__);
return OK;
}
/* This function sets default Cache-Control headers.
*
* Parameters:
* request_rec *r The request we are handling.
*
* Returns:
* Nothing.
*/
void am_set_cache_control_headers(request_rec *r)
{
/* Send Cache-Control header to ensure that:
* - no proxy in the path caches content inside this location (private),
* - user agent have to revalidate content on server (must-revalidate).
* - content is always stale as the session login status can change at any
* time synchronously (Redirect logout, session cookie is removed) or
* asynchronously (SOAP logout, session cookie still exists but is
* invalid),
*
* But never prohibit specifically any user agent to cache or store content
*
* Setting the headers in err_headers_out ensures that they will be
* sent for all responses.
*/
apr_table_setn(r->err_headers_out,
"Cache-Control", "private, max-age=0, must-revalidate");
}
/* This function reads the post data for a request.
*
* The data is stored in a buffer allocated from the request pool.
* After successful operation *data contains a pointer to the data and
* *length contains the length of the data.
* The data will always be null-terminated.
*
* Parameters:
* request_rec *r The request we read the form data from.
* char **data Pointer to where we will store the pointer
* to the data we read.
* apr_size_t *length Pointer to where we will store the length
* of the data we read. Pass NULL if you don't
* need to know the length of the data.
*
* Returns:
* OK if we successfully read the POST data.
* An error if we fail to read the data.
*/
int am_read_post_data(request_rec *r, char **data, apr_size_t *length)
{
apr_size_t bytes_read;
apr_size_t bytes_left;
apr_size_t len;
long read_length;
int rc;
/* Prepare to receive data from the client. We request that apache
* dechunks data if it is chunked.
*/
rc = ap_setup_client_block(r, REQUEST_CHUNKED_DECHUNK);
if (rc != OK) {
return rc;
}
/* This function will send a 100 Continue response if the client is
* waiting for that. If the client isn't going to send data, then this
* function will return 0.
*/
if (!ap_should_client_block(r)) {
len = 0;
} else {
len = r->remaining;
}
if (len >= 1024*1024) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Too large POST data payload (%lu bytes).",
(unsigned long)len);
return HTTP_BAD_REQUEST;
}
if (length != NULL) {
*length = len;
}
*data = (char *)apr_palloc(r->pool, len + 1);
if (*data == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Failed to allocate memory for %lu bytes of POST data.",
(unsigned long)len);
return HTTP_INTERNAL_SERVER_ERROR;
}
/* Make sure that the data is null-terminated. */
(*data)[len] = '\0';
bytes_read = 0;
bytes_left = len;
while (bytes_left > 0) {
/* Read data from the client. Returns 0 on EOF and -1 on
* error, the number of bytes otherwise.
*/
read_length = ap_get_client_block(r, &(*data)[bytes_read],
bytes_left);
if (read_length == 0) {
/* got the EOF */
(*data)[bytes_read] = '\0';
if (length != NULL) {
*length = bytes_read;
}
break;
}
else if (read_length < 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Failed to read POST data from client.");
return HTTP_INTERNAL_SERVER_ERROR;
}
bytes_read += read_length;
bytes_left -= read_length;
}
am_diag_printf(r, "POST data: %s\n", *data);
return OK;
}
/* extract_query_parameter is a function which extracts the value of
* a given parameter in a query string. The query string can be the
* query_string parameter of a GET request, or it can be the data
* passed to the web server in a POST request.
*
* Parameters:
* apr_pool_t *pool The memory pool which the memory for
* the value will be allocated from.
* const char *query_string Either the query_string from a GET
* request, or the data from a POST
* request.
* const char *name The name of the parameter to extract.
* Note that the search for this name is
* case sensitive.
*
* Returns:
* The value of the parameter or NULL if we don't find the parameter.
*/
char *am_extract_query_parameter(apr_pool_t *pool,
const char *query_string,
const char *name)
{
const char *ip;
const char *value_end;
apr_size_t namelen;
if (query_string == NULL) {
return NULL;
}
ip = query_string;
namelen = strlen(name);
/* Find parameter. Searches for /[^&]<name>[&=$]/.
* Moves ip to the first character after the name (either '&', '='
* or '\0').
*/
for (;;) {
/* First we find the name of the parameter. */
ip = strstr(ip, name);
if (ip == NULL) {
/* Parameter not found. */
return NULL;
}
/* Then we check what is before the parameter name. */
if (ip != query_string && ip[-1] != '&') {
/* Name not preceded by [^&]. */
ip++;
continue;
}
/* And last we check what follows the parameter name. */
if (ip[namelen] != '=' && ip[namelen] != '&'
&& ip[namelen] != '\0') {
/* Name not followed by [&=$]. */
ip++;
continue;
}
/* We have found the pattern. */
ip += namelen;
break;
}
/* Now ip points to the first character after the name. If this
* character is '&' or '\0', then this field doesn't have a value.
* If this character is '=', then this field has a value.
*/
if (ip[0] == '=') {
ip += 1;
}
/* The value is from ip to '&' or to the end of the string, whichever
* comes first. */
value_end = strchr(ip, '&');
if (value_end != NULL) {
/* '&' comes first. */
return apr_pstrndup(pool, ip, value_end - ip);
} else {
/* Value continues until the end of the string. */
return apr_pstrdup(pool, ip);
}
}
/* Convert a hexadecimal digit to an integer.
*
* Parameters:
* char c The digit we should convert.
*
* Returns:
* The digit as an integer, or -1 if it isn't a hex digit.
*/
static int am_unhex_digit(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return c - 'a' + 0xa;
} else if (c >= 'A' && c <= 'F') {
return c - 'A' + 0xa;
} else {
return -1;
}
}
/* This function urldecodes a string in-place.
*
* Parameters:
* char *data The string to urldecode.
*
* Returns:
* OK if successful or HTTP_BAD_REQUEST if any escape sequence decodes to a
* null-byte ('\0'), or if an invalid escape sequence is found.
*/
int am_urldecode(char *data)
{
char *ip;
char *op;
int c1, c2;
if (data == NULL) {
return HTTP_BAD_REQUEST;
}
ip = data;
op = data;
while (*ip) {
switch (*ip) {
case '+':
*op = ' ';
ip++;
op++;
break;
case '%':
/* Decode the hex digits. Note that we need to check the
* result of the first conversion before attempting the
* second conversion -- otherwise we may read past the end
* of the string.
*/
c1 = am_unhex_digit(ip[1]);
if (c1 < 0) {
return HTTP_BAD_REQUEST;
}
c2 = am_unhex_digit(ip[2]);
if (c2 < 0) {
return HTTP_BAD_REQUEST;
}
*op = (c1 << 4) | c2;
if (*op == '\0') {
/* null-byte. */
return HTTP_BAD_REQUEST;
}
ip += 3;
op++;
break;
default:
*op = *ip;
ip++;
op++;
}
}
*op = '\0';
return OK;
}
/* This function urlencodes a string. It will escape all characters
* except a-z, A-Z, 0-9, '_' and '.'.
*
* Parameters:
* apr_pool_t *pool The pool we should allocate memory from.
* const char *str The string we should urlencode.
*
* Returns:
* The urlencoded string, or NULL if str == NULL.
*/
char *am_urlencode(apr_pool_t *pool, const char *str)
{
const char *ip;
apr_size_t length;
char *ret;
char *op;
int hi, low;
/* Return NULL if str is NULL. */
if(str == NULL) {
return NULL;
}
/* Find the length of the output string. */
length = 0;
for(ip = str; *ip; ip++) {
if(*ip >= 'a' && *ip <= 'z') {
length++;
} else if(*ip >= 'A' && *ip <= 'Z') {
length++;
} else if(*ip >= '0' && *ip <= '9') {
length++;
} else if(*ip == '_' || *ip == '.') {
length++;
} else {
length += 3;
}
}
/* Add space for null-terminator. */
length++;
/* Allocate memory for string. */
ret = (char *)apr_palloc(pool, length);
/* Encode string. */
for(ip = str, op = ret; *ip; ip++, op++) {
if(*ip >= 'a' && *ip <= 'z') {
*op = *ip;
} else if(*ip >= 'A' && *ip <= 'Z') {
*op = *ip;
} else if(*ip >= '0' && *ip <= '9') {
*op = *ip;
} else if(*ip == '_' || *ip == '.') {
*op = *ip;
} else {
*op = '%';
op++;
hi = (*ip & 0xf0) >> 4;
if(hi < 0xa) {
*op = '0' + hi;
} else {
*op = 'A' + hi - 0xa;
}
op++;
low = *ip & 0x0f;
if(low < 0xa) {
*op = '0' + low;
} else {
*op = 'A' + low - 0xa;
}
}
}
/* Make output string null-terminated. */
*op = '\0';
return ret;
}
/*
* Check that a URL is safe for redirect.
*
* Parameters:
* request_rec *r The request we are processing.
* const char *url The URL we should check.
*
* Returns:
* OK on success, HTTP_BAD_REQUEST otherwise.
*/
int am_check_url(request_rec *r, const char *url)
{
const char *i;
for (i = url; *i; i++) {
if (*i >= 0 && *i < ' ') {
/* Deny all control-characters. */
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, HTTP_BAD_REQUEST, r,
"Control character detected in URL.");
return HTTP_BAD_REQUEST;
}
if (*i == '\\') {
/* Reject backslash character, as it can be used to bypass
* redirect URL validation. */
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, HTTP_BAD_REQUEST, r,
"Backslash character detected in URL.");
return HTTP_BAD_REQUEST;
}
}
return OK;
}
/* This function generates a given number of (pseudo)random bytes.
* The current implementation uses OpenSSL's RAND_*-functions.
*
* Parameters:
* request_rec *r The request we are generating random bytes for.
* The request is used for configuration and
* error/warning reporting.
* void *dest The address if the buffer we should fill with data.
* apr_size_t count The number of random bytes to create.
*
* Returns:
* OK on success, or HTTP_INTERNAL_SERVER on failure.
*/
int am_generate_random_bytes(request_rec *r, void *dest, apr_size_t count)
{
int rc;
rc = RAND_bytes((unsigned char *)dest, (int)count);
if(rc != 1) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error generating random data: %lu",
ERR_get_error());
return HTTP_INTERNAL_SERVER_ERROR;
}
return OK;
}
/* This function generates an id which is AM_ID_LENGTH characters long.
* The id will consist of hexadecimal characters.
*
* Parameters:
* request_rec *r The request we associate allocated memory with.
*
* Returns:
* The session id, made up of AM_ID_LENGTH hexadecimal characters,
* terminated by a null-byte.
*/
char *am_generate_id(request_rec *r)
{
int rc;
char *ret;
int rand_data_len;
unsigned char *rand_data;
int i;
unsigned char b;
int hi, low;
ret = (char *)apr_palloc(r->pool, AM_ID_LENGTH + 1);
/* We need to round the length of the random data _up_, in case the
* length of the session id isn't even.
*/
rand_data_len = (AM_ID_LENGTH + 1) / 2;
/* Fill the last rand_data_len bytes of the string with
* random bytes. This allows us to overwrite from the beginning of
* the string.
*/
rand_data = (unsigned char *)&ret[AM_ID_LENGTH - rand_data_len];
/* Generate random numbers. */
rc = am_generate_random_bytes(r, rand_data, rand_data_len);
if(rc != OK) {
return NULL;
}
/* Convert the random bytes to hexadecimal. Note that we will write
* AM_ID_LENGTH+1 characters if we have a non-even length of the
* session id. This is OK - we will simply overwrite the last character
* with the null-terminator afterwards.
*/
for(i = 0; i < AM_ID_LENGTH; i += 2) {
b = rand_data[i / 2];
hi = (b >> 4) & 0xf;
low = b & 0xf;
if(hi >= 0xa) {
ret[i] = 'a' + hi - 0xa;
} else {
ret[i] = '0' + hi;
}
if(low >= 0xa) {
ret[i+1] = 'a' + low - 0xa;
} else {
ret[i+1] = '0' + low;
}
}
/* Add null-terminator- */
ret[AM_ID_LENGTH] = '\0';
return ret;
}
/* This returns the directroy part of a path, a la dirname(3)
*
* Parameters:
* apr_pool_t p Pool to allocate memory from
* const char *path Path to extract directory from
*
* Returns:
* The directory part of path
*/
const char *am_filepath_dirname(apr_pool_t *p, const char *path)
{
char *cp;
/*
* Try Unix and then Windows style. Borrowed from
* apr_match_glob(), it seems it cannot be made more
* portable.
*/
if (((cp = strrchr(path, (int)'/')) == NULL) &&
((cp = strrchr(path, (int)'\\')) == NULL))
return ".";
return apr_pstrndup(p, path, cp - path);
}
/*
* Allocate and initialize a am_file_data_t
*
* Parameters:
* apr_pool_t *pool Allocation pool.
* const char *path If non-NULL initialize file_data->path to copy of path
*
* Returns:
* Newly allocated & initialized file_data_t
*/
am_file_data_t *am_file_data_new(apr_pool_t *pool, const char *path)
{
am_file_data_t *file_data = NULL;
if ((file_data = apr_pcalloc(pool, sizeof(am_file_data_t))) == NULL) {
return NULL;
}
file_data->pool = pool;
file_data->rv = APR_EINIT;
if (path) {
file_data->path = apr_pstrdup(file_data->pool, path);
}
return file_data;
}
/*
* Allocate a new am_file_data_t and copy
*
* Parameters:
* apr_pool_t *pool Allocation pool.
* am_file_data_t *src_file_data The src being copied.
*
* Returns:
* Newly allocated & initialized from src_file_data
*/
am_file_data_t *am_file_data_copy(apr_pool_t *pool,
am_file_data_t *src_file_data)
{
am_file_data_t *dst_file_data = NULL;
if ((dst_file_data = am_file_data_new(pool, src_file_data->path)) == NULL) {
return NULL;
}
dst_file_data->path = apr_pstrdup(pool, src_file_data->path);
dst_file_data->stat_time = src_file_data->stat_time;
dst_file_data->finfo = src_file_data->finfo;
dst_file_data->contents = apr_pstrdup(pool, src_file_data->contents);
dst_file_data->read_time = src_file_data->read_time;
dst_file_data->rv = src_file_data->rv;
dst_file_data->strerror = apr_pstrdup(pool, src_file_data->strerror);
dst_file_data->generated = src_file_data->generated;
return dst_file_data;
}
/*
* Peform a stat on a file to get it's properties
*
* A stat is performed on the file. If there was an error the
* result value is left in file_data->rv and an error description
* string is formatted and left in file_data->strerror and function
* returns the rv value. If the stat was successful the stat
* information is left in file_data->finfo and APR_SUCCESS
* set set as file_data->rv and returned as the function result.
*
* The file_data->stat_time indicates if and when the stat was
* performed, a zero time value indicates the operation has not yet
* been performed.
*
* Parameters:
* am_file_data_t *file_data Struct containing file information
*
* Returns:
* APR status code, same value as file_data->rv
*/
apr_status_t am_file_stat(am_file_data_t *file_data)
{
char buffer[512];
if (file_data == NULL) {
return APR_EINVAL;
}
file_data->strerror = NULL;
file_data->stat_time = apr_time_now();
file_data->rv = apr_stat(&file_data->finfo, file_data->path,
APR_FINFO_SIZE, file_data->pool);
if (file_data->rv != APR_SUCCESS) {
file_data->strerror =
apr_psprintf(file_data->pool,
"apr_stat: Error opening \"%s\" [%d] \"%s\"",
file_data->path, file_data->rv,
apr_strerror(file_data->rv, buffer, sizeof(buffer)));
}
return file_data->rv;
}
/*
* Read file into dynamically allocated buffer
*
* First a stat is performed on the file. If there was an error the
* result value is left in file_data->rv and an error description
* string is formatted and left in file_data->strerror and function
* returns the rv value. If the stat was successful the stat
* information is left in file_data->finfo.
*
* A buffer is dynamically allocated and the contents of the file is
* read into file_data->contents. If there was an error the result
* value is left in file_data->rv and an error description string is
* formatted and left in file_data->strerror and the function returns
* the rv value.
*
* The file_data->stat_time and file_data->read_time indicate if and
* when those operations were performed, a zero time value indicates
* the operation has not yet been performed.
*
* Parameters:
* am_file_data_t *file_data Struct containing file information
*
* Returns:
* APR status code, same value as file_data->rv
*/
apr_status_t am_file_read(am_file_data_t *file_data)
{
char buffer[512];
apr_file_t *fd;
apr_size_t nbytes;
if (file_data == NULL) {
return APR_EINVAL;
}
file_data->rv = APR_SUCCESS;
file_data->strerror = NULL;
am_file_stat(file_data);
if (file_data->rv != APR_SUCCESS) {
return file_data->rv;
}
if ((file_data->rv = apr_file_open(&fd, file_data->path,
APR_READ, 0, file_data->pool)) != 0) {
file_data->strerror =
apr_psprintf(file_data->pool,
"apr_file_open: Error opening \"%s\" [%d] \"%s\"",
file_data->path, file_data->rv,
apr_strerror(file_data->rv, buffer, sizeof(buffer)));
return file_data->rv;
}
file_data->read_time = apr_time_now();
nbytes = file_data->finfo.size;
file_data->contents = (char *)apr_palloc(file_data->pool, nbytes + 1);
file_data->rv = apr_file_read_full(fd, file_data->contents, nbytes, NULL);
if (file_data->rv != 0) {
file_data->strerror =
apr_psprintf(file_data->pool,
"apr_file_read_full: Error reading \"%s\" [%d] \"%s\"",
file_data->path, file_data->rv,
apr_strerror(file_data->rv, buffer, sizeof(buffer)));
(void)apr_file_close(fd);
return file_data->rv;
}
file_data->contents[nbytes] = '\0';
(void)apr_file_close(fd);
return file_data->rv;
}
/*
* Purge outdated saved POST requests.
*
* Parameters:
* request_rec *r The current request
*
* Returns:
* OK on success, or HTTP_INTERNAL_SERVER on failure.
*/
int am_postdir_cleanup(request_rec *r)
{
am_mod_cfg_rec *mod_cfg;
apr_dir_t *postdir;
apr_status_t rv;
char error_buffer[64];
apr_finfo_t afi;
char *fname;
int count;
apr_time_t expire_before;
mod_cfg = am_get_mod_cfg(r->server);
/* The oldes file we should keep. Delete files that are older. */
expire_before = apr_time_now() - mod_cfg->post_ttl * APR_USEC_PER_SEC;
/*
* Open our POST directory or create it.
*/
rv = apr_dir_open(&postdir, mod_cfg->post_dir, r->pool);
if (rv != 0) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Unable to open MellonPostDirectory \"%s\": %s",
mod_cfg->post_dir,
apr_strerror(rv, error_buffer, sizeof(error_buffer)));
return HTTP_INTERNAL_SERVER_ERROR;
}
/*
* Purge outdated items
*/
count = 0;
do {
rv = apr_dir_read(&afi, APR_FINFO_NAME|APR_FINFO_CTIME, postdir);
if (rv != OK)
break;
/* Skip dot_files */
if (afi.name[0] == '.')
continue;
if (afi.ctime < expire_before) {
fname = apr_psprintf(r->pool, "%s/%s", mod_cfg->post_dir, afi.name);
(void)apr_file_remove(fname , r->pool);
} else {
count++;
}
} while (1 /* CONSTCOND */);
(void)apr_dir_close(postdir);
if (count >= mod_cfg->post_count) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Too many saved POST sessions. "
"Increase MellonPostCount directive.");
return HTTP_INTERNAL_SERVER_ERROR;
}
return OK;
}
/*
* HTML-encode a string
*
* Parameters:
* request_rec *r The current request
* const char *str The string to encode
*
* Returns:
* The encoded string
*/
char *am_htmlencode(request_rec *r, const char *str)
{
const char *cp;
char *output;
apr_size_t outputlen;
int i;
outputlen = 0;
for (cp = str; *cp; cp++) {
switch (*cp) {
case '&':
outputlen += 5;
break;
case '"':
outputlen += 6;
break;
default:
outputlen += 1;
break;
}
}
i = 0;
output = apr_palloc(r->pool, outputlen + 1);
for (cp = str; *cp; cp++) {
switch (*cp) {
case '&':
(void)strcpy(&output[i], "&");
i += 5;
break;
case '"':
(void)strcpy(&output[i], """);
i += 6;
break;
default:
output[i] = *cp;
i += 1;
break;
}
}
output[i] = '\0';
return output;
}
/* This function produces the endpoint URL
*
* Parameters:
* request_rec *r The request we received.
*
* Returns:
* the endpoint URL
*/
char *am_get_endpoint_url(request_rec *r)
{
am_dir_cfg_rec *cfg = am_get_dir_cfg(r);
return ap_construct_url(r->pool, cfg->endpoint_path, r);
}
/*
* This function saves a POST request for later replay and updates
* the return URL.
*
* Parameters:
* request_rec *r The current request.
* const char **relay_state The returl URL
*
* Returns:
* OK on success, HTTP_INTERNAL_SERVER_ERROR otherwise
*/
int am_save_post(request_rec *r, const char **relay_state)
{
am_mod_cfg_rec *mod_cfg;
const char *content_type;
const char *charset;
const char *psf_id;
char *psf_name;
char *post_data;
apr_size_t post_data_len;
apr_size_t written;
apr_file_t *psf;
mod_cfg = am_get_mod_cfg(r->server);
if (mod_cfg->post_dir == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"MellonPostReplay enabled but MellonPostDirectory not set "
"-- cannot save post data");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (am_postdir_cleanup(r) != OK)
return HTTP_INTERNAL_SERVER_ERROR;
/* Check Content-Type */
content_type = apr_table_get(r->headers_in, "Content-Type");
if (content_type == NULL) {
content_type = "urlencoded";
charset = NULL;
} else {
if (am_has_header(r, content_type,
"application/x-www-form-urlencoded")) {
content_type = "urlencoded";
} else if (am_has_header(r, content_type,
"multipart/form-data")) {
content_type = "multipart";
} else {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Unknown POST Content-Type \"%s\"", content_type);
return HTTP_INTERNAL_SERVER_ERROR;
}
charset = am_get_header_attr(r, content_type, NULL, "charset");
}
if ((psf_id = am_generate_id(r)) == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r, "cannot generate id");
return HTTP_INTERNAL_SERVER_ERROR;
}
psf_name = apr_psprintf(r->pool, "%s/%s", mod_cfg->post_dir, psf_id);
if (apr_file_open(&psf, psf_name,
APR_WRITE|APR_CREATE|APR_BINARY,
APR_FPROT_UREAD|APR_FPROT_UWRITE,
r->pool) != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"cannot create POST session file");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (am_read_post_data(r, &post_data, &post_data_len) != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r, "cannot read POST data");
(void)apr_file_close(psf);
return HTTP_INTERNAL_SERVER_ERROR;
}
if (post_data_len > mod_cfg->post_size) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"POST data size %" APR_SIZE_T_FMT
" exceeds maximum %" APR_SIZE_T_FMT ". "
"Increase MellonPostSize directive.",
post_data_len, mod_cfg->post_size);
(void)apr_file_close(psf);
return HTTP_INTERNAL_SERVER_ERROR;
}
written = post_data_len;
if ((apr_file_write(psf, post_data, &written) != OK) ||
(written != post_data_len)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"cannot write to POST session file");
(void)apr_file_close(psf);
return HTTP_INTERNAL_SERVER_ERROR;
}
if (apr_file_close(psf) != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"cannot close POST session file");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (charset != NULL)
charset = apr_psprintf(r->pool, "&charset=%s",
am_urlencode(r->pool, charset));
else
charset = "";
*relay_state = apr_psprintf(r->pool,
"%srepost?id=%s&ReturnTo=%s&enctype=%s%s",
am_get_endpoint_url(r), psf_id,
am_urlencode(r->pool, *relay_state),
content_type, charset);
return OK;
}
/*
* This function replaces CRLF by LF in a string
*
* Parameters:
* request_rec *r The current request
* const char *str The string
*
* Returns:
* Output string
*/
const char *am_strip_cr(request_rec *r, const char *str)
{
char *output;
const char *cp;
apr_size_t i;
output = apr_palloc(r->pool, strlen(str) + 1);
i = 0;
for (cp = str; *cp; cp++) {
if ((*cp == '\r') && (*(cp + 1) == '\n'))
continue;
output[i++] = *cp;
}
output[i++] = '\0';
return (const char *)output;
}
/*
* This function replaces LF by CRLF in a string
*
* Parameters:
* request_rec *r The current request
* const char *str The string
*
* Returns:
* Output string
*/
const char *am_add_cr(request_rec *r, const char *str)
{
char *output;
const char *cp;
apr_size_t xlen;
apr_size_t i;
xlen = 0;
for (cp = str; *cp; cp++)
if (*cp == '\n')
xlen++;
output = apr_palloc(r->pool, strlen(str) + xlen + 1);
i = 0;
for (cp = str; *cp; cp++) {
if (*cp == '\n')
output[i++] = '\r';
output[i++] = *cp;
}
output[i++] = '\0';
return (const char *)output;
}
/*
* This function tokenize a string, just like strtok_r, except that
* the separator is a string instead of a character set.
*
* Parameters:
* const char *str The string to tokenize
* const char *sep The separator string
* char **last Pointer to state (char *)
*
* Returns:
* OK on success, HTTP_INTERNAL_SERVER_ERROR otherwise
*/
const char *am_xstrtok(request_rec *r, const char *str,
const char *sep, char **last)
{
char *s;
char *np;
/* Resume */
if (str != NULL)
s = apr_pstrdup(r->pool, str);
else
s = *last;
/* End of string */
if (*s == '\0')
return NULL;
/* Next sep exists? */
if ((np = strstr(s, sep)) == NULL) {
*last = s + strlen(s);
} else {
*last = np + strlen(sep);
memset(np, 0, strlen(sep));
}
return s;
}
/* This function strips leading spaces and tabs from a string
*
* Parameters:
* const char **s Pointer to the string
*
*/
void am_strip_blank(const char **s)
{
while ((**s == ' ') || (**s == '\t'))
(*s)++;
return;
}
/* This function extracts a MIME header from a MIME section
*
* Parameters:
* request_rec *r The request
* const char *m The MIME section
* const char *h The header to extract (case insensitive)
*
* Returns:
* The header value, or NULL on failure.
*/
const char *am_get_mime_header(request_rec *r, const char *m, const char *h)
{
const char *line;
char *l1;
const char *value;
char *l2;
for (line = am_xstrtok(r, m, "\n", &l1); line && *line;
line = am_xstrtok(r, NULL, "\n", &l1)) {
am_strip_blank(&line);
if (((value = am_xstrtok(r, line, ":", &l2)) != NULL) &&
(strcasecmp(value, h) == 0)) {
if ((value = am_xstrtok(r, NULL, ":", &l2)) != NULL)
am_strip_blank(&value);
return value;
}
}
return NULL;
}
/* This function extracts an attribute from a header
*
* Parameters:
* request_rec *r The request
* const char *h The header
* const char *v Optional header value to check (case insensitive)
* const char *a Optional attribute to extract (case insensitive)
*
* Returns:
* if i was provided, item value, or NULL on failure.
* if i is NULL, the whole header, or NULL on failure. This is
* useful for testing v.
*/
const char *am_get_header_attr(request_rec *r, const char *h,
const char *v, const char *a)
{
const char *value;
const char *attr;
char *l1;
const char *attr_value = NULL;
/* Looking for
* header-value; item_name="item_value"\n
*/
if ((value = am_xstrtok(r, h, ";", &l1)) == NULL)
return NULL;
am_strip_blank(&value);
/* If a header value was provided, check it */
if ((v != NULL) && (strcasecmp(value, v) != 0))
return NULL;
/* If no attribute name is provided, return everything */
if (a == NULL)
return h;
while ((attr = am_xstrtok(r, NULL, ";", &l1)) != NULL) {
const char *attr_name = NULL;
char *l2;
am_strip_blank(&attr);
attr_name = am_xstrtok(r, attr, "=", &l2);
if ((attr_name != NULL) && (strcasecmp(attr_name, a) == 0)) {
if ((attr_value = am_xstrtok(r, NULL, "=", &l2)) != NULL)
am_strip_blank(&attr_value);
break;
}
}
/* Remove leading and trailing quotes */
if (attr_value != NULL) {
apr_size_t len;
len = strlen(attr_value);
if ((len > 1) && (attr_value[len - 1] == '\"'))
attr_value = apr_pstrndup(r->pool, attr_value, len - 1);
if (attr_value[0] == '\"')
attr_value++;
}
return attr_value;
}
/* This function checks for a header name/value existence
*
* Parameters:
* request_rec *r The request
* const char *h The header (case insensitive)
* const char *v Optional header value to check (case insensitive)
*
* Returns:
* 0 if header does not exists or does not has the value, 1 otherwise
*/
int am_has_header(request_rec *r, const char *h, const char *v)
{
return (am_get_header_attr(r, h, v, NULL) != NULL);
}
/* This function extracts the body from a MIME section
*
* Parameters:
* request_rec *r The request
* const char *mime The MIME section
*
* Returns:
* The MIME section body, or NULL on failure.
*/
const char *am_get_mime_body(request_rec *r, const char *mime)
{
const char lflf[] = "\n\n";
const char *body;
apr_size_t body_len;
if ((body = strstr(mime, lflf)) == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r, "No MIME body");
return NULL;
}
body += strlen(lflf);
/* Strip tralling \n */
if ((body_len = strlen(body)) >= 1) {
if (body[body_len - 1] == '\n')
body = apr_pstrmemdup(r->pool, body, body_len - 1);
}
/* Turn back LF into CRLF */
return am_add_cr(r, body);
}
/* This function returns the URL for a given provider service (type + method)
*
* Parameters:
* request_rec *r The request
* LassoProfile *profile Login profile
* char *endpoint_name Service and method as specified in metadata
* e.g.: "SingleSignOnService HTTP-Redirect"
* Returns:
* The endpoint URL that must be freed by caller, or NULL on failure.
*/
char *
am_get_service_url(request_rec *r, LassoProfile *profile, char *service_name)
{
LassoProvider *provider;
gchar *url;
provider = lasso_server_get_provider(profile->server,
profile->remote_providerID);
if (LASSO_IS_PROVIDER(provider) == FALSE) {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"Cannot find provider service %s, no provider.",
service_name);
return NULL;
}
url = lasso_provider_get_metadata_one(provider, service_name);
if (url == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"Cannot find provider service %s from metadata.",
service_name);
return NULL;
}
return url;
}
/*------------------------ Begin Token Parsing Code --------------------------*/
typedef enum {
TOKEN_WHITESPACE = 1,
TOKEN_SEMICOLON,
TOKEN_COMMA,
TOKEN_EQUAL,
TOKEN_IDENTIFIER,
TOKEN_DBL_QUOTE_STRING,
} TokenType;
typedef struct {
TokenType type; /* The type of this token */
char *str; /* The string value of the token */
apr_size_t len; /* The number of characters in the token */
apr_size_t offset; /* The offset from the beginning of
the string to the start of the token */
} Token;
#ifdef DEBUG
/* Return string representation of TokenType enumeration
*
* Parameters:
* token_type A TokenType enumeration
* Returns: String name of token_type
*/
static const char *
token_type_str(TokenType token_type)
{
switch(token_type) {
case TOKEN_WHITESPACE: return "WHITESPACE";
case TOKEN_SEMICOLON: return "SEMICOLON";
case TOKEN_COMMA: return "COMMA";
case TOKEN_EQUAL: return "EQUAL";
case TOKEN_IDENTIFIER: return "IDENTIFIER";
case TOKEN_DBL_QUOTE_STRING: return "DBL_QUOTE_STRING";
default: return "unknown";
}
}
static void dump_tokens(request_rec *r, apr_array_header_t *tokens)
{
apr_size_t i;
for (i = 0; i < tokens->nelts; i++) {
Token token = APR_ARRAY_IDX(tokens, i, Token);
AM_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r,
"token[%2zd] %s \"%s\" offset=%lu len=%lu ", i,
token_type_str(token.type), token.str,
token.offset, token.len);
}
}
#endif
/* Initialize token and add to list of tokens
*
* Utility to assist tokenize function.
*
* A token object is created and added to the end of the list of
* tokens. It is initialized with the type of token, a copy of the
* string, it's length, and it's offset from the beginning of the
* string where it was found.
*
* Tokens with special processing needs are also handled here.
*
* A double quoted string will:
*
* * Have it's delimiting quotes removed.
* * Will unescape escaped characters.
*
* Parameters:
* tokens Array of Token objects.
* type The type of the token (e.g. TokenType).
* str The string the token was parsed from, used to compute
* the position of the token in the original string.
* start The first character in the token.
* end the last character in the token.
*/
static inline void
push_token(apr_array_header_t *tokens, TokenType type, const char *str,
const char *start, const char *end)
{
apr_size_t offset = start - str;
Token *token = apr_array_push(tokens);
if (type == TOKEN_DBL_QUOTE_STRING) {
/* do not include quotes in token value */
start++; end--;
}
token->type = type;
token->len = end - start;
token->offset = offset;
token->str = apr_pstrmemdup(tokens->pool, start, token->len);
if (type == TOKEN_DBL_QUOTE_STRING) {
/*
* The original HTTP 1.1 spec was ambiguous with respect to
* backslash quoting inside double quoted strings. This has since
* been resolved in this errata:
*
* http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p1-messaging-16.html#rfc.section.3.2.3
*
* Which states:
*
* Recipients that process the value of the quoted-string MUST
* handle a quoted-pair as if it were replaced by the octet
* following the backslash.
*
* Senders SHOULD NOT escape octets in quoted-strings that do not
* require escaping (i.e., other than DQUOTE and the backslash
* octet).
*/
char *p, *t;
for (p = token->str; *p; p++) {
if (p[0] == '\\' && p[1]) {
/*
* Found backslash with following character.
* Move rest of string down 1 character.
*/
for (t = p; *t; t++) {
t[0] = t[1];
}
token->len--;
}
}
}
}
/* Break a string into a series of tokens
*
* Given a string return an array of tokens. If the string cannot be
* successfully parsed an error string is returned at the location
* specified by the error parameter, if error is NULL then the parsing
* was successful. If an error occured the returned array of tokens
* will include all tokens parsed up until where the unrecognized
* input occurred. The input str is never modified.
*
* Parameters:
* pool memory allocation pool
* str input string to be parsed.
* ignore_whitespace if True whitespace tokens are not returned
* error location where error string is returned
* if NULL no error occurred
* Returns: array of Token objects
*/
static apr_array_header_t *
tokenize(apr_pool_t *pool, const char *str, bool ignore_whitespace,
char **error)
{
apr_array_header_t *tokens = apr_array_make(pool, 10, sizeof(Token));
const char *p, *start;
*error = NULL;
p = start = str;
while(*p) {
if (apr_isspace(*p)) { /* whitespace */
p++;
while(*p && apr_isspace(*p)) p++;
if (!ignore_whitespace) {
push_token(tokens, TOKEN_WHITESPACE, str, start, p);
}
start = p;
}
else if (apr_isalpha(*p)) { /* identifier: must begin with
alpha then any alphanumeric or
underscore */
p++;
while(*p && (apr_isalnum(*p) || *p == '_')) p++;
push_token(tokens, TOKEN_IDENTIFIER, str, start, p);
start = p;
}
else if (*p == '"') { /* double quoted string */
p++; /* step over double quote */
while(*p) {
if (*p == '\\') { /* backslash escape */
p++; /* step over backslash */
if (*p) {
p++; /* step over escaped character */
} else {
break; /* backslash at end of string, stop */
}
}
if (*p == '\"') break; /* terminating quote delimiter */
p++; /* keep scanning */
}
if (*p != '\"') {
*error = apr_psprintf(pool,
"unterminated string beginning at "
"position %" APR_SIZE_T_FMT " in \"%s\"",
start-str, str);
break;
}
p++;
push_token(tokens, TOKEN_DBL_QUOTE_STRING, str, start, p);
start = p;
}
else if (*p == '=') { /* equals */
p++;
push_token(tokens, TOKEN_EQUAL, str, start, p);
start = p;
}
else if (*p == ',') { /* comma */
p++;
push_token(tokens, TOKEN_COMMA, str, start, p);
start = p;
}
else if (*p == ';') { /* semicolon */
p++;
push_token(tokens, TOKEN_SEMICOLON, str, start, p);
start = p;
}
else { /* unrecognized token */
*error = apr_psprintf(pool,
"unknown token at "
"position %" APR_SIZE_T_FMT " in string \"%s\"",
p-str, str);
break;
}
}
return tokens;
}
/* Test if the token is what we're looking for
*
* Given an index into the tokens array determine if the token type
* matches. If the value parameter is non-NULL then the token's value
* must also match. If the array index is beyond the last array item
* false is returned.
*
* Parameters:
* tokens Array of Token objects
* index Index used to select the Token object from the Tokens array.
* If the index is beyond the last array item False is returned.
* type The token type which must match
* value If non-NULL then the token string value must be equal to this.
* Returns: True if the token matches, False otherwise.
*/
static bool
is_token(apr_array_header_t *tokens, apr_size_t index, TokenType type, const char *value)
{
if (index >= tokens->nelts) {
return false;
}
Token token = APR_ARRAY_IDX(tokens, index, Token);
if (token.type != type) {
return false;
}
if (value) {
if (!g_str_equal(token.str, value)) {
return false;
}
}
return true;
}
/*------------------------- End Token Parsing Code ---------------------------*/
/* Return message describing position an error when parsing.
*
* When parsing we expect tokens to appear in a certain sequence. We
* report the contents of the unexpected token and it's position in
* the string. However if the parsing error is due to the fact we've
* exhausted all tokens but are still expecting another token then our
* error message indicates we reached the end of the string.
*
* Parameters:
* tokens Array of Token objects.
* index Index in tokens array where bad token was found
*/
static inline const char *
parse_error_msg(apr_array_header_t *tokens, apr_size_t index)
{
if (index >= tokens->nelts) {
return "end of string";
}
return apr_psprintf(tokens->pool, "\"%s\" at position %" APR_SIZE_T_FMT,
APR_ARRAY_IDX(tokens, index, Token).str,
APR_ARRAY_IDX(tokens, index, Token).offset);
}
/* This function checks if an HTTP PAOS header is valid and
* returns any service options which may have been specified.
*
* A PAOS header is composed of a mandatory PAOS version and service
* values. A semicolon separates the version from the service values.
*
* Service values are delimited by semicolons, and options are
* comma-delimited from the service value and each other.
*
* The PAOS version must be in the form ver="xxx" (note the version
* string must be in double quotes).
*
* The ECP service must be specified, it MAY be followed by optional
* comma seperated options, all values must be in double quotes.
*
* ECP Service
* "urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp"
*
* Recognized Options:
*
* Support for channel bindings
* urn:oasis:names:tc:SAML:protocol:ext:channel-binding
*
* Support for Holder-of-Key subject confirmation
* urn:oasis:names:tc:SAML:2.0:cm:holder-of-key
*
* Request for signed SAML request
* urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp:2.0:WantAuthnRequestsSigned
*
* Request to delegate credentials to the service provider
* urn:oasis:names:tc:SAML:2.0:conditions:delegation
*
*
* Example PAOS HTTP header::
*
* PAOS: ver="urn:liberty:paos:2003-08";
* "urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp",
* "urn:oasis:names:tc:SAML:protocol:ext:channel-binding",
* "urn:oasis:names:tc:SAML:2.0:cm:holder-of-key"
*
* Parameters:
* request_rec *r The request
* const char *header The PAOS header value
* ECPServiceOptions *options_return
* Pointer to location to receive options,
* may be NULL. Bitmask of option flags.
*
* Returns:
* true if the PAOS header is valid, false otherwise. If options is non-NULL
* then the set of option flags is returned there.
*
*/
bool am_parse_paos_header(request_rec *r, const char *header,
ECPServiceOptions *options_return)
{
bool result = false;
ECPServiceOptions options = 0;
apr_array_header_t *tokens;
apr_size_t i;
char *error;
AM_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r,
"PAOS header: \"%s\"", header);
tokens = tokenize(r->pool, header, true, &error);
#ifdef DEBUG
dump_tokens(r, tokens);
#endif
if (error) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r, "%s", error);
goto cleanup;
}
/* Header must begin with "ver=xxx" where xxx is paos version */
if (!is_token(tokens, 0, TOKEN_IDENTIFIER, "ver") ||
!is_token(tokens, 1, TOKEN_EQUAL, NULL) ||
!is_token(tokens, 2, TOKEN_DBL_QUOTE_STRING, LASSO_PAOS_HREF)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"invalid PAOS header, "
"expected header to begin with ver=\"%s\", "
"actual header=\"%s\"",
LASSO_PAOS_HREF, header);
goto cleanup;
}
/* Next is the service value, separated from the version by a semicolon */
if (!is_token(tokens, 3, TOKEN_SEMICOLON, NULL)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"invalid PAOS header, "
"expected semicolon after PAOS version "
"but found %s in header=\"%s\"",
parse_error_msg(tokens, 3),
header);
goto cleanup;
}
if (!is_token(tokens, 4, TOKEN_DBL_QUOTE_STRING, LASSO_ECP_HREF)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"invalid PAOS header, "
"expected service token to be \"%s\", "
"but found %s in header=\"%s\"",
LASSO_ECP_HREF,
parse_error_msg(tokens, 4),
header);
goto cleanup;
}
/* After the service value there may be optional flags separated by commas */
if (tokens->nelts == 5) { /* no options */
result = true;
goto cleanup;
}
/* More tokens after the service value, must be options, iterate over them */
for (i = 5; i < tokens->nelts; i++) {
if (!is_token(tokens, i, TOKEN_COMMA, NULL)) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"invalid PAOS header, "
"expected comma after PAOS service "
"but found %s in header=\"%s\"",
parse_error_msg(tokens, i),
header);
goto cleanup;
}
if (++i > tokens->nelts) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"invalid PAOS header, "
"expected option after comma "
"in header=\"%s\"",
header);
goto cleanup;
}
Token token = APR_ARRAY_IDX(tokens, i, Token);
if (token.type != TOKEN_DBL_QUOTE_STRING) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"invalid PAOS header, "
"expected quoted string after comma "
"but found %s in header=\"%s\"",
parse_error_msg(tokens, i),
header);
goto cleanup;
}
/* Have an option string, convert it to a bit flag */
const char *value = token.str;
if (g_str_equal(value, LASSO_SAML_EXT_CHANNEL_BINDING)) {
options |= ECP_SERVICE_OPTION_CHANNEL_BINDING;
} else if (g_str_equal(value, LASSO_SAML2_CONFIRMATION_METHOD_HOLDER_OF_KEY)) {
options |= ECP_SERVICE_OPTION_HOLDER_OF_KEY;
} else if (g_str_equal(value, LASSO_SAML2_ECP_PROFILE_WANT_AUTHN_SIGNED)) {
options |= ECP_SERVICE_OPTION_WANT_AUTHN_SIGNED;
} else if (g_str_equal(value, LASSO_SAML2_CONDITIONS_DELEGATION)) {
options |= ECP_SERVICE_OPTION_DELEGATION;
} else {
AM_LOG_RERROR(APLOG_MARK, APLOG_WARNING, 0, r,
"Unknown PAOS service option = \"%s\"",
value);
goto cleanup;
}
}
result = true;
cleanup:
if (options_return) {
*options_return = options;
}
return result;
}
/* This function checks if Accept header has a media type
*
* Given an Accept header value like this:
*
* "text/html,application/xhtml+xml,application/xml;q=0.9"
*
* Parse the string and find name of each media type, ignore any parameters
* bound to the name. Test to see if the name matches the input media_type.
*
* Parameters:
* request_rec *r The request
* const char *header The header value
* const char *media_type media type header value to check (case insensitive)
*
* Returns:
* true if media type is in header, false otherwise
*/
bool am_header_has_media_type(request_rec *r, const char *header, const char *media_type)
{
bool result = false;
char **comma_tokens = NULL;
char **media_ranges = NULL;
char *media_range = NULL;
if (header == NULL) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"invalid Accept header, NULL");
goto cleanup;
}
/*
* Split the header into a list of media_range tokens separated by
* a comma and iterate over the list.
*/
comma_tokens = g_strsplit(header, ",", 0);
for (media_ranges = comma_tokens, media_range = *media_ranges;
media_range;
media_range = *(++media_ranges)) {
char **semicolon_tokens = NULL;
char *name = NULL;
/*
* Split the media_range into a name and parameters, each
* separated by a semicolon. The first element in the list is
* the media_type name, subsequent params are optional and ignored.
*/
media_range = g_strstrip(media_range);
semicolon_tokens = g_strsplit(media_range, ";", 0);
/*
* Does the media_type match our required media_type?
* If so clean up and return success.
*/
name = g_strstrip(semicolon_tokens[0]);
if (name && g_str_equal(name, media_type)) {
result = true;
g_strfreev(semicolon_tokens);
goto cleanup;
}
g_strfreev(semicolon_tokens);
}
cleanup:
g_strfreev(comma_tokens);
return result;
}
/*
* Lookup a config string in a specific language. If lang is NULL and
* the config string had been defined without a language qualifier
* return the unqualified value. If not found NULL is returned.
*/
const char *am_get_config_langstring(apr_hash_t *h, const char *lang)
{
char *string;
if (lang == NULL) {
lang = "";
}
string = (char *)apr_hash_get(h, lang, APR_HASH_KEY_STRING);
return string;
}
/*
* Get the value of boolean query parameter.
*
* Parameters:
* request_rec *r The request
* const char *name The name of the query parameter
* int *return_value The address of the variable to receive
* the boolean value
* int default_value The value returned if parameter is absent or
* in event of an error
*
* Returns:
* OK on success, HTTP error otherwise
*
* Looks for the named parameter in the query parameters, if found
* parses the value which must be one of:
*
* * true
* * false
*
* If value cannot be parsed HTTP_BAD_REQUEST is returned.
*
* If not found, or if there is an error, the returned value is set to
* default_value.
*/
int am_get_boolean_query_parameter(request_rec *r, const char *name,
int *return_value, int default_value)
{
char *value_str;
int ret = OK;
*return_value = default_value;
value_str = am_extract_query_parameter(r->pool, r->args, name);
if (value_str != NULL) {
ret = am_urldecode(value_str);
if (ret != OK) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Error urldecoding \"%s\" boolean query parameter, "
"value=\"%s\"", name, value_str);
return ret;
}
if(!strcmp(value_str, "true")) {
*return_value = TRUE;
} else if(!strcmp(value_str, "false")) {
*return_value = FALSE;
} else {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"Invalid value for \"%s\" boolean query parameter, "
"value=\"%s\"", name, value_str);
ret = HTTP_BAD_REQUEST;
}
}
return ret;
}
/*
* Get the URL of the AssertionConsumerServer having specific protocol
* binding.
*
* Parameters:
* LassoProvider *provider The provider whose endpoints will be scanned.
* const char *binding The required binding short name.
*
* Returns:
* The endpoint URL or NULL if not found. Must be freed with g_free().
*
* Lasso does not provide a public API to select a provider endpoint
* by binding. The best we can do is iterate over a list of endpoint
* descriptors and select a matching descriptor.
*
* Lasso does not document the format of these descriptor names but
* essentially a descriptor is a space separated concatenation of the
* endpoint properties. For SAML2 one can assume it is the endpoint
* type, optionally followed by the protocol binding name, optionally
* followd by the index (if the endpoint type is indexed). If the
* endpoint is a response location then "ResponseLocation" will be
* appended as the final token. For example here is a list of
* descriptors returned for a service provider (note they are
* unordered).
*
* "AssertionConsumerService HTTP-POST 0"
* "AuthnRequestsSigned"
* "AssertionConsumerService PAOS 2"
* "SingleLogoutService HTTP-Redirect"
* "SingleLogoutService SOAP"
* "AssertionConsumerService HTTP-Artifact 1"
* "NameIDFormat"
* "SingleLogoutService HTTP-POST ResponseLocation"
*
* The possible binding names are:
*
* "SOAP"
* "HTTP-Redirect"
* "HTTP-POST"
* "HTTP-Artifact"
* "PAOS"
* "URI"
*
* We know the AssertionConsumerService is indexed. If there is more
* than one endpoint with the required binding we select the one with
* the lowest index assuming it is preferred.
*/
char *am_get_assertion_consumer_service_by_binding(LassoProvider *provider, const char *binding)
{
GList *descriptors;
char *url;
char *selected_descriptor;
char *descriptor;
char **tokens;
guint n_tokens;
GList *i;
char *endptr;
long descriptor_index, min_index;
url = NULL;
selected_descriptor = NULL;
min_index = LONG_MAX;
/* The descriptor list is unordered */
descriptors = lasso_provider_get_metadata_keys_for_role(provider,
LASSO_PROVIDER_ROLE_SP);
for (i = g_list_first(descriptors), tokens=NULL;
i;
i = g_list_next(i), g_strfreev(tokens)) {
descriptor = i->data;
descriptor_index = LONG_MAX;
/*
* Split the descriptor into tokens, only consider descriptors
* which have at least 3 tokens and whose first token is
* AssertionConsumerService
*/
tokens = g_strsplit(descriptor, " ", 0);
n_tokens = g_strv_length(tokens);
if (n_tokens < 3) continue;
if (!g_str_equal(tokens[0], "AssertionConsumerService")) continue;
if (!g_str_equal(tokens[1], binding)) continue;
descriptor_index = strtol(tokens[2], &endptr, 10);
if (tokens[2] == endptr) continue; /* could not parse int */
if (descriptor_index < min_index) {
selected_descriptor = descriptor;
min_index = descriptor_index;
}
}
if (selected_descriptor) {
url = lasso_provider_get_metadata_one_for_role(provider,
LASSO_PROVIDER_ROLE_SP,
selected_descriptor);
}
lasso_release_list_of_strings(descriptors);
return url;
}
#ifdef HAVE_ECP
/* String representation of ECPServiceOptions bitmask
*
* ECPServiceOptions is a bitmask of flags. Return a comma separated string
* of all the flags. If any bit in the bitmask is unaccounted for an
* extra string will be appended of the form "(unknown bits = x)".
*
* Parameters:
* pool memory allocation pool
* options bitmask of PAOS options
*/
char *am_ecp_service_options_str(apr_pool_t *pool, ECPServiceOptions options)
{
apr_array_header_t *names = apr_array_make(pool, 4, sizeof(const char *));
if (options & ECP_SERVICE_OPTION_CHANNEL_BINDING) {
APR_ARRAY_PUSH(names, const char *) = "channel-binding";
options &= ~ECP_SERVICE_OPTION_CHANNEL_BINDING;
}
if (options & ECP_SERVICE_OPTION_HOLDER_OF_KEY) {
APR_ARRAY_PUSH(names, const char *) = "holder-of-key";
options &= ~ECP_SERVICE_OPTION_HOLDER_OF_KEY;
}
if (options & ECP_SERVICE_OPTION_WANT_AUTHN_SIGNED) {
APR_ARRAY_PUSH(names, const char *) = "want-authn-signed";
options &= ~ECP_SERVICE_OPTION_WANT_AUTHN_SIGNED;
}
if (options & ECP_SERVICE_OPTION_DELEGATION) {
APR_ARRAY_PUSH(names, const char *) = "delegation";
options &= ~ECP_SERVICE_OPTION_DELEGATION;
}
if (options) {
APR_ARRAY_PUSH(names, const char *) =
apr_psprintf(pool, "(unknown bits = %#x)", options);
}
return apr_array_pstrcat(pool, names, ',');
}
/* Determine if request is compatible with PAOS, decode headers
*
* To indicate support for the ECP profile, and the PAOS binding, the
* request MUST include the following HTTP header fields:
*
* 1. An Accept header indicating acceptance of the MIME type
* "application/vnd.paos+xml"
*
* 2. A PAOS header specifying the PAOS version with a value, at minimum, of
* "urn:liberty:paos:2003-08" and a supported service value of
* "urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp". The service value MAY
* contain option values.
*
* This function validates the Accept header the the PAOS header, if
* all condidtions are met it returns true, false otherwise. If the
* validation succeeds any ECP options specified along with the
* ECP service are parsed and stored in req_cfg->ecp_service_options
*
* Any error discovered during processing are returned in the
* error_code parameter, zero indicates success. This function never
* returns true if an error occurred.
*
* Parameters:
* request_rec *r The current request.
* int * error_code Return error code here
*
*/
bool am_is_paos_request(request_rec *r, int *error_code)
{
const char *accept_header = NULL;
const char *paos_header = NULL;
bool have_paos_media_type = false;
bool valid_paos_header = false;
bool is_paos = false;
ECPServiceOptions ecp_service_options = 0;
*error_code = 0;
accept_header = apr_table_get(r->headers_in, "Accept");
paos_header = apr_table_get(r->headers_in, "PAOS");
if (accept_header) {
if (am_header_has_media_type(r, accept_header, MEDIA_TYPE_PAOS)) {
have_paos_media_type = true;
}
}
if (paos_header) {
if (am_parse_paos_header(r, paos_header, &ecp_service_options)) {
valid_paos_header = true;
} else {
if (*error_code == 0)
*error_code = AM_ERROR_INVALID_PAOS_HEADER;
}
}
if (have_paos_media_type) {
if (valid_paos_header) {
is_paos = true;
} else {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"request supplied PAOS media type in Accept header "
"but omitted valid PAOS header");
if (*error_code == 0)
*error_code = AM_ERROR_MISSING_PAOS_HEADER;
}
} else {
if (valid_paos_header) {
AM_LOG_RERROR(APLOG_MARK, APLOG_ERR, 0, r,
"request supplied valid PAOS header "
"but omitted PAOS media type in Accept header");
if (*error_code == 0)
*error_code = AM_ERROR_MISSING_PAOS_MEDIA_TYPE;
}
}
AM_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r,
"have_paos_media_type=%s valid_paos_header=%s is_paos=%s "
"error_code=%d ecp options=[%s]",
have_paos_media_type ? "True" : "False",
valid_paos_header ? "True" : "False",
is_paos ? "True" : "False",
*error_code,
am_ecp_service_options_str(r->pool, ecp_service_options));
if (is_paos) {
am_req_cfg_rec *req_cfg;
req_cfg = am_get_req_cfg(r);
req_cfg->ecp_service_options = ecp_service_options;
}
return is_paos;
}
#endif /* HAVE_ECP */
char *
am_saml_response_status_str(request_rec *r, LassoNode *node)
{
LassoSamlp2StatusResponse *response = (LassoSamlp2StatusResponse*)node;
LassoSamlp2Status *status = NULL;
const char *status_code1 = NULL;
const char *status_code2 = NULL;
if (!LASSO_IS_SAMLP2_STATUS_RESPONSE(response)) {
return apr_psprintf(r->pool,
"error, expected LassoSamlp2StatusResponse "
"but got %s",
lasso_node_get_name((LassoNode*)response));
}
status = response->Status;
if (status == NULL ||
!LASSO_IS_SAMLP2_STATUS(status) ||
status->StatusCode == NULL ||
status->StatusCode->Value == NULL) {
return apr_psprintf(r->pool, "Status missing");
}
status_code1 = status->StatusCode->Value;
if (status->StatusCode->StatusCode) {
status_code2 = status->StatusCode->StatusCode->Value;
}
return apr_psprintf(r->pool,
"StatusCode1=\"%s\", StatusCode2=\"%s\", "
"StatusMessage=\"%s\"",
status_code1, status_code2, status->StatusMessage);
}
| ./CrossVul/dataset_final_sorted/CWE-601/c/good_1392_0 |
crossvul-cpp_data_bad_1001_3 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/***************************************************************************
* Copyright (C) 2017-2019 ZmartZone IAM
* Copyright (C) 2013-2017 Ping Identity Corporation
* All rights reserved.
*
* For further information please contact:
*
* Ping Identity Corporation
* 1099 18th St Suite 2950
* Denver, CO 80202
* 303.468.2900
* http://www.pingidentity.com
*
* DISCLAIMER OF WARRANTIES:
*
* THE SOFTWARE PROVIDED HEREUNDER IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
* ANY WARRANTIES OR REPRESENTATIONS EXPRESS, IMPLIED OR STATUTORY; INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF QUALITY, PERFORMANCE, NONINFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NOR ARE THERE ANY
* WARRANTIES CREATED BY A COURSE OR DEALING, COURSE OF PERFORMANCE OR TRADE
* USAGE. FURTHERMORE, THERE ARE NO WARRANTIES THAT THE SOFTWARE WILL MEET
* YOUR NEEDS OR BE FREE FROM ERRORS, OR THAT THE OPERATION OF THE SOFTWARE
* WILL BE UNINTERRUPTED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES 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.
*
* Initially based on mod_auth_cas.c:
* https://github.com/Jasig/mod_auth_cas
*
* Other code copied/borrowed/adapted:
* shared memory caching: mod_auth_mellon
*
* @Author: Hans Zandbelt - hans.zandbelt@zmartzone.eu
*
**************************************************************************/
#include "apr_hash.h"
#include "apr_strings.h"
#include "ap_config.h"
#include "ap_provider.h"
#include "apr_lib.h"
#include "apr_file_io.h"
#include "apr_sha1.h"
#include "apr_base64.h"
#include "httpd.h"
#include "http_core.h"
#include "http_config.h"
#include "http_log.h"
#include "http_protocol.h"
#include "http_request.h"
#include "mod_auth_openidc.h"
#define ERROR 2
static int oidc_handle_logout_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *url);
// TODO:
// - sort out oidc_cfg vs. oidc_dir_cfg stuff
// - rigid input checking on discovery responses
// - check self-issued support
// - README.quickstart
// - refresh metadata once-per too? (for non-signing key changes)
extern module AP_MODULE_DECLARE_DATA auth_openidc_module;
/*
* clean any suspicious headers in the HTTP request sent by the user agent
*/
static void oidc_scrub_request_headers(request_rec *r, const char *claim_prefix,
apr_hash_t *scrub) {
const int prefix_len = claim_prefix ? strlen(claim_prefix) : 0;
/* get an array representation of the incoming HTTP headers */
const apr_array_header_t * const h = apr_table_elts(r->headers_in);
/* table to keep the non-suspicious headers */
apr_table_t *clean_headers = apr_table_make(r->pool, h->nelts);
/* loop over the incoming HTTP headers */
const apr_table_entry_t * const e = (const apr_table_entry_t *) h->elts;
int i;
for (i = 0; i < h->nelts; i++) {
const char * const k = e[i].key;
/* is this header's name equivalent to a header that needs scrubbing? */
const char *hdr =
(k != NULL) && (scrub != NULL) ?
apr_hash_get(scrub, k, APR_HASH_KEY_STRING) : NULL;
const int header_matches = (hdr != NULL)
&& (oidc_strnenvcmp(k, hdr, -1) == 0);
/*
* would this header be interpreted as a mod_auth_openidc attribute? Note
* that prefix_len will be zero if no attr_prefix is defined,
* so this will always be false. Also note that we do not
* scrub headers if the prefix is empty because every header
* would match.
*/
const int prefix_matches = (k != NULL) && prefix_len
&& (oidc_strnenvcmp(k, claim_prefix, prefix_len) == 0);
/* add to the clean_headers if non-suspicious, skip and report otherwise */
if (!prefix_matches && !header_matches) {
apr_table_addn(clean_headers, k, e[i].val);
} else {
oidc_warn(r, "scrubbed suspicious request header (%s: %.32s)", k,
e[i].val);
}
}
/* overwrite the incoming headers with the cleaned result */
r->headers_in = clean_headers;
}
/*
* scrub all mod_auth_openidc related headers
*/
void oidc_scrub_headers(request_rec *r) {
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
const char *prefix = oidc_cfg_claim_prefix(r);
apr_hash_t *hdrs = apr_hash_make(r->pool);
if (apr_strnatcmp(prefix, "") == 0) {
if ((cfg->white_listed_claims != NULL)
&& (apr_hash_count(cfg->white_listed_claims) > 0))
hdrs = apr_hash_overlay(r->pool, cfg->white_listed_claims, hdrs);
else
oidc_warn(r,
"both " OIDCClaimPrefix " and " OIDCWhiteListedClaims " are empty: this renders an insecure setup!");
}
char *authn_hdr = oidc_cfg_dir_authn_header(r);
if (authn_hdr != NULL)
apr_hash_set(hdrs, authn_hdr, APR_HASH_KEY_STRING, authn_hdr);
/*
* scrub all headers starting with OIDC_ first
*/
oidc_scrub_request_headers(r, OIDC_DEFAULT_HEADER_PREFIX, hdrs);
/*
* then see if the claim headers need to be removed on top of that
* (i.e. the prefix does not start with the default OIDC_)
*/
if ((strstr(prefix, OIDC_DEFAULT_HEADER_PREFIX) != prefix)) {
oidc_scrub_request_headers(r, prefix, NULL);
}
}
/*
* strip the session cookie from the headers sent to the application/backend
*/
void oidc_strip_cookies(request_rec *r) {
char *cookie, *ctx, *result = NULL;
const char *name = NULL;
int i;
apr_array_header_t *strip = oidc_dir_cfg_strip_cookies(r);
char *cookies = apr_pstrdup(r->pool, oidc_util_hdr_in_cookie_get(r));
if ((cookies != NULL) && (strip != NULL)) {
oidc_debug(r,
"looking for the following cookies to strip from cookie header: %s",
apr_array_pstrcat(r->pool, strip, OIDC_CHAR_COMMA));
cookie = apr_strtok(cookies, OIDC_STR_SEMI_COLON, &ctx);
do {
while (cookie != NULL && *cookie == OIDC_CHAR_SPACE)
cookie++;
for (i = 0; i < strip->nelts; i++) {
name = ((const char**) strip->elts)[i];
if ((strncmp(cookie, name, strlen(name)) == 0)
&& (cookie[strlen(name)] == OIDC_CHAR_EQUAL)) {
oidc_debug(r, "stripping: %s", name);
break;
}
}
if (i == strip->nelts) {
result = result ? apr_psprintf(r->pool, "%s%s%s", result,
OIDC_STR_SEMI_COLON, cookie) :
cookie;
}
cookie = apr_strtok(NULL, OIDC_STR_SEMI_COLON, &ctx);
} while (cookie != NULL);
oidc_util_hdr_in_cookie_set(r, result);
}
}
#define OIDC_SHA1_LEN 20
/*
* calculates a hash value based on request fingerprint plus a provided nonce string.
*/
static char *oidc_get_browser_state_hash(request_rec *r, const char *nonce) {
oidc_debug(r, "enter");
/* helper to hold to header values */
const char *value = NULL;
/* the hash context */
apr_sha1_ctx_t sha1;
/* Initialize the hash context */
apr_sha1_init(&sha1);
/* get the X-FORWARDED-FOR header value */
value = oidc_util_hdr_in_x_forwarded_for_get(r);
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, strlen(value));
/* get the USER-AGENT header value */
value = oidc_util_hdr_in_user_agent_get(r);
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, strlen(value));
/* get the remote client IP address or host name */
/*
int remotehost_is_ip;
value = ap_get_remote_host(r->connection, r->per_dir_config,
REMOTE_NOLOOKUP, &remotehost_is_ip);
apr_sha1_update(&sha1, value, strlen(value));
*/
/* concat the nonce parameter to the hash input */
apr_sha1_update(&sha1, nonce, strlen(nonce));
/* concat the token binding ID if present */
value = oidc_util_get_provided_token_binding_id(r);
if (value != NULL) {
oidc_debug(r,
"Provided Token Binding ID environment variable found; adding its value to the state");
apr_sha1_update(&sha1, value, strlen(value));
}
/* finalize the hash input and calculate the resulting hash output */
unsigned char hash[OIDC_SHA1_LEN];
apr_sha1_final(hash, &sha1);
/* base64url-encode the resulting hash and return it */
char *result = NULL;
oidc_base64url_encode(r, &result, (const char *) hash, OIDC_SHA1_LEN, TRUE);
return result;
}
/*
* return the name for the state cookie
*/
static char *oidc_get_state_cookie_name(request_rec *r, const char *state) {
return apr_psprintf(r->pool, "%s%s", OIDC_STATE_COOKIE_PREFIX, state);
}
/*
* return the static provider configuration, i.e. from a metadata URL or configuration primitives
*/
static apr_byte_t oidc_provider_static_config(request_rec *r, oidc_cfg *c,
oidc_provider_t **provider) {
json_t *j_provider = NULL;
char *s_json = NULL;
/* see if we should configure a static provider based on external (cached) metadata */
if ((c->metadata_dir != NULL) || (c->provider.metadata_url == NULL)) {
*provider = &c->provider;
return TRUE;
}
oidc_cache_get_provider(r, c->provider.metadata_url, &s_json);
if (s_json == NULL) {
if (oidc_metadata_provider_retrieve(r, c, NULL,
c->provider.metadata_url, &j_provider, &s_json) == FALSE) {
oidc_error(r, "could not retrieve metadata from url: %s",
c->provider.metadata_url);
return FALSE;
}
oidc_cache_set_provider(r, c->provider.metadata_url, s_json,
apr_time_now() + (c->provider_metadata_refresh_interval <= 0 ? apr_time_from_sec( OIDC_CACHE_PROVIDER_METADATA_EXPIRY_DEFAULT) : c->provider_metadata_refresh_interval));
} else {
oidc_util_decode_json_object(r, s_json, &j_provider);
/* check to see if it is valid metadata */
if (oidc_metadata_provider_is_valid(r, c, j_provider, NULL) == FALSE) {
oidc_error(r,
"cache corruption detected: invalid metadata from url: %s",
c->provider.metadata_url);
return FALSE;
}
}
*provider = apr_pcalloc(r->pool, sizeof(oidc_provider_t));
memcpy(*provider, &c->provider, sizeof(oidc_provider_t));
if (oidc_metadata_provider_parse(r, c, j_provider, *provider) == FALSE) {
oidc_error(r, "could not parse metadata from url: %s",
c->provider.metadata_url);
if (j_provider)
json_decref(j_provider);
return FALSE;
}
json_decref(j_provider);
return TRUE;
}
/*
* return the oidc_provider_t struct for the specified issuer
*/
static oidc_provider_t *oidc_get_provider_for_issuer(request_rec *r,
oidc_cfg *c, const char *issuer, apr_byte_t allow_discovery) {
/* by default we'll assume that we're dealing with a single statically configured OP */
oidc_provider_t *provider = NULL;
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return NULL;
/* unless a metadata directory was configured, so we'll try and get the provider settings from there */
if (c->metadata_dir != NULL) {
/* try and get metadata from the metadata directory for the OP that sent this response */
if ((oidc_metadata_get(r, c, issuer, &provider, allow_discovery)
== FALSE) || (provider == NULL)) {
/* don't know nothing about this OP/issuer */
oidc_error(r, "no provider metadata found for issuer \"%s\"",
issuer);
return NULL;
}
}
return provider;
}
/*
* find out whether the request is a response from an IDP discovery page
*/
static apr_byte_t oidc_is_discovery_response(request_rec *r, oidc_cfg *cfg) {
/*
* prereq: this is a call to the configured redirect_uri, now see if:
* the OIDC_DISC_OP_PARAM is present
*/
return oidc_util_request_has_parameter(r, OIDC_DISC_OP_PARAM)
|| oidc_util_request_has_parameter(r, OIDC_DISC_USER_PARAM);
}
/*
* return the HTTP method being called: only for POST data persistence purposes
*/
static const char *oidc_original_request_method(request_rec *r, oidc_cfg *cfg,
apr_byte_t handle_discovery_response) {
const char *method = OIDC_METHOD_GET;
char *m = NULL;
if ((handle_discovery_response == TRUE)
&& (oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, cfg)))
&& (oidc_is_discovery_response(r, cfg))) {
oidc_util_get_request_parameter(r, OIDC_DISC_RM_PARAM, &m);
if (m != NULL)
method = apr_pstrdup(r->pool, m);
} else {
/*
* if POST preserve is not enabled for this location, there's no point in preserving
* the method either which would result in POSTing empty data on return;
* so we revert to legacy behavior
*/
if (oidc_cfg_dir_preserve_post(r) == 0)
return OIDC_METHOD_GET;
const char *content_type = oidc_util_hdr_in_content_type_get(r);
if ((r->method_number == M_POST) && (apr_strnatcmp(content_type,
OIDC_CONTENT_TYPE_FORM_ENCODED) == 0))
method = OIDC_METHOD_FORM_POST;
}
oidc_debug(r, "return: %s", method);
return method;
}
/*
* send an OpenID Connect authorization request to the specified provider preserving POST parameters using HTML5 storage
*/
apr_byte_t oidc_post_preserve_javascript(request_rec *r, const char *location,
char **javascript, char **javascript_method) {
if (oidc_cfg_dir_preserve_post(r) == 0)
return FALSE;
oidc_debug(r, "enter");
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
const char *method = oidc_original_request_method(r, cfg, FALSE);
if (apr_strnatcmp(method, OIDC_METHOD_FORM_POST) != 0)
return FALSE;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return FALSE;
}
const apr_array_header_t *arr = apr_table_elts(params);
const apr_table_entry_t *elts = (const apr_table_entry_t*) arr->elts;
int i;
char *json = "";
for (i = 0; i < arr->nelts; i++) {
json = apr_psprintf(r->pool, "%s'%s': '%s'%s", json,
oidc_util_escape_string(r, elts[i].key),
oidc_util_escape_string(r, elts[i].val),
i < arr->nelts - 1 ? "," : "");
}
json = apr_psprintf(r->pool, "{ %s }", json);
const char *jmethod = "preserveOnLoad";
const char *jscript =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function %s() {\n"
" sessionStorage.setItem('mod_auth_openidc_preserve_post_params', JSON.stringify(%s));\n"
" %s"
" }\n"
" </script>\n", jmethod, json,
location ?
apr_psprintf(r->pool, "window.location='%s';\n",
location) :
"");
if (location == NULL) {
if (javascript_method)
*javascript_method = apr_pstrdup(r->pool, jmethod);
if (javascript)
*javascript = apr_pstrdup(r->pool, jscript);
} else {
oidc_util_html_send(r, "Preserving...", jscript, jmethod,
"<p>Preserving...</p>", OK);
}
return TRUE;
}
/*
* restore POST parameters on original_url from HTML5 local storage
*/
static int oidc_request_post_preserved_restore(request_rec *r,
const char *original_url) {
oidc_debug(r, "enter: original_url=%s", original_url);
const char *method = "postOnLoad";
const char *script =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function str_decode(string) {\n"
" try {\n"
" result = decodeURIComponent(string);\n"
" } catch (e) {\n"
" result = unescape(string);\n"
" }\n"
" return result;\n"
" }\n"
" function %s() {\n"
" var mod_auth_openidc_preserve_post_params = JSON.parse(sessionStorage.getItem('mod_auth_openidc_preserve_post_params'));\n"
" sessionStorage.removeItem('mod_auth_openidc_preserve_post_params');\n"
" for (var key in mod_auth_openidc_preserve_post_params) {\n"
" var input = document.createElement(\"input\");\n"
" input.name = str_decode(key);\n"
" input.value = str_decode(mod_auth_openidc_preserve_post_params[key]);\n"
" input.type = \"hidden\";\n"
" document.forms[0].appendChild(input);\n"
" }\n"
" document.forms[0].action = '%s';\n"
" document.forms[0].submit();\n"
" }\n"
" </script>\n", method, original_url);
const char *body = " <p>Restoring...</p>\n"
" <form method=\"post\"></form>\n";
return oidc_util_html_send(r, "Restoring...", script, method, body,
OK);
}
/*
* parse state that was sent to us by the issuer
*/
static apr_byte_t oidc_unsolicited_proto_state(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t **proto_state) {
char *alg = NULL;
oidc_debug(r, "enter: state header=%s",
oidc_proto_peek_jwt_header(r, state, &alg));
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret,
oidc_alg2keysize(alg), OIDC_JOSE_ALG_SHA256,
TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwt_t *jwt = NULL;
if (oidc_jwt_parse(r->pool, state, &jwt,
oidc_util_merge_symmetric_key(r->pool, c->private_keys, jwk),
&err) == FALSE) {
oidc_error(r,
"could not parse JWT from state: invalid unsolicited response: %s",
oidc_jose_e2s(r->pool, err));
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully parsed JWT from state");
if (jwt->payload.iss == NULL) {
oidc_error(r, "no \"%s\" could be retrieved from JWT state, aborting",
OIDC_CLAIM_ISS);
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_provider_t *provider = oidc_get_provider_for_issuer(r, c,
jwt->payload.iss, FALSE);
if (provider == NULL) {
oidc_jwt_destroy(jwt);
return FALSE;
}
/* validate the state JWT, validating optional exp + iat */
if (oidc_proto_validate_jwt(r, jwt, provider->issuer, FALSE, FALSE,
provider->idtoken_iat_slack,
OIDC_TOKEN_BINDING_POLICY_DISABLED) == FALSE) {
oidc_jwt_destroy(jwt);
return FALSE;
}
char *rfp = NULL;
if (oidc_jose_get_string(r->pool, jwt->payload.value.json, OIDC_CLAIM_RFP,
TRUE, &rfp, &err) == FALSE) {
oidc_error(r,
"no \"%s\" claim could be retrieved from JWT state, aborting: %s",
OIDC_CLAIM_RFP, oidc_jose_e2s(r->pool, err));
oidc_jwt_destroy(jwt);
return FALSE;
}
if (apr_strnatcmp(rfp, OIDC_PROTO_ISS) != 0) {
oidc_error(r, "\"%s\" (%s) does not match \"%s\", aborting",
OIDC_CLAIM_RFP, rfp, OIDC_PROTO_ISS);
oidc_jwt_destroy(jwt);
return FALSE;
}
char *target_link_uri = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_TARGET_LINK_URI,
FALSE, &target_link_uri, NULL);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
oidc_error(r,
"no \"%s\" claim could be retrieved from JWT state and no " OIDCDefaultURL " is set, aborting",
OIDC_CLAIM_TARGET_LINK_URI);
oidc_jwt_destroy(jwt);
return FALSE;
}
target_link_uri = c->default_sso_url;
}
if (c->metadata_dir != NULL) {
if ((oidc_metadata_get(r, c, jwt->payload.iss, &provider, FALSE)
== FALSE) || (provider == NULL)) {
oidc_error(r, "no provider metadata found for provider \"%s\"",
jwt->payload.iss);
oidc_jwt_destroy(jwt);
return FALSE;
}
}
char *jti = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json, OIDC_CLAIM_JTI,
FALSE, &jti,
NULL);
if (jti == NULL) {
char *cser = oidc_jwt_serialize(r->pool, jwt, &err);
if (cser == NULL)
return FALSE;
if (oidc_util_hash_string_and_base64url_encode(r, OIDC_JOSE_ALG_SHA256,
cser, &jti) == FALSE) {
oidc_error(r,
"oidc_util_hash_string_and_base64url_encode returned an error");
return FALSE;
}
}
char *replay = NULL;
oidc_cache_get_jti(r, jti, &replay);
if (replay != NULL) {
oidc_error(r,
"the \"%s\" value (%s) passed in the browser state was found in the cache already; possible replay attack!?",
OIDC_CLAIM_JTI, jti);
oidc_jwt_destroy(jwt);
return FALSE;
}
/* jti cache duration is the configured replay prevention window for token issuance plus 10 seconds for safety */
apr_time_t jti_cache_duration = apr_time_from_sec(
provider->idtoken_iat_slack * 2 + 10);
/* store it in the cache for the calculated duration */
oidc_cache_set_jti(r, jti, jti, apr_time_now() + jti_cache_duration);
oidc_debug(r,
"jti \"%s\" validated successfully and is now cached for %" APR_TIME_T_FMT " seconds",
jti, apr_time_sec(jti_cache_duration));
jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret, 0,
NULL, TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwks_uri_t jwks_uri = { provider->jwks_uri,
provider->jwks_refresh_interval, provider->ssl_validate_server };
if (oidc_proto_jwt_verify(r, c, jwt, &jwks_uri,
oidc_util_merge_symmetric_key(r->pool, NULL, jwk)) == FALSE) {
oidc_error(r, "state JWT could not be validated, aborting");
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully verified state JWT");
*proto_state = oidc_proto_state_new();
oidc_proto_state_set_issuer(*proto_state, jwt->payload.iss);
oidc_proto_state_set_original_url(*proto_state, target_link_uri);
oidc_proto_state_set_original_method(*proto_state, OIDC_METHOD_GET);
oidc_proto_state_set_response_mode(*proto_state, provider->response_mode);
oidc_proto_state_set_response_type(*proto_state, provider->response_type);
oidc_proto_state_set_timestamp_now(*proto_state);
oidc_jwt_destroy(jwt);
return TRUE;
}
typedef struct oidc_state_cookies_t {
char *name;
apr_time_t timestamp;
struct oidc_state_cookies_t *next;
} oidc_state_cookies_t;
static int oidc_delete_oldest_state_cookies(request_rec *r,
int number_of_valid_state_cookies, int max_number_of_state_cookies,
oidc_state_cookies_t *first) {
oidc_state_cookies_t *cur = NULL, *prev = NULL, *prev_oldest = NULL,
*oldest = NULL;
while (number_of_valid_state_cookies >= max_number_of_state_cookies) {
oldest = first;
prev_oldest = NULL;
prev = first;
cur = first->next;
while (cur) {
if ((cur->timestamp < oldest->timestamp)) {
oldest = cur;
prev_oldest = prev;
}
prev = cur;
cur = cur->next;
}
oidc_warn(r,
"deleting oldest state cookie: %s (time until expiry %" APR_TIME_T_FMT " seconds)",
oldest->name, apr_time_sec(oldest->timestamp - apr_time_now()));
oidc_util_set_cookie(r, oldest->name, "", 0, NULL);
if (prev_oldest)
prev_oldest->next = oldest->next;
else
first = first->next;
number_of_valid_state_cookies--;
}
return number_of_valid_state_cookies;
}
/*
* clean state cookies that have expired i.e. for outstanding requests that will never return
* successfully and return the number of remaining valid cookies/outstanding-requests while
* doing so
*/
static int oidc_clean_expired_state_cookies(request_rec *r, oidc_cfg *c,
const char *currentCookieName, int delete_oldest) {
int number_of_valid_state_cookies = 0;
oidc_state_cookies_t *first = NULL, *last = NULL;
char *cookie, *tokenizerCtx = NULL;
char *cookies = apr_pstrdup(r->pool, oidc_util_hdr_in_cookie_get(r));
if (cookies != NULL) {
cookie = apr_strtok(cookies, OIDC_STR_SEMI_COLON, &tokenizerCtx);
while (cookie != NULL) {
while (*cookie == OIDC_CHAR_SPACE)
cookie++;
if (strstr(cookie, OIDC_STATE_COOKIE_PREFIX) == cookie) {
char *cookieName = cookie;
while (cookie != NULL && *cookie != OIDC_CHAR_EQUAL)
cookie++;
if (*cookie == OIDC_CHAR_EQUAL) {
*cookie = '\0';
cookie++;
if ((currentCookieName == NULL)
|| (apr_strnatcmp(cookieName, currentCookieName)
!= 0)) {
oidc_proto_state_t *proto_state =
oidc_proto_state_from_cookie(r, c, cookie);
if (proto_state != NULL) {
json_int_t ts = oidc_proto_state_get_timestamp(
proto_state);
if (apr_time_now() > ts + apr_time_from_sec(c->state_timeout)) {
oidc_error(r,
"state (%s) has expired (original_url=%s)",
cookieName,
oidc_proto_state_get_original_url(
proto_state));
oidc_util_set_cookie(r, cookieName, "", 0,
NULL);
} else {
if (first == NULL) {
first = apr_pcalloc(r->pool,
sizeof(oidc_state_cookies_t));
last = first;
} else {
last->next = apr_pcalloc(r->pool,
sizeof(oidc_state_cookies_t));
last = last->next;
}
last->name = cookieName;
last->timestamp = ts;
last->next = NULL;
number_of_valid_state_cookies++;
}
oidc_proto_state_destroy(proto_state);
}
}
}
}
cookie = apr_strtok(NULL, OIDC_STR_SEMI_COLON, &tokenizerCtx);
}
}
if (delete_oldest > 0)
number_of_valid_state_cookies = oidc_delete_oldest_state_cookies(r,
number_of_valid_state_cookies, c->max_number_of_state_cookies,
first);
return number_of_valid_state_cookies;
}
/*
* restore the state that was maintained between authorization request and response in an encrypted cookie
*/
static apr_byte_t oidc_restore_proto_state(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t **proto_state) {
oidc_debug(r, "enter");
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* clean expired state cookies to avoid pollution */
oidc_clean_expired_state_cookies(r, c, cookieName, FALSE);
/* get the state cookie value first */
char *cookieValue = oidc_util_get_cookie(r, cookieName);
if (cookieValue == NULL) {
oidc_error(r, "no \"%s\" state cookie found", cookieName);
return oidc_unsolicited_proto_state(r, c, state, proto_state);
}
/* clear state cookie because we don't need it anymore */
oidc_util_set_cookie(r, cookieName, "", 0, NULL);
*proto_state = oidc_proto_state_from_cookie(r, c, cookieValue);
if (*proto_state == NULL)
return FALSE;
const char *nonce = oidc_proto_state_get_nonce(*proto_state);
/* calculate the hash of the browser fingerprint concatenated with the nonce */
char *calc = oidc_get_browser_state_hash(r, nonce);
/* compare the calculated hash with the value provided in the authorization response */
if (apr_strnatcmp(calc, state) != 0) {
oidc_error(r,
"calculated state from cookie does not match state parameter passed back in URL: \"%s\" != \"%s\"",
state, calc);
oidc_proto_state_destroy(*proto_state);
return FALSE;
}
apr_time_t ts = oidc_proto_state_get_timestamp(*proto_state);
/* check that the timestamp is not beyond the valid interval */
if (apr_time_now() > ts + apr_time_from_sec(c->state_timeout)) {
oidc_error(r, "state has expired");
/*
* note that this overrides redirection to the OIDCDefaultURL as done later...
* see: https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!msg/mod_auth_openidc/L4JFBw-XCNU/BWi2Fmk2AwAJ
*/
oidc_util_html_send_error(r, c->error_template,
"Invalid Authentication Response",
apr_psprintf(r->pool,
"This is due to a timeout; please restart your authentication session by re-entering the URL/bookmark you originally wanted to access: %s",
oidc_proto_state_get_original_url(*proto_state)),
OK);
oidc_proto_state_destroy(*proto_state);
return FALSE;
}
/* add the state */
oidc_proto_state_set_state(*proto_state, state);
/* log the restored state object */
oidc_debug(r, "restored state: %s",
oidc_proto_state_to_string(r, *proto_state));
/* we've made it */
return TRUE;
}
/*
* set the state that is maintained between an authorization request and an authorization response
* in a cookie in the browser that is cryptographically bound to that state
*/
static int oidc_authorization_request_set_cookie(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t *proto_state) {
/*
* create a cookie consisting of 8 elements:
* random value, original URL, original method, issuer, response_type, response_mod, prompt and timestamp
* encoded as JSON, encrypting the resulting JSON value
*/
char *cookieValue = oidc_proto_state_to_cookie(r, c, proto_state);
if (cookieValue == NULL)
return HTTP_INTERNAL_SERVER_ERROR;
/*
* clean expired state cookies to avoid pollution and optionally
* try to avoid the number of state cookies exceeding a max
*/
int number_of_cookies = oidc_clean_expired_state_cookies(r, c, NULL,
oidc_cfg_delete_oldest_state_cookies(c));
int max_number_of_cookies = oidc_cfg_max_number_of_state_cookies(c);
if ((max_number_of_cookies > 0)
&& (number_of_cookies >= max_number_of_cookies)) {
oidc_warn(r,
"the number of existing, valid state cookies (%d) has exceeded the limit (%d), no additional authorization request + state cookie can be generated, aborting the request",
number_of_cookies, max_number_of_cookies);
/*
* TODO: the html_send code below caters for the case that there's a user behind a
* browser generating this request, rather than a piece of XHR code; how would an
* XHR client handle this?
*/
/*
* it appears that sending content with a 503 turns the HTTP status code
* into a 200 so we'll avoid that for now: the user will see Apache specific
* readable text anyway
*
return oidc_util_html_send_error(r, c->error_template,
"Too Many Outstanding Requests",
apr_psprintf(r->pool,
"No authentication request could be generated since there are too many outstanding authentication requests already; you may have to wait up to %d seconds to be able to create a new request",
c->state_timeout),
HTTP_SERVICE_UNAVAILABLE);
*/
return HTTP_SERVICE_UNAVAILABLE;
}
/* assemble the cookie name for the state cookie */
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* set it as a cookie */
oidc_util_set_cookie(r, cookieName, cookieValue, -1,
c->cookie_same_site ? OIDC_COOKIE_EXT_SAME_SITE_LAX : NULL);
return HTTP_OK;
}
/*
* get the mod_auth_openidc related context from the (userdata in the) request
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
static apr_table_t *oidc_request_state(request_rec *rr) {
/* our state is always stored in the main request */
request_rec *r = (rr->main != NULL) ? rr->main : rr;
/* our state is a table, get it */
apr_table_t *state = NULL;
apr_pool_userdata_get((void **) &state, OIDC_USERDATA_KEY, r->pool);
/* if it does not exist, we'll create a new table */
if (state == NULL) {
state = apr_table_make(r->pool, 5);
apr_pool_userdata_set(state, OIDC_USERDATA_KEY, NULL, r->pool);
}
/* return the resulting table, always non-null now */
return state;
}
/*
* set a name/value pair in the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
void oidc_request_state_set(request_rec *r, const char *key, const char *value) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* put the name/value pair in that table */
apr_table_set(state, key, value);
}
/*
* get a name/value pair from the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
const char*oidc_request_state_get(request_rec *r, const char *key) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* return the value from the table */
return apr_table_get(state, key);
}
/*
* set the claims from a JSON object (c.q. id_token or user_info response) stored
* in the session in to HTTP headers passed on to the application
*/
static apr_byte_t oidc_set_app_claims(request_rec *r,
const oidc_cfg * const cfg, oidc_session_t *session,
const char *s_claims) {
json_t *j_claims = NULL;
/* decode the string-encoded attributes in to a JSON structure */
if (s_claims != NULL) {
if (oidc_util_decode_json_object(r, s_claims, &j_claims) == FALSE)
return FALSE;
}
/* set the resolved claims a HTTP headers for the application */
if (j_claims != NULL) {
oidc_util_set_app_infos(r, j_claims, oidc_cfg_claim_prefix(r),
cfg->claim_delimiter, oidc_cfg_dir_pass_info_in_headers(r),
oidc_cfg_dir_pass_info_in_envvars(r));
/* release resources */
json_decref(j_claims);
}
return TRUE;
}
static int oidc_authenticate_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, const char *original_url,
const char *login_hint, const char *id_token_hint, const char *prompt,
const char *auth_request_params, const char *path_scope);
/*
* log message about max session duration
*/
static void oidc_log_session_expires(request_rec *r, const char *msg,
apr_time_t session_expires) {
char buf[APR_RFC822_DATE_LEN + 1];
apr_rfc822_date(buf, session_expires);
oidc_debug(r, "%s: %s (in %" APR_TIME_T_FMT " secs from now)", msg, buf,
apr_time_sec(session_expires - apr_time_now()));
}
/*
* see if this is a non-browser request
*/
static apr_byte_t oidc_is_xml_http_request(request_rec *r) {
if ((oidc_util_hdr_in_x_requested_with_get(r) != NULL)
&& (apr_strnatcasecmp(oidc_util_hdr_in_x_requested_with_get(r),
OIDC_HTTP_HDR_VAL_XML_HTTP_REQUEST) == 0))
return TRUE;
if ((oidc_util_hdr_in_accept_contains(r, OIDC_CONTENT_TYPE_TEXT_HTML)
== FALSE) && (oidc_util_hdr_in_accept_contains(r,
OIDC_CONTENT_TYPE_APP_XHTML_XML) == FALSE)
&& (oidc_util_hdr_in_accept_contains(r,
OIDC_CONTENT_TYPE_ANY) == FALSE))
return TRUE;
return FALSE;
}
/*
* find out which action we need to take when encountering an unauthenticated request
*/
static int oidc_handle_unauthenticated_user(request_rec *r, oidc_cfg *c) {
/* see if we've configured OIDCUnAuthAction for this path */
switch (oidc_dir_cfg_unauth_action(r)) {
case OIDC_UNAUTH_RETURN410:
return HTTP_GONE;
case OIDC_UNAUTH_RETURN401:
return HTTP_UNAUTHORIZED;
case OIDC_UNAUTH_PASS:
r->user = "";
/*
* we're not going to pass information about an authenticated user to the application,
* but we do need to scrub the headers that mod_auth_openidc would set for security reasons
*/
oidc_scrub_headers(r);
return OK;
case OIDC_UNAUTH_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return HTTP_UNAUTHORIZED;
}
/*
* else: no session (regardless of whether it is main or sub-request),
* and we need to authenticate the user
*/
return oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
}
/*
* check if maximum session duration was exceeded
*/
static int oidc_check_max_session_duration(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
/* get the session expiry from the session data */
apr_time_t session_expires = oidc_session_get_session_expires(r, session);
/* check the expire timestamp against the current time */
if (apr_time_now() > session_expires) {
oidc_warn(r, "maximum session duration exceeded for user: %s",
session->remote_user);
oidc_session_kill(r, session);
return oidc_handle_unauthenticated_user(r, cfg);
}
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
return OK;
}
/*
* validate received session cookie against the domain it was issued for:
*
* this handles the case where the cache configured is a the same single memcache, Redis, or file
* backend for different (virtual) hosts, or a client-side cookie protected with the same secret
*
* it also handles the case that a cookie is unexpectedly shared across multiple hosts in
* name-based virtual hosting even though the OP(s) would be the same
*/
static apr_byte_t oidc_check_cookie_domain(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
const char *c_cookie_domain =
cfg->cookie_domain ?
cfg->cookie_domain : oidc_get_current_url_host(r);
const char *s_cookie_domain = oidc_session_get_cookie_domain(r, session);
if ((s_cookie_domain == NULL)
|| (apr_strnatcmp(c_cookie_domain, s_cookie_domain) != 0)) {
oidc_warn(r,
"aborting: detected attempt to play cookie against a different domain/host than issued for! (issued=%s, current=%s)",
s_cookie_domain, c_cookie_domain);
return FALSE;
}
return TRUE;
}
/*
* get a handle to the provider configuration via the "issuer" stored in the session
*/
apr_byte_t oidc_get_provider_from_session(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t **provider) {
oidc_debug(r, "enter");
/* get the issuer value from the session state */
const char *issuer = oidc_session_get_issuer(r, session);
if (issuer == NULL) {
oidc_error(r, "session corrupted: no issuer found in session");
return FALSE;
}
/* get the provider info associated with the issuer value */
oidc_provider_t *p = oidc_get_provider_for_issuer(r, c, issuer, FALSE);
if (p == NULL) {
oidc_error(r, "session corrupted: no provider found for issuer: %s",
issuer);
return FALSE;
}
*provider = p;
return TRUE;
}
/*
* store claims resolved from the userinfo endpoint in the session
*/
static void oidc_store_userinfo_claims(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider, const char *claims,
const char *userinfo_jwt) {
oidc_debug(r, "enter");
/* see if we've resolved any claims */
if (claims != NULL) {
/*
* Successfully decoded a set claims from the response so we can store them
* (well actually the stringified representation in the response)
* in the session context safely now
*/
oidc_session_set_userinfo_claims(r, session, claims);
if (c->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* this will also clear the entry if a JWT was not returned at this point */
oidc_session_set_userinfo_jwt(r, session, userinfo_jwt);
}
} else {
/*
* clear the existing claims because we could not refresh them
*/
oidc_session_set_userinfo_claims(r, session, NULL);
oidc_session_set_userinfo_jwt(r, session, NULL);
}
/* store the last refresh time if we've configured a userinfo refresh interval */
if (provider->userinfo_refresh_interval > 0)
oidc_session_reset_userinfo_last_refresh(r, session);
}
/*
* execute refresh token grant to refresh the existing access token
*/
static apr_byte_t oidc_refresh_access_token(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider,
char **new_access_token) {
oidc_debug(r, "enter");
/* get the refresh token that was stored in the session */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if (refresh_token == NULL) {
oidc_warn(r,
"refresh token routine called but no refresh_token found in the session");
return FALSE;
}
/* elements returned in the refresh response */
char *s_id_token = NULL;
int expires_in = -1;
char *s_token_type = NULL;
char *s_access_token = NULL;
char *s_refresh_token = NULL;
/* refresh the tokens by calling the token endpoint */
if (oidc_proto_refresh_request(r, c, provider, refresh_token, &s_id_token,
&s_access_token, &s_token_type, &expires_in,
&s_refresh_token) == FALSE) {
oidc_error(r, "access_token could not be refreshed");
return FALSE;
}
/* store the new access_token in the session and discard the old one */
oidc_session_set_access_token(r, session, s_access_token);
oidc_session_set_access_token_expires(r, session, expires_in);
/* reset the access token refresh timestamp */
oidc_session_reset_access_token_last_refresh(r, session);
/* see if we need to return it as a parameter */
if (new_access_token != NULL)
*new_access_token = s_access_token;
/* if we have a new refresh token (rolling refresh), store it in the session and overwrite the old one */
if (s_refresh_token != NULL)
oidc_session_set_refresh_token(r, session, s_refresh_token);
return TRUE;
}
/*
* retrieve claims from the userinfo endpoint and return the stringified response
*/
static const char *oidc_retrieve_claims_from_userinfo_endpoint(request_rec *r,
oidc_cfg *c, oidc_provider_t *provider, const char *access_token,
oidc_session_t *session, char *id_token_sub, char **userinfo_jwt) {
oidc_debug(r, "enter");
char *result = NULL;
char *refreshed_access_token = NULL;
/* see if a userinfo endpoint is set, otherwise there's nothing to do for us */
if (provider->userinfo_endpoint_url == NULL) {
oidc_debug(r,
"not retrieving userinfo claims because userinfo_endpoint is not set");
return NULL;
}
/* see if there's an access token, otherwise we can't call the userinfo endpoint at all */
if (access_token == NULL) {
oidc_debug(r,
"not retrieving userinfo claims because access_token is not provided");
return NULL;
}
if ((id_token_sub == NULL) && (session != NULL)) {
// when refreshing claims from the userinfo endpoint
json_t *id_token_claims = oidc_session_get_idtoken_claims_json(r,
session);
if (id_token_claims == NULL) {
oidc_error(r, "no id_token_claims found in session");
return NULL;
}
oidc_jose_get_string(r->pool, id_token_claims, OIDC_CLAIM_SUB, FALSE,
&id_token_sub, NULL);
}
// TODO: return code should indicate whether the token expired or some other error occurred
// TODO: long-term: session storage should be JSON (with explicit types and less conversion, using standard routines)
/* try to get claims from the userinfo endpoint using the provided access token */
if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub, access_token,
&result, userinfo_jwt) == FALSE) {
/* see if we have an existing session and we are refreshing the user info claims */
if (session != NULL) {
/* first call to user info endpoint failed, but the access token may have just expired, so refresh it */
if (oidc_refresh_access_token(r, c, session, provider,
&refreshed_access_token) == TRUE) {
/* try again with the new access token */
if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub,
refreshed_access_token, &result, userinfo_jwt) == FALSE) {
oidc_error(r,
"resolving user info claims with the refreshed access token failed, nothing will be stored in the session");
result = NULL;
}
} else {
oidc_warn(r,
"refreshing access token failed, claims will not be retrieved/refreshed from the userinfo endpoint");
result = NULL;
}
} else {
oidc_error(r,
"resolving user info claims with the existing/provided access token failed, nothing will be stored in the session");
result = NULL;
}
}
return result;
}
/*
* get (new) claims from the userinfo endpoint
*/
static apr_byte_t oidc_refresh_claims_from_userinfo_endpoint(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session) {
oidc_provider_t *provider = NULL;
const char *claims = NULL;
const char *access_token = NULL;
char *userinfo_jwt = NULL;
/* get the current provider info */
if (oidc_get_provider_from_session(r, cfg, session, &provider) == FALSE)
return FALSE;
/* see if we can do anything here, i.e. we have a userinfo endpoint and a refresh interval is configured */
apr_time_t interval = apr_time_from_sec(
provider->userinfo_refresh_interval);
oidc_debug(r, "userinfo_endpoint=%s, interval=%d",
provider->userinfo_endpoint_url,
provider->userinfo_refresh_interval);
if ((provider->userinfo_endpoint_url != NULL) && (interval > 0)) {
/* get the last refresh timestamp from the session info */
apr_time_t last_refresh = oidc_session_get_userinfo_last_refresh(r,
session);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(last_refresh + interval - apr_time_now()));
/* see if we need to refresh again */
if (last_refresh + interval < apr_time_now()) {
/* get the current access token */
access_token = oidc_session_get_access_token(r, session);
/* retrieve the current claims */
claims = oidc_retrieve_claims_from_userinfo_endpoint(r, cfg,
provider, access_token, session, NULL, &userinfo_jwt);
/* store claims resolved from userinfo endpoint */
oidc_store_userinfo_claims(r, cfg, session, provider, claims,
userinfo_jwt);
/* indicated something changed */
return TRUE;
}
}
return FALSE;
}
/*
* copy the claims and id_token from the session to the request state and optionally return them
*/
static void oidc_copy_tokens_to_request_state(request_rec *r,
oidc_session_t *session, const char **s_id_token, const char **s_claims) {
const char *id_token = oidc_session_get_idtoken_claims(r, session);
const char *claims = oidc_session_get_userinfo_claims(r, session);
oidc_debug(r, "id_token=%s claims=%s", id_token, claims);
if (id_token != NULL) {
oidc_request_state_set(r, OIDC_REQUEST_STATE_KEY_IDTOKEN, id_token);
if (s_id_token != NULL)
*s_id_token = id_token;
}
if (claims != NULL) {
oidc_request_state_set(r, OIDC_REQUEST_STATE_KEY_CLAIMS, claims);
if (s_claims != NULL)
*s_claims = claims;
}
}
/*
* pass refresh_token, access_token and access_token_expires as headers/environment variables to the application
*/
static apr_byte_t oidc_session_pass_tokens_and_save(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session, apr_byte_t needs_save) {
apr_byte_t pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
apr_byte_t pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
/* set the refresh_token in the app headers/variables, if enabled for this location/directory */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if ((oidc_cfg_dir_pass_refresh_token(r) != 0) && (refresh_token != NULL)) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_REFRESH_TOKEN, refresh_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* set the access_token in the app headers/variables */
const char *access_token = oidc_session_get_access_token(r, session);
if (access_token != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ACCESS_TOKEN, access_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* set the expiry timestamp in the app headers/variables */
const char *access_token_expires = oidc_session_get_access_token_expires(r,
session);
if (access_token_expires != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ACCESS_TOKEN_EXP,
access_token_expires,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/*
* reset the session inactivity timer
* but only do this once per 10% of the inactivity timeout interval (with a max to 60 seconds)
* for performance reasons
*
* now there's a small chance that the session ends 10% (or a minute) earlier than configured/expected
* cq. when there's a request after a recent save (so no update) and then no activity happens until
* a request comes in just before the session should expire
* ("recent" and "just before" refer to 10%-with-a-max-of-60-seconds of the inactivity interval after
* the start/last-update and before the expiry of the session respectively)
*
* this is be deemed acceptable here because of performance gain
*/
apr_time_t interval = apr_time_from_sec(cfg->session_inactivity_timeout);
apr_time_t now = apr_time_now();
apr_time_t slack = interval / 10;
if (slack > apr_time_from_sec(60))
slack = apr_time_from_sec(60);
if (session->expiry - now < interval - slack) {
session->expiry = now + interval;
needs_save = TRUE;
}
/* log message about session expiry */
oidc_log_session_expires(r, "session inactivity timeout", session->expiry);
/* check if something was updated in the session and we need to save it again */
if (needs_save)
if (oidc_session_save(r, session, FALSE) == FALSE)
return FALSE;
return TRUE;
}
static apr_byte_t oidc_refresh_access_token_before_expiry(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session, int ttl_minimum, int logout_on_error) {
const char *s_access_token_expires = NULL;
apr_time_t t_expires = -1;
oidc_provider_t *provider = NULL;
oidc_debug(r, "ttl_minimum=%d", ttl_minimum);
if (ttl_minimum < 0)
return FALSE;
s_access_token_expires = oidc_session_get_access_token_expires(r, session);
if (s_access_token_expires == NULL) {
oidc_debug(r,
"no access token expires_in stored in the session (i.e. returned from in the authorization response), so cannot refresh the access token based on TTL requirement");
return FALSE;
}
if (oidc_session_get_refresh_token(r, session) == NULL) {
oidc_debug(r,
"no refresh token stored in the session, so cannot refresh the access token based on TTL requirement");
return FALSE;
}
if (sscanf(s_access_token_expires, "%" APR_TIME_T_FMT, &t_expires) != 1) {
oidc_error(r, "could not parse s_access_token_expires %s",
s_access_token_expires);
return FALSE;
}
t_expires = apr_time_from_sec(t_expires - ttl_minimum);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(t_expires - apr_time_now()));
if (t_expires > apr_time_now())
return FALSE;
if (oidc_get_provider_from_session(r, cfg, session, &provider) == FALSE)
return FALSE;
if (oidc_refresh_access_token(r, cfg, session, provider,
NULL) == FALSE) {
oidc_warn(r, "access_token could not be refreshed, logout=%d", logout_on_error & OIDC_LOGOUT_ON_ERROR_REFRESH);
if (logout_on_error & OIDC_LOGOUT_ON_ERROR_REFRESH)
return ERROR;
else
return FALSE;
}
return TRUE;
}
/*
* handle the case where we have identified an existing authentication session for a user
*/
static int oidc_handle_existing_session(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
oidc_debug(r, "enter");
/* track if the session needs to be updated/saved into the cache */
apr_byte_t needs_save = FALSE;
/* set the user in the main request for further (incl. sub-request) processing */
r->user = apr_pstrdup(r->pool, session->remote_user);
oidc_debug(r, "set remote_user to \"%s\"", r->user);
/* get the header name in which the remote user name needs to be passed */
char *authn_header = oidc_cfg_dir_authn_header(r);
apr_byte_t pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
apr_byte_t pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
/* verify current cookie domain against issued cookie domain */
if (oidc_check_cookie_domain(r, cfg, session) == FALSE)
return HTTP_UNAUTHORIZED;
/* check if the maximum session duration was exceeded */
int rc = oidc_check_max_session_duration(r, cfg, session);
if (rc != OK)
return rc;
/* if needed, refresh the access token */
needs_save = oidc_refresh_access_token_before_expiry(r, cfg, session,
oidc_cfg_dir_refresh_access_token_before_expiry(r),
oidc_cfg_dir_logout_on_error_refresh(r));
if (needs_save == ERROR)
return oidc_handle_logout_request(r, cfg, session, cfg->default_slo_url);
/* if needed, refresh claims from the user info endpoint */
if (oidc_refresh_claims_from_userinfo_endpoint(r, cfg, session) == TRUE)
needs_save = TRUE;
/*
* we're going to pass the information that we have to the application,
* but first we need to scrub the headers that we're going to use for security reasons
*/
oidc_scrub_headers(r);
/* set the user authentication HTTP header if set and required */
if ((r->user != NULL) && (authn_header != NULL))
oidc_util_hdr_in_set(r, authn_header, r->user);
const char *s_claims = NULL;
const char *s_id_token = NULL;
/* copy id_token and claims from session to request state and obtain their values */
oidc_copy_tokens_to_request_state(r, session, &s_id_token, &s_claims);
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_CLAIMS)) {
/* set the userinfo claims in the app headers */
if (oidc_set_app_claims(r, cfg, session, s_claims) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_JSON_OBJECT)) {
/* pass the userinfo JSON object to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_USERINFO_JSON, s_claims,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_JWT)) {
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* get the compact serialized JWT from the session */
const char *s_userinfo_jwt = oidc_session_get_userinfo_jwt(r,
session);
if (s_userinfo_jwt != NULL) {
/* pass the compact serialized JWT to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_USERINFO_JWT,
s_userinfo_jwt,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
} else {
oidc_debug(r,
"configured to pass userinfo in a JWT, but no such JWT was found in the session (probably no such JWT was returned from the userinfo endpoint)");
}
} else {
oidc_error(r,
"session type \"client-cookie\" does not allow storing/passing a userinfo JWT; use \"" OIDCSessionType " server-cache\" for that");
}
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_CLAIMS)) {
/* set the id_token in the app headers */
if (oidc_set_app_claims(r, cfg, session, s_id_token) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_PAYLOAD)) {
/* pass the id_token JSON object to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ID_TOKEN_PAYLOAD, s_id_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_SERIALIZED)) {
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* get the compact serialized JWT from the session */
const char *s_id_token = oidc_session_get_idtoken(r, session);
/* pass the compact serialized JWT to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ID_TOKEN, s_id_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
} else {
oidc_error(r,
"session type \"client-cookie\" does not allow storing/passing the id_token; use \"" OIDCSessionType " server-cache\" for that");
}
}
/* pass the at, rt and at expiry to the application, possibly update the session expiry and save the session */
if (oidc_session_pass_tokens_and_save(r, cfg, session, needs_save) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* return "user authenticated" status */
return OK;
}
/*
* helper function for basic/implicit client flows upon receiving an authorization response:
* check that it matches the state stored in the browser and return the variables associated
* with the state, such as original_url and OP oidc_provider_t pointer.
*/
static apr_byte_t oidc_authorization_response_match_state(request_rec *r,
oidc_cfg *c, const char *state, struct oidc_provider_t **provider,
oidc_proto_state_t **proto_state) {
oidc_debug(r, "enter (state=%s)", state);
if ((state == NULL) || (apr_strnatcmp(state, "") == 0)) {
oidc_error(r, "state parameter is not set");
return FALSE;
}
/* check the state parameter against what we stored in a cookie */
if (oidc_restore_proto_state(r, c, state, proto_state) == FALSE) {
oidc_error(r, "unable to restore state");
return FALSE;
}
*provider = oidc_get_provider_for_issuer(r, c,
oidc_proto_state_get_issuer(*proto_state), FALSE);
return (*provider != NULL);
}
/*
* redirect the browser to the session logout endpoint
*/
static int oidc_session_redirect_parent_window_to_logout(request_rec *r,
oidc_cfg *c) {
oidc_debug(r, "enter");
char *java_script = apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" window.top.location.href = '%s?session=logout';\n"
" </script>\n", oidc_get_redirect_uri(r, c));
return oidc_util_html_send(r, "Redirecting...", java_script, NULL, NULL,
OK);
}
/*
* handle an error returned by the OP
*/
static int oidc_authorization_response_error(request_rec *r, oidc_cfg *c,
oidc_proto_state_t *proto_state, const char *error,
const char *error_description) {
const char *prompt = oidc_proto_state_get_prompt(proto_state);
if (prompt != NULL)
prompt = apr_pstrdup(r->pool, prompt);
oidc_proto_state_destroy(proto_state);
if ((prompt != NULL)
&& (apr_strnatcmp(prompt, OIDC_PROTO_PROMPT_NONE) == 0)) {
return oidc_session_redirect_parent_window_to_logout(r, c);
}
return oidc_util_html_send_error(r, c->error_template,
apr_psprintf(r->pool, "OpenID Connect Provider error: %s", error),
error_description, OK);
}
/*
* get the r->user for this request based on the configuration for OIDC/OAuth
*/
apr_byte_t oidc_get_remote_user(request_rec *r, const char *claim_name,
const char *reg_exp, const char *replace, json_t *json,
char **request_user) {
/* get the claim value from the JSON object */
json_t *username = json_object_get(json, claim_name);
if ((username == NULL) || (!json_is_string(username))) {
oidc_warn(r, "JSON object did not contain a \"%s\" string", claim_name);
return FALSE;
}
*request_user = apr_pstrdup(r->pool, json_string_value(username));
if (reg_exp != NULL) {
char *error_str = NULL;
if (replace == NULL) {
if (oidc_util_regexp_first_match(r->pool, *request_user, reg_exp,
request_user, &error_str) == FALSE) {
oidc_error(r, "oidc_util_regexp_first_match failed: %s",
error_str);
*request_user = NULL;
return FALSE;
}
} else if (oidc_util_regexp_substitute(r->pool, *request_user, reg_exp,
replace, request_user, &error_str) == FALSE) {
oidc_error(r, "oidc_util_regexp_substitute failed: %s", error_str);
*request_user = NULL;
return FALSE;
}
}
return TRUE;
}
/*
* set the unique user identifier that will be propagated in the Apache r->user and REMOTE_USER variables
*/
static apr_byte_t oidc_set_request_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, oidc_jwt_t *jwt, const char *s_claims) {
char *issuer = provider->issuer;
char *claim_name = apr_pstrdup(r->pool, c->remote_user_claim.claim_name);
int n = strlen(claim_name);
apr_byte_t post_fix_with_issuer = (claim_name[n - 1] == OIDC_CHAR_AT);
if (post_fix_with_issuer == TRUE) {
claim_name[n - 1] = '\0';
issuer =
(strstr(issuer, "https://") == NULL) ?
apr_pstrdup(r->pool, issuer) :
apr_pstrdup(r->pool, issuer + strlen("https://"));
}
/* extract the username claim (default: "sub") from the id_token payload or user claims */
apr_byte_t rc = FALSE;
char *remote_user = NULL;
json_t *claims = NULL;
oidc_util_decode_json_object(r, s_claims, &claims);
if (claims == NULL) {
rc = oidc_get_remote_user(r, claim_name, c->remote_user_claim.reg_exp,
c->remote_user_claim.replace, jwt->payload.value.json,
&remote_user);
} else {
oidc_util_json_merge(r, jwt->payload.value.json, claims);
rc = oidc_get_remote_user(r, claim_name, c->remote_user_claim.reg_exp,
c->remote_user_claim.replace, claims, &remote_user);
json_decref(claims);
}
if ((rc == FALSE) || (remote_user == NULL)) {
oidc_error(r,
"" OIDCRemoteUserClaim "is set to \"%s\", but could not set the remote user based on the requested claim \"%s\" and the available claims for the user",
c->remote_user_claim.claim_name, claim_name);
return FALSE;
}
if (post_fix_with_issuer == TRUE)
remote_user = apr_psprintf(r->pool, "%s%s%s", remote_user, OIDC_STR_AT,
issuer);
r->user = apr_pstrdup(r->pool, remote_user);
oidc_debug(r, "set remote_user to \"%s\" based on claim: \"%s\"%s", r->user,
c->remote_user_claim.claim_name,
c->remote_user_claim.reg_exp ?
apr_psprintf(r->pool,
" and expression: \"%s\" and replace string: \"%s\"",
c->remote_user_claim.reg_exp,
c->remote_user_claim.replace) :
"");
return TRUE;
}
static char *oidc_make_sid_iss_unique(request_rec *r, const char *sid,
const char *issuer) {
return apr_psprintf(r->pool, "%s@%s", sid, issuer);
}
/*
* store resolved information in the session
*/
static apr_byte_t oidc_save_in_session(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider,
const char *remoteUser, const char *id_token, oidc_jwt_t *id_token_jwt,
const char *claims, const char *access_token, const int expires_in,
const char *refresh_token, const char *session_state, const char *state,
const char *original_url, const char *userinfo_jwt) {
/* store the user in the session */
session->remote_user = remoteUser;
/* set the session expiry to the inactivity timeout */
session->expiry =
apr_time_now() + apr_time_from_sec(c->session_inactivity_timeout);
/* store the claims payload in the id_token for later reference */
oidc_session_set_idtoken_claims(r, session,
id_token_jwt->payload.value.str);
if (c->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* store the compact serialized representation of the id_token for later reference */
oidc_session_set_idtoken(r, session, id_token);
}
/* store the issuer in the session (at least needed for session mgmt and token refresh */
oidc_session_set_issuer(r, session, provider->issuer);
/* store the state and original URL in the session for handling browser-back more elegantly */
oidc_session_set_request_state(r, session, state);
oidc_session_set_original_url(r, session, original_url);
if ((session_state != NULL) && (provider->check_session_iframe != NULL)) {
/* store the session state and required parameters session management */
oidc_session_set_session_state(r, session, session_state);
oidc_debug(r,
"session management enabled: stored session_state (%s), check_session_iframe (%s) and client_id (%s) in the session",
session_state, provider->check_session_iframe,
provider->client_id);
} else if (provider->check_session_iframe == NULL) {
oidc_debug(r,
"session management disabled: \"check_session_iframe\" is not set in provider configuration");
} else {
oidc_debug(r,
"session management disabled: no \"session_state\" value is provided in the authentication response even though \"check_session_iframe\" (%s) is set in the provider configuration",
provider->check_session_iframe);
}
/* store claims resolved from userinfo endpoint */
oidc_store_userinfo_claims(r, c, session, provider, claims, userinfo_jwt);
/* see if we have an access_token */
if (access_token != NULL) {
/* store the access_token in the session context */
oidc_session_set_access_token(r, session, access_token);
/* store the associated expires_in value */
oidc_session_set_access_token_expires(r, session, expires_in);
/* reset the access token refresh timestamp */
oidc_session_reset_access_token_last_refresh(r, session);
}
/* see if we have a refresh_token */
if (refresh_token != NULL) {
/* store the refresh_token in the session context */
oidc_session_set_refresh_token(r, session, refresh_token);
}
/* store max session duration in the session as a hard cut-off expiry timestamp */
apr_time_t session_expires =
(provider->session_max_duration == 0) ?
apr_time_from_sec(id_token_jwt->payload.exp) :
(apr_time_now()
+ apr_time_from_sec(provider->session_max_duration));
oidc_session_set_session_expires(r, session, session_expires);
oidc_debug(r,
"provider->session_max_duration = %d, session_expires=%" APR_TIME_T_FMT,
provider->session_max_duration, session_expires);
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
/* store the domain for which this session is valid */
oidc_session_set_cookie_domain(r, session,
c->cookie_domain ? c->cookie_domain : oidc_get_current_url_host(r));
char *sid = NULL;
oidc_debug(r, "provider->backchannel_logout_supported=%d",
provider->backchannel_logout_supported);
if (provider->backchannel_logout_supported > 0) {
oidc_jose_get_string(r->pool, id_token_jwt->payload.value.json,
OIDC_CLAIM_SID, FALSE, &sid, NULL);
if (sid == NULL)
sid = id_token_jwt->payload.sub;
session->sid = oidc_make_sid_iss_unique(r, sid, provider->issuer);
}
/* store the session */
return oidc_session_save(r, session, TRUE);
}
/*
* parse the expiry for the access token
*/
static int oidc_parse_expires_in(request_rec *r, const char *expires_in) {
if (expires_in != NULL) {
char *ptr = NULL;
long number = strtol(expires_in, &ptr, 10);
if (number <= 0) {
oidc_warn(r,
"could not convert \"expires_in\" value (%s) to a number",
expires_in);
return -1;
}
return number;
}
return -1;
}
/*
* handle the different flows (hybrid, implicit, Authorization Code)
*/
static apr_byte_t oidc_handle_flows(request_rec *r, oidc_cfg *c,
oidc_proto_state_t *proto_state, oidc_provider_t *provider,
apr_table_t *params, const char *response_mode, oidc_jwt_t **jwt) {
apr_byte_t rc = FALSE;
const char *requested_response_type = oidc_proto_state_get_response_type(
proto_state);
/* handle the requested response type/mode */
if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_IDTOKEN_TOKEN)) {
rc = oidc_proto_authorization_response_code_idtoken_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_IDTOKEN)) {
rc = oidc_proto_authorization_response_code_idtoken(r, c, proto_state,
provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_TOKEN)) {
rc = oidc_proto_handle_authorization_response_code_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE)) {
rc = oidc_proto_handle_authorization_response_code(r, c, proto_state,
provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_IDTOKEN_TOKEN)) {
rc = oidc_proto_handle_authorization_response_idtoken_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_IDTOKEN)) {
rc = oidc_proto_handle_authorization_response_idtoken(r, c, proto_state,
provider, params, response_mode, jwt);
} else {
oidc_error(r, "unsupported response type: \"%s\"",
requested_response_type);
}
if ((rc == FALSE) && (*jwt != NULL)) {
oidc_jwt_destroy(*jwt);
*jwt = NULL;
}
return rc;
}
/* handle the browser back on an authorization response */
static apr_byte_t oidc_handle_browser_back(request_rec *r, const char *r_state,
oidc_session_t *session) {
/* see if we have an existing session and browser-back was used */
const char *s_state = NULL, *o_url = NULL;
if (session->remote_user != NULL) {
s_state = oidc_session_get_request_state(r, session);
o_url = oidc_session_get_original_url(r, session);
if ((r_state != NULL) && (s_state != NULL)
&& (apr_strnatcmp(r_state, s_state) == 0)) {
/* log the browser back event detection */
oidc_warn(r,
"browser back detected, redirecting to original URL: %s",
o_url);
/* go back to the URL that he originally tried to access */
oidc_util_hdr_out_location_set(r, o_url);
return TRUE;
}
}
return FALSE;
}
/*
* complete the handling of an authorization response by obtaining, parsing and verifying the
* id_token and storing the authenticated user state in the session
*/
static int oidc_handle_authorization_response(request_rec *r, oidc_cfg *c,
oidc_session_t *session, apr_table_t *params, const char *response_mode) {
oidc_debug(r, "enter, response_mode=%s", response_mode);
oidc_provider_t *provider = NULL;
oidc_proto_state_t *proto_state = NULL;
oidc_jwt_t *jwt = NULL;
/* see if this response came from a browser-back event */
if (oidc_handle_browser_back(r, apr_table_get(params, OIDC_PROTO_STATE),
session) == TRUE)
return HTTP_MOVED_TEMPORARILY;
/* match the returned state parameter against the state stored in the browser */
if (oidc_authorization_response_match_state(r, c,
apr_table_get(params, OIDC_PROTO_STATE), &provider,
&proto_state) == FALSE) {
if (c->default_sso_url != NULL) {
oidc_warn(r,
"invalid authorization response state; a default SSO URL is set, sending the user there: %s",
c->default_sso_url);
oidc_util_hdr_out_location_set(r, c->default_sso_url);
return HTTP_MOVED_TEMPORARILY;
}
oidc_error(r,
"invalid authorization response state and no default SSO URL is set, sending an error...");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if the response is an error response */
if (apr_table_get(params, OIDC_PROTO_ERROR) != NULL)
return oidc_authorization_response_error(r, c, proto_state,
apr_table_get(params, OIDC_PROTO_ERROR),
apr_table_get(params, OIDC_PROTO_ERROR_DESCRIPTION));
/* handle the code, implicit or hybrid flow */
if (oidc_handle_flows(r, c, proto_state, provider, params, response_mode,
&jwt) == FALSE)
return oidc_authorization_response_error(r, c, proto_state,
"Error in handling response type.", NULL);
if (jwt == NULL) {
oidc_error(r, "no id_token was provided");
return oidc_authorization_response_error(r, c, proto_state,
"No id_token was provided.", NULL);
}
int expires_in = oidc_parse_expires_in(r,
apr_table_get(params, OIDC_PROTO_EXPIRES_IN));
char *userinfo_jwt = NULL;
/*
* optionally resolve additional claims against the userinfo endpoint
* parsed claims are not actually used here but need to be parsed anyway for error checking purposes
*/
const char *claims = oidc_retrieve_claims_from_userinfo_endpoint(r, c,
provider, apr_table_get(params, OIDC_PROTO_ACCESS_TOKEN), NULL,
jwt->payload.sub, &userinfo_jwt);
/* restore the original protected URL that the user was trying to access */
const char *original_url = oidc_proto_state_get_original_url(proto_state);
if (original_url != NULL)
original_url = apr_pstrdup(r->pool, original_url);
const char *original_method = oidc_proto_state_get_original_method(
proto_state);
if (original_method != NULL)
original_method = apr_pstrdup(r->pool, original_method);
const char *prompt = oidc_proto_state_get_prompt(proto_state);
/* set the user */
if (oidc_set_request_user(r, c, provider, jwt, claims) == TRUE) {
/* session management: if the user in the new response is not equal to the old one, error out */
if ((prompt != NULL)
&& (apr_strnatcmp(prompt, OIDC_PROTO_PROMPT_NONE) == 0)) {
// TOOD: actually need to compare sub? (need to store it in the session separately then
//const char *sub = NULL;
//oidc_session_get(r, session, "sub", &sub);
//if (apr_strnatcmp(sub, jwt->payload.sub) != 0) {
if (apr_strnatcmp(session->remote_user, r->user) != 0) {
oidc_warn(r,
"user set from new id_token is different from current one");
oidc_jwt_destroy(jwt);
return oidc_authorization_response_error(r, c, proto_state,
"User changed!", NULL);
}
}
/* store resolved information in the session */
if (oidc_save_in_session(r, c, session, provider, r->user,
apr_table_get(params, OIDC_PROTO_ID_TOKEN), jwt, claims,
apr_table_get(params, OIDC_PROTO_ACCESS_TOKEN), expires_in,
apr_table_get(params, OIDC_PROTO_REFRESH_TOKEN),
apr_table_get(params, OIDC_PROTO_SESSION_STATE),
apr_table_get(params, OIDC_PROTO_STATE), original_url,
userinfo_jwt) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
} else {
oidc_error(r, "remote user could not be set");
return oidc_authorization_response_error(r, c, proto_state,
"Remote user could not be set: contact the website administrator",
NULL);
}
/* cleanup */
oidc_proto_state_destroy(proto_state);
oidc_jwt_destroy(jwt);
/* check that we've actually authenticated a user; functions as error handling for oidc_get_remote_user */
if (r->user == NULL)
return HTTP_UNAUTHORIZED;
/* log the successful response */
oidc_debug(r,
"session created and stored, returning to original URL: %s, original method: %s",
original_url, original_method);
/* check whether form post data was preserved; if so restore it */
if (apr_strnatcmp(original_method, OIDC_METHOD_FORM_POST) == 0) {
return oidc_request_post_preserved_restore(r, original_url);
}
/* now we've authenticated the user so go back to the URL that he originally tried to access */
oidc_util_hdr_out_location_set(r, original_url);
/* do the actual redirect to the original URL */
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle an OpenID Connect Authorization Response using the POST (+fragment->POST) response_mode
*/
static int oidc_handle_post_authorization_response(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
oidc_debug(r, "enter");
/* initialize local variables */
char *response_mode = NULL;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if we've got any POST-ed data at all */
if ((apr_table_elts(params)->nelts < 1)
|| ((apr_table_elts(params)->nelts == 1)
&& apr_table_get(params, OIDC_PROTO_RESPONSE_MODE)
&& (apr_strnatcmp(
apr_table_get(params, OIDC_PROTO_RESPONSE_MODE),
OIDC_PROTO_RESPONSE_MODE_FRAGMENT) == 0))) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"You've hit an OpenID Connect Redirect URI with no parameters, this is an invalid request; you should not open this URL in your browser directly, or have the server administrator use a different " OIDCRedirectURI " setting.",
HTTP_INTERNAL_SERVER_ERROR);
}
/* get the parameters */
response_mode = (char *) apr_table_get(params, OIDC_PROTO_RESPONSE_MODE);
/* do the actual implicit work */
return oidc_handle_authorization_response(r, c, session, params,
response_mode ? response_mode : OIDC_PROTO_RESPONSE_MODE_FORM_POST);
}
/*
* handle an OpenID Connect Authorization Response using the redirect response_mode
*/
static int oidc_handle_redirect_authorization_response(request_rec *r,
oidc_cfg *c, oidc_session_t *session) {
oidc_debug(r, "enter");
/* read the parameters from the query string */
apr_table_t *params = apr_table_make(r->pool, 8);
oidc_util_read_form_encoded_params(r, params, r->args);
/* do the actual work */
return oidc_handle_authorization_response(r, c, session, params,
OIDC_PROTO_RESPONSE_MODE_QUERY);
}
/*
* present the user with an OP selection screen
*/
static int oidc_discovery(request_rec *r, oidc_cfg *cfg) {
oidc_debug(r, "enter");
/* obtain the URL we're currently accessing, to be stored in the state/session */
char *current_url = oidc_get_current_url(r);
const char *method = oidc_original_request_method(r, cfg, FALSE);
/* generate CSRF token */
char *csrf = NULL;
if (oidc_proto_generate_nonce(r, &csrf, 8) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
char *path_scopes = oidc_dir_cfg_path_scope(r);
char *path_auth_request_params = oidc_dir_cfg_path_auth_request_params(r);
char *discover_url = oidc_cfg_dir_discover_url(r);
/* see if there's an external discovery page configured */
if (discover_url != NULL) {
/* yes, assemble the parameters for external discovery */
char *url = apr_psprintf(r->pool, "%s%s%s=%s&%s=%s&%s=%s&%s=%s",
discover_url,
strchr(discover_url, OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
OIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url),
OIDC_DISC_RM_PARAM, method,
OIDC_DISC_CB_PARAM,
oidc_util_escape_string(r, oidc_get_redirect_uri(r, cfg)),
OIDC_CSRF_NAME, oidc_util_escape_string(r, csrf));
if (path_scopes != NULL)
url = apr_psprintf(r->pool, "%s&%s=%s", url, OIDC_DISC_SC_PARAM,
oidc_util_escape_string(r, path_scopes));
if (path_auth_request_params != NULL)
url = apr_psprintf(r->pool, "%s&%s=%s", url, OIDC_DISC_AR_PARAM,
oidc_util_escape_string(r, path_auth_request_params));
/* log what we're about to do */
oidc_debug(r, "redirecting to external discovery page: %s", url);
/* set CSRF cookie */
oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1,
cfg->cookie_same_site ?
OIDC_COOKIE_EXT_SAME_SITE_STRICT :
NULL);
/* see if we need to preserve POST parameters through Javascript/HTML5 storage */
if (oidc_post_preserve_javascript(r, url, NULL, NULL) == TRUE)
return OK;
/* do the actual redirect to an external discovery page */
oidc_util_hdr_out_location_set(r, url);
return HTTP_MOVED_TEMPORARILY;
}
/* get a list of all providers configured in the metadata directory */
apr_array_header_t *arr = NULL;
if (oidc_metadata_list(r, cfg, &arr) == FALSE)
return oidc_util_html_send_error(r, cfg->error_template,
"Configuration Error",
"No configured providers found, contact your administrator",
HTTP_UNAUTHORIZED);
/* assemble a where-are-you-from IDP discovery HTML page */
const char *s = " <h3>Select your OpenID Connect Identity Provider</h3>\n";
/* list all configured providers in there */
int i;
for (i = 0; i < arr->nelts; i++) {
const char *issuer = ((const char**) arr->elts)[i];
// TODO: html escape (especially & character)
char *href = apr_psprintf(r->pool,
"%s?%s=%s&%s=%s&%s=%s&%s=%s",
oidc_get_redirect_uri(r, cfg), OIDC_DISC_OP_PARAM,
oidc_util_escape_string(r, issuer),
OIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url),
OIDC_DISC_RM_PARAM, method,
OIDC_CSRF_NAME, csrf);
if (path_scopes != NULL)
href = apr_psprintf(r->pool, "%s&%s=%s", href,
OIDC_DISC_SC_PARAM, oidc_util_escape_string(r, path_scopes));
if (path_auth_request_params != NULL)
href = apr_psprintf(r->pool, "%s&%s=%s", href,
OIDC_DISC_AR_PARAM,
oidc_util_escape_string(r, path_auth_request_params));
char *display =
(strstr(issuer, "https://") == NULL) ?
apr_pstrdup(r->pool, issuer) :
apr_pstrdup(r->pool, issuer + strlen("https://"));
/* strip port number */
//char *p = strstr(display, ":");
//if (p != NULL) *p = '\0';
/* point back to the redirect_uri, where the selection is handled, with an IDP selection and return_to URL */
s = apr_psprintf(r->pool, "%s<p><a href=\"%s\">%s</a></p>\n", s, href,
display);
}
/* add an option to enter an account or issuer name for dynamic OP discovery */
s = apr_psprintf(r->pool, "%s<form method=\"get\" action=\"%s\">\n", s,
oidc_get_redirect_uri(r, cfg));
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_RT_PARAM, current_url);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_RM_PARAM, method);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_CSRF_NAME, csrf);
if (path_scopes != NULL)
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_SC_PARAM, path_scopes);
if (path_auth_request_params != NULL)
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_AR_PARAM, path_auth_request_params);
s =
apr_psprintf(r->pool,
"%s<p>Or enter your account name (eg. "mike@seed.gluu.org", or an IDP identifier (eg. "mitreid.org"):</p>\n",
s);
s = apr_psprintf(r->pool,
"%s<p><input type=\"text\" name=\"%s\" value=\"%s\"></p>\n", s,
OIDC_DISC_OP_PARAM, "");
s = apr_psprintf(r->pool,
"%s<p><input type=\"submit\" value=\"Submit\"></p>\n", s);
s = apr_psprintf(r->pool, "%s</form>\n", s);
oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1,
cfg->cookie_same_site ? OIDC_COOKIE_EXT_SAME_SITE_STRICT : NULL);
char *javascript = NULL, *javascript_method = NULL;
char *html_head =
"<style type=\"text/css\">body {text-align: center}</style>";
if (oidc_post_preserve_javascript(r, NULL, &javascript,
&javascript_method) == TRUE)
html_head = apr_psprintf(r->pool, "%s%s", html_head, javascript);
/* now send the HTML contents to the user agent */
return oidc_util_html_send(r, "OpenID Connect Provider Discovery",
html_head, javascript_method, s, OK);
}
/*
* authenticate the user to the selected OP, if the OP is not selected yet perform discovery first
*/
static int oidc_authenticate_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, const char *original_url,
const char *login_hint, const char *id_token_hint, const char *prompt,
const char *auth_request_params, const char *path_scope) {
oidc_debug(r, "enter");
if (provider == NULL) {
// TODO: should we use an explicit redirect to the discovery endpoint (maybe a "discovery" param to the redirect_uri)?
if (c->metadata_dir != NULL)
return oidc_discovery(r, c);
/* we're not using multiple OP's configured in a metadata directory, pick the statically configured OP */
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
/* generate the random nonce value that correlates requests and responses */
char *nonce = NULL;
if (oidc_proto_generate_nonce(r, &nonce, OIDC_PROTO_NONCE_LENGTH) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
char *pkce_state = NULL;
char *code_challenge = NULL;
if ((oidc_util_spaced_string_contains(r->pool, provider->response_type,
OIDC_PROTO_CODE) == TRUE) && (provider->pkce != NULL)) {
/* generate the code verifier value that correlates authorization requests and code exchange requests */
if (provider->pkce->state(r, &pkce_state) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* generate the PKCE code challenge */
if (provider->pkce->challenge(r, pkce_state, &code_challenge) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
/* create the state between request/response */
oidc_proto_state_t *proto_state = oidc_proto_state_new();
oidc_proto_state_set_original_url(proto_state, original_url);
oidc_proto_state_set_original_method(proto_state,
oidc_original_request_method(r, c, TRUE));
oidc_proto_state_set_issuer(proto_state, provider->issuer);
oidc_proto_state_set_response_type(proto_state, provider->response_type);
oidc_proto_state_set_nonce(proto_state, nonce);
oidc_proto_state_set_timestamp_now(proto_state);
if (provider->response_mode)
oidc_proto_state_set_response_mode(proto_state,
provider->response_mode);
if (prompt)
oidc_proto_state_set_prompt(proto_state, prompt);
if (pkce_state)
oidc_proto_state_set_pkce_state(proto_state, pkce_state);
/* get a hash value that fingerprints the browser concatenated with the random input */
char *state = oidc_get_browser_state_hash(r, nonce);
/*
* create state that restores the context when the authorization response comes in
* and cryptographically bind it to the browser
*/
int rc = oidc_authorization_request_set_cookie(r, c, state, proto_state);
if (rc != HTTP_OK) {
oidc_proto_state_destroy(proto_state);
return rc;
}
/*
* printout errors if Cookie settings are not going to work
* TODO: separate this code out into its own function
*/
apr_uri_t o_uri;
memset(&o_uri, 0, sizeof(apr_uri_t));
apr_uri_t r_uri;
memset(&r_uri, 0, sizeof(apr_uri_t));
apr_uri_parse(r->pool, original_url, &o_uri);
apr_uri_parse(r->pool, oidc_get_redirect_uri(r, c), &r_uri);
if ((apr_strnatcmp(o_uri.scheme, r_uri.scheme) != 0)
&& (apr_strnatcmp(r_uri.scheme, "https") == 0)) {
oidc_error(r,
"the URL scheme (%s) of the configured " OIDCRedirectURI " does not match the URL scheme of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!",
r_uri.scheme, o_uri.scheme);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
if (c->cookie_domain == NULL) {
if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
char *p = strstr(o_uri.hostname, r_uri.hostname);
if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
oidc_error(r,
"the URL hostname (%s) of the configured " OIDCRedirectURI " does not match the URL hostname of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!",
r_uri.hostname, o_uri.hostname);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
} else {
if (!oidc_util_cookie_domain_valid(r_uri.hostname, c->cookie_domain)) {
oidc_error(r,
"the domain (%s) configured in " OIDCCookieDomain " does not match the URL hostname (%s) of the URL being accessed (%s): setting \"state\" and \"session\" cookies will not work!!",
c->cookie_domain, o_uri.hostname, original_url);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
/* send off to the OpenID Connect Provider */
// TODO: maybe show intermediate/progress screen "redirecting to"
return oidc_proto_authorization_request(r, provider, login_hint,
oidc_get_redirect_uri_iss(r, c, provider), state, proto_state,
id_token_hint, code_challenge, auth_request_params, path_scope);
}
/*
* check if the target_link_uri matches to configuration settings to prevent an open redirect
*/
static int oidc_target_link_uri_matches_configuration(request_rec *r,
oidc_cfg *cfg, const char *target_link_uri) {
apr_uri_t o_uri;
apr_uri_parse(r->pool, target_link_uri, &o_uri);
if (o_uri.hostname == NULL) {
oidc_error(r,
"could not parse the \"target_link_uri\" (%s) in to a valid URL: aborting.",
target_link_uri);
return FALSE;
}
apr_uri_t r_uri;
apr_uri_parse(r->pool, oidc_get_redirect_uri(r, cfg), &r_uri);
if (cfg->cookie_domain == NULL) {
/* cookie_domain set: see if the target_link_uri matches the redirect_uri host (because the session cookie will be set host-wide) */
if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
char *p = strstr(o_uri.hostname, r_uri.hostname);
if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
oidc_error(r,
"the URL hostname (%s) of the configured " OIDCRedirectURI " does not match the URL hostname of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
r_uri.hostname, o_uri.hostname);
return FALSE;
}
}
} else {
/* cookie_domain set: see if the target_link_uri is within the cookie_domain */
char *p = strstr(o_uri.hostname, cfg->cookie_domain);
if ((p == NULL) || (apr_strnatcmp(cfg->cookie_domain, p) != 0)) {
oidc_error(r,
"the domain (%s) configured in " OIDCCookieDomain " does not match the URL hostname (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.hostname, target_link_uri);
return FALSE;
}
}
/* see if the cookie_path setting matches the target_link_uri path */
char *cookie_path = oidc_cfg_dir_cookie_path(r);
if (cookie_path != NULL) {
char *p = (o_uri.path != NULL) ? strstr(o_uri.path, cookie_path) : NULL;
if ((p == NULL) || (p != o_uri.path)) {
oidc_error(r,
"the path (%s) configured in " OIDCCookiePath " does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.path, target_link_uri);
return FALSE;
} else if (strlen(o_uri.path) > strlen(cookie_path)) {
int n = strlen(cookie_path);
if (cookie_path[n - 1] == OIDC_CHAR_FORWARD_SLASH)
n--;
if (o_uri.path[n] != OIDC_CHAR_FORWARD_SLASH) {
oidc_error(r,
"the path (%s) configured in " OIDCCookiePath " does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.path, target_link_uri);
return FALSE;
}
}
}
return TRUE;
}
/*
* handle a response from an IDP discovery page and/or handle 3rd-party initiated SSO
*/
static int oidc_handle_discovery_response(request_rec *r, oidc_cfg *c) {
/* variables to hold the values returned in the response */
char *issuer = NULL, *target_link_uri = NULL, *login_hint = NULL,
*auth_request_params = NULL, *csrf_cookie, *csrf_query = NULL,
*user = NULL, *path_scopes;
oidc_provider_t *provider = NULL;
oidc_util_get_request_parameter(r, OIDC_DISC_OP_PARAM, &issuer);
oidc_util_get_request_parameter(r, OIDC_DISC_USER_PARAM, &user);
oidc_util_get_request_parameter(r, OIDC_DISC_RT_PARAM, &target_link_uri);
oidc_util_get_request_parameter(r, OIDC_DISC_LH_PARAM, &login_hint);
oidc_util_get_request_parameter(r, OIDC_DISC_SC_PARAM, &path_scopes);
oidc_util_get_request_parameter(r, OIDC_DISC_AR_PARAM,
&auth_request_params);
oidc_util_get_request_parameter(r, OIDC_CSRF_NAME, &csrf_query);
csrf_cookie = oidc_util_get_cookie(r, OIDC_CSRF_NAME);
/* do CSRF protection if not 3rd party initiated SSO */
if (csrf_cookie) {
/* clean CSRF cookie */
oidc_util_set_cookie(r, OIDC_CSRF_NAME, "", 0, NULL);
/* compare CSRF cookie value with query parameter value */
if ((csrf_query == NULL)
|| apr_strnatcmp(csrf_query, csrf_cookie) != 0) {
oidc_warn(r,
"CSRF protection failed, no Discovery and dynamic client registration will be allowed");
csrf_cookie = NULL;
}
}
// TODO: trim issuer/accountname/domain input and do more input validation
oidc_debug(r,
"issuer=\"%s\", target_link_uri=\"%s\", login_hint=\"%s\", user=\"%s\"",
issuer, target_link_uri, login_hint, user);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"SSO to this module without specifying a \"target_link_uri\" parameter is not possible because " OIDCDefaultURL " is not set.",
HTTP_INTERNAL_SERVER_ERROR);
}
target_link_uri = c->default_sso_url;
}
/* do open redirect prevention */
if (oidc_target_link_uri_matches_configuration(r, c,
target_link_uri) == FALSE) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"\"target_link_uri\" parameter does not match configuration settings, aborting to prevent an open redirect.",
HTTP_UNAUTHORIZED);
}
/* see if this is a static setup */
if (c->metadata_dir == NULL) {
if ((oidc_provider_static_config(r, c, &provider) == TRUE)
&& (issuer != NULL)) {
if (apr_strnatcmp(provider->issuer, issuer) != 0) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
apr_psprintf(r->pool,
"The \"iss\" value must match the configured providers' one (%s != %s).",
issuer, c->provider.issuer),
HTTP_INTERNAL_SERVER_ERROR);
}
}
return oidc_authenticate_user(r, c, NULL, target_link_uri, login_hint,
NULL, NULL, auth_request_params, path_scopes);
}
/* find out if the user entered an account name or selected an OP manually */
if (user != NULL) {
if (login_hint == NULL)
login_hint = apr_pstrdup(r->pool, user);
/* normalize the user identifier */
if (strstr(user, "https://") != user)
user = apr_psprintf(r->pool, "https://%s", user);
/* got an user identifier as input, perform OP discovery with that */
if (oidc_proto_url_based_discovery(r, c, user, &issuer) == FALSE) {
/* something did not work out, show a user facing error */
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"Could not resolve the provided user identifier to an OpenID Connect provider; check your syntax.",
HTTP_NOT_FOUND);
}
/* issuer is set now, so let's continue as planned */
} else if (strstr(issuer, OIDC_STR_AT) != NULL) {
if (login_hint == NULL) {
login_hint = apr_pstrdup(r->pool, issuer);
//char *p = strstr(issuer, OIDC_STR_AT);
//*p = '\0';
}
/* got an account name as input, perform OP discovery with that */
if (oidc_proto_account_based_discovery(r, c, issuer, &issuer) == FALSE) {
/* something did not work out, show a user facing error */
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"Could not resolve the provided account name to an OpenID Connect provider; check your syntax.",
HTTP_NOT_FOUND);
}
/* issuer is set now, so let's continue as planned */
}
/* strip trailing '/' */
int n = strlen(issuer);
if (issuer[n - 1] == OIDC_CHAR_FORWARD_SLASH)
issuer[n - 1] = '\0';
/* try and get metadata from the metadata directories for the selected OP */
if ((oidc_metadata_get(r, c, issuer, &provider, csrf_cookie != NULL) == TRUE)
&& (provider != NULL)) {
/* now we've got a selected OP, send the user there to authenticate */
return oidc_authenticate_user(r, c, provider, target_link_uri,
login_hint, NULL, NULL, auth_request_params, path_scopes);
}
/* something went wrong */
return oidc_util_html_send_error(r, c->error_template, "Invalid Request",
"Could not find valid provider metadata for the selected OpenID Connect provider; contact the administrator",
HTTP_NOT_FOUND);
}
static apr_uint32_t oidc_transparent_pixel[17] = { 0x474e5089, 0x0a1a0a0d,
0x0d000000, 0x52444849, 0x01000000, 0x01000000, 0x00000408, 0x0c1cb500,
0x00000002, 0x4144490b, 0x639c7854, 0x0000cffa, 0x02010702, 0x71311c9a,
0x00000000, 0x444e4549, 0x826042ae };
static apr_byte_t oidc_is_front_channel_logout(const char *logout_param_value) {
return ((logout_param_value != NULL)
&& ((apr_strnatcmp(logout_param_value,
OIDC_GET_STYLE_LOGOUT_PARAM_VALUE) == 0)
|| (apr_strnatcmp(logout_param_value,
OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0)));
}
static apr_byte_t oidc_is_back_channel_logout(const char *logout_param_value) {
return ((logout_param_value != NULL) && (apr_strnatcmp(logout_param_value,
OIDC_BACKCHANNEL_STYLE_LOGOUT_PARAM_VALUE) == 0));
}
/*
* revoke refresh token and access token stored in the session if the
* OP has an RFC 7009 compliant token revocation endpoint
*/
static void oidc_revoke_tokens(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *response = NULL;
char *basic_auth = NULL;
char *bearer_auth = NULL;
apr_table_t *params = NULL;
const char *token = NULL;
oidc_provider_t *provider = NULL;
oidc_debug(r, "enter");
if (oidc_get_provider_from_session(r, c, session, &provider) == FALSE)
goto out;
oidc_debug(r, "revocation_endpoint=%s",
provider->revocation_endpoint_url ?
provider->revocation_endpoint_url : "(null)");
if (provider->revocation_endpoint_url == NULL)
goto out;
params = apr_table_make(r->pool, 4);
// add the token endpoint authentication credentials to the revocation endpoint call...
if (oidc_proto_token_endpoint_auth(r, c, provider->token_endpoint_auth,
provider->client_id, provider->client_secret,
provider->client_signing_keys, provider->token_endpoint_url, params,
NULL, &basic_auth, &bearer_auth) == FALSE)
goto out;
// TODO: use oauth.ssl_validate_server ...
token = oidc_session_get_refresh_token(r, session);
if (token != NULL) {
apr_table_addn(params, "token_type_hint", "refresh_token");
apr_table_addn(params, "token", token);
if (oidc_util_http_post_form(r, provider->revocation_endpoint_url,
params, basic_auth, bearer_auth, c->oauth.ssl_validate_server,
&response, c->http_timeout_long, c->outgoing_proxy,
oidc_dir_cfg_pass_cookies(r), NULL,
NULL) == FALSE) {
oidc_warn(r, "revoking refresh token failed");
}
apr_table_clear(params);
}
token = oidc_session_get_access_token(r, session);
if (token != NULL) {
apr_table_addn(params, "token_type_hint", "access_token");
apr_table_addn(params, "token", token);
if (oidc_util_http_post_form(r, provider->revocation_endpoint_url,
params, basic_auth, bearer_auth, c->oauth.ssl_validate_server,
&response, c->http_timeout_long, c->outgoing_proxy,
oidc_dir_cfg_pass_cookies(r), NULL,
NULL) == FALSE) {
oidc_warn(r, "revoking access token failed");
}
}
out:
oidc_debug(r, "leave");
}
/*
* handle a local logout
*/
static int oidc_handle_logout_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *url) {
oidc_debug(r, "enter (url=%s)", url);
/* if there's no remote_user then there's no (stored) session to kill */
if (session->remote_user != NULL) {
oidc_revoke_tokens(r, c, session);
/* remove session state (cq. cache entry and cookie) */
oidc_session_kill(r, session);
}
/* see if this is the OP calling us */
if (oidc_is_front_channel_logout(url)) {
/* set recommended cache control headers */
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_CACHE_CONTROL,
"no-cache, no-store");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_PRAGMA, "no-cache");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_P3P, "CAO PSA OUR");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_EXPIRES, "0");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_X_FRAME_OPTIONS, "DENY");
/* see if this is PF-PA style logout in which case we return a transparent pixel */
const char *accept = oidc_util_hdr_in_accept_get(r);
if ((apr_strnatcmp(url, OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0)
|| ((accept) && strstr(accept, OIDC_CONTENT_TYPE_IMAGE_PNG))) {
return oidc_util_http_send(r,
(const char *) &oidc_transparent_pixel,
sizeof(oidc_transparent_pixel), OIDC_CONTENT_TYPE_IMAGE_PNG,
OK);
}
/* standard HTTP based logout: should be called in an iframe from the OP */
return oidc_util_html_send(r, "Logged Out", NULL, NULL,
"<p>Logged Out</p>", OK);
}
/* see if we don't need to go somewhere special after killing the session locally */
if (url == NULL)
return oidc_util_html_send(r, "Logged Out", NULL, NULL,
"<p>Logged Out</p>", OK);
/* send the user to the specified where-to-go-after-logout URL */
oidc_util_hdr_out_location_set(r, url);
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle a backchannel logout
*/
#define OIDC_EVENTS_BLOGOUT_KEY "http://schemas.openid.net/event/backchannel-logout"
static int oidc_handle_logout_backchannel(request_rec *r, oidc_cfg *cfg) {
oidc_debug(r, "enter");
const char *logout_token = NULL;
oidc_jwt_t *jwt = NULL;
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
oidc_provider_t *provider = NULL;
char *sid = NULL, *uuid = NULL;
oidc_session_t session;
int rc = HTTP_BAD_REQUEST;
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r,
"could not read POST-ed parameters to the logout endpoint");
goto out;
}
logout_token = apr_table_get(params, OIDC_PROTO_LOGOUT_TOKEN);
if (logout_token == NULL) {
oidc_error(r,
"backchannel lggout endpoint was called but could not find a parameter named \"%s\"",
OIDC_PROTO_LOGOUT_TOKEN);
goto out;
}
// TODO: jwk symmetric key based on provider
// TODO: share more code with regular id_token validation and unsolicited state
if (oidc_jwt_parse(r->pool, logout_token, &jwt,
oidc_util_merge_symmetric_key(r->pool, cfg->private_keys, NULL),
&err) == FALSE) {
oidc_error(r, "oidc_jwt_parse failed: %s", oidc_jose_e2s(r->pool, err));
goto out;
}
provider = oidc_get_provider_for_issuer(r, cfg, jwt->payload.iss, FALSE);
if (provider == NULL) {
oidc_error(r, "no provider found for issuer: %s", jwt->payload.iss);
goto out;
}
// TODO: destroy the JWK used for decryption
jwk = NULL;
if (oidc_util_create_symmetric_key(r, provider->client_secret, 0,
NULL, TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwks_uri_t jwks_uri = { provider->jwks_uri,
provider->jwks_refresh_interval, provider->ssl_validate_server };
if (oidc_proto_jwt_verify(r, cfg, jwt, &jwks_uri,
oidc_util_merge_symmetric_key(r->pool, NULL, jwk)) == FALSE) {
oidc_error(r, "id_token signature could not be validated, aborting");
goto out;
}
// oidc_proto_validate_idtoken would try and require a token binding cnf
// if the policy is set to "required", so don't use that here
if (oidc_proto_validate_jwt(r, jwt, provider->issuer, FALSE, FALSE,
provider->idtoken_iat_slack,
OIDC_TOKEN_BINDING_POLICY_DISABLED) == FALSE)
goto out;
/* verify the "aud" and "azp" values */
if (oidc_proto_validate_aud_and_azp(r, cfg, provider,
&jwt->payload) == FALSE)
goto out;
json_t *events = json_object_get(jwt->payload.value.json,
OIDC_CLAIM_EVENTS);
if (events == NULL) {
oidc_error(r, "\"%s\" claim could not be found in logout token",
OIDC_CLAIM_EVENTS);
goto out;
}
json_t *blogout = json_object_get(events, OIDC_EVENTS_BLOGOUT_KEY);
if (!json_is_object(blogout)) {
oidc_error(r, "\"%s\" object could not be found in \"%s\" claim",
OIDC_EVENTS_BLOGOUT_KEY, OIDC_CLAIM_EVENTS);
goto out;
}
char *nonce = NULL;
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_NONCE, &nonce, NULL);
if (nonce != NULL) {
oidc_error(r,
"rejecting logout request/token since it contains a \"%s\" claim",
OIDC_CLAIM_NONCE);
goto out;
}
char *jti = NULL;
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_JTI, &jti, NULL);
if (jti != NULL) {
char *replay = NULL;
oidc_cache_get_jti(r, jti, &replay);
if (replay != NULL) {
oidc_error(r,
"the \"%s\" value (%s) passed in logout token was found in the cache already; possible replay attack!?",
OIDC_CLAIM_JTI, jti);
goto out;
}
}
/* jti cache duration is the configured replay prevention window for token issuance plus 10 seconds for safety */
apr_time_t jti_cache_duration = apr_time_from_sec(
provider->idtoken_iat_slack * 2 + 10);
/* store it in the cache for the calculated duration */
oidc_cache_set_jti(r, jti, jti, apr_time_now() + jti_cache_duration);
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_EVENTS, &sid, NULL);
// TODO: by-spec we should cater for the fact that "sid" has been provided
// in the id_token returned in the authentication request, but "sub"
// is used in the logout token but that requires a 2nd entry in the
// cache and a separate session "sub" member, ugh; we'll just assume
// that is "sid" is specified in the id_token, the OP will actually use
// this for logout
// (and probably call us multiple times or the same sub if needed)
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_SID, &sid, NULL);
if (sid == NULL)
sid = jwt->payload.sub;
if (sid == NULL) {
oidc_error(r, "no \"sub\" and no \"sid\" claim found in logout token");
goto out;
}
// TODO: when dealing with sub instead of a true sid, we'll be killing all sessions for
// a specific user, across hosts that share the *same* cache backend
// if those hosts haven't been configured with a different OIDCCryptoPassphrase
// - perhaps that's even acceptable since non-memory caching is encrypted by default
// and memory-based caching doesn't suffer from this (different shm segments)?
// - it will result in 400 errors returned from backchannel logout calls to the other hosts...
sid = oidc_make_sid_iss_unique(r, sid, provider->issuer);
oidc_cache_get_sid(r, sid, &uuid);
if (uuid == NULL) {
oidc_error(r,
"could not find session based on sid/sub provided in logout token: %s",
sid);
goto out;
}
// revoke tokens if we can get a handle on those
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
if (oidc_session_load_cache_by_uuid(r, cfg, uuid, &session) != FALSE)
if (oidc_session_extract(r, &session) != FALSE)
oidc_revoke_tokens(r, cfg, &session);
}
// clear the session cache
oidc_cache_set_sid(r, sid, NULL, 0);
oidc_cache_set_session(r, uuid, NULL, 0);
rc = OK;
out:
if (jwk != NULL) {
oidc_jwk_destroy(jwk);
jwk = NULL;
}
if (jwt != NULL) {
oidc_jwt_destroy(jwt);
jwt = NULL;
}
return rc;
}
/*
* perform (single) logout
*/
static int oidc_handle_logout(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
oidc_provider_t *provider = NULL;
/* pickup the command or URL where the user wants to go after logout */
char *url = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_LOGOUT, &url);
oidc_debug(r, "enter (url=%s)", url);
if (oidc_is_front_channel_logout(url)) {
return oidc_handle_logout_request(r, c, session, url);
} else if (oidc_is_back_channel_logout(url)) {
return oidc_handle_logout_backchannel(r, c);
}
if ((url == NULL) || (apr_strnatcmp(url, "") == 0)) {
url = c->default_slo_url;
} else {
/* do input validation on the logout parameter value */
const char *error_description = NULL;
apr_uri_t uri;
if (apr_uri_parse(r->pool, url, &uri) != APR_SUCCESS) {
const char *error_description = apr_psprintf(r->pool,
"Logout URL malformed: %s", url);
oidc_error(r, "%s", error_description);
return oidc_util_html_send_error(r, c->error_template,
"Malformed URL", error_description,
HTTP_INTERNAL_SERVER_ERROR);
}
const char *c_host = oidc_get_current_url_host(r);
if ((uri.hostname != NULL)
&& ((strstr(c_host, uri.hostname) == NULL)
|| (strstr(uri.hostname, c_host) == NULL))) {
error_description =
apr_psprintf(r->pool,
"logout value \"%s\" does not match the hostname of the current request \"%s\"",
apr_uri_unparse(r->pool, &uri, 0), c_host);
oidc_error(r, "%s", error_description);
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request", error_description,
HTTP_INTERNAL_SERVER_ERROR);
}
/* validate the URL to prevent HTTP header splitting */
if (((strstr(url, "\n") != NULL) || strstr(url, "\r") != NULL)) {
error_description =
apr_psprintf(r->pool,
"logout value \"%s\" contains illegal \"\n\" or \"\r\" character(s)",
url);
oidc_error(r, "%s", error_description);
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request", error_description,
HTTP_INTERNAL_SERVER_ERROR);
}
}
oidc_get_provider_from_session(r, c, session, &provider);
if ((provider != NULL) && (provider->end_session_endpoint != NULL)) {
const char *id_token_hint = oidc_session_get_idtoken(r, session);
char *logout_request = apr_pstrdup(r->pool,
provider->end_session_endpoint);
if (id_token_hint != NULL) {
logout_request = apr_psprintf(r->pool, "%s%sid_token_hint=%s",
logout_request, strchr(logout_request ? logout_request : "",
OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
oidc_util_escape_string(r, id_token_hint));
}
if (url != NULL) {
logout_request = apr_psprintf(r->pool,
"%s%spost_logout_redirect_uri=%s", logout_request,
strchr(logout_request ? logout_request : "",
OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
oidc_util_escape_string(r, url));
}
url = logout_request;
}
return oidc_handle_logout_request(r, c, session, url);
}
/*
* handle request for JWKs
*/
int oidc_handle_jwks(request_rec *r, oidc_cfg *c) {
/* pickup requested JWKs type */
// char *jwks_type = NULL;
// oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_JWKS, &jwks_type);
char *jwks = apr_pstrdup(r->pool, "{ \"keys\" : [");
apr_hash_index_t *hi = NULL;
apr_byte_t first = TRUE;
oidc_jose_error_t err;
if (c->public_keys != NULL) {
/* loop over the RSA public keys */
for (hi = apr_hash_first(r->pool, c->public_keys); hi; hi =
apr_hash_next(hi)) {
const char *s_kid = NULL;
oidc_jwk_t *jwk = NULL;
char *s_json = NULL;
apr_hash_this(hi, (const void**) &s_kid, NULL, (void**) &jwk);
if (oidc_jwk_to_json(r->pool, jwk, &s_json, &err) == TRUE) {
jwks = apr_psprintf(r->pool, "%s%s %s ", jwks, first ? "" : ",",
s_json);
first = FALSE;
} else {
oidc_error(r,
"could not convert RSA JWK to JSON using oidc_jwk_to_json: %s",
oidc_jose_e2s(r->pool, err));
}
}
}
// TODO: send stuff if first == FALSE?
jwks = apr_psprintf(r->pool, "%s ] }", jwks);
return oidc_util_http_send(r, jwks, strlen(jwks), OIDC_CONTENT_TYPE_JSON,
OK);
}
static int oidc_handle_session_management_iframe_op(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *check_session_iframe) {
oidc_debug(r, "enter");
oidc_util_hdr_out_location_set(r, check_session_iframe);
return HTTP_MOVED_TEMPORARILY;
}
static int oidc_handle_session_management_iframe_rp(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *client_id,
const char *check_session_iframe) {
oidc_debug(r, "enter");
const char *java_script =
" <script type=\"text/javascript\">\n"
" var targetOrigin = '%s';\n"
" var message = '%s' + ' ' + '%s';\n"
" var timerID;\n"
"\n"
" function checkSession() {\n"
" console.debug('checkSession: posting ' + message + ' to ' + targetOrigin);\n"
" var win = window.parent.document.getElementById('%s').contentWindow;\n"
" win.postMessage( message, targetOrigin);\n"
" }\n"
"\n"
" function setTimer() {\n"
" checkSession();\n"
" timerID = setInterval('checkSession()', %d);\n"
" }\n"
"\n"
" function receiveMessage(e) {\n"
" console.debug('receiveMessage: ' + e.data + ' from ' + e.origin);\n"
" if (e.origin !== targetOrigin ) {\n"
" console.debug('receiveMessage: cross-site scripting attack?');\n"
" return;\n"
" }\n"
" if (e.data != 'unchanged') {\n"
" clearInterval(timerID);\n"
" if (e.data == 'changed') {\n"
" window.location.href = '%s?session=check';\n"
" } else {\n"
" window.location.href = '%s?session=logout';\n"
" }\n"
" }\n"
" }\n"
"\n"
" window.addEventListener('message', receiveMessage, false);\n"
"\n"
" </script>\n";
/* determine the origin for the check_session_iframe endpoint */
char *origin = apr_pstrdup(r->pool, check_session_iframe);
apr_uri_t uri;
apr_uri_parse(r->pool, check_session_iframe, &uri);
char *p = strstr(origin, uri.path);
*p = '\0';
/* the element identifier for the OP iframe */
const char *op_iframe_id = "openidc-op";
/* restore the OP session_state from the session */
const char *session_state = oidc_session_get_session_state(r, session);
if (session_state == NULL) {
oidc_warn(r,
"no session_state found in the session; the OP does probably not support session management!?");
return OK;
}
char *s_poll_interval = NULL;
oidc_util_get_request_parameter(r, "poll", &s_poll_interval);
int poll_interval = s_poll_interval ? strtol(s_poll_interval, NULL, 10) : 0;
if ((poll_interval <= 0) || (poll_interval > 3600 * 24))
poll_interval = 3000;
const char *redirect_uri = oidc_get_redirect_uri(r, c);
java_script = apr_psprintf(r->pool, java_script, origin, client_id,
session_state, op_iframe_id, poll_interval, redirect_uri,
redirect_uri);
return oidc_util_html_send(r, NULL, java_script, "setTimer", NULL, OK);
}
/*
* handle session management request
*/
static int oidc_handle_session_management(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *cmd = NULL;
const char *id_token_hint = NULL;
oidc_provider_t *provider = NULL;
/* get the command passed to the session management handler */
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_SESSION, &cmd);
if (cmd == NULL) {
oidc_error(r, "session management handler called with no command");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if this is a local logout during session management */
if (apr_strnatcmp("logout", cmd) == 0) {
oidc_debug(r,
"[session=logout] calling oidc_handle_logout_request because of session mgmt local logout call.");
return oidc_handle_logout_request(r, c, session, c->default_slo_url);
}
oidc_get_provider_from_session(r, c, session, &provider);
/* see if this is a request for the OP iframe */
if (apr_strnatcmp("iframe_op", cmd) == 0) {
if (provider->check_session_iframe != NULL) {
return oidc_handle_session_management_iframe_op(r, c, session,
provider->check_session_iframe);
}
return HTTP_NOT_FOUND;
}
/* see if this is a request for the RP iframe */
if (apr_strnatcmp("iframe_rp", cmd) == 0) {
if ((provider->client_id != NULL)
&& (provider->check_session_iframe != NULL)) {
return oidc_handle_session_management_iframe_rp(r, c, session,
provider->client_id, provider->check_session_iframe);
}
oidc_debug(r,
"iframe_rp command issued but no client (%s) and/or no check_session_iframe (%s) set",
provider->client_id, provider->check_session_iframe);
return HTTP_NOT_FOUND;
}
/* see if this is a request check the login state with the OP */
if (apr_strnatcmp("check", cmd) == 0) {
id_token_hint = oidc_session_get_idtoken(r, session);
if ((session->remote_user != NULL) && (provider != NULL)) {
/*
* TODO: this doesn't work with per-path provided auth_request_params and scopes
* as oidc_dir_cfg_path_auth_request_params and oidc_dir_cfg_path_scope will pick
* those for the redirect_uri itself; do we need to store those as part of the
* session now?
*/
return oidc_authenticate_user(r, c, provider,
apr_psprintf(r->pool, "%s?session=iframe_rp",
oidc_get_redirect_uri_iss(r, c, provider)), NULL,
id_token_hint, "none",
oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
}
oidc_debug(r,
"[session=check] calling oidc_handle_logout_request because no session found.");
return oidc_session_redirect_parent_window_to_logout(r, c);
}
/* handle failure in fallthrough */
oidc_error(r, "unknown command: %s", cmd);
return HTTP_INTERNAL_SERVER_ERROR;
}
/*
* handle refresh token request
*/
static int oidc_handle_refresh_token_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *return_to = NULL;
char *r_access_token = NULL;
char *error_code = NULL;
/* get the command passed to the session management handler */
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_REFRESH,
&return_to);
oidc_util_get_request_parameter(r, OIDC_PROTO_ACCESS_TOKEN,
&r_access_token);
/* check the input parameters */
if (return_to == NULL) {
oidc_error(r,
"refresh token request handler called with no URL to return to");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (r_access_token == NULL) {
oidc_error(r,
"refresh token request handler called with no access_token parameter");
error_code = "no_access_token";
goto end;
}
const char *s_access_token = oidc_session_get_access_token(r, session);
if (s_access_token == NULL) {
oidc_error(r,
"no existing access_token found in the session, nothing to refresh");
error_code = "no_access_token_exists";
goto end;
}
/* compare the access_token parameter used for XSRF protection */
if (apr_strnatcmp(s_access_token, r_access_token) != 0) {
oidc_error(r,
"access_token passed in refresh request does not match the one stored in the session");
error_code = "no_access_token_match";
goto end;
}
/* get a handle to the provider configuration */
oidc_provider_t *provider = NULL;
if (oidc_get_provider_from_session(r, c, session, &provider) == FALSE) {
error_code = "session_corruption";
goto end;
}
/* execute the actual refresh grant */
if (oidc_refresh_access_token(r, c, session, provider, NULL) == FALSE) {
oidc_error(r, "access_token could not be refreshed");
error_code = "refresh_failed";
goto end;
}
/* pass the tokens to the application and save the session, possibly updating the expiry */
if (oidc_session_pass_tokens_and_save(r, c, session, TRUE) == FALSE) {
error_code = "session_corruption";
goto end;
}
end:
/* pass optional error message to the return URL */
if (error_code != NULL)
return_to = apr_psprintf(r->pool, "%s%serror_code=%s", return_to,
strchr(return_to ? return_to : "", OIDC_CHAR_QUERY) ?
OIDC_STR_AMP :
OIDC_STR_QUERY, oidc_util_escape_string(r, error_code));
/* add the redirect location header */
oidc_util_hdr_out_location_set(r, return_to);
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle request object by reference request
*/
static int oidc_handle_request_uri(request_rec *r, oidc_cfg *c) {
char *request_ref = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_REQUEST_URI,
&request_ref);
if (request_ref == NULL) {
oidc_error(r, "no \"%s\" parameter found",
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI);
return HTTP_BAD_REQUEST;
}
char *jwt = NULL;
oidc_cache_get_request_uri(r, request_ref, &jwt);
if (jwt == NULL) {
oidc_error(r, "no cached JWT found for %s reference: %s",
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI, request_ref);
return HTTP_NOT_FOUND;
}
oidc_cache_set_request_uri(r, request_ref, NULL, 0);
return oidc_util_http_send(r, jwt, strlen(jwt), OIDC_CONTENT_TYPE_JWT, OK);
}
/*
* handle a request to invalidate a cached access token introspection result
*/
int oidc_handle_remove_at_cache(request_rec *r, oidc_cfg *c) {
char *access_token = NULL;
oidc_util_get_request_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REMOVE_AT_CACHE, &access_token);
char *cache_entry = NULL;
oidc_cache_get_access_token(r, access_token, &cache_entry);
if (cache_entry == NULL) {
oidc_error(r, "no cached access token found for value: %s",
access_token);
return HTTP_NOT_FOUND;
}
oidc_cache_set_access_token(r, access_token, NULL, 0);
return OK;
}
#define OIDC_INFO_PARAM_ACCESS_TOKEN_REFRESH_INTERVAL "access_token_refresh_interval"
/*
* handle request for session info
*/
static int oidc_handle_info_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
int rc = HTTP_UNAUTHORIZED;
apr_byte_t needs_save = FALSE;
char *s_format = NULL, *s_interval = NULL, *r_value = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_INFO,
&s_format);
oidc_util_get_request_parameter(r,
OIDC_INFO_PARAM_ACCESS_TOKEN_REFRESH_INTERVAL, &s_interval);
/* see if this is a request for a format that is supported */
if ((apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_JSON, s_format) != 0)
&& (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_HTML, s_format) != 0)) {
oidc_warn(r, "request for unknown format: %s", s_format);
return HTTP_UNSUPPORTED_MEDIA_TYPE;
}
/* check that we actually have a user session and this is someone calling with a proper session cookie */
if (session->remote_user == NULL) {
oidc_warn(r, "no user session found");
return HTTP_UNAUTHORIZED;
}
/* set the user in the main request for further (incl. sub-request and authz) processing */
r->user = apr_pstrdup(r->pool, session->remote_user);
if (c->info_hook_data == NULL) {
oidc_warn(r, "no data configured to return in " OIDCInfoHook);
return HTTP_NOT_FOUND;
}
/* see if we can and need to refresh the access token */
if ((s_interval != NULL)
&& (oidc_session_get_refresh_token(r, session) != NULL)) {
apr_time_t t_interval;
if (sscanf(s_interval, "%" APR_TIME_T_FMT, &t_interval) == 1) {
t_interval = apr_time_from_sec(t_interval);
/* get the last refresh timestamp from the session info */
apr_time_t last_refresh =
oidc_session_get_access_token_last_refresh(r, session);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(last_refresh + t_interval - apr_time_now()));
/* see if we need to refresh again */
if (last_refresh + t_interval < apr_time_now()) {
/* get the current provider info */
oidc_provider_t *provider = NULL;
if (oidc_get_provider_from_session(r, c, session,
&provider) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* execute the actual refresh grant */
if (oidc_refresh_access_token(r, c, session, provider,
NULL) == FALSE)
oidc_warn(r, "access_token could not be refreshed");
else
needs_save = TRUE;
}
}
}
/* create the JSON object */
json_t *json = json_object();
/* add a timestamp of creation in there for the caller */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_TIMESTAMP,
APR_HASH_KEY_STRING)) {
json_object_set_new(json, OIDC_HOOK_INFO_TIMESTAMP,
json_integer(apr_time_sec(apr_time_now())));
}
/*
* refresh the claims from the userinfo endpoint
* side-effect is that this may refresh the access token if not already done
* note that OIDCUserInfoRefreshInterval should be set to control the refresh policy
*/
needs_save |= oidc_refresh_claims_from_userinfo_endpoint(r, c, session);
/* include the access token in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ACCES_TOKEN,
APR_HASH_KEY_STRING)) {
const char *access_token = oidc_session_get_access_token(r, session);
if (access_token != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_ACCES_TOKEN,
json_string(access_token));
}
/* include the access token expiry timestamp in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ACCES_TOKEN_EXP,
APR_HASH_KEY_STRING)) {
const char *access_token_expires =
oidc_session_get_access_token_expires(r, session);
if (access_token_expires != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_ACCES_TOKEN_EXP,
json_string(access_token_expires));
}
/* include the id_token claims in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ID_TOKEN,
APR_HASH_KEY_STRING)) {
json_t *id_token = oidc_session_get_idtoken_claims_json(r, session);
if (id_token)
json_object_set_new(json, OIDC_HOOK_INFO_ID_TOKEN, id_token);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_USER_INFO,
APR_HASH_KEY_STRING)) {
/* include the claims from the userinfo endpoint the session info */
json_t *claims = oidc_session_get_userinfo_claims_json(r, session);
if (claims)
json_object_set_new(json, OIDC_HOOK_INFO_USER_INFO, claims);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_SESSION,
APR_HASH_KEY_STRING)) {
json_t *j_session = json_object();
json_object_set(j_session, OIDC_HOOK_INFO_SESSION_STATE,
session->state);
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_UUID,
json_string(session->uuid));
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_TIMEOUT,
json_integer(apr_time_sec(session->expiry)));
apr_time_t session_expires = oidc_session_get_session_expires(r,
session);
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_EXP,
json_integer(apr_time_sec(session_expires)));
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_REMOTE_USER,
json_string(session->remote_user));
json_object_set_new(json, OIDC_HOOK_INFO_SESSION, j_session);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_REFRESH_TOKEN,
APR_HASH_KEY_STRING)) {
/* include the refresh token in the session info */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if (refresh_token != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_REFRESH_TOKEN,
json_string(refresh_token));
}
if (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_JSON, s_format) == 0) {
/* JSON-encode the result */
r_value = oidc_util_encode_json_object(r, json, 0);
/* return the stringified JSON result */
rc = oidc_util_http_send(r, r_value, strlen(r_value),
OIDC_CONTENT_TYPE_JSON, OK);
} else if (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_HTML, s_format) == 0) {
/* JSON-encode the result */
r_value = oidc_util_encode_json_object(r, json, JSON_INDENT(2));
rc = oidc_util_html_send(r, "Session Info", NULL, NULL,
apr_psprintf(r->pool, "<pre>%s</pre>", r_value), OK);
}
/* free the allocated resources */
json_decref(json);
/* pass the tokens to the application and save the session, possibly updating the expiry */
if (oidc_session_pass_tokens_and_save(r, c, session, needs_save) == FALSE) {
oidc_warn(r, "error saving session");
rc = HTTP_INTERNAL_SERVER_ERROR;
}
return rc;
}
/*
* handle all requests to the redirect_uri
*/
int oidc_handle_redirect_uri_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
if (oidc_proto_is_redirect_authorization_response(r, c)) {
/* this is an authorization response from the OP using the Basic Client profile or a Hybrid flow*/
return oidc_handle_redirect_authorization_response(r, c, session);
/*
*
* Note that we are checking for logout *before* checking for a POST authorization response
* to handle backchannel POST-based logout
*
* so any POST to the Redirect URI that does not have a logout query parameter will be handled
* as an authorization response; alternatively we could assume that a POST response has no
* parameters
*/
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_LOGOUT)) {
/* handle logout */
return oidc_handle_logout(r, c, session);
} else if (oidc_proto_is_post_authorization_response(r, c)) {
/* this is an authorization response using the fragment(+POST) response_mode with the Implicit Client profile */
return oidc_handle_post_authorization_response(r, c, session);
} else if (oidc_is_discovery_response(r, c)) {
/* this is response from the OP discovery page */
return oidc_handle_discovery_response(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_JWKS)) {
/* handle JWKs request */
return oidc_handle_jwks(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_SESSION)) {
/* handle session management request */
return oidc_handle_session_management(r, c, session);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REFRESH)) {
/* handle refresh token request */
return oidc_handle_refresh_token_request(r, c, session);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI)) {
/* handle request object by reference request */
return oidc_handle_request_uri(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REMOVE_AT_CACHE)) {
/* handle request to invalidate access token cache */
return oidc_handle_remove_at_cache(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_INFO)) {
if (session->remote_user == NULL)
return HTTP_UNAUTHORIZED;
/* set r->user, set headers/env-vars, update expiry, update userinfo + AT */
int rc = oidc_handle_existing_session(r, c, session);
if (rc != OK)
return rc;
return oidc_handle_info_request(r, c, session);
} else if ((r->args == NULL) || (apr_strnatcmp(r->args, "") == 0)) {
/* this is a "bare" request to the redirect URI, indicating implicit flow using the fragment response_mode */
return oidc_proto_javascript_implicit(r, c);
}
/* this is not an authorization response or logout request */
/* check for "error" response */
if (oidc_util_request_has_parameter(r, OIDC_PROTO_ERROR)) {
// char *error = NULL, *descr = NULL;
// oidc_util_get_request_parameter(r, "error", &error);
// oidc_util_get_request_parameter(r, "error_description", &descr);
//
// /* send user facing error to browser */
// return oidc_util_html_send_error(r, error, descr, DONE);
return oidc_handle_redirect_authorization_response(r, c, session);
}
oidc_error(r,
"The OpenID Connect callback URL received an invalid request: %s; returning HTTP_INTERNAL_SERVER_ERROR",
r->args);
/* something went wrong */
return oidc_util_html_send_error(r, c->error_template, "Invalid Request",
apr_psprintf(r->pool,
"The OpenID Connect callback URL received an invalid request"),
HTTP_INTERNAL_SERVER_ERROR);
}
#define OIDC_AUTH_TYPE_OPENID_CONNECT "openid-connect"
#define OIDC_AUTH_TYPE_OPENID_OAUTH20 "oauth20"
#define OIDC_AUTH_TYPE_OPENID_BOTH "auth-openidc"
/*
* main routine: handle OpenID Connect authentication
*/
static int oidc_check_userid_openidc(request_rec *r, oidc_cfg *c) {
if (oidc_get_redirect_uri(r, c) == NULL) {
oidc_error(r,
"configuration error: the authentication type is set to \"" OIDC_AUTH_TYPE_OPENID_CONNECT "\" but " OIDCRedirectURI " has not been set");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* check if this is a sub-request or an initial request */
if (ap_is_initial_req(r)) {
int rc = OK;
/* load the session from the request state; this will be a new "empty" session if no state exists */
oidc_session_t *session = NULL;
oidc_session_load(r, &session);
/* see if the initial request is to the redirect URI; this handles potential logout too */
if (oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, c))) {
/* handle request to the redirect_uri */
rc = oidc_handle_redirect_uri_request(r, c, session);
/* free resources allocated for the session */
oidc_session_free(r, session);
return rc;
/* initial request to non-redirect URI, check if we have an existing session */
} else if (session->remote_user != NULL) {
/* this is initial request and we already have a session */
rc = oidc_handle_existing_session(r, c, session);
/* free resources allocated for the session */
oidc_session_free(r, session);
/* strip any cookies that we need to */
oidc_strip_cookies(r);
return rc;
}
/* free resources allocated for the session */
oidc_session_free(r, session);
/*
* else: initial request, we have no session and it is not an authorization or
* discovery response: just hit the default flow for unauthenticated users
*/
} else {
/* not an initial request, try to recycle what we've already established in the main request */
if (r->main != NULL)
r->user = r->main->user;
else if (r->prev != NULL)
r->user = r->prev->user;
if (r->user != NULL) {
/* this is a sub-request and we have a session (headers will have been scrubbed and set already) */
oidc_debug(r,
"recycling user '%s' from initial request for sub-request",
r->user);
/*
* apparently request state can get lost in sub-requests, so let's see
* if we need to restore id_token and/or claims from the session cache
*/
const char *s_id_token = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_IDTOKEN);
if (s_id_token == NULL) {
oidc_session_t *session = NULL;
oidc_session_load(r, &session);
oidc_copy_tokens_to_request_state(r, session, NULL, NULL);
/* free resources allocated for the session */
oidc_session_free(r, session);
}
/* strip any cookies that we need to */
oidc_strip_cookies(r);
return OK;
}
/*
* else: not initial request, but we could not find a session, so:
* just hit the default flow for unauthenticated users
*/
}
return oidc_handle_unauthenticated_user(r, c);
}
/*
* main routine: handle "mixed" OIDC/OAuth authentication
*/
static int oidc_check_mixed_userid_oauth(request_rec *r, oidc_cfg *c) {
/* get the bearer access token from the Authorization header */
const char *access_token = NULL;
if (oidc_oauth_get_bearer_token(r, &access_token) == TRUE)
return oidc_oauth_check_userid(r, c, access_token);
/* no bearer token found: then treat this as a regular OIDC browser request */
return oidc_check_userid_openidc(r, c);
}
/*
* generic Apache authentication hook for this module: dispatches to OpenID Connect or OAuth 2.0 specific routines
*/
int oidc_check_user_id(request_rec *r) {
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
/* log some stuff about the incoming HTTP request */
oidc_debug(r, "incoming request: \"%s?%s\", ap_is_initial_req(r)=%d",
r->parsed_uri.path, r->args, ap_is_initial_req(r));
/* see if any authentication has been defined at all */
if (ap_auth_type(r) == NULL)
return DECLINED;
/* see if we've configured OpenID Connect user authentication for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_CONNECT) == 0)
return oidc_check_userid_openidc(r, c);
/* see if we've configured OAuth 2.0 access control for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0)
return oidc_oauth_check_userid(r, c, NULL);
/* see if we've configured "mixed mode" for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_BOTH) == 0)
return oidc_check_mixed_userid_oauth(r, c);
/* this is not for us but for some other handler */
return DECLINED;
}
/*
* get the claims and id_token from request state
*/
static void oidc_authz_get_claims_and_idtoken(request_rec *r, json_t **claims,
json_t **id_token) {
const char *s_claims = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_CLAIMS);
if (s_claims != NULL)
oidc_util_decode_json_object(r, s_claims, claims);
const char *s_id_token = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_IDTOKEN);
if (s_id_token != NULL)
oidc_util_decode_json_object(r, s_id_token, id_token);
}
#if MODULE_MAGIC_NUMBER_MAJOR >= 20100714
/*
* find out which action we need to take when encountering an unauthorized request
*/
static authz_status oidc_handle_unauthorized_user24(request_rec *r) {
oidc_debug(r, "enter");
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0) {
oidc_oauth_return_www_authenticate(r, "insufficient_scope",
"Different scope(s) or other claims required");
return AUTHZ_DENIED;
}
/* see if we've configured OIDCUnAutzAction for this path */
switch (oidc_dir_cfg_unautz_action(r)) {
// TODO: document that AuthzSendForbiddenOnFailure is required to return 403 FORBIDDEN
case OIDC_UNAUTZ_RETURN403:
case OIDC_UNAUTZ_RETURN401:
return AUTHZ_DENIED;
break;
case OIDC_UNAUTZ_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return AUTHZ_DENIED;
break;
}
oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
const char *location = oidc_util_hdr_out_location_get(r);
if (location != NULL) {
oidc_debug(r, "send HTML refresh with authorization redirect: %s",
location);
char *html_head = apr_psprintf(r->pool,
"<meta http-equiv=\"refresh\" content=\"0; url=%s\">",
location);
oidc_util_html_send(r, "Stepup Authentication", html_head, NULL, NULL,
HTTP_UNAUTHORIZED);
}
return AUTHZ_DENIED;
}
/*
* generic Apache >=2.4 authorization hook for this module
* handles both OpenID Connect or OAuth 2.0 in the same way, based on the claims stored in the session
*/
authz_status oidc_authz_checker(request_rec *r, const char *require_args,
const void *parsed_require_args,
oidc_authz_match_claim_fn_type match_claim_fn) {
oidc_debug(r, "enter");
/* check for anonymous access and PASS mode */
if (r->user != NULL && strlen(r->user) == 0) {
r->user = NULL;
if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS)
return AUTHZ_GRANTED;
}
/* get the set of claims from the request state (they've been set in the authentication part earlier */
json_t *claims = NULL, *id_token = NULL;
oidc_authz_get_claims_and_idtoken(r, &claims, &id_token);
/* merge id_token claims (e.g. "iss") in to claims json object */
if (claims)
oidc_util_json_merge(r, id_token, claims);
/* dispatch to the >=2.4 specific authz routine */
authz_status rc = oidc_authz_worker24(r, claims ? claims : id_token,
require_args, match_claim_fn);
/* cleanup */
if (claims)
json_decref(claims);
if (id_token)
json_decref(id_token);
if ((rc == AUTHZ_DENIED) && ap_auth_type(r))
rc = oidc_handle_unauthorized_user24(r);
return rc;
}
authz_status oidc_authz_checker_claim(request_rec *r, const char *require_args,
const void *parsed_require_args) {
return oidc_authz_checker(r, require_args, parsed_require_args,
oidc_authz_match_claim);
}
#ifdef USE_LIBJQ
authz_status oidc_authz_checker_claims_expr(request_rec *r, const char *require_args, const void *parsed_require_args) {
return oidc_authz_checker(r, require_args, parsed_require_args, oidc_authz_match_claims_expr);
}
#endif
#else
/*
* find out which action we need to take when encountering an unauthorized request
*/
static int oidc_handle_unauthorized_user22(request_rec *r) {
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
if (apr_strnatcasecmp((const char *) ap_auth_type(r), OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0) {
oidc_oauth_return_www_authenticate(r, "insufficient_scope", "Different scope(s) or other claims required");
return HTTP_UNAUTHORIZED;
}
/* see if we've configured OIDCUnAutzAction for this path */
switch (oidc_dir_cfg_unautz_action(r)) {
case OIDC_UNAUTZ_RETURN403:
return HTTP_FORBIDDEN;
case OIDC_UNAUTZ_RETURN401:
return HTTP_UNAUTHORIZED;
case OIDC_UNAUTZ_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return HTTP_UNAUTHORIZED;
}
return oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r), oidc_dir_cfg_path_scope(r));
}
/*
* generic Apache <2.4 authorization hook for this module
* handles both OpenID Connect and OAuth 2.0 in the same way, based on the claims stored in the request context
*/
int oidc_auth_checker(request_rec *r) {
/* check for anonymous access and PASS mode */
if (r->user != NULL && strlen(r->user) == 0) {
r->user = NULL;
if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS)
return OK;
}
/* get the set of claims from the request state (they've been set in the authentication part earlier */
json_t *claims = NULL, *id_token = NULL;
oidc_authz_get_claims_and_idtoken(r, &claims, &id_token);
/* get the Require statements */
const apr_array_header_t * const reqs_arr = ap_requires(r);
/* see if we have any */
const require_line * const reqs =
reqs_arr ? (require_line *) reqs_arr->elts : NULL;
if (!reqs_arr) {
oidc_debug(r,
"no require statements found, so declining to perform authorization.");
return DECLINED;
}
/* merge id_token claims (e.g. "iss") in to claims json object */
if (claims)
oidc_util_json_merge(r, id_token, claims);
/* dispatch to the <2.4 specific authz routine */
int rc = oidc_authz_worker22(r, claims ? claims : id_token, reqs,
reqs_arr->nelts);
/* cleanup */
if (claims)
json_decref(claims);
if (id_token)
json_decref(id_token);
if ((rc == HTTP_UNAUTHORIZED) && ap_auth_type(r))
rc = oidc_handle_unauthorized_user22(r);
return rc;
}
#endif
apr_byte_t oidc_enabled(request_rec *r) {
if (ap_auth_type(r) == NULL)
return FALSE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_CONNECT) == 0)
return TRUE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0)
return TRUE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_BOTH) == 0)
return TRUE;
return FALSE;
}
/*
* handle content generating requests
*/
int oidc_content_handler(request_rec *r) {
if (oidc_enabled(r) == FALSE)
return DECLINED;
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
return oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, c)) ?
OK : DECLINED;
}
extern const command_rec oidc_config_cmds[];
module AP_MODULE_DECLARE_DATA auth_openidc_module = {
STANDARD20_MODULE_STUFF,
oidc_create_dir_config,
oidc_merge_dir_config,
oidc_create_server_config,
oidc_merge_server_config,
oidc_config_cmds,
oidc_register_hooks
};
| ./CrossVul/dataset_final_sorted/CWE-601/c/bad_1001_3 |
crossvul-cpp_data_good_1369_0 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/***************************************************************************
* Copyright (C) 2017-2019 ZmartZone IAM
* Copyright (C) 2013-2017 Ping Identity Corporation
* All rights reserved.
*
* For further information please contact:
*
* Ping Identity Corporation
* 1099 18th St Suite 2950
* Denver, CO 80202
* 303.468.2900
* http://www.pingidentity.com
*
* DISCLAIMER OF WARRANTIES:
*
* THE SOFTWARE PROVIDED HEREUNDER IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
* ANY WARRANTIES OR REPRESENTATIONS EXPRESS, IMPLIED OR STATUTORY; INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF QUALITY, PERFORMANCE, NONINFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NOR ARE THERE ANY
* WARRANTIES CREATED BY A COURSE OR DEALING, COURSE OF PERFORMANCE OR TRADE
* USAGE. FURTHERMORE, THERE ARE NO WARRANTIES THAT THE SOFTWARE WILL MEET
* YOUR NEEDS OR BE FREE FROM ERRORS, OR THAT THE OPERATION OF THE SOFTWARE
* WILL BE UNINTERRUPTED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES 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.
*
* Initially based on mod_auth_cas.c:
* https://github.com/Jasig/mod_auth_cas
*
* Other code copied/borrowed/adapted:
* shared memory caching: mod_auth_mellon
*
* @Author: Hans Zandbelt - hans.zandbelt@zmartzone.eu
*
**************************************************************************/
#include "apr_hash.h"
#include "apr_strings.h"
#include "ap_config.h"
#include "ap_provider.h"
#include "apr_lib.h"
#include "apr_file_io.h"
#include "apr_sha1.h"
#include "apr_base64.h"
#include "httpd.h"
#include "http_core.h"
#include "http_config.h"
#include "http_log.h"
#include "http_protocol.h"
#include "http_request.h"
#include "mod_auth_openidc.h"
#define ERROR 2
static int oidc_handle_logout_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *url);
// TODO:
// - sort out oidc_cfg vs. oidc_dir_cfg stuff
// - rigid input checking on discovery responses
// - check self-issued support
// - README.quickstart
// - refresh metadata once-per too? (for non-signing key changes)
extern module AP_MODULE_DECLARE_DATA auth_openidc_module;
/*
* clean any suspicious headers in the HTTP request sent by the user agent
*/
static void oidc_scrub_request_headers(request_rec *r, const char *claim_prefix,
apr_hash_t *scrub) {
const int prefix_len = claim_prefix ? strlen(claim_prefix) : 0;
/* get an array representation of the incoming HTTP headers */
const apr_array_header_t * const h = apr_table_elts(r->headers_in);
/* table to keep the non-suspicious headers */
apr_table_t *clean_headers = apr_table_make(r->pool, h->nelts);
/* loop over the incoming HTTP headers */
const apr_table_entry_t * const e = (const apr_table_entry_t *) h->elts;
int i;
for (i = 0; i < h->nelts; i++) {
const char * const k = e[i].key;
/* is this header's name equivalent to a header that needs scrubbing? */
const char *hdr =
(k != NULL) && (scrub != NULL) ?
apr_hash_get(scrub, k, APR_HASH_KEY_STRING) : NULL;
const int header_matches = (hdr != NULL)
&& (oidc_strnenvcmp(k, hdr, -1) == 0);
/*
* would this header be interpreted as a mod_auth_openidc attribute? Note
* that prefix_len will be zero if no attr_prefix is defined,
* so this will always be false. Also note that we do not
* scrub headers if the prefix is empty because every header
* would match.
*/
const int prefix_matches = (k != NULL) && prefix_len
&& (oidc_strnenvcmp(k, claim_prefix, prefix_len) == 0);
/* add to the clean_headers if non-suspicious, skip and report otherwise */
if (!prefix_matches && !header_matches) {
apr_table_addn(clean_headers, k, e[i].val);
} else {
oidc_warn(r, "scrubbed suspicious request header (%s: %.32s)", k,
e[i].val);
}
}
/* overwrite the incoming headers with the cleaned result */
r->headers_in = clean_headers;
}
/*
* scrub all mod_auth_openidc related headers
*/
void oidc_scrub_headers(request_rec *r) {
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
const char *prefix = oidc_cfg_claim_prefix(r);
apr_hash_t *hdrs = apr_hash_make(r->pool);
if (apr_strnatcmp(prefix, "") == 0) {
if ((cfg->white_listed_claims != NULL)
&& (apr_hash_count(cfg->white_listed_claims) > 0))
hdrs = apr_hash_overlay(r->pool, cfg->white_listed_claims, hdrs);
else
oidc_warn(r,
"both " OIDCClaimPrefix " and " OIDCWhiteListedClaims " are empty: this renders an insecure setup!");
}
char *authn_hdr = oidc_cfg_dir_authn_header(r);
if (authn_hdr != NULL)
apr_hash_set(hdrs, authn_hdr, APR_HASH_KEY_STRING, authn_hdr);
/*
* scrub all headers starting with OIDC_ first
*/
oidc_scrub_request_headers(r, OIDC_DEFAULT_HEADER_PREFIX, hdrs);
/*
* then see if the claim headers need to be removed on top of that
* (i.e. the prefix does not start with the default OIDC_)
*/
if ((strstr(prefix, OIDC_DEFAULT_HEADER_PREFIX) != prefix)) {
oidc_scrub_request_headers(r, prefix, NULL);
}
}
/*
* strip the session cookie from the headers sent to the application/backend
*/
void oidc_strip_cookies(request_rec *r) {
char *cookie, *ctx, *result = NULL;
const char *name = NULL;
int i;
apr_array_header_t *strip = oidc_dir_cfg_strip_cookies(r);
char *cookies = apr_pstrdup(r->pool, oidc_util_hdr_in_cookie_get(r));
if ((cookies != NULL) && (strip != NULL)) {
oidc_debug(r,
"looking for the following cookies to strip from cookie header: %s",
apr_array_pstrcat(r->pool, strip, OIDC_CHAR_COMMA));
cookie = apr_strtok(cookies, OIDC_STR_SEMI_COLON, &ctx);
do {
while (cookie != NULL && *cookie == OIDC_CHAR_SPACE)
cookie++;
for (i = 0; i < strip->nelts; i++) {
name = ((const char**) strip->elts)[i];
if ((strncmp(cookie, name, strlen(name)) == 0)
&& (cookie[strlen(name)] == OIDC_CHAR_EQUAL)) {
oidc_debug(r, "stripping: %s", name);
break;
}
}
if (i == strip->nelts) {
result = result ? apr_psprintf(r->pool, "%s%s%s", result,
OIDC_STR_SEMI_COLON, cookie) :
cookie;
}
cookie = apr_strtok(NULL, OIDC_STR_SEMI_COLON, &ctx);
} while (cookie != NULL);
oidc_util_hdr_in_cookie_set(r, result);
}
}
#define OIDC_SHA1_LEN 20
/*
* calculates a hash value based on request fingerprint plus a provided nonce string.
*/
static char *oidc_get_browser_state_hash(request_rec *r, const char *nonce) {
oidc_debug(r, "enter");
/* helper to hold to header values */
const char *value = NULL;
/* the hash context */
apr_sha1_ctx_t sha1;
/* Initialize the hash context */
apr_sha1_init(&sha1);
/* get the X-FORWARDED-FOR header value */
value = oidc_util_hdr_in_x_forwarded_for_get(r);
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, strlen(value));
/* get the USER-AGENT header value */
value = oidc_util_hdr_in_user_agent_get(r);
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, strlen(value));
/* get the remote client IP address or host name */
/*
int remotehost_is_ip;
value = ap_get_remote_host(r->connection, r->per_dir_config,
REMOTE_NOLOOKUP, &remotehost_is_ip);
apr_sha1_update(&sha1, value, strlen(value));
*/
/* concat the nonce parameter to the hash input */
apr_sha1_update(&sha1, nonce, strlen(nonce));
/* concat the token binding ID if present */
value = oidc_util_get_provided_token_binding_id(r);
if (value != NULL) {
oidc_debug(r,
"Provided Token Binding ID environment variable found; adding its value to the state");
apr_sha1_update(&sha1, value, strlen(value));
}
/* finalize the hash input and calculate the resulting hash output */
unsigned char hash[OIDC_SHA1_LEN];
apr_sha1_final(hash, &sha1);
/* base64url-encode the resulting hash and return it */
char *result = NULL;
oidc_base64url_encode(r, &result, (const char *) hash, OIDC_SHA1_LEN, TRUE);
return result;
}
/*
* return the name for the state cookie
*/
static char *oidc_get_state_cookie_name(request_rec *r, const char *state) {
return apr_psprintf(r->pool, "%s%s", OIDC_STATE_COOKIE_PREFIX, state);
}
/*
* return the static provider configuration, i.e. from a metadata URL or configuration primitives
*/
static apr_byte_t oidc_provider_static_config(request_rec *r, oidc_cfg *c,
oidc_provider_t **provider) {
json_t *j_provider = NULL;
char *s_json = NULL;
/* see if we should configure a static provider based on external (cached) metadata */
if ((c->metadata_dir != NULL) || (c->provider.metadata_url == NULL)) {
*provider = &c->provider;
return TRUE;
}
oidc_cache_get_provider(r, c->provider.metadata_url, &s_json);
if (s_json == NULL) {
if (oidc_metadata_provider_retrieve(r, c, NULL,
c->provider.metadata_url, &j_provider, &s_json) == FALSE) {
oidc_error(r, "could not retrieve metadata from url: %s",
c->provider.metadata_url);
return FALSE;
}
oidc_cache_set_provider(r, c->provider.metadata_url, s_json,
apr_time_now() + (c->provider_metadata_refresh_interval <= 0 ? apr_time_from_sec( OIDC_CACHE_PROVIDER_METADATA_EXPIRY_DEFAULT) : c->provider_metadata_refresh_interval));
} else {
oidc_util_decode_json_object(r, s_json, &j_provider);
/* check to see if it is valid metadata */
if (oidc_metadata_provider_is_valid(r, c, j_provider, NULL) == FALSE) {
oidc_error(r,
"cache corruption detected: invalid metadata from url: %s",
c->provider.metadata_url);
return FALSE;
}
}
*provider = apr_pcalloc(r->pool, sizeof(oidc_provider_t));
memcpy(*provider, &c->provider, sizeof(oidc_provider_t));
if (oidc_metadata_provider_parse(r, c, j_provider, *provider) == FALSE) {
oidc_error(r, "could not parse metadata from url: %s",
c->provider.metadata_url);
if (j_provider)
json_decref(j_provider);
return FALSE;
}
json_decref(j_provider);
return TRUE;
}
/*
* return the oidc_provider_t struct for the specified issuer
*/
static oidc_provider_t *oidc_get_provider_for_issuer(request_rec *r,
oidc_cfg *c, const char *issuer, apr_byte_t allow_discovery) {
/* by default we'll assume that we're dealing with a single statically configured OP */
oidc_provider_t *provider = NULL;
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return NULL;
/* unless a metadata directory was configured, so we'll try and get the provider settings from there */
if (c->metadata_dir != NULL) {
/* try and get metadata from the metadata directory for the OP that sent this response */
if ((oidc_metadata_get(r, c, issuer, &provider, allow_discovery)
== FALSE) || (provider == NULL)) {
/* don't know nothing about this OP/issuer */
oidc_error(r, "no provider metadata found for issuer \"%s\"",
issuer);
return NULL;
}
}
return provider;
}
/*
* find out whether the request is a response from an IDP discovery page
*/
static apr_byte_t oidc_is_discovery_response(request_rec *r, oidc_cfg *cfg) {
/*
* prereq: this is a call to the configured redirect_uri, now see if:
* the OIDC_DISC_OP_PARAM is present
*/
return oidc_util_request_has_parameter(r, OIDC_DISC_OP_PARAM)
|| oidc_util_request_has_parameter(r, OIDC_DISC_USER_PARAM);
}
/*
* return the HTTP method being called: only for POST data persistence purposes
*/
static const char *oidc_original_request_method(request_rec *r, oidc_cfg *cfg,
apr_byte_t handle_discovery_response) {
const char *method = OIDC_METHOD_GET;
char *m = NULL;
if ((handle_discovery_response == TRUE)
&& (oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, cfg)))
&& (oidc_is_discovery_response(r, cfg))) {
oidc_util_get_request_parameter(r, OIDC_DISC_RM_PARAM, &m);
if (m != NULL)
method = apr_pstrdup(r->pool, m);
} else {
/*
* if POST preserve is not enabled for this location, there's no point in preserving
* the method either which would result in POSTing empty data on return;
* so we revert to legacy behavior
*/
if (oidc_cfg_dir_preserve_post(r) == 0)
return OIDC_METHOD_GET;
const char *content_type = oidc_util_hdr_in_content_type_get(r);
if ((r->method_number == M_POST) && (apr_strnatcmp(content_type,
OIDC_CONTENT_TYPE_FORM_ENCODED) == 0))
method = OIDC_METHOD_FORM_POST;
}
oidc_debug(r, "return: %s", method);
return method;
}
/*
* send an OpenID Connect authorization request to the specified provider preserving POST parameters using HTML5 storage
*/
apr_byte_t oidc_post_preserve_javascript(request_rec *r, const char *location,
char **javascript, char **javascript_method) {
if (oidc_cfg_dir_preserve_post(r) == 0)
return FALSE;
oidc_debug(r, "enter");
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
const char *method = oidc_original_request_method(r, cfg, FALSE);
if (apr_strnatcmp(method, OIDC_METHOD_FORM_POST) != 0)
return FALSE;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return FALSE;
}
const apr_array_header_t *arr = apr_table_elts(params);
const apr_table_entry_t *elts = (const apr_table_entry_t*) arr->elts;
int i;
char *json = "";
for (i = 0; i < arr->nelts; i++) {
json = apr_psprintf(r->pool, "%s'%s': '%s'%s", json,
oidc_util_escape_string(r, elts[i].key),
oidc_util_escape_string(r, elts[i].val),
i < arr->nelts - 1 ? "," : "");
}
json = apr_psprintf(r->pool, "{ %s }", json);
const char *jmethod = "preserveOnLoad";
const char *jscript =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function %s() {\n"
" sessionStorage.setItem('mod_auth_openidc_preserve_post_params', JSON.stringify(%s));\n"
" %s"
" }\n"
" </script>\n", jmethod, json,
location ?
apr_psprintf(r->pool, "window.location='%s';\n",
location) :
"");
if (location == NULL) {
if (javascript_method)
*javascript_method = apr_pstrdup(r->pool, jmethod);
if (javascript)
*javascript = apr_pstrdup(r->pool, jscript);
} else {
oidc_util_html_send(r, "Preserving...", jscript, jmethod,
"<p>Preserving...</p>", OK);
}
return TRUE;
}
/*
* restore POST parameters on original_url from HTML5 local storage
*/
static int oidc_request_post_preserved_restore(request_rec *r,
const char *original_url) {
oidc_debug(r, "enter: original_url=%s", original_url);
const char *method = "postOnLoad";
const char *script =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function str_decode(string) {\n"
" try {\n"
" result = decodeURIComponent(string);\n"
" } catch (e) {\n"
" result = unescape(string);\n"
" }\n"
" return result;\n"
" }\n"
" function %s() {\n"
" var mod_auth_openidc_preserve_post_params = JSON.parse(sessionStorage.getItem('mod_auth_openidc_preserve_post_params'));\n"
" sessionStorage.removeItem('mod_auth_openidc_preserve_post_params');\n"
" for (var key in mod_auth_openidc_preserve_post_params) {\n"
" var input = document.createElement(\"input\");\n"
" input.name = str_decode(key);\n"
" input.value = str_decode(mod_auth_openidc_preserve_post_params[key]);\n"
" input.type = \"hidden\";\n"
" document.forms[0].appendChild(input);\n"
" }\n"
" document.forms[0].action = '%s';\n"
" document.forms[0].submit();\n"
" }\n"
" </script>\n", method, original_url);
const char *body = " <p>Restoring...</p>\n"
" <form method=\"post\"></form>\n";
return oidc_util_html_send(r, "Restoring...", script, method, body,
OK);
}
/*
* parse state that was sent to us by the issuer
*/
static apr_byte_t oidc_unsolicited_proto_state(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t **proto_state) {
char *alg = NULL;
oidc_debug(r, "enter: state header=%s",
oidc_proto_peek_jwt_header(r, state, &alg));
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret,
oidc_alg2keysize(alg), OIDC_JOSE_ALG_SHA256,
TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwt_t *jwt = NULL;
if (oidc_jwt_parse(r->pool, state, &jwt,
oidc_util_merge_symmetric_key(r->pool, c->private_keys, jwk),
&err) == FALSE) {
oidc_error(r,
"could not parse JWT from state: invalid unsolicited response: %s",
oidc_jose_e2s(r->pool, err));
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully parsed JWT from state");
if (jwt->payload.iss == NULL) {
oidc_error(r, "no \"%s\" could be retrieved from JWT state, aborting",
OIDC_CLAIM_ISS);
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_provider_t *provider = oidc_get_provider_for_issuer(r, c,
jwt->payload.iss, FALSE);
if (provider == NULL) {
oidc_jwt_destroy(jwt);
return FALSE;
}
/* validate the state JWT, validating optional exp + iat */
if (oidc_proto_validate_jwt(r, jwt, provider->issuer, FALSE, FALSE,
provider->idtoken_iat_slack,
OIDC_TOKEN_BINDING_POLICY_DISABLED) == FALSE) {
oidc_jwt_destroy(jwt);
return FALSE;
}
char *rfp = NULL;
if (oidc_jose_get_string(r->pool, jwt->payload.value.json, OIDC_CLAIM_RFP,
TRUE, &rfp, &err) == FALSE) {
oidc_error(r,
"no \"%s\" claim could be retrieved from JWT state, aborting: %s",
OIDC_CLAIM_RFP, oidc_jose_e2s(r->pool, err));
oidc_jwt_destroy(jwt);
return FALSE;
}
if (apr_strnatcmp(rfp, OIDC_PROTO_ISS) != 0) {
oidc_error(r, "\"%s\" (%s) does not match \"%s\", aborting",
OIDC_CLAIM_RFP, rfp, OIDC_PROTO_ISS);
oidc_jwt_destroy(jwt);
return FALSE;
}
char *target_link_uri = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_TARGET_LINK_URI,
FALSE, &target_link_uri, NULL);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
oidc_error(r,
"no \"%s\" claim could be retrieved from JWT state and no " OIDCDefaultURL " is set, aborting",
OIDC_CLAIM_TARGET_LINK_URI);
oidc_jwt_destroy(jwt);
return FALSE;
}
target_link_uri = c->default_sso_url;
}
if (c->metadata_dir != NULL) {
if ((oidc_metadata_get(r, c, jwt->payload.iss, &provider, FALSE)
== FALSE) || (provider == NULL)) {
oidc_error(r, "no provider metadata found for provider \"%s\"",
jwt->payload.iss);
oidc_jwt_destroy(jwt);
return FALSE;
}
}
char *jti = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json, OIDC_CLAIM_JTI,
FALSE, &jti,
NULL);
if (jti == NULL) {
char *cser = oidc_jwt_serialize(r->pool, jwt, &err);
if (cser == NULL)
return FALSE;
if (oidc_util_hash_string_and_base64url_encode(r, OIDC_JOSE_ALG_SHA256,
cser, &jti) == FALSE) {
oidc_error(r,
"oidc_util_hash_string_and_base64url_encode returned an error");
return FALSE;
}
}
char *replay = NULL;
oidc_cache_get_jti(r, jti, &replay);
if (replay != NULL) {
oidc_error(r,
"the \"%s\" value (%s) passed in the browser state was found in the cache already; possible replay attack!?",
OIDC_CLAIM_JTI, jti);
oidc_jwt_destroy(jwt);
return FALSE;
}
/* jti cache duration is the configured replay prevention window for token issuance plus 10 seconds for safety */
apr_time_t jti_cache_duration = apr_time_from_sec(
provider->idtoken_iat_slack * 2 + 10);
/* store it in the cache for the calculated duration */
oidc_cache_set_jti(r, jti, jti, apr_time_now() + jti_cache_duration);
oidc_debug(r,
"jti \"%s\" validated successfully and is now cached for %" APR_TIME_T_FMT " seconds",
jti, apr_time_sec(jti_cache_duration));
jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret, 0,
NULL, TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwks_uri_t jwks_uri = { provider->jwks_uri,
provider->jwks_refresh_interval, provider->ssl_validate_server };
if (oidc_proto_jwt_verify(r, c, jwt, &jwks_uri,
oidc_util_merge_symmetric_key(r->pool, NULL, jwk)) == FALSE) {
oidc_error(r, "state JWT could not be validated, aborting");
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully verified state JWT");
*proto_state = oidc_proto_state_new();
oidc_proto_state_set_issuer(*proto_state, jwt->payload.iss);
oidc_proto_state_set_original_url(*proto_state, target_link_uri);
oidc_proto_state_set_original_method(*proto_state, OIDC_METHOD_GET);
oidc_proto_state_set_response_mode(*proto_state, provider->response_mode);
oidc_proto_state_set_response_type(*proto_state, provider->response_type);
oidc_proto_state_set_timestamp_now(*proto_state);
oidc_jwt_destroy(jwt);
return TRUE;
}
typedef struct oidc_state_cookies_t {
char *name;
apr_time_t timestamp;
struct oidc_state_cookies_t *next;
} oidc_state_cookies_t;
static int oidc_delete_oldest_state_cookies(request_rec *r,
int number_of_valid_state_cookies, int max_number_of_state_cookies,
oidc_state_cookies_t *first) {
oidc_state_cookies_t *cur = NULL, *prev = NULL, *prev_oldest = NULL,
*oldest = NULL;
while (number_of_valid_state_cookies >= max_number_of_state_cookies) {
oldest = first;
prev_oldest = NULL;
prev = first;
cur = first->next;
while (cur) {
if ((cur->timestamp < oldest->timestamp)) {
oldest = cur;
prev_oldest = prev;
}
prev = cur;
cur = cur->next;
}
oidc_warn(r,
"deleting oldest state cookie: %s (time until expiry %" APR_TIME_T_FMT " seconds)",
oldest->name, apr_time_sec(oldest->timestamp - apr_time_now()));
oidc_util_set_cookie(r, oldest->name, "", 0, NULL);
if (prev_oldest)
prev_oldest->next = oldest->next;
else
first = first->next;
number_of_valid_state_cookies--;
}
return number_of_valid_state_cookies;
}
/*
* clean state cookies that have expired i.e. for outstanding requests that will never return
* successfully and return the number of remaining valid cookies/outstanding-requests while
* doing so
*/
static int oidc_clean_expired_state_cookies(request_rec *r, oidc_cfg *c,
const char *currentCookieName, int delete_oldest) {
int number_of_valid_state_cookies = 0;
oidc_state_cookies_t *first = NULL, *last = NULL;
char *cookie, *tokenizerCtx = NULL;
char *cookies = apr_pstrdup(r->pool, oidc_util_hdr_in_cookie_get(r));
if (cookies != NULL) {
cookie = apr_strtok(cookies, OIDC_STR_SEMI_COLON, &tokenizerCtx);
while (cookie != NULL) {
while (*cookie == OIDC_CHAR_SPACE)
cookie++;
if (strstr(cookie, OIDC_STATE_COOKIE_PREFIX) == cookie) {
char *cookieName = cookie;
while (cookie != NULL && *cookie != OIDC_CHAR_EQUAL)
cookie++;
if (*cookie == OIDC_CHAR_EQUAL) {
*cookie = '\0';
cookie++;
if ((currentCookieName == NULL)
|| (apr_strnatcmp(cookieName, currentCookieName)
!= 0)) {
oidc_proto_state_t *proto_state =
oidc_proto_state_from_cookie(r, c, cookie);
if (proto_state != NULL) {
json_int_t ts = oidc_proto_state_get_timestamp(
proto_state);
if (apr_time_now() > ts + apr_time_from_sec(c->state_timeout)) {
oidc_error(r,
"state (%s) has expired (original_url=%s)",
cookieName,
oidc_proto_state_get_original_url(
proto_state));
oidc_util_set_cookie(r, cookieName, "", 0,
NULL);
} else {
if (first == NULL) {
first = apr_pcalloc(r->pool,
sizeof(oidc_state_cookies_t));
last = first;
} else {
last->next = apr_pcalloc(r->pool,
sizeof(oidc_state_cookies_t));
last = last->next;
}
last->name = cookieName;
last->timestamp = ts;
last->next = NULL;
number_of_valid_state_cookies++;
}
oidc_proto_state_destroy(proto_state);
}
}
}
}
cookie = apr_strtok(NULL, OIDC_STR_SEMI_COLON, &tokenizerCtx);
}
}
if (delete_oldest > 0)
number_of_valid_state_cookies = oidc_delete_oldest_state_cookies(r,
number_of_valid_state_cookies, c->max_number_of_state_cookies,
first);
return number_of_valid_state_cookies;
}
/*
* restore the state that was maintained between authorization request and response in an encrypted cookie
*/
static apr_byte_t oidc_restore_proto_state(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t **proto_state) {
oidc_debug(r, "enter");
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* clean expired state cookies to avoid pollution */
oidc_clean_expired_state_cookies(r, c, cookieName, FALSE);
/* get the state cookie value first */
char *cookieValue = oidc_util_get_cookie(r, cookieName);
if (cookieValue == NULL) {
oidc_error(r, "no \"%s\" state cookie found", cookieName);
return oidc_unsolicited_proto_state(r, c, state, proto_state);
}
/* clear state cookie because we don't need it anymore */
oidc_util_set_cookie(r, cookieName, "", 0, NULL);
*proto_state = oidc_proto_state_from_cookie(r, c, cookieValue);
if (*proto_state == NULL)
return FALSE;
const char *nonce = oidc_proto_state_get_nonce(*proto_state);
/* calculate the hash of the browser fingerprint concatenated with the nonce */
char *calc = oidc_get_browser_state_hash(r, nonce);
/* compare the calculated hash with the value provided in the authorization response */
if (apr_strnatcmp(calc, state) != 0) {
oidc_error(r,
"calculated state from cookie does not match state parameter passed back in URL: \"%s\" != \"%s\"",
state, calc);
oidc_proto_state_destroy(*proto_state);
return FALSE;
}
apr_time_t ts = oidc_proto_state_get_timestamp(*proto_state);
/* check that the timestamp is not beyond the valid interval */
if (apr_time_now() > ts + apr_time_from_sec(c->state_timeout)) {
oidc_error(r, "state has expired");
/*
* note that this overrides redirection to the OIDCDefaultURL as done later...
* see: https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!msg/mod_auth_openidc/L4JFBw-XCNU/BWi2Fmk2AwAJ
*/
oidc_util_html_send_error(r, c->error_template,
"Invalid Authentication Response",
apr_psprintf(r->pool,
"This is due to a timeout; please restart your authentication session by re-entering the URL/bookmark you originally wanted to access: %s",
oidc_proto_state_get_original_url(*proto_state)),
OK);
oidc_proto_state_destroy(*proto_state);
return FALSE;
}
/* add the state */
oidc_proto_state_set_state(*proto_state, state);
/* log the restored state object */
oidc_debug(r, "restored state: %s",
oidc_proto_state_to_string(r, *proto_state));
/* we've made it */
return TRUE;
}
/*
* set the state that is maintained between an authorization request and an authorization response
* in a cookie in the browser that is cryptographically bound to that state
*/
static int oidc_authorization_request_set_cookie(request_rec *r, oidc_cfg *c,
const char *state, oidc_proto_state_t *proto_state) {
/*
* create a cookie consisting of 8 elements:
* random value, original URL, original method, issuer, response_type, response_mod, prompt and timestamp
* encoded as JSON, encrypting the resulting JSON value
*/
char *cookieValue = oidc_proto_state_to_cookie(r, c, proto_state);
if (cookieValue == NULL)
return HTTP_INTERNAL_SERVER_ERROR;
/*
* clean expired state cookies to avoid pollution and optionally
* try to avoid the number of state cookies exceeding a max
*/
int number_of_cookies = oidc_clean_expired_state_cookies(r, c, NULL,
oidc_cfg_delete_oldest_state_cookies(c));
int max_number_of_cookies = oidc_cfg_max_number_of_state_cookies(c);
if ((max_number_of_cookies > 0)
&& (number_of_cookies >= max_number_of_cookies)) {
oidc_warn(r,
"the number of existing, valid state cookies (%d) has exceeded the limit (%d), no additional authorization request + state cookie can be generated, aborting the request",
number_of_cookies, max_number_of_cookies);
/*
* TODO: the html_send code below caters for the case that there's a user behind a
* browser generating this request, rather than a piece of XHR code; how would an
* XHR client handle this?
*/
/*
* it appears that sending content with a 503 turns the HTTP status code
* into a 200 so we'll avoid that for now: the user will see Apache specific
* readable text anyway
*
return oidc_util_html_send_error(r, c->error_template,
"Too Many Outstanding Requests",
apr_psprintf(r->pool,
"No authentication request could be generated since there are too many outstanding authentication requests already; you may have to wait up to %d seconds to be able to create a new request",
c->state_timeout),
HTTP_SERVICE_UNAVAILABLE);
*/
return HTTP_SERVICE_UNAVAILABLE;
}
/* assemble the cookie name for the state cookie */
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* set it as a cookie */
oidc_util_set_cookie(r, cookieName, cookieValue, -1,
c->cookie_same_site ? OIDC_COOKIE_EXT_SAME_SITE_LAX : NULL);
return HTTP_OK;
}
/*
* get the mod_auth_openidc related context from the (userdata in the) request
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
static apr_table_t *oidc_request_state(request_rec *rr) {
/* our state is always stored in the main request */
request_rec *r = (rr->main != NULL) ? rr->main : rr;
/* our state is a table, get it */
apr_table_t *state = NULL;
apr_pool_userdata_get((void **) &state, OIDC_USERDATA_KEY, r->pool);
/* if it does not exist, we'll create a new table */
if (state == NULL) {
state = apr_table_make(r->pool, 5);
apr_pool_userdata_set(state, OIDC_USERDATA_KEY, NULL, r->pool);
}
/* return the resulting table, always non-null now */
return state;
}
/*
* set a name/value pair in the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
void oidc_request_state_set(request_rec *r, const char *key, const char *value) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* put the name/value pair in that table */
apr_table_set(state, key, value);
}
/*
* get a name/value pair from the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
const char*oidc_request_state_get(request_rec *r, const char *key) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* return the value from the table */
return apr_table_get(state, key);
}
/*
* set the claims from a JSON object (c.q. id_token or user_info response) stored
* in the session in to HTTP headers passed on to the application
*/
static apr_byte_t oidc_set_app_claims(request_rec *r,
const oidc_cfg * const cfg, oidc_session_t *session,
const char *s_claims) {
json_t *j_claims = NULL;
/* decode the string-encoded attributes in to a JSON structure */
if (s_claims != NULL) {
if (oidc_util_decode_json_object(r, s_claims, &j_claims) == FALSE)
return FALSE;
}
/* set the resolved claims a HTTP headers for the application */
if (j_claims != NULL) {
oidc_util_set_app_infos(r, j_claims, oidc_cfg_claim_prefix(r),
cfg->claim_delimiter, oidc_cfg_dir_pass_info_in_headers(r),
oidc_cfg_dir_pass_info_in_envvars(r));
/* release resources */
json_decref(j_claims);
}
return TRUE;
}
static int oidc_authenticate_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, const char *original_url,
const char *login_hint, const char *id_token_hint, const char *prompt,
const char *auth_request_params, const char *path_scope);
/*
* log message about max session duration
*/
static void oidc_log_session_expires(request_rec *r, const char *msg,
apr_time_t session_expires) {
char buf[APR_RFC822_DATE_LEN + 1];
apr_rfc822_date(buf, session_expires);
oidc_debug(r, "%s: %s (in %" APR_TIME_T_FMT " secs from now)", msg, buf,
apr_time_sec(session_expires - apr_time_now()));
}
/*
* see if this is a non-browser request
*/
static apr_byte_t oidc_is_xml_http_request(request_rec *r) {
if ((oidc_util_hdr_in_x_requested_with_get(r) != NULL)
&& (apr_strnatcasecmp(oidc_util_hdr_in_x_requested_with_get(r),
OIDC_HTTP_HDR_VAL_XML_HTTP_REQUEST) == 0))
return TRUE;
if ((oidc_util_hdr_in_accept_contains(r, OIDC_CONTENT_TYPE_TEXT_HTML)
== FALSE) && (oidc_util_hdr_in_accept_contains(r,
OIDC_CONTENT_TYPE_APP_XHTML_XML) == FALSE)
&& (oidc_util_hdr_in_accept_contains(r,
OIDC_CONTENT_TYPE_ANY) == FALSE))
return TRUE;
return FALSE;
}
/*
* find out which action we need to take when encountering an unauthenticated request
*/
static int oidc_handle_unauthenticated_user(request_rec *r, oidc_cfg *c) {
/* see if we've configured OIDCUnAuthAction for this path */
switch (oidc_dir_cfg_unauth_action(r)) {
case OIDC_UNAUTH_RETURN410:
return HTTP_GONE;
case OIDC_UNAUTH_RETURN401:
return HTTP_UNAUTHORIZED;
case OIDC_UNAUTH_PASS:
r->user = "";
/*
* we're not going to pass information about an authenticated user to the application,
* but we do need to scrub the headers that mod_auth_openidc would set for security reasons
*/
oidc_scrub_headers(r);
return OK;
case OIDC_UNAUTH_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return HTTP_UNAUTHORIZED;
}
/*
* else: no session (regardless of whether it is main or sub-request),
* and we need to authenticate the user
*/
return oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
}
/*
* check if maximum session duration was exceeded
*/
static int oidc_check_max_session_duration(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
/* get the session expiry from the session data */
apr_time_t session_expires = oidc_session_get_session_expires(r, session);
/* check the expire timestamp against the current time */
if (apr_time_now() > session_expires) {
oidc_warn(r, "maximum session duration exceeded for user: %s",
session->remote_user);
oidc_session_kill(r, session);
return oidc_handle_unauthenticated_user(r, cfg);
}
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
return OK;
}
/*
* validate received session cookie against the domain it was issued for:
*
* this handles the case where the cache configured is a the same single memcache, Redis, or file
* backend for different (virtual) hosts, or a client-side cookie protected with the same secret
*
* it also handles the case that a cookie is unexpectedly shared across multiple hosts in
* name-based virtual hosting even though the OP(s) would be the same
*/
static apr_byte_t oidc_check_cookie_domain(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
const char *c_cookie_domain =
cfg->cookie_domain ?
cfg->cookie_domain : oidc_get_current_url_host(r);
const char *s_cookie_domain = oidc_session_get_cookie_domain(r, session);
if ((s_cookie_domain == NULL)
|| (apr_strnatcmp(c_cookie_domain, s_cookie_domain) != 0)) {
oidc_warn(r,
"aborting: detected attempt to play cookie against a different domain/host than issued for! (issued=%s, current=%s)",
s_cookie_domain, c_cookie_domain);
return FALSE;
}
return TRUE;
}
/*
* get a handle to the provider configuration via the "issuer" stored in the session
*/
apr_byte_t oidc_get_provider_from_session(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t **provider) {
oidc_debug(r, "enter");
/* get the issuer value from the session state */
const char *issuer = oidc_session_get_issuer(r, session);
if (issuer == NULL) {
oidc_error(r, "session corrupted: no issuer found in session");
return FALSE;
}
/* get the provider info associated with the issuer value */
oidc_provider_t *p = oidc_get_provider_for_issuer(r, c, issuer, FALSE);
if (p == NULL) {
oidc_error(r, "session corrupted: no provider found for issuer: %s",
issuer);
return FALSE;
}
*provider = p;
return TRUE;
}
/*
* store claims resolved from the userinfo endpoint in the session
*/
static void oidc_store_userinfo_claims(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider, const char *claims,
const char *userinfo_jwt) {
oidc_debug(r, "enter");
/* see if we've resolved any claims */
if (claims != NULL) {
/*
* Successfully decoded a set claims from the response so we can store them
* (well actually the stringified representation in the response)
* in the session context safely now
*/
oidc_session_set_userinfo_claims(r, session, claims);
if (c->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* this will also clear the entry if a JWT was not returned at this point */
oidc_session_set_userinfo_jwt(r, session, userinfo_jwt);
}
} else {
/*
* clear the existing claims because we could not refresh them
*/
oidc_session_set_userinfo_claims(r, session, NULL);
oidc_session_set_userinfo_jwt(r, session, NULL);
}
/* store the last refresh time if we've configured a userinfo refresh interval */
if (provider->userinfo_refresh_interval > 0)
oidc_session_reset_userinfo_last_refresh(r, session);
}
/*
* execute refresh token grant to refresh the existing access token
*/
static apr_byte_t oidc_refresh_access_token(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider,
char **new_access_token) {
oidc_debug(r, "enter");
/* get the refresh token that was stored in the session */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if (refresh_token == NULL) {
oidc_warn(r,
"refresh token routine called but no refresh_token found in the session");
return FALSE;
}
/* elements returned in the refresh response */
char *s_id_token = NULL;
int expires_in = -1;
char *s_token_type = NULL;
char *s_access_token = NULL;
char *s_refresh_token = NULL;
/* refresh the tokens by calling the token endpoint */
if (oidc_proto_refresh_request(r, c, provider, refresh_token, &s_id_token,
&s_access_token, &s_token_type, &expires_in,
&s_refresh_token) == FALSE) {
oidc_error(r, "access_token could not be refreshed");
return FALSE;
}
/* store the new access_token in the session and discard the old one */
oidc_session_set_access_token(r, session, s_access_token);
oidc_session_set_access_token_expires(r, session, expires_in);
/* reset the access token refresh timestamp */
oidc_session_reset_access_token_last_refresh(r, session);
/* see if we need to return it as a parameter */
if (new_access_token != NULL)
*new_access_token = s_access_token;
/* if we have a new refresh token (rolling refresh), store it in the session and overwrite the old one */
if (s_refresh_token != NULL)
oidc_session_set_refresh_token(r, session, s_refresh_token);
return TRUE;
}
/*
* retrieve claims from the userinfo endpoint and return the stringified response
*/
static const char *oidc_retrieve_claims_from_userinfo_endpoint(request_rec *r,
oidc_cfg *c, oidc_provider_t *provider, const char *access_token,
oidc_session_t *session, char *id_token_sub, char **userinfo_jwt) {
oidc_debug(r, "enter");
char *result = NULL;
char *refreshed_access_token = NULL;
/* see if a userinfo endpoint is set, otherwise there's nothing to do for us */
if (provider->userinfo_endpoint_url == NULL) {
oidc_debug(r,
"not retrieving userinfo claims because userinfo_endpoint is not set");
return NULL;
}
/* see if there's an access token, otherwise we can't call the userinfo endpoint at all */
if (access_token == NULL) {
oidc_debug(r,
"not retrieving userinfo claims because access_token is not provided");
return NULL;
}
if ((id_token_sub == NULL) && (session != NULL)) {
// when refreshing claims from the userinfo endpoint
json_t *id_token_claims = oidc_session_get_idtoken_claims_json(r,
session);
if (id_token_claims == NULL) {
oidc_error(r, "no id_token_claims found in session");
return NULL;
}
oidc_jose_get_string(r->pool, id_token_claims, OIDC_CLAIM_SUB, FALSE,
&id_token_sub, NULL);
}
// TODO: return code should indicate whether the token expired or some other error occurred
// TODO: long-term: session storage should be JSON (with explicit types and less conversion, using standard routines)
/* try to get claims from the userinfo endpoint using the provided access token */
if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub, access_token,
&result, userinfo_jwt) == FALSE) {
/* see if we have an existing session and we are refreshing the user info claims */
if (session != NULL) {
/* first call to user info endpoint failed, but the access token may have just expired, so refresh it */
if (oidc_refresh_access_token(r, c, session, provider,
&refreshed_access_token) == TRUE) {
/* try again with the new access token */
if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub,
refreshed_access_token, &result, userinfo_jwt) == FALSE) {
oidc_error(r,
"resolving user info claims with the refreshed access token failed, nothing will be stored in the session");
result = NULL;
}
} else {
oidc_warn(r,
"refreshing access token failed, claims will not be retrieved/refreshed from the userinfo endpoint");
result = NULL;
}
} else {
oidc_error(r,
"resolving user info claims with the existing/provided access token failed, nothing will be stored in the session");
result = NULL;
}
}
return result;
}
/*
* get (new) claims from the userinfo endpoint
*/
static apr_byte_t oidc_refresh_claims_from_userinfo_endpoint(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session) {
oidc_provider_t *provider = NULL;
const char *claims = NULL;
const char *access_token = NULL;
char *userinfo_jwt = NULL;
/* get the current provider info */
if (oidc_get_provider_from_session(r, cfg, session, &provider) == FALSE)
return FALSE;
/* see if we can do anything here, i.e. we have a userinfo endpoint and a refresh interval is configured */
apr_time_t interval = apr_time_from_sec(
provider->userinfo_refresh_interval);
oidc_debug(r, "userinfo_endpoint=%s, interval=%d",
provider->userinfo_endpoint_url,
provider->userinfo_refresh_interval);
if ((provider->userinfo_endpoint_url != NULL) && (interval > 0)) {
/* get the last refresh timestamp from the session info */
apr_time_t last_refresh = oidc_session_get_userinfo_last_refresh(r,
session);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(last_refresh + interval - apr_time_now()));
/* see if we need to refresh again */
if (last_refresh + interval < apr_time_now()) {
/* get the current access token */
access_token = oidc_session_get_access_token(r, session);
/* retrieve the current claims */
claims = oidc_retrieve_claims_from_userinfo_endpoint(r, cfg,
provider, access_token, session, NULL, &userinfo_jwt);
/* store claims resolved from userinfo endpoint */
oidc_store_userinfo_claims(r, cfg, session, provider, claims,
userinfo_jwt);
/* indicated something changed */
return TRUE;
}
}
return FALSE;
}
/*
* copy the claims and id_token from the session to the request state and optionally return them
*/
static void oidc_copy_tokens_to_request_state(request_rec *r,
oidc_session_t *session, const char **s_id_token, const char **s_claims) {
const char *id_token = oidc_session_get_idtoken_claims(r, session);
const char *claims = oidc_session_get_userinfo_claims(r, session);
oidc_debug(r, "id_token=%s claims=%s", id_token, claims);
if (id_token != NULL) {
oidc_request_state_set(r, OIDC_REQUEST_STATE_KEY_IDTOKEN, id_token);
if (s_id_token != NULL)
*s_id_token = id_token;
}
if (claims != NULL) {
oidc_request_state_set(r, OIDC_REQUEST_STATE_KEY_CLAIMS, claims);
if (s_claims != NULL)
*s_claims = claims;
}
}
/*
* pass refresh_token, access_token and access_token_expires as headers/environment variables to the application
*/
static apr_byte_t oidc_session_pass_tokens_and_save(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session, apr_byte_t needs_save) {
apr_byte_t pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
apr_byte_t pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
/* set the refresh_token in the app headers/variables, if enabled for this location/directory */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if ((oidc_cfg_dir_pass_refresh_token(r) != 0) && (refresh_token != NULL)) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_REFRESH_TOKEN, refresh_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* set the access_token in the app headers/variables */
const char *access_token = oidc_session_get_access_token(r, session);
if (access_token != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ACCESS_TOKEN, access_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* set the expiry timestamp in the app headers/variables */
const char *access_token_expires = oidc_session_get_access_token_expires(r,
session);
if (access_token_expires != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ACCESS_TOKEN_EXP,
access_token_expires,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/*
* reset the session inactivity timer
* but only do this once per 10% of the inactivity timeout interval (with a max to 60 seconds)
* for performance reasons
*
* now there's a small chance that the session ends 10% (or a minute) earlier than configured/expected
* cq. when there's a request after a recent save (so no update) and then no activity happens until
* a request comes in just before the session should expire
* ("recent" and "just before" refer to 10%-with-a-max-of-60-seconds of the inactivity interval after
* the start/last-update and before the expiry of the session respectively)
*
* this is be deemed acceptable here because of performance gain
*/
apr_time_t interval = apr_time_from_sec(cfg->session_inactivity_timeout);
apr_time_t now = apr_time_now();
apr_time_t slack = interval / 10;
if (slack > apr_time_from_sec(60))
slack = apr_time_from_sec(60);
if (session->expiry - now < interval - slack) {
session->expiry = now + interval;
needs_save = TRUE;
}
/* log message about session expiry */
oidc_log_session_expires(r, "session inactivity timeout", session->expiry);
/* check if something was updated in the session and we need to save it again */
if (needs_save)
if (oidc_session_save(r, session, FALSE) == FALSE)
return FALSE;
return TRUE;
}
static apr_byte_t oidc_refresh_access_token_before_expiry(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session, int ttl_minimum, int logout_on_error) {
const char *s_access_token_expires = NULL;
apr_time_t t_expires = -1;
oidc_provider_t *provider = NULL;
oidc_debug(r, "ttl_minimum=%d", ttl_minimum);
if (ttl_minimum < 0)
return FALSE;
s_access_token_expires = oidc_session_get_access_token_expires(r, session);
if (s_access_token_expires == NULL) {
oidc_debug(r,
"no access token expires_in stored in the session (i.e. returned from in the authorization response), so cannot refresh the access token based on TTL requirement");
return FALSE;
}
if (oidc_session_get_refresh_token(r, session) == NULL) {
oidc_debug(r,
"no refresh token stored in the session, so cannot refresh the access token based on TTL requirement");
return FALSE;
}
if (sscanf(s_access_token_expires, "%" APR_TIME_T_FMT, &t_expires) != 1) {
oidc_error(r, "could not parse s_access_token_expires %s",
s_access_token_expires);
return FALSE;
}
t_expires = apr_time_from_sec(t_expires - ttl_minimum);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(t_expires - apr_time_now()));
if (t_expires > apr_time_now())
return FALSE;
if (oidc_get_provider_from_session(r, cfg, session, &provider) == FALSE)
return FALSE;
if (oidc_refresh_access_token(r, cfg, session, provider,
NULL) == FALSE) {
oidc_warn(r, "access_token could not be refreshed, logout=%d", logout_on_error & OIDC_LOGOUT_ON_ERROR_REFRESH);
if (logout_on_error & OIDC_LOGOUT_ON_ERROR_REFRESH)
return ERROR;
else
return FALSE;
}
return TRUE;
}
/*
* handle the case where we have identified an existing authentication session for a user
*/
static int oidc_handle_existing_session(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
oidc_debug(r, "enter");
/* track if the session needs to be updated/saved into the cache */
apr_byte_t needs_save = FALSE;
/* set the user in the main request for further (incl. sub-request) processing */
r->user = apr_pstrdup(r->pool, session->remote_user);
oidc_debug(r, "set remote_user to \"%s\"", r->user);
/* get the header name in which the remote user name needs to be passed */
char *authn_header = oidc_cfg_dir_authn_header(r);
apr_byte_t pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
apr_byte_t pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
/* verify current cookie domain against issued cookie domain */
if (oidc_check_cookie_domain(r, cfg, session) == FALSE)
return HTTP_UNAUTHORIZED;
/* check if the maximum session duration was exceeded */
int rc = oidc_check_max_session_duration(r, cfg, session);
if (rc != OK)
return rc;
/* if needed, refresh the access token */
needs_save = oidc_refresh_access_token_before_expiry(r, cfg, session,
oidc_cfg_dir_refresh_access_token_before_expiry(r),
oidc_cfg_dir_logout_on_error_refresh(r));
if (needs_save == ERROR)
return oidc_handle_logout_request(r, cfg, session, cfg->default_slo_url);
/* if needed, refresh claims from the user info endpoint */
if (oidc_refresh_claims_from_userinfo_endpoint(r, cfg, session) == TRUE)
needs_save = TRUE;
/*
* we're going to pass the information that we have to the application,
* but first we need to scrub the headers that we're going to use for security reasons
*/
oidc_scrub_headers(r);
/* set the user authentication HTTP header if set and required */
if ((r->user != NULL) && (authn_header != NULL))
oidc_util_hdr_in_set(r, authn_header, r->user);
const char *s_claims = NULL;
const char *s_id_token = NULL;
/* copy id_token and claims from session to request state and obtain their values */
oidc_copy_tokens_to_request_state(r, session, &s_id_token, &s_claims);
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_CLAIMS)) {
/* set the userinfo claims in the app headers */
if (oidc_set_app_claims(r, cfg, session, s_claims) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_JSON_OBJECT)) {
/* pass the userinfo JSON object to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_USERINFO_JSON, s_claims,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
if ((cfg->pass_userinfo_as & OIDC_PASS_USERINFO_AS_JWT)) {
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* get the compact serialized JWT from the session */
const char *s_userinfo_jwt = oidc_session_get_userinfo_jwt(r,
session);
if (s_userinfo_jwt != NULL) {
/* pass the compact serialized JWT to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_USERINFO_JWT,
s_userinfo_jwt,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
} else {
oidc_debug(r,
"configured to pass userinfo in a JWT, but no such JWT was found in the session (probably no such JWT was returned from the userinfo endpoint)");
}
} else {
oidc_error(r,
"session type \"client-cookie\" does not allow storing/passing a userinfo JWT; use \"" OIDCSessionType " server-cache\" for that");
}
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_CLAIMS)) {
/* set the id_token in the app headers */
if (oidc_set_app_claims(r, cfg, session, s_id_token) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_PAYLOAD)) {
/* pass the id_token JSON object to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ID_TOKEN_PAYLOAD, s_id_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_SERIALIZED)) {
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* get the compact serialized JWT from the session */
const char *s_id_token = oidc_session_get_idtoken(r, session);
/* pass the compact serialized JWT to the app in a header or environment variable */
oidc_util_set_app_info(r, OIDC_APP_INFO_ID_TOKEN, s_id_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
} else {
oidc_error(r,
"session type \"client-cookie\" does not allow storing/passing the id_token; use \"" OIDCSessionType " server-cache\" for that");
}
}
/* pass the at, rt and at expiry to the application, possibly update the session expiry and save the session */
if (oidc_session_pass_tokens_and_save(r, cfg, session, needs_save) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* return "user authenticated" status */
return OK;
}
/*
* helper function for basic/implicit client flows upon receiving an authorization response:
* check that it matches the state stored in the browser and return the variables associated
* with the state, such as original_url and OP oidc_provider_t pointer.
*/
static apr_byte_t oidc_authorization_response_match_state(request_rec *r,
oidc_cfg *c, const char *state, struct oidc_provider_t **provider,
oidc_proto_state_t **proto_state) {
oidc_debug(r, "enter (state=%s)", state);
if ((state == NULL) || (apr_strnatcmp(state, "") == 0)) {
oidc_error(r, "state parameter is not set");
return FALSE;
}
/* check the state parameter against what we stored in a cookie */
if (oidc_restore_proto_state(r, c, state, proto_state) == FALSE) {
oidc_error(r, "unable to restore state");
return FALSE;
}
*provider = oidc_get_provider_for_issuer(r, c,
oidc_proto_state_get_issuer(*proto_state), FALSE);
return (*provider != NULL);
}
/*
* redirect the browser to the session logout endpoint
*/
static int oidc_session_redirect_parent_window_to_logout(request_rec *r,
oidc_cfg *c) {
oidc_debug(r, "enter");
char *java_script = apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" window.top.location.href = '%s?session=logout';\n"
" </script>\n", oidc_get_redirect_uri(r, c));
return oidc_util_html_send(r, "Redirecting...", java_script, NULL, NULL,
OK);
}
/*
* handle an error returned by the OP
*/
static int oidc_authorization_response_error(request_rec *r, oidc_cfg *c,
oidc_proto_state_t *proto_state, const char *error,
const char *error_description) {
const char *prompt = oidc_proto_state_get_prompt(proto_state);
if (prompt != NULL)
prompt = apr_pstrdup(r->pool, prompt);
oidc_proto_state_destroy(proto_state);
if ((prompt != NULL)
&& (apr_strnatcmp(prompt, OIDC_PROTO_PROMPT_NONE) == 0)) {
return oidc_session_redirect_parent_window_to_logout(r, c);
}
return oidc_util_html_send_error(r, c->error_template,
apr_psprintf(r->pool, "OpenID Connect Provider error: %s", error),
error_description, OK);
}
/*
* get the r->user for this request based on the configuration for OIDC/OAuth
*/
apr_byte_t oidc_get_remote_user(request_rec *r, const char *claim_name,
const char *reg_exp, const char *replace, json_t *json,
char **request_user) {
/* get the claim value from the JSON object */
json_t *username = json_object_get(json, claim_name);
if ((username == NULL) || (!json_is_string(username))) {
oidc_warn(r, "JSON object did not contain a \"%s\" string", claim_name);
return FALSE;
}
*request_user = apr_pstrdup(r->pool, json_string_value(username));
if (reg_exp != NULL) {
char *error_str = NULL;
if (replace == NULL) {
if (oidc_util_regexp_first_match(r->pool, *request_user, reg_exp,
request_user, &error_str) == FALSE) {
oidc_error(r, "oidc_util_regexp_first_match failed: %s",
error_str);
*request_user = NULL;
return FALSE;
}
} else if (oidc_util_regexp_substitute(r->pool, *request_user, reg_exp,
replace, request_user, &error_str) == FALSE) {
oidc_error(r, "oidc_util_regexp_substitute failed: %s", error_str);
*request_user = NULL;
return FALSE;
}
}
return TRUE;
}
/*
* set the unique user identifier that will be propagated in the Apache r->user and REMOTE_USER variables
*/
static apr_byte_t oidc_set_request_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, oidc_jwt_t *jwt, const char *s_claims) {
char *issuer = provider->issuer;
char *claim_name = apr_pstrdup(r->pool, c->remote_user_claim.claim_name);
int n = strlen(claim_name);
apr_byte_t post_fix_with_issuer = (claim_name[n - 1] == OIDC_CHAR_AT);
if (post_fix_with_issuer == TRUE) {
claim_name[n - 1] = '\0';
issuer =
(strstr(issuer, "https://") == NULL) ?
apr_pstrdup(r->pool, issuer) :
apr_pstrdup(r->pool, issuer + strlen("https://"));
}
/* extract the username claim (default: "sub") from the id_token payload or user claims */
apr_byte_t rc = FALSE;
char *remote_user = NULL;
json_t *claims = NULL;
oidc_util_decode_json_object(r, s_claims, &claims);
if (claims == NULL) {
rc = oidc_get_remote_user(r, claim_name, c->remote_user_claim.reg_exp,
c->remote_user_claim.replace, jwt->payload.value.json,
&remote_user);
} else {
oidc_util_json_merge(r, jwt->payload.value.json, claims);
rc = oidc_get_remote_user(r, claim_name, c->remote_user_claim.reg_exp,
c->remote_user_claim.replace, claims, &remote_user);
json_decref(claims);
}
if ((rc == FALSE) || (remote_user == NULL)) {
oidc_error(r,
"" OIDCRemoteUserClaim "is set to \"%s\", but could not set the remote user based on the requested claim \"%s\" and the available claims for the user",
c->remote_user_claim.claim_name, claim_name);
return FALSE;
}
if (post_fix_with_issuer == TRUE)
remote_user = apr_psprintf(r->pool, "%s%s%s", remote_user, OIDC_STR_AT,
issuer);
r->user = apr_pstrdup(r->pool, remote_user);
oidc_debug(r, "set remote_user to \"%s\" based on claim: \"%s\"%s", r->user,
c->remote_user_claim.claim_name,
c->remote_user_claim.reg_exp ?
apr_psprintf(r->pool,
" and expression: \"%s\" and replace string: \"%s\"",
c->remote_user_claim.reg_exp,
c->remote_user_claim.replace) :
"");
return TRUE;
}
static char *oidc_make_sid_iss_unique(request_rec *r, const char *sid,
const char *issuer) {
return apr_psprintf(r->pool, "%s@%s", sid, issuer);
}
/*
* store resolved information in the session
*/
static apr_byte_t oidc_save_in_session(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider,
const char *remoteUser, const char *id_token, oidc_jwt_t *id_token_jwt,
const char *claims, const char *access_token, const int expires_in,
const char *refresh_token, const char *session_state, const char *state,
const char *original_url, const char *userinfo_jwt) {
/* store the user in the session */
session->remote_user = remoteUser;
/* set the session expiry to the inactivity timeout */
session->expiry =
apr_time_now() + apr_time_from_sec(c->session_inactivity_timeout);
/* store the claims payload in the id_token for later reference */
oidc_session_set_idtoken_claims(r, session,
id_token_jwt->payload.value.str);
if (c->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* store the compact serialized representation of the id_token for later reference */
oidc_session_set_idtoken(r, session, id_token);
}
/* store the issuer in the session (at least needed for session mgmt and token refresh */
oidc_session_set_issuer(r, session, provider->issuer);
/* store the state and original URL in the session for handling browser-back more elegantly */
oidc_session_set_request_state(r, session, state);
oidc_session_set_original_url(r, session, original_url);
if ((session_state != NULL) && (provider->check_session_iframe != NULL)) {
/* store the session state and required parameters session management */
oidc_session_set_session_state(r, session, session_state);
oidc_debug(r,
"session management enabled: stored session_state (%s), check_session_iframe (%s) and client_id (%s) in the session",
session_state, provider->check_session_iframe,
provider->client_id);
} else if (provider->check_session_iframe == NULL) {
oidc_debug(r,
"session management disabled: \"check_session_iframe\" is not set in provider configuration");
} else {
oidc_debug(r,
"session management disabled: no \"session_state\" value is provided in the authentication response even though \"check_session_iframe\" (%s) is set in the provider configuration",
provider->check_session_iframe);
}
/* store claims resolved from userinfo endpoint */
oidc_store_userinfo_claims(r, c, session, provider, claims, userinfo_jwt);
/* see if we have an access_token */
if (access_token != NULL) {
/* store the access_token in the session context */
oidc_session_set_access_token(r, session, access_token);
/* store the associated expires_in value */
oidc_session_set_access_token_expires(r, session, expires_in);
/* reset the access token refresh timestamp */
oidc_session_reset_access_token_last_refresh(r, session);
}
/* see if we have a refresh_token */
if (refresh_token != NULL) {
/* store the refresh_token in the session context */
oidc_session_set_refresh_token(r, session, refresh_token);
}
/* store max session duration in the session as a hard cut-off expiry timestamp */
apr_time_t session_expires =
(provider->session_max_duration == 0) ?
apr_time_from_sec(id_token_jwt->payload.exp) :
(apr_time_now()
+ apr_time_from_sec(provider->session_max_duration));
oidc_session_set_session_expires(r, session, session_expires);
oidc_debug(r,
"provider->session_max_duration = %d, session_expires=%" APR_TIME_T_FMT,
provider->session_max_duration, session_expires);
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
/* store the domain for which this session is valid */
oidc_session_set_cookie_domain(r, session,
c->cookie_domain ? c->cookie_domain : oidc_get_current_url_host(r));
char *sid = NULL;
oidc_debug(r, "provider->backchannel_logout_supported=%d",
provider->backchannel_logout_supported);
if (provider->backchannel_logout_supported > 0) {
oidc_jose_get_string(r->pool, id_token_jwt->payload.value.json,
OIDC_CLAIM_SID, FALSE, &sid, NULL);
if (sid == NULL)
sid = id_token_jwt->payload.sub;
session->sid = oidc_make_sid_iss_unique(r, sid, provider->issuer);
}
/* store the session */
return oidc_session_save(r, session, TRUE);
}
/*
* parse the expiry for the access token
*/
static int oidc_parse_expires_in(request_rec *r, const char *expires_in) {
if (expires_in != NULL) {
char *ptr = NULL;
long number = strtol(expires_in, &ptr, 10);
if (number <= 0) {
oidc_warn(r,
"could not convert \"expires_in\" value (%s) to a number",
expires_in);
return -1;
}
return number;
}
return -1;
}
/*
* handle the different flows (hybrid, implicit, Authorization Code)
*/
static apr_byte_t oidc_handle_flows(request_rec *r, oidc_cfg *c,
oidc_proto_state_t *proto_state, oidc_provider_t *provider,
apr_table_t *params, const char *response_mode, oidc_jwt_t **jwt) {
apr_byte_t rc = FALSE;
const char *requested_response_type = oidc_proto_state_get_response_type(
proto_state);
/* handle the requested response type/mode */
if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_IDTOKEN_TOKEN)) {
rc = oidc_proto_authorization_response_code_idtoken_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_IDTOKEN)) {
rc = oidc_proto_authorization_response_code_idtoken(r, c, proto_state,
provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE_TOKEN)) {
rc = oidc_proto_handle_authorization_response_code_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_CODE)) {
rc = oidc_proto_handle_authorization_response_code(r, c, proto_state,
provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_IDTOKEN_TOKEN)) {
rc = oidc_proto_handle_authorization_response_idtoken_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
OIDC_PROTO_RESPONSE_TYPE_IDTOKEN)) {
rc = oidc_proto_handle_authorization_response_idtoken(r, c, proto_state,
provider, params, response_mode, jwt);
} else {
oidc_error(r, "unsupported response type: \"%s\"",
requested_response_type);
}
if ((rc == FALSE) && (*jwt != NULL)) {
oidc_jwt_destroy(*jwt);
*jwt = NULL;
}
return rc;
}
/* handle the browser back on an authorization response */
static apr_byte_t oidc_handle_browser_back(request_rec *r, const char *r_state,
oidc_session_t *session) {
/* see if we have an existing session and browser-back was used */
const char *s_state = NULL, *o_url = NULL;
if (session->remote_user != NULL) {
s_state = oidc_session_get_request_state(r, session);
o_url = oidc_session_get_original_url(r, session);
if ((r_state != NULL) && (s_state != NULL)
&& (apr_strnatcmp(r_state, s_state) == 0)) {
/* log the browser back event detection */
oidc_warn(r,
"browser back detected, redirecting to original URL: %s",
o_url);
/* go back to the URL that he originally tried to access */
oidc_util_hdr_out_location_set(r, o_url);
return TRUE;
}
}
return FALSE;
}
/*
* complete the handling of an authorization response by obtaining, parsing and verifying the
* id_token and storing the authenticated user state in the session
*/
static int oidc_handle_authorization_response(request_rec *r, oidc_cfg *c,
oidc_session_t *session, apr_table_t *params, const char *response_mode) {
oidc_debug(r, "enter, response_mode=%s", response_mode);
oidc_provider_t *provider = NULL;
oidc_proto_state_t *proto_state = NULL;
oidc_jwt_t *jwt = NULL;
/* see if this response came from a browser-back event */
if (oidc_handle_browser_back(r, apr_table_get(params, OIDC_PROTO_STATE),
session) == TRUE)
return HTTP_MOVED_TEMPORARILY;
/* match the returned state parameter against the state stored in the browser */
if (oidc_authorization_response_match_state(r, c,
apr_table_get(params, OIDC_PROTO_STATE), &provider,
&proto_state) == FALSE) {
if (c->default_sso_url != NULL) {
oidc_warn(r,
"invalid authorization response state; a default SSO URL is set, sending the user there: %s",
c->default_sso_url);
oidc_util_hdr_out_location_set(r, c->default_sso_url);
return HTTP_MOVED_TEMPORARILY;
}
oidc_error(r,
"invalid authorization response state and no default SSO URL is set, sending an error...");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if the response is an error response */
if (apr_table_get(params, OIDC_PROTO_ERROR) != NULL)
return oidc_authorization_response_error(r, c, proto_state,
apr_table_get(params, OIDC_PROTO_ERROR),
apr_table_get(params, OIDC_PROTO_ERROR_DESCRIPTION));
/* handle the code, implicit or hybrid flow */
if (oidc_handle_flows(r, c, proto_state, provider, params, response_mode,
&jwt) == FALSE)
return oidc_authorization_response_error(r, c, proto_state,
"Error in handling response type.", NULL);
if (jwt == NULL) {
oidc_error(r, "no id_token was provided");
return oidc_authorization_response_error(r, c, proto_state,
"No id_token was provided.", NULL);
}
int expires_in = oidc_parse_expires_in(r,
apr_table_get(params, OIDC_PROTO_EXPIRES_IN));
char *userinfo_jwt = NULL;
/*
* optionally resolve additional claims against the userinfo endpoint
* parsed claims are not actually used here but need to be parsed anyway for error checking purposes
*/
const char *claims = oidc_retrieve_claims_from_userinfo_endpoint(r, c,
provider, apr_table_get(params, OIDC_PROTO_ACCESS_TOKEN), NULL,
jwt->payload.sub, &userinfo_jwt);
/* restore the original protected URL that the user was trying to access */
const char *original_url = oidc_proto_state_get_original_url(proto_state);
if (original_url != NULL)
original_url = apr_pstrdup(r->pool, original_url);
const char *original_method = oidc_proto_state_get_original_method(
proto_state);
if (original_method != NULL)
original_method = apr_pstrdup(r->pool, original_method);
const char *prompt = oidc_proto_state_get_prompt(proto_state);
/* set the user */
if (oidc_set_request_user(r, c, provider, jwt, claims) == TRUE) {
/* session management: if the user in the new response is not equal to the old one, error out */
if ((prompt != NULL)
&& (apr_strnatcmp(prompt, OIDC_PROTO_PROMPT_NONE) == 0)) {
// TOOD: actually need to compare sub? (need to store it in the session separately then
//const char *sub = NULL;
//oidc_session_get(r, session, "sub", &sub);
//if (apr_strnatcmp(sub, jwt->payload.sub) != 0) {
if (apr_strnatcmp(session->remote_user, r->user) != 0) {
oidc_warn(r,
"user set from new id_token is different from current one");
oidc_jwt_destroy(jwt);
return oidc_authorization_response_error(r, c, proto_state,
"User changed!", NULL);
}
}
/* store resolved information in the session */
if (oidc_save_in_session(r, c, session, provider, r->user,
apr_table_get(params, OIDC_PROTO_ID_TOKEN), jwt, claims,
apr_table_get(params, OIDC_PROTO_ACCESS_TOKEN), expires_in,
apr_table_get(params, OIDC_PROTO_REFRESH_TOKEN),
apr_table_get(params, OIDC_PROTO_SESSION_STATE),
apr_table_get(params, OIDC_PROTO_STATE), original_url,
userinfo_jwt) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
} else {
oidc_error(r, "remote user could not be set");
return oidc_authorization_response_error(r, c, proto_state,
"Remote user could not be set: contact the website administrator",
NULL);
}
/* cleanup */
oidc_proto_state_destroy(proto_state);
oidc_jwt_destroy(jwt);
/* check that we've actually authenticated a user; functions as error handling for oidc_get_remote_user */
if (r->user == NULL)
return HTTP_UNAUTHORIZED;
/* log the successful response */
oidc_debug(r,
"session created and stored, returning to original URL: %s, original method: %s",
original_url, original_method);
/* check whether form post data was preserved; if so restore it */
if (apr_strnatcmp(original_method, OIDC_METHOD_FORM_POST) == 0) {
return oidc_request_post_preserved_restore(r, original_url);
}
/* now we've authenticated the user so go back to the URL that he originally tried to access */
oidc_util_hdr_out_location_set(r, original_url);
/* do the actual redirect to the original URL */
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle an OpenID Connect Authorization Response using the POST (+fragment->POST) response_mode
*/
static int oidc_handle_post_authorization_response(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
oidc_debug(r, "enter");
/* initialize local variables */
char *response_mode = NULL;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if we've got any POST-ed data at all */
if ((apr_table_elts(params)->nelts < 1)
|| ((apr_table_elts(params)->nelts == 1)
&& apr_table_get(params, OIDC_PROTO_RESPONSE_MODE)
&& (apr_strnatcmp(
apr_table_get(params, OIDC_PROTO_RESPONSE_MODE),
OIDC_PROTO_RESPONSE_MODE_FRAGMENT) == 0))) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"You've hit an OpenID Connect Redirect URI with no parameters, this is an invalid request; you should not open this URL in your browser directly, or have the server administrator use a different " OIDCRedirectURI " setting.",
HTTP_INTERNAL_SERVER_ERROR);
}
/* get the parameters */
response_mode = (char *) apr_table_get(params, OIDC_PROTO_RESPONSE_MODE);
/* do the actual implicit work */
return oidc_handle_authorization_response(r, c, session, params,
response_mode ? response_mode : OIDC_PROTO_RESPONSE_MODE_FORM_POST);
}
/*
* handle an OpenID Connect Authorization Response using the redirect response_mode
*/
static int oidc_handle_redirect_authorization_response(request_rec *r,
oidc_cfg *c, oidc_session_t *session) {
oidc_debug(r, "enter");
/* read the parameters from the query string */
apr_table_t *params = apr_table_make(r->pool, 8);
oidc_util_read_form_encoded_params(r, params, r->args);
/* do the actual work */
return oidc_handle_authorization_response(r, c, session, params,
OIDC_PROTO_RESPONSE_MODE_QUERY);
}
/*
* present the user with an OP selection screen
*/
static int oidc_discovery(request_rec *r, oidc_cfg *cfg) {
oidc_debug(r, "enter");
/* obtain the URL we're currently accessing, to be stored in the state/session */
char *current_url = oidc_get_current_url(r);
const char *method = oidc_original_request_method(r, cfg, FALSE);
/* generate CSRF token */
char *csrf = NULL;
if (oidc_proto_generate_nonce(r, &csrf, 8) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
char *path_scopes = oidc_dir_cfg_path_scope(r);
char *path_auth_request_params = oidc_dir_cfg_path_auth_request_params(r);
char *discover_url = oidc_cfg_dir_discover_url(r);
/* see if there's an external discovery page configured */
if (discover_url != NULL) {
/* yes, assemble the parameters for external discovery */
char *url = apr_psprintf(r->pool, "%s%s%s=%s&%s=%s&%s=%s&%s=%s",
discover_url,
strchr(discover_url, OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
OIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url),
OIDC_DISC_RM_PARAM, method,
OIDC_DISC_CB_PARAM,
oidc_util_escape_string(r, oidc_get_redirect_uri(r, cfg)),
OIDC_CSRF_NAME, oidc_util_escape_string(r, csrf));
if (path_scopes != NULL)
url = apr_psprintf(r->pool, "%s&%s=%s", url, OIDC_DISC_SC_PARAM,
oidc_util_escape_string(r, path_scopes));
if (path_auth_request_params != NULL)
url = apr_psprintf(r->pool, "%s&%s=%s", url, OIDC_DISC_AR_PARAM,
oidc_util_escape_string(r, path_auth_request_params));
/* log what we're about to do */
oidc_debug(r, "redirecting to external discovery page: %s", url);
/* set CSRF cookie */
oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1,
cfg->cookie_same_site ?
OIDC_COOKIE_EXT_SAME_SITE_STRICT :
NULL);
/* see if we need to preserve POST parameters through Javascript/HTML5 storage */
if (oidc_post_preserve_javascript(r, url, NULL, NULL) == TRUE)
return OK;
/* do the actual redirect to an external discovery page */
oidc_util_hdr_out_location_set(r, url);
return HTTP_MOVED_TEMPORARILY;
}
/* get a list of all providers configured in the metadata directory */
apr_array_header_t *arr = NULL;
if (oidc_metadata_list(r, cfg, &arr) == FALSE)
return oidc_util_html_send_error(r, cfg->error_template,
"Configuration Error",
"No configured providers found, contact your administrator",
HTTP_UNAUTHORIZED);
/* assemble a where-are-you-from IDP discovery HTML page */
const char *s = " <h3>Select your OpenID Connect Identity Provider</h3>\n";
/* list all configured providers in there */
int i;
for (i = 0; i < arr->nelts; i++) {
const char *issuer = ((const char**) arr->elts)[i];
// TODO: html escape (especially & character)
char *href = apr_psprintf(r->pool,
"%s?%s=%s&%s=%s&%s=%s&%s=%s",
oidc_get_redirect_uri(r, cfg), OIDC_DISC_OP_PARAM,
oidc_util_escape_string(r, issuer),
OIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url),
OIDC_DISC_RM_PARAM, method,
OIDC_CSRF_NAME, csrf);
if (path_scopes != NULL)
href = apr_psprintf(r->pool, "%s&%s=%s", href,
OIDC_DISC_SC_PARAM, oidc_util_escape_string(r, path_scopes));
if (path_auth_request_params != NULL)
href = apr_psprintf(r->pool, "%s&%s=%s", href,
OIDC_DISC_AR_PARAM,
oidc_util_escape_string(r, path_auth_request_params));
char *display =
(strstr(issuer, "https://") == NULL) ?
apr_pstrdup(r->pool, issuer) :
apr_pstrdup(r->pool, issuer + strlen("https://"));
/* strip port number */
//char *p = strstr(display, ":");
//if (p != NULL) *p = '\0';
/* point back to the redirect_uri, where the selection is handled, with an IDP selection and return_to URL */
s = apr_psprintf(r->pool, "%s<p><a href=\"%s\">%s</a></p>\n", s, href,
display);
}
/* add an option to enter an account or issuer name for dynamic OP discovery */
s = apr_psprintf(r->pool, "%s<form method=\"get\" action=\"%s\">\n", s,
oidc_get_redirect_uri(r, cfg));
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_RT_PARAM, current_url);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_RM_PARAM, method);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_CSRF_NAME, csrf);
if (path_scopes != NULL)
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_SC_PARAM, path_scopes);
if (path_auth_request_params != NULL)
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_AR_PARAM, path_auth_request_params);
s =
apr_psprintf(r->pool,
"%s<p>Or enter your account name (eg. "mike@seed.gluu.org", or an IDP identifier (eg. "mitreid.org"):</p>\n",
s);
s = apr_psprintf(r->pool,
"%s<p><input type=\"text\" name=\"%s\" value=\"%s\"></p>\n", s,
OIDC_DISC_OP_PARAM, "");
s = apr_psprintf(r->pool,
"%s<p><input type=\"submit\" value=\"Submit\"></p>\n", s);
s = apr_psprintf(r->pool, "%s</form>\n", s);
oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1,
cfg->cookie_same_site ? OIDC_COOKIE_EXT_SAME_SITE_STRICT : NULL);
char *javascript = NULL, *javascript_method = NULL;
char *html_head =
"<style type=\"text/css\">body {text-align: center}</style>";
if (oidc_post_preserve_javascript(r, NULL, &javascript,
&javascript_method) == TRUE)
html_head = apr_psprintf(r->pool, "%s%s", html_head, javascript);
/* now send the HTML contents to the user agent */
return oidc_util_html_send(r, "OpenID Connect Provider Discovery",
html_head, javascript_method, s, OK);
}
/*
* authenticate the user to the selected OP, if the OP is not selected yet perform discovery first
*/
static int oidc_authenticate_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, const char *original_url,
const char *login_hint, const char *id_token_hint, const char *prompt,
const char *auth_request_params, const char *path_scope) {
oidc_debug(r, "enter");
if (provider == NULL) {
// TODO: should we use an explicit redirect to the discovery endpoint (maybe a "discovery" param to the redirect_uri)?
if (c->metadata_dir != NULL)
return oidc_discovery(r, c);
/* we're not using multiple OP's configured in a metadata directory, pick the statically configured OP */
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
/* generate the random nonce value that correlates requests and responses */
char *nonce = NULL;
if (oidc_proto_generate_nonce(r, &nonce, OIDC_PROTO_NONCE_LENGTH) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
char *pkce_state = NULL;
char *code_challenge = NULL;
if ((oidc_util_spaced_string_contains(r->pool, provider->response_type,
OIDC_PROTO_CODE) == TRUE) && (provider->pkce != NULL)) {
/* generate the code verifier value that correlates authorization requests and code exchange requests */
if (provider->pkce->state(r, &pkce_state) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* generate the PKCE code challenge */
if (provider->pkce->challenge(r, pkce_state, &code_challenge) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
/* create the state between request/response */
oidc_proto_state_t *proto_state = oidc_proto_state_new();
oidc_proto_state_set_original_url(proto_state, original_url);
oidc_proto_state_set_original_method(proto_state,
oidc_original_request_method(r, c, TRUE));
oidc_proto_state_set_issuer(proto_state, provider->issuer);
oidc_proto_state_set_response_type(proto_state, provider->response_type);
oidc_proto_state_set_nonce(proto_state, nonce);
oidc_proto_state_set_timestamp_now(proto_state);
if (provider->response_mode)
oidc_proto_state_set_response_mode(proto_state,
provider->response_mode);
if (prompt)
oidc_proto_state_set_prompt(proto_state, prompt);
if (pkce_state)
oidc_proto_state_set_pkce_state(proto_state, pkce_state);
/* get a hash value that fingerprints the browser concatenated with the random input */
char *state = oidc_get_browser_state_hash(r, nonce);
/*
* create state that restores the context when the authorization response comes in
* and cryptographically bind it to the browser
*/
int rc = oidc_authorization_request_set_cookie(r, c, state, proto_state);
if (rc != HTTP_OK) {
oidc_proto_state_destroy(proto_state);
return rc;
}
/*
* printout errors if Cookie settings are not going to work
* TODO: separate this code out into its own function
*/
apr_uri_t o_uri;
memset(&o_uri, 0, sizeof(apr_uri_t));
apr_uri_t r_uri;
memset(&r_uri, 0, sizeof(apr_uri_t));
apr_uri_parse(r->pool, original_url, &o_uri);
apr_uri_parse(r->pool, oidc_get_redirect_uri(r, c), &r_uri);
if ((apr_strnatcmp(o_uri.scheme, r_uri.scheme) != 0)
&& (apr_strnatcmp(r_uri.scheme, "https") == 0)) {
oidc_error(r,
"the URL scheme (%s) of the configured " OIDCRedirectURI " does not match the URL scheme of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!",
r_uri.scheme, o_uri.scheme);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
if (c->cookie_domain == NULL) {
if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
char *p = strstr(o_uri.hostname, r_uri.hostname);
if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
oidc_error(r,
"the URL hostname (%s) of the configured " OIDCRedirectURI " does not match the URL hostname of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!",
r_uri.hostname, o_uri.hostname);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
} else {
if (!oidc_util_cookie_domain_valid(r_uri.hostname, c->cookie_domain)) {
oidc_error(r,
"the domain (%s) configured in " OIDCCookieDomain " does not match the URL hostname (%s) of the URL being accessed (%s): setting \"state\" and \"session\" cookies will not work!!",
c->cookie_domain, o_uri.hostname, original_url);
oidc_proto_state_destroy(proto_state);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
/* send off to the OpenID Connect Provider */
// TODO: maybe show intermediate/progress screen "redirecting to"
return oidc_proto_authorization_request(r, provider, login_hint,
oidc_get_redirect_uri_iss(r, c, provider), state, proto_state,
id_token_hint, code_challenge, auth_request_params, path_scope);
}
/*
* check if the target_link_uri matches to configuration settings to prevent an open redirect
*/
static int oidc_target_link_uri_matches_configuration(request_rec *r,
oidc_cfg *cfg, const char *target_link_uri) {
apr_uri_t o_uri;
apr_uri_parse(r->pool, target_link_uri, &o_uri);
if (o_uri.hostname == NULL) {
oidc_error(r,
"could not parse the \"target_link_uri\" (%s) in to a valid URL: aborting.",
target_link_uri);
return FALSE;
}
apr_uri_t r_uri;
apr_uri_parse(r->pool, oidc_get_redirect_uri(r, cfg), &r_uri);
if (cfg->cookie_domain == NULL) {
/* cookie_domain set: see if the target_link_uri matches the redirect_uri host (because the session cookie will be set host-wide) */
if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
char *p = strstr(o_uri.hostname, r_uri.hostname);
if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
oidc_error(r,
"the URL hostname (%s) of the configured " OIDCRedirectURI " does not match the URL hostname of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
r_uri.hostname, o_uri.hostname);
return FALSE;
}
}
} else {
/* cookie_domain set: see if the target_link_uri is within the cookie_domain */
char *p = strstr(o_uri.hostname, cfg->cookie_domain);
if ((p == NULL) || (apr_strnatcmp(cfg->cookie_domain, p) != 0)) {
oidc_error(r,
"the domain (%s) configured in " OIDCCookieDomain " does not match the URL hostname (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.hostname, target_link_uri);
return FALSE;
}
}
/* see if the cookie_path setting matches the target_link_uri path */
char *cookie_path = oidc_cfg_dir_cookie_path(r);
if (cookie_path != NULL) {
char *p = (o_uri.path != NULL) ? strstr(o_uri.path, cookie_path) : NULL;
if ((p == NULL) || (p != o_uri.path)) {
oidc_error(r,
"the path (%s) configured in " OIDCCookiePath " does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.path, target_link_uri);
return FALSE;
} else if (strlen(o_uri.path) > strlen(cookie_path)) {
int n = strlen(cookie_path);
if (cookie_path[n - 1] == OIDC_CHAR_FORWARD_SLASH)
n--;
if (o_uri.path[n] != OIDC_CHAR_FORWARD_SLASH) {
oidc_error(r,
"the path (%s) configured in " OIDCCookiePath " does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.path, target_link_uri);
return FALSE;
}
}
}
return TRUE;
}
/*
* handle a response from an IDP discovery page and/or handle 3rd-party initiated SSO
*/
static int oidc_handle_discovery_response(request_rec *r, oidc_cfg *c) {
/* variables to hold the values returned in the response */
char *issuer = NULL, *target_link_uri = NULL, *login_hint = NULL,
*auth_request_params = NULL, *csrf_cookie, *csrf_query = NULL,
*user = NULL, *path_scopes;
oidc_provider_t *provider = NULL;
oidc_util_get_request_parameter(r, OIDC_DISC_OP_PARAM, &issuer);
oidc_util_get_request_parameter(r, OIDC_DISC_USER_PARAM, &user);
oidc_util_get_request_parameter(r, OIDC_DISC_RT_PARAM, &target_link_uri);
oidc_util_get_request_parameter(r, OIDC_DISC_LH_PARAM, &login_hint);
oidc_util_get_request_parameter(r, OIDC_DISC_SC_PARAM, &path_scopes);
oidc_util_get_request_parameter(r, OIDC_DISC_AR_PARAM,
&auth_request_params);
oidc_util_get_request_parameter(r, OIDC_CSRF_NAME, &csrf_query);
csrf_cookie = oidc_util_get_cookie(r, OIDC_CSRF_NAME);
/* do CSRF protection if not 3rd party initiated SSO */
if (csrf_cookie) {
/* clean CSRF cookie */
oidc_util_set_cookie(r, OIDC_CSRF_NAME, "", 0, NULL);
/* compare CSRF cookie value with query parameter value */
if ((csrf_query == NULL)
|| apr_strnatcmp(csrf_query, csrf_cookie) != 0) {
oidc_warn(r,
"CSRF protection failed, no Discovery and dynamic client registration will be allowed");
csrf_cookie = NULL;
}
}
// TODO: trim issuer/accountname/domain input and do more input validation
oidc_debug(r,
"issuer=\"%s\", target_link_uri=\"%s\", login_hint=\"%s\", user=\"%s\"",
issuer, target_link_uri, login_hint, user);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"SSO to this module without specifying a \"target_link_uri\" parameter is not possible because " OIDCDefaultURL " is not set.",
HTTP_INTERNAL_SERVER_ERROR);
}
target_link_uri = c->default_sso_url;
}
/* do open redirect prevention */
if (oidc_target_link_uri_matches_configuration(r, c,
target_link_uri) == FALSE) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"\"target_link_uri\" parameter does not match configuration settings, aborting to prevent an open redirect.",
HTTP_UNAUTHORIZED);
}
/* see if this is a static setup */
if (c->metadata_dir == NULL) {
if ((oidc_provider_static_config(r, c, &provider) == TRUE)
&& (issuer != NULL)) {
if (apr_strnatcmp(provider->issuer, issuer) != 0) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
apr_psprintf(r->pool,
"The \"iss\" value must match the configured providers' one (%s != %s).",
issuer, c->provider.issuer),
HTTP_INTERNAL_SERVER_ERROR);
}
}
return oidc_authenticate_user(r, c, NULL, target_link_uri, login_hint,
NULL, NULL, auth_request_params, path_scopes);
}
/* find out if the user entered an account name or selected an OP manually */
if (user != NULL) {
if (login_hint == NULL)
login_hint = apr_pstrdup(r->pool, user);
/* normalize the user identifier */
if (strstr(user, "https://") != user)
user = apr_psprintf(r->pool, "https://%s", user);
/* got an user identifier as input, perform OP discovery with that */
if (oidc_proto_url_based_discovery(r, c, user, &issuer) == FALSE) {
/* something did not work out, show a user facing error */
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"Could not resolve the provided user identifier to an OpenID Connect provider; check your syntax.",
HTTP_NOT_FOUND);
}
/* issuer is set now, so let's continue as planned */
} else if (strstr(issuer, OIDC_STR_AT) != NULL) {
if (login_hint == NULL) {
login_hint = apr_pstrdup(r->pool, issuer);
//char *p = strstr(issuer, OIDC_STR_AT);
//*p = '\0';
}
/* got an account name as input, perform OP discovery with that */
if (oidc_proto_account_based_discovery(r, c, issuer, &issuer) == FALSE) {
/* something did not work out, show a user facing error */
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"Could not resolve the provided account name to an OpenID Connect provider; check your syntax.",
HTTP_NOT_FOUND);
}
/* issuer is set now, so let's continue as planned */
}
/* strip trailing '/' */
int n = strlen(issuer);
if (issuer[n - 1] == OIDC_CHAR_FORWARD_SLASH)
issuer[n - 1] = '\0';
/* try and get metadata from the metadata directories for the selected OP */
if ((oidc_metadata_get(r, c, issuer, &provider, csrf_cookie != NULL) == TRUE)
&& (provider != NULL)) {
/* now we've got a selected OP, send the user there to authenticate */
return oidc_authenticate_user(r, c, provider, target_link_uri,
login_hint, NULL, NULL, auth_request_params, path_scopes);
}
/* something went wrong */
return oidc_util_html_send_error(r, c->error_template, "Invalid Request",
"Could not find valid provider metadata for the selected OpenID Connect provider; contact the administrator",
HTTP_NOT_FOUND);
}
static apr_uint32_t oidc_transparent_pixel[17] = { 0x474e5089, 0x0a1a0a0d,
0x0d000000, 0x52444849, 0x01000000, 0x01000000, 0x00000408, 0x0c1cb500,
0x00000002, 0x4144490b, 0x639c7854, 0x0000cffa, 0x02010702, 0x71311c9a,
0x00000000, 0x444e4549, 0x826042ae };
static apr_byte_t oidc_is_front_channel_logout(const char *logout_param_value) {
return ((logout_param_value != NULL)
&& ((apr_strnatcmp(logout_param_value,
OIDC_GET_STYLE_LOGOUT_PARAM_VALUE) == 0)
|| (apr_strnatcmp(logout_param_value,
OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0)));
}
static apr_byte_t oidc_is_back_channel_logout(const char *logout_param_value) {
return ((logout_param_value != NULL) && (apr_strnatcmp(logout_param_value,
OIDC_BACKCHANNEL_STYLE_LOGOUT_PARAM_VALUE) == 0));
}
/*
* revoke refresh token and access token stored in the session if the
* OP has an RFC 7009 compliant token revocation endpoint
*/
static void oidc_revoke_tokens(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *response = NULL;
char *basic_auth = NULL;
char *bearer_auth = NULL;
apr_table_t *params = NULL;
const char *token = NULL;
oidc_provider_t *provider = NULL;
oidc_debug(r, "enter");
if (oidc_get_provider_from_session(r, c, session, &provider) == FALSE)
goto out;
oidc_debug(r, "revocation_endpoint=%s",
provider->revocation_endpoint_url ?
provider->revocation_endpoint_url : "(null)");
if (provider->revocation_endpoint_url == NULL)
goto out;
params = apr_table_make(r->pool, 4);
// add the token endpoint authentication credentials to the revocation endpoint call...
if (oidc_proto_token_endpoint_auth(r, c, provider->token_endpoint_auth,
provider->client_id, provider->client_secret,
provider->client_signing_keys, provider->token_endpoint_url, params,
NULL, &basic_auth, &bearer_auth) == FALSE)
goto out;
// TODO: use oauth.ssl_validate_server ...
token = oidc_session_get_refresh_token(r, session);
if (token != NULL) {
apr_table_addn(params, "token_type_hint", "refresh_token");
apr_table_addn(params, "token", token);
if (oidc_util_http_post_form(r, provider->revocation_endpoint_url,
params, basic_auth, bearer_auth, c->oauth.ssl_validate_server,
&response, c->http_timeout_long, c->outgoing_proxy,
oidc_dir_cfg_pass_cookies(r), NULL,
NULL) == FALSE) {
oidc_warn(r, "revoking refresh token failed");
}
apr_table_clear(params);
}
token = oidc_session_get_access_token(r, session);
if (token != NULL) {
apr_table_addn(params, "token_type_hint", "access_token");
apr_table_addn(params, "token", token);
if (oidc_util_http_post_form(r, provider->revocation_endpoint_url,
params, basic_auth, bearer_auth, c->oauth.ssl_validate_server,
&response, c->http_timeout_long, c->outgoing_proxy,
oidc_dir_cfg_pass_cookies(r), NULL,
NULL) == FALSE) {
oidc_warn(r, "revoking access token failed");
}
}
out:
oidc_debug(r, "leave");
}
/*
* handle a local logout
*/
static int oidc_handle_logout_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *url) {
oidc_debug(r, "enter (url=%s)", url);
/* if there's no remote_user then there's no (stored) session to kill */
if (session->remote_user != NULL) {
oidc_revoke_tokens(r, c, session);
/* remove session state (cq. cache entry and cookie) */
oidc_session_kill(r, session);
}
/* see if this is the OP calling us */
if (oidc_is_front_channel_logout(url)) {
/* set recommended cache control headers */
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_CACHE_CONTROL,
"no-cache, no-store");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_PRAGMA, "no-cache");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_P3P, "CAO PSA OUR");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_EXPIRES, "0");
oidc_util_hdr_err_out_add(r, OIDC_HTTP_HDR_X_FRAME_OPTIONS, "DENY");
/* see if this is PF-PA style logout in which case we return a transparent pixel */
const char *accept = oidc_util_hdr_in_accept_get(r);
if ((apr_strnatcmp(url, OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0)
|| ((accept) && strstr(accept, OIDC_CONTENT_TYPE_IMAGE_PNG))) {
return oidc_util_http_send(r,
(const char *) &oidc_transparent_pixel,
sizeof(oidc_transparent_pixel), OIDC_CONTENT_TYPE_IMAGE_PNG,
OK);
}
/* standard HTTP based logout: should be called in an iframe from the OP */
return oidc_util_html_send(r, "Logged Out", NULL, NULL,
"<p>Logged Out</p>", OK);
}
/* see if we don't need to go somewhere special after killing the session locally */
if (url == NULL)
return oidc_util_html_send(r, "Logged Out", NULL, NULL,
"<p>Logged Out</p>", OK);
/* send the user to the specified where-to-go-after-logout URL */
oidc_util_hdr_out_location_set(r, url);
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle a backchannel logout
*/
#define OIDC_EVENTS_BLOGOUT_KEY "http://schemas.openid.net/event/backchannel-logout"
static int oidc_handle_logout_backchannel(request_rec *r, oidc_cfg *cfg) {
oidc_debug(r, "enter");
const char *logout_token = NULL;
oidc_jwt_t *jwt = NULL;
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
oidc_provider_t *provider = NULL;
char *sid = NULL, *uuid = NULL;
oidc_session_t session;
int rc = HTTP_BAD_REQUEST;
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params, FALSE, NULL) == FALSE) {
oidc_error(r,
"could not read POST-ed parameters to the logout endpoint");
goto out;
}
logout_token = apr_table_get(params, OIDC_PROTO_LOGOUT_TOKEN);
if (logout_token == NULL) {
oidc_error(r,
"backchannel lggout endpoint was called but could not find a parameter named \"%s\"",
OIDC_PROTO_LOGOUT_TOKEN);
goto out;
}
// TODO: jwk symmetric key based on provider
// TODO: share more code with regular id_token validation and unsolicited state
if (oidc_jwt_parse(r->pool, logout_token, &jwt,
oidc_util_merge_symmetric_key(r->pool, cfg->private_keys, NULL),
&err) == FALSE) {
oidc_error(r, "oidc_jwt_parse failed: %s", oidc_jose_e2s(r->pool, err));
goto out;
}
provider = oidc_get_provider_for_issuer(r, cfg, jwt->payload.iss, FALSE);
if (provider == NULL) {
oidc_error(r, "no provider found for issuer: %s", jwt->payload.iss);
goto out;
}
// TODO: destroy the JWK used for decryption
jwk = NULL;
if (oidc_util_create_symmetric_key(r, provider->client_secret, 0,
NULL, TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwks_uri_t jwks_uri = { provider->jwks_uri,
provider->jwks_refresh_interval, provider->ssl_validate_server };
if (oidc_proto_jwt_verify(r, cfg, jwt, &jwks_uri,
oidc_util_merge_symmetric_key(r->pool, NULL, jwk)) == FALSE) {
oidc_error(r, "id_token signature could not be validated, aborting");
goto out;
}
// oidc_proto_validate_idtoken would try and require a token binding cnf
// if the policy is set to "required", so don't use that here
if (oidc_proto_validate_jwt(r, jwt, provider->issuer, FALSE, FALSE,
provider->idtoken_iat_slack,
OIDC_TOKEN_BINDING_POLICY_DISABLED) == FALSE)
goto out;
/* verify the "aud" and "azp" values */
if (oidc_proto_validate_aud_and_azp(r, cfg, provider,
&jwt->payload) == FALSE)
goto out;
json_t *events = json_object_get(jwt->payload.value.json,
OIDC_CLAIM_EVENTS);
if (events == NULL) {
oidc_error(r, "\"%s\" claim could not be found in logout token",
OIDC_CLAIM_EVENTS);
goto out;
}
json_t *blogout = json_object_get(events, OIDC_EVENTS_BLOGOUT_KEY);
if (!json_is_object(blogout)) {
oidc_error(r, "\"%s\" object could not be found in \"%s\" claim",
OIDC_EVENTS_BLOGOUT_KEY, OIDC_CLAIM_EVENTS);
goto out;
}
char *nonce = NULL;
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_NONCE, &nonce, NULL);
if (nonce != NULL) {
oidc_error(r,
"rejecting logout request/token since it contains a \"%s\" claim",
OIDC_CLAIM_NONCE);
goto out;
}
char *jti = NULL;
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_JTI, &jti, NULL);
if (jti != NULL) {
char *replay = NULL;
oidc_cache_get_jti(r, jti, &replay);
if (replay != NULL) {
oidc_error(r,
"the \"%s\" value (%s) passed in logout token was found in the cache already; possible replay attack!?",
OIDC_CLAIM_JTI, jti);
goto out;
}
}
/* jti cache duration is the configured replay prevention window for token issuance plus 10 seconds for safety */
apr_time_t jti_cache_duration = apr_time_from_sec(
provider->idtoken_iat_slack * 2 + 10);
/* store it in the cache for the calculated duration */
oidc_cache_set_jti(r, jti, jti, apr_time_now() + jti_cache_duration);
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_EVENTS, &sid, NULL);
// TODO: by-spec we should cater for the fact that "sid" has been provided
// in the id_token returned in the authentication request, but "sub"
// is used in the logout token but that requires a 2nd entry in the
// cache and a separate session "sub" member, ugh; we'll just assume
// that is "sid" is specified in the id_token, the OP will actually use
// this for logout
// (and probably call us multiple times or the same sub if needed)
oidc_json_object_get_string(r->pool, jwt->payload.value.json,
OIDC_CLAIM_SID, &sid, NULL);
if (sid == NULL)
sid = jwt->payload.sub;
if (sid == NULL) {
oidc_error(r, "no \"sub\" and no \"sid\" claim found in logout token");
goto out;
}
// TODO: when dealing with sub instead of a true sid, we'll be killing all sessions for
// a specific user, across hosts that share the *same* cache backend
// if those hosts haven't been configured with a different OIDCCryptoPassphrase
// - perhaps that's even acceptable since non-memory caching is encrypted by default
// and memory-based caching doesn't suffer from this (different shm segments)?
// - it will result in 400 errors returned from backchannel logout calls to the other hosts...
sid = oidc_make_sid_iss_unique(r, sid, provider->issuer);
oidc_cache_get_sid(r, sid, &uuid);
if (uuid == NULL) {
oidc_error(r,
"could not find session based on sid/sub provided in logout token: %s",
sid);
goto out;
}
// revoke tokens if we can get a handle on those
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
if (oidc_session_load_cache_by_uuid(r, cfg, uuid, &session) != FALSE)
if (oidc_session_extract(r, &session) != FALSE)
oidc_revoke_tokens(r, cfg, &session);
}
// clear the session cache
oidc_cache_set_sid(r, sid, NULL, 0);
oidc_cache_set_session(r, uuid, NULL, 0);
rc = OK;
out:
if (jwk != NULL) {
oidc_jwk_destroy(jwk);
jwk = NULL;
}
if (jwt != NULL) {
oidc_jwt_destroy(jwt);
jwt = NULL;
}
return rc;
}
static apr_byte_t oidc_validate_post_logout_url(request_rec *r, const char *url,
char **err_str, char **err_desc) {
apr_uri_t uri;
const char *c_host = NULL;
if (apr_uri_parse(r->pool, url, &uri) != APR_SUCCESS) {
*err_str = apr_pstrdup(r->pool, "Malformed URL");
*err_desc = apr_psprintf(r->pool, "Logout URL malformed: %s", url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
c_host = oidc_get_current_url_host(r);
if ((uri.hostname != NULL)
&& ((strstr(c_host, uri.hostname) == NULL)
|| (strstr(uri.hostname, c_host) == NULL))) {
*err_str = apr_pstrdup(r->pool, "Invalid Request");
*err_desc =
apr_psprintf(r->pool,
"logout value \"%s\" does not match the hostname of the current request \"%s\"",
apr_uri_unparse(r->pool, &uri, 0), c_host);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
} else if ((uri.hostname == NULL) && (strstr(url, "/") != url)) {
*err_str = apr_pstrdup(r->pool, "Malformed URL");
*err_desc =
apr_psprintf(r->pool,
"No hostname was parsed and it does not seem to be relative, i.e starting with '/': %s",
url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
} else if ((uri.hostname == NULL) && (strstr(url, "//") == url)) {
*err_str = apr_pstrdup(r->pool, "Malformed URL");
*err_desc =
apr_psprintf(r->pool,
"No hostname was parsed and starting with '//': %s",
url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
} else if ((uri.hostname == NULL) && (strstr(url, "/\\") == url)) {
*err_str = apr_pstrdup(r->pool, "Malformed URL");
*err_desc =
apr_psprintf(r->pool,
"No hostname was parsed and starting with '/\\': %s",
url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
/* validate the URL to prevent HTTP header splitting */
if (((strstr(url, "\n") != NULL) || strstr(url, "\r") != NULL)) {
*err_str = apr_pstrdup(r->pool, "Invalid Request");
*err_desc =
apr_psprintf(r->pool,
"logout value \"%s\" contains illegal \"\n\" or \"\r\" character(s)",
url);
oidc_error(r, "%s: %s", *err_str, *err_desc);
return FALSE;
}
return TRUE;
}
/*
* perform (single) logout
*/
static int oidc_handle_logout(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
oidc_provider_t *provider = NULL;
/* pickup the command or URL where the user wants to go after logout */
char *url = NULL;
char *error_str = NULL;
char *error_description = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_LOGOUT, &url);
oidc_debug(r, "enter (url=%s)", url);
if (oidc_is_front_channel_logout(url)) {
return oidc_handle_logout_request(r, c, session, url);
} else if (oidc_is_back_channel_logout(url)) {
return oidc_handle_logout_backchannel(r, c);
}
if ((url == NULL) || (apr_strnatcmp(url, "") == 0)) {
url = c->default_slo_url;
} else {
/* do input validation on the logout parameter value */
if (oidc_validate_post_logout_url(r, url, &error_str,
&error_description) == FALSE) {
return oidc_util_html_send_error(r, c->error_template, error_str,
error_description,
HTTP_BAD_REQUEST);
}
}
oidc_get_provider_from_session(r, c, session, &provider);
if ((provider != NULL) && (provider->end_session_endpoint != NULL)) {
const char *id_token_hint = oidc_session_get_idtoken(r, session);
char *logout_request = apr_pstrdup(r->pool,
provider->end_session_endpoint);
if (id_token_hint != NULL) {
logout_request = apr_psprintf(r->pool, "%s%sid_token_hint=%s",
logout_request, strchr(logout_request ? logout_request : "",
OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
oidc_util_escape_string(r, id_token_hint));
}
if (url != NULL) {
logout_request = apr_psprintf(r->pool,
"%s%spost_logout_redirect_uri=%s", logout_request,
strchr(logout_request ? logout_request : "",
OIDC_CHAR_QUERY) != NULL ?
OIDC_STR_AMP :
OIDC_STR_QUERY,
oidc_util_escape_string(r, url));
}
url = logout_request;
}
return oidc_handle_logout_request(r, c, session, url);
}
/*
* handle request for JWKs
*/
int oidc_handle_jwks(request_rec *r, oidc_cfg *c) {
/* pickup requested JWKs type */
// char *jwks_type = NULL;
// oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_JWKS, &jwks_type);
char *jwks = apr_pstrdup(r->pool, "{ \"keys\" : [");
apr_hash_index_t *hi = NULL;
apr_byte_t first = TRUE;
oidc_jose_error_t err;
if (c->public_keys != NULL) {
/* loop over the RSA public keys */
for (hi = apr_hash_first(r->pool, c->public_keys); hi; hi =
apr_hash_next(hi)) {
const char *s_kid = NULL;
oidc_jwk_t *jwk = NULL;
char *s_json = NULL;
apr_hash_this(hi, (const void**) &s_kid, NULL, (void**) &jwk);
if (oidc_jwk_to_json(r->pool, jwk, &s_json, &err) == TRUE) {
jwks = apr_psprintf(r->pool, "%s%s %s ", jwks, first ? "" : ",",
s_json);
first = FALSE;
} else {
oidc_error(r,
"could not convert RSA JWK to JSON using oidc_jwk_to_json: %s",
oidc_jose_e2s(r->pool, err));
}
}
}
// TODO: send stuff if first == FALSE?
jwks = apr_psprintf(r->pool, "%s ] }", jwks);
return oidc_util_http_send(r, jwks, strlen(jwks), OIDC_CONTENT_TYPE_JSON,
OK);
}
static int oidc_handle_session_management_iframe_op(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *check_session_iframe) {
oidc_debug(r, "enter");
oidc_util_hdr_out_location_set(r, check_session_iframe);
return HTTP_MOVED_TEMPORARILY;
}
static int oidc_handle_session_management_iframe_rp(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *client_id,
const char *check_session_iframe) {
oidc_debug(r, "enter");
const char *java_script =
" <script type=\"text/javascript\">\n"
" var targetOrigin = '%s';\n"
" var message = '%s' + ' ' + '%s';\n"
" var timerID;\n"
"\n"
" function checkSession() {\n"
" console.debug('checkSession: posting ' + message + ' to ' + targetOrigin);\n"
" var win = window.parent.document.getElementById('%s').contentWindow;\n"
" win.postMessage( message, targetOrigin);\n"
" }\n"
"\n"
" function setTimer() {\n"
" checkSession();\n"
" timerID = setInterval('checkSession()', %d);\n"
" }\n"
"\n"
" function receiveMessage(e) {\n"
" console.debug('receiveMessage: ' + e.data + ' from ' + e.origin);\n"
" if (e.origin !== targetOrigin ) {\n"
" console.debug('receiveMessage: cross-site scripting attack?');\n"
" return;\n"
" }\n"
" if (e.data != 'unchanged') {\n"
" clearInterval(timerID);\n"
" if (e.data == 'changed') {\n"
" window.location.href = '%s?session=check';\n"
" } else {\n"
" window.location.href = '%s?session=logout';\n"
" }\n"
" }\n"
" }\n"
"\n"
" window.addEventListener('message', receiveMessage, false);\n"
"\n"
" </script>\n";
/* determine the origin for the check_session_iframe endpoint */
char *origin = apr_pstrdup(r->pool, check_session_iframe);
apr_uri_t uri;
apr_uri_parse(r->pool, check_session_iframe, &uri);
char *p = strstr(origin, uri.path);
*p = '\0';
/* the element identifier for the OP iframe */
const char *op_iframe_id = "openidc-op";
/* restore the OP session_state from the session */
const char *session_state = oidc_session_get_session_state(r, session);
if (session_state == NULL) {
oidc_warn(r,
"no session_state found in the session; the OP does probably not support session management!?");
return OK;
}
char *s_poll_interval = NULL;
oidc_util_get_request_parameter(r, "poll", &s_poll_interval);
int poll_interval = s_poll_interval ? strtol(s_poll_interval, NULL, 10) : 0;
if ((poll_interval <= 0) || (poll_interval > 3600 * 24))
poll_interval = 3000;
const char *redirect_uri = oidc_get_redirect_uri(r, c);
java_script = apr_psprintf(r->pool, java_script, origin, client_id,
session_state, op_iframe_id, poll_interval, redirect_uri,
redirect_uri);
return oidc_util_html_send(r, NULL, java_script, "setTimer", NULL, OK);
}
/*
* handle session management request
*/
static int oidc_handle_session_management(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *cmd = NULL;
const char *id_token_hint = NULL;
oidc_provider_t *provider = NULL;
/* get the command passed to the session management handler */
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_SESSION, &cmd);
if (cmd == NULL) {
oidc_error(r, "session management handler called with no command");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if this is a local logout during session management */
if (apr_strnatcmp("logout", cmd) == 0) {
oidc_debug(r,
"[session=logout] calling oidc_handle_logout_request because of session mgmt local logout call.");
return oidc_handle_logout_request(r, c, session, c->default_slo_url);
}
oidc_get_provider_from_session(r, c, session, &provider);
/* see if this is a request for the OP iframe */
if (apr_strnatcmp("iframe_op", cmd) == 0) {
if (provider->check_session_iframe != NULL) {
return oidc_handle_session_management_iframe_op(r, c, session,
provider->check_session_iframe);
}
return HTTP_NOT_FOUND;
}
/* see if this is a request for the RP iframe */
if (apr_strnatcmp("iframe_rp", cmd) == 0) {
if ((provider->client_id != NULL)
&& (provider->check_session_iframe != NULL)) {
return oidc_handle_session_management_iframe_rp(r, c, session,
provider->client_id, provider->check_session_iframe);
}
oidc_debug(r,
"iframe_rp command issued but no client (%s) and/or no check_session_iframe (%s) set",
provider->client_id, provider->check_session_iframe);
return HTTP_NOT_FOUND;
}
/* see if this is a request check the login state with the OP */
if (apr_strnatcmp("check", cmd) == 0) {
id_token_hint = oidc_session_get_idtoken(r, session);
if ((session->remote_user != NULL) && (provider != NULL)) {
/*
* TODO: this doesn't work with per-path provided auth_request_params and scopes
* as oidc_dir_cfg_path_auth_request_params and oidc_dir_cfg_path_scope will pick
* those for the redirect_uri itself; do we need to store those as part of the
* session now?
*/
return oidc_authenticate_user(r, c, provider,
apr_psprintf(r->pool, "%s?session=iframe_rp",
oidc_get_redirect_uri_iss(r, c, provider)), NULL,
id_token_hint, "none",
oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
}
oidc_debug(r,
"[session=check] calling oidc_handle_logout_request because no session found.");
return oidc_session_redirect_parent_window_to_logout(r, c);
}
/* handle failure in fallthrough */
oidc_error(r, "unknown command: %s", cmd);
return HTTP_INTERNAL_SERVER_ERROR;
}
/*
* handle refresh token request
*/
static int oidc_handle_refresh_token_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *return_to = NULL;
char *r_access_token = NULL;
char *error_code = NULL;
/* get the command passed to the session management handler */
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_REFRESH,
&return_to);
oidc_util_get_request_parameter(r, OIDC_PROTO_ACCESS_TOKEN,
&r_access_token);
/* check the input parameters */
if (return_to == NULL) {
oidc_error(r,
"refresh token request handler called with no URL to return to");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (r_access_token == NULL) {
oidc_error(r,
"refresh token request handler called with no access_token parameter");
error_code = "no_access_token";
goto end;
}
const char *s_access_token = oidc_session_get_access_token(r, session);
if (s_access_token == NULL) {
oidc_error(r,
"no existing access_token found in the session, nothing to refresh");
error_code = "no_access_token_exists";
goto end;
}
/* compare the access_token parameter used for XSRF protection */
if (apr_strnatcmp(s_access_token, r_access_token) != 0) {
oidc_error(r,
"access_token passed in refresh request does not match the one stored in the session");
error_code = "no_access_token_match";
goto end;
}
/* get a handle to the provider configuration */
oidc_provider_t *provider = NULL;
if (oidc_get_provider_from_session(r, c, session, &provider) == FALSE) {
error_code = "session_corruption";
goto end;
}
/* execute the actual refresh grant */
if (oidc_refresh_access_token(r, c, session, provider, NULL) == FALSE) {
oidc_error(r, "access_token could not be refreshed");
error_code = "refresh_failed";
goto end;
}
/* pass the tokens to the application and save the session, possibly updating the expiry */
if (oidc_session_pass_tokens_and_save(r, c, session, TRUE) == FALSE) {
error_code = "session_corruption";
goto end;
}
end:
/* pass optional error message to the return URL */
if (error_code != NULL)
return_to = apr_psprintf(r->pool, "%s%serror_code=%s", return_to,
strchr(return_to ? return_to : "", OIDC_CHAR_QUERY) ?
OIDC_STR_AMP :
OIDC_STR_QUERY, oidc_util_escape_string(r, error_code));
/* add the redirect location header */
oidc_util_hdr_out_location_set(r, return_to);
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle request object by reference request
*/
static int oidc_handle_request_uri(request_rec *r, oidc_cfg *c) {
char *request_ref = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_REQUEST_URI,
&request_ref);
if (request_ref == NULL) {
oidc_error(r, "no \"%s\" parameter found",
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI);
return HTTP_BAD_REQUEST;
}
char *jwt = NULL;
oidc_cache_get_request_uri(r, request_ref, &jwt);
if (jwt == NULL) {
oidc_error(r, "no cached JWT found for %s reference: %s",
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI, request_ref);
return HTTP_NOT_FOUND;
}
oidc_cache_set_request_uri(r, request_ref, NULL, 0);
return oidc_util_http_send(r, jwt, strlen(jwt), OIDC_CONTENT_TYPE_JWT, OK);
}
/*
* handle a request to invalidate a cached access token introspection result
*/
int oidc_handle_remove_at_cache(request_rec *r, oidc_cfg *c) {
char *access_token = NULL;
oidc_util_get_request_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REMOVE_AT_CACHE, &access_token);
char *cache_entry = NULL;
oidc_cache_get_access_token(r, access_token, &cache_entry);
if (cache_entry == NULL) {
oidc_error(r, "no cached access token found for value: %s",
access_token);
return HTTP_NOT_FOUND;
}
oidc_cache_set_access_token(r, access_token, NULL, 0);
return OK;
}
#define OIDC_INFO_PARAM_ACCESS_TOKEN_REFRESH_INTERVAL "access_token_refresh_interval"
/*
* handle request for session info
*/
static int oidc_handle_info_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
int rc = HTTP_UNAUTHORIZED;
apr_byte_t needs_save = FALSE;
char *s_format = NULL, *s_interval = NULL, *r_value = NULL;
oidc_util_get_request_parameter(r, OIDC_REDIRECT_URI_REQUEST_INFO,
&s_format);
oidc_util_get_request_parameter(r,
OIDC_INFO_PARAM_ACCESS_TOKEN_REFRESH_INTERVAL, &s_interval);
/* see if this is a request for a format that is supported */
if ((apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_JSON, s_format) != 0)
&& (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_HTML, s_format) != 0)) {
oidc_warn(r, "request for unknown format: %s", s_format);
return HTTP_UNSUPPORTED_MEDIA_TYPE;
}
/* check that we actually have a user session and this is someone calling with a proper session cookie */
if (session->remote_user == NULL) {
oidc_warn(r, "no user session found");
return HTTP_UNAUTHORIZED;
}
/* set the user in the main request for further (incl. sub-request and authz) processing */
r->user = apr_pstrdup(r->pool, session->remote_user);
if (c->info_hook_data == NULL) {
oidc_warn(r, "no data configured to return in " OIDCInfoHook);
return HTTP_NOT_FOUND;
}
/* see if we can and need to refresh the access token */
if ((s_interval != NULL)
&& (oidc_session_get_refresh_token(r, session) != NULL)) {
apr_time_t t_interval;
if (sscanf(s_interval, "%" APR_TIME_T_FMT, &t_interval) == 1) {
t_interval = apr_time_from_sec(t_interval);
/* get the last refresh timestamp from the session info */
apr_time_t last_refresh =
oidc_session_get_access_token_last_refresh(r, session);
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(last_refresh + t_interval - apr_time_now()));
/* see if we need to refresh again */
if (last_refresh + t_interval < apr_time_now()) {
/* get the current provider info */
oidc_provider_t *provider = NULL;
if (oidc_get_provider_from_session(r, c, session,
&provider) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* execute the actual refresh grant */
if (oidc_refresh_access_token(r, c, session, provider,
NULL) == FALSE)
oidc_warn(r, "access_token could not be refreshed");
else
needs_save = TRUE;
}
}
}
/* create the JSON object */
json_t *json = json_object();
/* add a timestamp of creation in there for the caller */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_TIMESTAMP,
APR_HASH_KEY_STRING)) {
json_object_set_new(json, OIDC_HOOK_INFO_TIMESTAMP,
json_integer(apr_time_sec(apr_time_now())));
}
/*
* refresh the claims from the userinfo endpoint
* side-effect is that this may refresh the access token if not already done
* note that OIDCUserInfoRefreshInterval should be set to control the refresh policy
*/
needs_save |= oidc_refresh_claims_from_userinfo_endpoint(r, c, session);
/* include the access token in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ACCES_TOKEN,
APR_HASH_KEY_STRING)) {
const char *access_token = oidc_session_get_access_token(r, session);
if (access_token != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_ACCES_TOKEN,
json_string(access_token));
}
/* include the access token expiry timestamp in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ACCES_TOKEN_EXP,
APR_HASH_KEY_STRING)) {
const char *access_token_expires =
oidc_session_get_access_token_expires(r, session);
if (access_token_expires != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_ACCES_TOKEN_EXP,
json_string(access_token_expires));
}
/* include the id_token claims in the session info */
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_ID_TOKEN,
APR_HASH_KEY_STRING)) {
json_t *id_token = oidc_session_get_idtoken_claims_json(r, session);
if (id_token)
json_object_set_new(json, OIDC_HOOK_INFO_ID_TOKEN, id_token);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_USER_INFO,
APR_HASH_KEY_STRING)) {
/* include the claims from the userinfo endpoint the session info */
json_t *claims = oidc_session_get_userinfo_claims_json(r, session);
if (claims)
json_object_set_new(json, OIDC_HOOK_INFO_USER_INFO, claims);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_SESSION,
APR_HASH_KEY_STRING)) {
json_t *j_session = json_object();
json_object_set(j_session, OIDC_HOOK_INFO_SESSION_STATE,
session->state);
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_UUID,
json_string(session->uuid));
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_TIMEOUT,
json_integer(apr_time_sec(session->expiry)));
apr_time_t session_expires = oidc_session_get_session_expires(r,
session);
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_EXP,
json_integer(apr_time_sec(session_expires)));
json_object_set_new(j_session, OIDC_HOOK_INFO_SESSION_REMOTE_USER,
json_string(session->remote_user));
json_object_set_new(json, OIDC_HOOK_INFO_SESSION, j_session);
}
if (apr_hash_get(c->info_hook_data, OIDC_HOOK_INFO_REFRESH_TOKEN,
APR_HASH_KEY_STRING)) {
/* include the refresh token in the session info */
const char *refresh_token = oidc_session_get_refresh_token(r, session);
if (refresh_token != NULL)
json_object_set_new(json, OIDC_HOOK_INFO_REFRESH_TOKEN,
json_string(refresh_token));
}
if (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_JSON, s_format) == 0) {
/* JSON-encode the result */
r_value = oidc_util_encode_json_object(r, json, 0);
/* return the stringified JSON result */
rc = oidc_util_http_send(r, r_value, strlen(r_value),
OIDC_CONTENT_TYPE_JSON, OK);
} else if (apr_strnatcmp(OIDC_HOOK_INFO_FORMAT_HTML, s_format) == 0) {
/* JSON-encode the result */
r_value = oidc_util_encode_json_object(r, json, JSON_INDENT(2));
rc = oidc_util_html_send(r, "Session Info", NULL, NULL,
apr_psprintf(r->pool, "<pre>%s</pre>", r_value), OK);
}
/* free the allocated resources */
json_decref(json);
/* pass the tokens to the application and save the session, possibly updating the expiry */
if (oidc_session_pass_tokens_and_save(r, c, session, needs_save) == FALSE) {
oidc_warn(r, "error saving session");
rc = HTTP_INTERNAL_SERVER_ERROR;
}
return rc;
}
/*
* handle all requests to the redirect_uri
*/
int oidc_handle_redirect_uri_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
if (oidc_proto_is_redirect_authorization_response(r, c)) {
/* this is an authorization response from the OP using the Basic Client profile or a Hybrid flow*/
return oidc_handle_redirect_authorization_response(r, c, session);
/*
*
* Note that we are checking for logout *before* checking for a POST authorization response
* to handle backchannel POST-based logout
*
* so any POST to the Redirect URI that does not have a logout query parameter will be handled
* as an authorization response; alternatively we could assume that a POST response has no
* parameters
*/
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_LOGOUT)) {
/* handle logout */
return oidc_handle_logout(r, c, session);
} else if (oidc_proto_is_post_authorization_response(r, c)) {
/* this is an authorization response using the fragment(+POST) response_mode with the Implicit Client profile */
return oidc_handle_post_authorization_response(r, c, session);
} else if (oidc_is_discovery_response(r, c)) {
/* this is response from the OP discovery page */
return oidc_handle_discovery_response(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_JWKS)) {
/* handle JWKs request */
return oidc_handle_jwks(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_SESSION)) {
/* handle session management request */
return oidc_handle_session_management(r, c, session);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REFRESH)) {
/* handle refresh token request */
return oidc_handle_refresh_token_request(r, c, session);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REQUEST_URI)) {
/* handle request object by reference request */
return oidc_handle_request_uri(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_REMOVE_AT_CACHE)) {
/* handle request to invalidate access token cache */
return oidc_handle_remove_at_cache(r, c);
} else if (oidc_util_request_has_parameter(r,
OIDC_REDIRECT_URI_REQUEST_INFO)) {
if (session->remote_user == NULL)
return HTTP_UNAUTHORIZED;
/* set r->user, set headers/env-vars, update expiry, update userinfo + AT */
int rc = oidc_handle_existing_session(r, c, session);
if (rc != OK)
return rc;
return oidc_handle_info_request(r, c, session);
} else if ((r->args == NULL) || (apr_strnatcmp(r->args, "") == 0)) {
/* this is a "bare" request to the redirect URI, indicating implicit flow using the fragment response_mode */
return oidc_proto_javascript_implicit(r, c);
}
/* this is not an authorization response or logout request */
/* check for "error" response */
if (oidc_util_request_has_parameter(r, OIDC_PROTO_ERROR)) {
// char *error = NULL, *descr = NULL;
// oidc_util_get_request_parameter(r, "error", &error);
// oidc_util_get_request_parameter(r, "error_description", &descr);
//
// /* send user facing error to browser */
// return oidc_util_html_send_error(r, error, descr, DONE);
return oidc_handle_redirect_authorization_response(r, c, session);
}
oidc_error(r,
"The OpenID Connect callback URL received an invalid request: %s; returning HTTP_INTERNAL_SERVER_ERROR",
r->args);
/* something went wrong */
return oidc_util_html_send_error(r, c->error_template, "Invalid Request",
apr_psprintf(r->pool,
"The OpenID Connect callback URL received an invalid request"),
HTTP_INTERNAL_SERVER_ERROR);
}
#define OIDC_AUTH_TYPE_OPENID_CONNECT "openid-connect"
#define OIDC_AUTH_TYPE_OPENID_OAUTH20 "oauth20"
#define OIDC_AUTH_TYPE_OPENID_BOTH "auth-openidc"
/*
* main routine: handle OpenID Connect authentication
*/
static int oidc_check_userid_openidc(request_rec *r, oidc_cfg *c) {
if (oidc_get_redirect_uri(r, c) == NULL) {
oidc_error(r,
"configuration error: the authentication type is set to \"" OIDC_AUTH_TYPE_OPENID_CONNECT "\" but " OIDCRedirectURI " has not been set");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* check if this is a sub-request or an initial request */
if (ap_is_initial_req(r)) {
int rc = OK;
/* load the session from the request state; this will be a new "empty" session if no state exists */
oidc_session_t *session = NULL;
oidc_session_load(r, &session);
/* see if the initial request is to the redirect URI; this handles potential logout too */
if (oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, c))) {
/* handle request to the redirect_uri */
rc = oidc_handle_redirect_uri_request(r, c, session);
/* free resources allocated for the session */
oidc_session_free(r, session);
return rc;
/* initial request to non-redirect URI, check if we have an existing session */
} else if (session->remote_user != NULL) {
/* this is initial request and we already have a session */
rc = oidc_handle_existing_session(r, c, session);
/* free resources allocated for the session */
oidc_session_free(r, session);
/* strip any cookies that we need to */
oidc_strip_cookies(r);
return rc;
}
/* free resources allocated for the session */
oidc_session_free(r, session);
/*
* else: initial request, we have no session and it is not an authorization or
* discovery response: just hit the default flow for unauthenticated users
*/
} else {
/* not an initial request, try to recycle what we've already established in the main request */
if (r->main != NULL)
r->user = r->main->user;
else if (r->prev != NULL)
r->user = r->prev->user;
if (r->user != NULL) {
/* this is a sub-request and we have a session (headers will have been scrubbed and set already) */
oidc_debug(r,
"recycling user '%s' from initial request for sub-request",
r->user);
/*
* apparently request state can get lost in sub-requests, so let's see
* if we need to restore id_token and/or claims from the session cache
*/
const char *s_id_token = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_IDTOKEN);
if (s_id_token == NULL) {
oidc_session_t *session = NULL;
oidc_session_load(r, &session);
oidc_copy_tokens_to_request_state(r, session, NULL, NULL);
/* free resources allocated for the session */
oidc_session_free(r, session);
}
/* strip any cookies that we need to */
oidc_strip_cookies(r);
return OK;
}
/*
* else: not initial request, but we could not find a session, so:
* just hit the default flow for unauthenticated users
*/
}
return oidc_handle_unauthenticated_user(r, c);
}
/*
* main routine: handle "mixed" OIDC/OAuth authentication
*/
static int oidc_check_mixed_userid_oauth(request_rec *r, oidc_cfg *c) {
/* get the bearer access token from the Authorization header */
const char *access_token = NULL;
if (oidc_oauth_get_bearer_token(r, &access_token) == TRUE)
return oidc_oauth_check_userid(r, c, access_token);
/* no bearer token found: then treat this as a regular OIDC browser request */
return oidc_check_userid_openidc(r, c);
}
/*
* generic Apache authentication hook for this module: dispatches to OpenID Connect or OAuth 2.0 specific routines
*/
int oidc_check_user_id(request_rec *r) {
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
/* log some stuff about the incoming HTTP request */
oidc_debug(r, "incoming request: \"%s?%s\", ap_is_initial_req(r)=%d",
r->parsed_uri.path, r->args, ap_is_initial_req(r));
/* see if any authentication has been defined at all */
if (ap_auth_type(r) == NULL)
return DECLINED;
/* see if we've configured OpenID Connect user authentication for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_CONNECT) == 0)
return oidc_check_userid_openidc(r, c);
/* see if we've configured OAuth 2.0 access control for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0)
return oidc_oauth_check_userid(r, c, NULL);
/* see if we've configured "mixed mode" for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_BOTH) == 0)
return oidc_check_mixed_userid_oauth(r, c);
/* this is not for us but for some other handler */
return DECLINED;
}
/*
* get the claims and id_token from request state
*/
static void oidc_authz_get_claims_and_idtoken(request_rec *r, json_t **claims,
json_t **id_token) {
const char *s_claims = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_CLAIMS);
if (s_claims != NULL)
oidc_util_decode_json_object(r, s_claims, claims);
const char *s_id_token = oidc_request_state_get(r,
OIDC_REQUEST_STATE_KEY_IDTOKEN);
if (s_id_token != NULL)
oidc_util_decode_json_object(r, s_id_token, id_token);
}
#if MODULE_MAGIC_NUMBER_MAJOR >= 20100714
/*
* find out which action we need to take when encountering an unauthorized request
*/
static authz_status oidc_handle_unauthorized_user24(request_rec *r) {
oidc_debug(r, "enter");
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0) {
oidc_oauth_return_www_authenticate(r, "insufficient_scope",
"Different scope(s) or other claims required");
return AUTHZ_DENIED;
}
/* see if we've configured OIDCUnAutzAction for this path */
switch (oidc_dir_cfg_unautz_action(r)) {
// TODO: document that AuthzSendForbiddenOnFailure is required to return 403 FORBIDDEN
case OIDC_UNAUTZ_RETURN403:
case OIDC_UNAUTZ_RETURN401:
return AUTHZ_DENIED;
break;
case OIDC_UNAUTZ_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return AUTHZ_DENIED;
break;
}
oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r),
oidc_dir_cfg_path_scope(r));
const char *location = oidc_util_hdr_out_location_get(r);
if (location != NULL) {
oidc_debug(r, "send HTML refresh with authorization redirect: %s",
location);
char *html_head = apr_psprintf(r->pool,
"<meta http-equiv=\"refresh\" content=\"0; url=%s\">",
location);
oidc_util_html_send(r, "Stepup Authentication", html_head, NULL, NULL,
HTTP_UNAUTHORIZED);
}
return AUTHZ_DENIED;
}
/*
* generic Apache >=2.4 authorization hook for this module
* handles both OpenID Connect or OAuth 2.0 in the same way, based on the claims stored in the session
*/
authz_status oidc_authz_checker(request_rec *r, const char *require_args,
const void *parsed_require_args,
oidc_authz_match_claim_fn_type match_claim_fn) {
oidc_debug(r, "enter");
/* check for anonymous access and PASS mode */
if (r->user != NULL && strlen(r->user) == 0) {
r->user = NULL;
if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS)
return AUTHZ_GRANTED;
}
/* get the set of claims from the request state (they've been set in the authentication part earlier */
json_t *claims = NULL, *id_token = NULL;
oidc_authz_get_claims_and_idtoken(r, &claims, &id_token);
/* merge id_token claims (e.g. "iss") in to claims json object */
if (claims)
oidc_util_json_merge(r, id_token, claims);
/* dispatch to the >=2.4 specific authz routine */
authz_status rc = oidc_authz_worker24(r, claims ? claims : id_token,
require_args, match_claim_fn);
/* cleanup */
if (claims)
json_decref(claims);
if (id_token)
json_decref(id_token);
if ((rc == AUTHZ_DENIED) && ap_auth_type(r))
rc = oidc_handle_unauthorized_user24(r);
return rc;
}
authz_status oidc_authz_checker_claim(request_rec *r, const char *require_args,
const void *parsed_require_args) {
return oidc_authz_checker(r, require_args, parsed_require_args,
oidc_authz_match_claim);
}
#ifdef USE_LIBJQ
authz_status oidc_authz_checker_claims_expr(request_rec *r, const char *require_args, const void *parsed_require_args) {
return oidc_authz_checker(r, require_args, parsed_require_args, oidc_authz_match_claims_expr);
}
#endif
#else
/*
* find out which action we need to take when encountering an unauthorized request
*/
static int oidc_handle_unauthorized_user22(request_rec *r) {
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
if (apr_strnatcasecmp((const char *) ap_auth_type(r), OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0) {
oidc_oauth_return_www_authenticate(r, "insufficient_scope", "Different scope(s) or other claims required");
return HTTP_UNAUTHORIZED;
}
/* see if we've configured OIDCUnAutzAction for this path */
switch (oidc_dir_cfg_unautz_action(r)) {
case OIDC_UNAUTZ_RETURN403:
return HTTP_FORBIDDEN;
case OIDC_UNAUTZ_RETURN401:
return HTTP_UNAUTHORIZED;
case OIDC_UNAUTZ_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if (oidc_is_xml_http_request(r) == TRUE)
return HTTP_UNAUTHORIZED;
}
return oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, oidc_dir_cfg_path_auth_request_params(r), oidc_dir_cfg_path_scope(r));
}
/*
* generic Apache <2.4 authorization hook for this module
* handles both OpenID Connect and OAuth 2.0 in the same way, based on the claims stored in the request context
*/
int oidc_auth_checker(request_rec *r) {
/* check for anonymous access and PASS mode */
if (r->user != NULL && strlen(r->user) == 0) {
r->user = NULL;
if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS)
return OK;
}
/* get the set of claims from the request state (they've been set in the authentication part earlier */
json_t *claims = NULL, *id_token = NULL;
oidc_authz_get_claims_and_idtoken(r, &claims, &id_token);
/* get the Require statements */
const apr_array_header_t * const reqs_arr = ap_requires(r);
/* see if we have any */
const require_line * const reqs =
reqs_arr ? (require_line *) reqs_arr->elts : NULL;
if (!reqs_arr) {
oidc_debug(r,
"no require statements found, so declining to perform authorization.");
return DECLINED;
}
/* merge id_token claims (e.g. "iss") in to claims json object */
if (claims)
oidc_util_json_merge(r, id_token, claims);
/* dispatch to the <2.4 specific authz routine */
int rc = oidc_authz_worker22(r, claims ? claims : id_token, reqs,
reqs_arr->nelts);
/* cleanup */
if (claims)
json_decref(claims);
if (id_token)
json_decref(id_token);
if ((rc == HTTP_UNAUTHORIZED) && ap_auth_type(r))
rc = oidc_handle_unauthorized_user22(r);
return rc;
}
#endif
apr_byte_t oidc_enabled(request_rec *r) {
if (ap_auth_type(r) == NULL)
return FALSE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_CONNECT) == 0)
return TRUE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_OAUTH20) == 0)
return TRUE;
if (apr_strnatcasecmp((const char *) ap_auth_type(r),
OIDC_AUTH_TYPE_OPENID_BOTH) == 0)
return TRUE;
return FALSE;
}
/*
* handle content generating requests
*/
int oidc_content_handler(request_rec *r) {
if (oidc_enabled(r) == FALSE)
return DECLINED;
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
return oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, c)) ?
OK : DECLINED;
}
extern const command_rec oidc_config_cmds[];
module AP_MODULE_DECLARE_DATA auth_openidc_module = {
STANDARD20_MODULE_STUFF,
oidc_create_dir_config,
oidc_merge_dir_config,
oidc_create_server_config,
oidc_merge_server_config,
oidc_config_cmds,
oidc_register_hooks
};
| ./CrossVul/dataset_final_sorted/CWE-601/c/good_1369_0 |
crossvul-cpp_data_bad_1981_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-295/cpp/bad_1981_0 |
crossvul-cpp_data_good_1981_0 | #include "MCWin32.h" // Should be included first.
#include "MCIMAPSession.h"
#include <libetpan/libetpan.h>
#include <string.h>
#include <stdlib.h>
#include "MCDefines.h"
#include "MCIMAPSearchExpression.h"
#include "MCIMAPFolder.h"
#include "MCIMAPMessage.h"
#include "MCIMAPPart.h"
#include "MCMessageHeader.h"
#include "MCAbstractPart.h"
#include "MCIMAPProgressCallback.h"
#include "MCIMAPNamespace.h"
#include "MCIMAPSyncResult.h"
#include "MCIMAPFolderStatus.h"
#include "MCConnectionLogger.h"
#include "MCConnectionLoggerUtils.h"
#include "MCHTMLRenderer.h"
#include "MCString.h"
#include "MCUtils.h"
#include "MCHTMLRendererIMAPDataCallback.h"
#include "MCHTMLBodyRendererTemplateCallback.h"
#include "MCCertificateUtils.h"
#include "MCIMAPIdentity.h"
#include "MCLibetpan.h"
#include "MCDataStreamDecoder.h"
using namespace mailcore;
class LoadByChunkProgress : public Object, public IMAPProgressCallback {
public:
LoadByChunkProgress();
virtual ~LoadByChunkProgress();
virtual void setOffset(uint32_t offset);
virtual void setEstimatedSize(uint32_t estimatedSize);
virtual void setProgressCallback(IMAPProgressCallback * progressCallback);
virtual void bodyProgress(IMAPSession * session, unsigned int current, unsigned int maximum);
private:
uint32_t mOffset;
uint32_t mEstimatedSize;
IMAPProgressCallback * mProgressCallback; // non retained
};
LoadByChunkProgress::LoadByChunkProgress()
{
mOffset = 0;
mEstimatedSize = 0;
mProgressCallback = NULL;
}
LoadByChunkProgress::~LoadByChunkProgress()
{
}
void LoadByChunkProgress::setOffset(uint32_t offset)
{
mOffset = offset;
}
void LoadByChunkProgress::setEstimatedSize(uint32_t estimatedSize)
{
mEstimatedSize = estimatedSize;
}
void LoadByChunkProgress::setProgressCallback(IMAPProgressCallback * progressCallback)
{
mProgressCallback = progressCallback;
}
void LoadByChunkProgress::bodyProgress(IMAPSession * session, unsigned int current, unsigned int maximum)
{
// In case of loading attachment by chunks we need report overall progress
if (mEstimatedSize > 0 && mEstimatedSize > maximum) {
maximum = mEstimatedSize;
current += mOffset;
}
mProgressCallback->bodyProgress(session, current, maximum);
}
enum {
STATE_DISCONNECTED,
STATE_CONNECTED,
STATE_LOGGEDIN,
STATE_SELECTED,
};
String * mailcore::IMAPNamespacePersonal = NULL;
String * mailcore::IMAPNamespaceOther = NULL;
String * mailcore::IMAPNamespaceShared = NULL;
static Array * resultsWithError(int r, clist * list, ErrorCode * pError);
INITIALIZE(IMAPSEssion)
{
AutoreleasePool * pool = new AutoreleasePool();
IMAPNamespacePersonal = (String *) MCSTR("IMAPNamespacePersonal")->retain();
IMAPNamespaceOther = (String *) MCSTR("IMAPNamespaceOther")->retain();
IMAPNamespaceShared = (String *) MCSTR("IMAPNamespaceShared")->retain();
pool->release();
}
#define MAX_IDLE_DELAY (9 * 60)
#define LOCK() pthread_mutex_lock(&mIdleLock)
#define UNLOCK() pthread_mutex_unlock(&mIdleLock)
static struct mailimap_flag_list * flags_to_lep(MessageFlag value)
{
struct mailimap_flag_list * flag_list;
flag_list = mailimap_flag_list_new_empty();
if ((value & MessageFlagSeen) != 0) {
mailimap_flag_list_add(flag_list, mailimap_flag_new_seen());
}
if ((value & MessageFlagFlagged) != 0) {
mailimap_flag_list_add(flag_list, mailimap_flag_new_flagged());
}
if ((value & MessageFlagDeleted) != 0) {
mailimap_flag_list_add(flag_list, mailimap_flag_new_deleted());
}
if ((value & MessageFlagAnswered) != 0) {
mailimap_flag_list_add(flag_list, mailimap_flag_new_answered());
}
if ((value & MessageFlagDraft) != 0) {
mailimap_flag_list_add(flag_list, mailimap_flag_new_draft());
}
if ((value & MessageFlagForwarded) != 0) {
mailimap_flag_list_add(flag_list, mailimap_flag_new_flag_keyword(strdup("$Forwarded")));
}
if ((value & MessageFlagMDNSent) != 0) {
mailimap_flag_list_add(flag_list, mailimap_flag_new_flag_keyword(strdup("$MDNSent")));
}
if ((value & MessageFlagSubmitPending) != 0) {
mailimap_flag_list_add(flag_list, mailimap_flag_new_flag_keyword(strdup("$SubmitPending")));
}
if ((value & MessageFlagSubmitted) != 0) {
mailimap_flag_list_add(flag_list, mailimap_flag_new_flag_keyword(strdup("$Submitted")));
}
return flag_list;
}
static MessageFlag flag_from_lep(struct mailimap_flag * flag)
{
switch (flag->fl_type) {
case MAILIMAP_FLAG_ANSWERED:
return MessageFlagAnswered;
case MAILIMAP_FLAG_FLAGGED:
return MessageFlagFlagged;
case MAILIMAP_FLAG_DELETED:
return MessageFlagDeleted;
case MAILIMAP_FLAG_SEEN:
return MessageFlagSeen;
case MAILIMAP_FLAG_DRAFT:
return MessageFlagDraft;
case MAILIMAP_FLAG_KEYWORD:
if (strcasecmp(flag->fl_data.fl_keyword, "$Forwarded") == 0) {
return MessageFlagForwarded;
}
else if (strcasecmp(flag->fl_data.fl_keyword, "$MDNSent") == 0) {
return MessageFlagMDNSent;
}
else if (strcasecmp(flag->fl_data.fl_keyword, "$SubmitPending") == 0) {
return MessageFlagSubmitPending;
}
else if (strcasecmp(flag->fl_data.fl_keyword, "$Submitted") == 0) {
return MessageFlagSubmitted;
}
}
return MessageFlagNone;
}
static MessageFlag flags_from_lep_att_dynamic(struct mailimap_msg_att_dynamic * att_dynamic)
{
if (att_dynamic->att_list == NULL)
return MessageFlagNone;
MessageFlag flags;
clistiter * iter;
flags = MessageFlagNone;
for(iter = clist_begin(att_dynamic->att_list) ;iter != NULL ; iter = clist_next(iter)) {
struct mailimap_flag_fetch * flag_fetch;
struct mailimap_flag * flag;
flag_fetch = (struct mailimap_flag_fetch *) clist_content(iter);
if (flag_fetch->fl_type != MAILIMAP_FLAG_FETCH_OTHER) {
continue;
}
flag = flag_fetch->fl_flag;
flags = (MessageFlag) (flags | flag_from_lep(flag));
}
return flags;
}
static bool isKnownCustomFlag(const char * keyword)
{
return !(strcmp(keyword, "$MDNSent") != 0 && strcmp(keyword, "$Forwarded") != 0 && strcmp(keyword, "$SubmitPending") != 0 && strcmp(keyword, "$Submitted") != 0);
}
static Array * custom_flags_from_lep_att_dynamic(struct mailimap_msg_att_dynamic * att_dynamic)
{
if (att_dynamic->att_list == NULL)
return NULL;
clistiter * iter;
bool hasCustomFlags = false;
for (iter = clist_begin(att_dynamic->att_list); iter != NULL; iter = clist_next(iter)) {
struct mailimap_flag_fetch * flag_fetch;
struct mailimap_flag * flag;
flag_fetch = (struct mailimap_flag_fetch *) clist_content(iter);
if (flag_fetch->fl_type != MAILIMAP_FLAG_FETCH_OTHER) {
continue;
}
flag = flag_fetch->fl_flag;
if (flag->fl_type == MAILIMAP_FLAG_KEYWORD) {
if (!isKnownCustomFlag(flag->fl_data.fl_keyword)) {
hasCustomFlags = true;
}
}
}
if (!hasCustomFlags)
return NULL;
Array * result = Array::array();
for (iter = clist_begin(att_dynamic->att_list); iter != NULL; iter = clist_next(iter)) {
struct mailimap_flag_fetch * flag_fetch;
struct mailimap_flag * flag;
flag_fetch = (struct mailimap_flag_fetch *) clist_content(iter);
if (flag_fetch->fl_type != MAILIMAP_FLAG_FETCH_OTHER) {
continue;
}
flag = flag_fetch->fl_flag;
if (flag->fl_type == MAILIMAP_FLAG_KEYWORD) {
if (!isKnownCustomFlag(flag->fl_data.fl_keyword)) {
String * customFlag;
customFlag = String::stringWithUTF8Characters(flag->fl_data.fl_keyword);
result->addObject(customFlag);
}
}
}
return result;
}
#pragma mark set conversion
static Array * arrayFromSet(struct mailimap_set * imap_set)
{
Array * result;
clistiter * iter;
result = Array::array();
for(iter = clist_begin(imap_set->set_list) ; iter != NULL ; iter = clist_next(iter)) {
struct mailimap_set_item * item;
unsigned long i;
item = (struct mailimap_set_item *) clist_content(iter);
for(i = item->set_first ; i <= item->set_last ; i ++) {
Value * nb;
nb = Value::valueWithUnsignedLongValue(i);
result->addObject(nb);
}
}
return result;
}
static clist * splitSet(struct mailimap_set * set, unsigned int splitCount)
{
struct mailimap_set * current_set;
clist * result;
unsigned int count;
result = clist_new();
current_set = NULL;
count = 0;
for(clistiter * iter = clist_begin(set->set_list) ; iter != NULL ; iter = clist_next(iter)) {
struct mailimap_set_item * item;
if (current_set == NULL) {
current_set = mailimap_set_new_empty();
}
item = (struct mailimap_set_item *) clist_content(iter);
mailimap_set_add_interval(current_set, item->set_first, item->set_last);
count ++;
if (count >= splitCount) {
clist_append(result, current_set);
current_set = NULL;
count = 0;
}
}
if (current_set != NULL) {
clist_append(result, current_set);
}
return result;
}
static struct mailimap_set * setFromIndexSet(IndexSet * indexSet)
{
struct mailimap_set * imap_set;
imap_set = mailimap_set_new_empty();
for(unsigned int i = 0 ; i < indexSet->rangesCount() ; i ++) {
uint64_t left = RangeLeftBound(indexSet->allRanges()[i]);
uint64_t right = RangeRightBound(indexSet->allRanges()[i]);
if (right == UINT64_MAX) {
right = 0;
}
mailimap_set_add_interval(imap_set, (uint32_t) left, (uint32_t) right);
}
return imap_set;
}
static IndexSet * indexSetFromSet(struct mailimap_set * imap_set)
{
IndexSet * indexSet = IndexSet::indexSet();
for(clistiter * cur = clist_begin(imap_set->set_list) ; cur != NULL ; cur = clist_next(cur)) {
struct mailimap_set_item * item = (struct mailimap_set_item *) clist_content(cur);
if (item->set_last == 0) {
indexSet->addRange(RangeMake(item->set_first, UINT64_MAX));
}
else {
indexSet->addRange(RangeMake(item->set_first, item->set_last - item->set_first));
}
}
return indexSet;
}
void IMAPSession::init()
{
mHostname = NULL;
mPort = 0;
mUsername = NULL;
mPassword = NULL;
mOAuth2Token = NULL;
mAuthType = AuthTypeSASLNone;
mConnectionType = ConnectionTypeClear;
mCheckCertificateEnabled = true;
mIsCertificateValid = true;
mVoIPEnabled = true;
mDelimiter = 0;
mBodyProgressEnabled = true;
mIdleEnabled = false;
mXListEnabled = false;
mQResyncEnabled = false;
mCondstoreEnabled = false;
mXYMHighestModseqEnabled = false;
mIdentityEnabled = false;
mNamespaceEnabled = false;
mCompressionEnabled = false;
mIsGmail = false;
mAllowsNewPermanentFlags = false;
mWelcomeString = NULL;
mNeedsMboxMailWorkaround = false;
mDefaultNamespace = NULL;
mFetchedNamespace = NULL;
mFetchedIdentity = NULL;
mServerIdentity = new IMAPIdentity();
mClientIdentity = new IMAPIdentity();
mTimeout = 30;
mUIDValidity = 0;
mUIDNext = 0;
mModSequenceValue = 0;
mFolderMsgCount = 0;
mFirstUnseenUid = 0;
mYahooServer = false;
mRamblerRuServer = false;
mHermesServer = false;
mQipServer = false;
mLastFetchedSequenceNumber = 0;
mCurrentFolder = NULL;
mCurrentCapabilities = NULL;
pthread_mutex_init(&mIdleLock, NULL);
mState = STATE_DISCONNECTED;
mImap = NULL;
mProgressCallback = NULL;
mProgressItemsCount = 0;
mConnectionLogger = NULL;
pthread_mutex_init(&mConnectionLoggerLock, NULL);
mAutomaticConfigurationEnabled = true;
mAutomaticConfigurationDone = false;
mShouldDisconnect = false;
mNeedsReselect = false;
mLoginResponse = NULL;
mGmailUserDisplayName = NULL;
mUnparsedResponseData = NULL;
}
IMAPSession::IMAPSession()
{
init();
}
IMAPSession::~IMAPSession()
{
MC_SAFE_RELEASE(mUnparsedResponseData);
MC_SAFE_RELEASE(mGmailUserDisplayName);
MC_SAFE_RELEASE(mLoginResponse);
MC_SAFE_RELEASE(mFetchedIdentity);
MC_SAFE_RELEASE(mClientIdentity);
MC_SAFE_RELEASE(mServerIdentity);
MC_SAFE_RELEASE(mHostname);
MC_SAFE_RELEASE(mUsername);
MC_SAFE_RELEASE(mPassword);
MC_SAFE_RELEASE(mOAuth2Token);
MC_SAFE_RELEASE(mWelcomeString);
MC_SAFE_RELEASE(mDefaultNamespace);
MC_SAFE_RELEASE(mFetchedNamespace);
MC_SAFE_RELEASE(mCurrentFolder);
MC_SAFE_RELEASE(mCurrentCapabilities);
pthread_mutex_destroy(&mIdleLock);
pthread_mutex_destroy(&mConnectionLoggerLock);
}
void IMAPSession::setHostname(String * hostname)
{
MC_SAFE_REPLACE_COPY(String, mHostname, hostname);
}
String * IMAPSession::hostname()
{
return mHostname;
}
void IMAPSession::setPort(unsigned int port)
{
mPort = port;
}
unsigned int IMAPSession::port()
{
return mPort;
}
void IMAPSession::setUsername(String * username)
{
MC_SAFE_REPLACE_COPY(String, mUsername, username);
}
String * IMAPSession::username()
{
return mUsername;
}
void IMAPSession::setPassword(String * password)
{
MC_SAFE_REPLACE_COPY(String, mPassword, password);
}
String * IMAPSession::password()
{
return mPassword;
}
void IMAPSession::setOAuth2Token(String * token)
{
MC_SAFE_REPLACE_COPY(String, mOAuth2Token, token);
}
String * IMAPSession::OAuth2Token()
{
return mOAuth2Token;
}
void IMAPSession::setAuthType(AuthType authType)
{
mAuthType = authType;
}
AuthType IMAPSession::authType()
{
return mAuthType;
}
void IMAPSession::setConnectionType(ConnectionType connectionType)
{
mConnectionType = connectionType;
}
ConnectionType IMAPSession::connectionType()
{
return mConnectionType;
}
void IMAPSession::setTimeout(time_t timeout)
{
mTimeout = timeout;
}
time_t IMAPSession::timeout()
{
return mTimeout;
}
void IMAPSession::setCheckCertificateEnabled(bool enabled)
{
mCheckCertificateEnabled = enabled;
}
bool IMAPSession::isCheckCertificateEnabled()
{
return mCheckCertificateEnabled;
}
bool IMAPSession::isCertificateValid()
{
return mIsCertificateValid;
}
void IMAPSession::setVoIPEnabled(bool enabled)
{
mVoIPEnabled = enabled;
}
bool IMAPSession::isVoIPEnabled()
{
return mVoIPEnabled;
}
String * IMAPSession::loginResponse()
{
return mLoginResponse;
}
Data * IMAPSession::unparsedResponseData()
{
return mUnparsedResponseData;
}
static bool hasError(int errorCode)
{
return ((errorCode != MAILIMAP_NO_ERROR) && (errorCode != MAILIMAP_NO_ERROR_AUTHENTICATED) &&
(errorCode != MAILIMAP_NO_ERROR_NON_AUTHENTICATED));
}
bool IMAPSession::checkCertificate()
{
return mailcore::checkCertificate(mImap->imap_stream, hostname());
}
void IMAPSession::body_progress(size_t current, size_t maximum, void * context)
{
IMAPSession * session;
session = (IMAPSession *) context;
session->bodyProgress((unsigned int) current, (unsigned int) maximum);
}
void IMAPSession::items_progress(size_t current, size_t maximum, void * context)
{
IMAPSession * session;
session = (IMAPSession *) context;
session->itemsProgress((unsigned int) current, (unsigned int) maximum);
}
static void logger(mailimap * imap, int log_type, const char * buffer, size_t size, void * context)
{
IMAPSession * session = (IMAPSession *) context;
session->lockConnectionLogger();
if (session->connectionLoggerNoLock() == NULL) {
session->unlockConnectionLogger();
return;
}
ConnectionLogType type = getConnectionType(log_type);
if ((int) type == -1) {
session->unlockConnectionLogger();
return;
}
bool isBuffer = isBufferFromLogType(log_type);
if (isBuffer) {
AutoreleasePool * pool = new AutoreleasePool();
Data * data = Data::dataWithBytes(buffer, (unsigned int) size);
session->connectionLoggerNoLock()->log(session, type, data);
pool->release();
}
else {
session->connectionLoggerNoLock()->log(session, type, NULL);
}
session->unlockConnectionLogger();
}
void IMAPSession::setup()
{
if (mImap != NULL) {
unsetup();
}
mImap = mailimap_new(0, NULL);
mailimap_set_timeout(mImap, timeout());
mailimap_set_progress_callback(mImap, body_progress, IMAPSession::items_progress, this);
mailimap_set_logger(mImap, logger, this);
}
void IMAPSession::unsetup()
{
mailimap * imap;
LOCK();
imap = mImap;
mImap = NULL;
mIdleEnabled = false;
UNLOCK();
if (imap != NULL) {
if (imap->imap_stream != NULL) {
mailstream_close(imap->imap_stream);
imap->imap_stream = NULL;
}
mailimap_free(imap);
imap = NULL;
}
mState = STATE_DISCONNECTED;
}
void IMAPSession::connect(ErrorCode * pError)
{
int r;
setup();
MCLog("connect %s", MCUTF8DESC(this));
MCAssert(mState == STATE_DISCONNECTED);
if (mHostname == NULL) {
* pError = ErrorInvalidAccount;
goto close;
}
switch (mConnectionType) {
case ConnectionTypeStartTLS:
MCLog("STARTTLS connect");
r = mailimap_socket_connect_voip(mImap, MCUTF8(mHostname), mPort, isVoIPEnabled());
if (hasError(r)) {
* pError = ErrorConnection;
goto close;
}
r = mailimap_socket_starttls(mImap);
if (hasError(r)) {
MCLog("no TLS %i", r);
* pError = ErrorTLSNotAvailable;
goto close;
}
mIsCertificateValid = checkCertificate();
if (isCheckCertificateEnabled() && !mIsCertificateValid) {
* pError = ErrorCertificate;
goto close;
}
break;
case ConnectionTypeTLS:
r = mailimap_ssl_connect_voip(mImap, MCUTF8(mHostname), mPort, isVoIPEnabled());
MCLog("ssl connect %s %u %u", MCUTF8(mHostname), mPort, r);
if (hasError(r)) {
MCLog("connect error %i", r);
* pError = ErrorConnection;
goto close;
}
mIsCertificateValid = checkCertificate();
if (isCheckCertificateEnabled() && !mIsCertificateValid) {
* pError = ErrorCertificate;
goto close;
}
break;
default:
MCLog("socket connect %s %u", MCUTF8(mHostname), mPort);
r = mailimap_socket_connect_voip(mImap, MCUTF8(mHostname), mPort, isVoIPEnabled());
MCLog("socket connect %i", r);
if (hasError(r)) {
MCLog("connect error %i", r);
* pError = ErrorConnection;
goto close;
}
break;
}
mailstream_low * low;
String * identifierString;
char * identifier;
low = mailstream_get_low(mImap->imap_stream);
identifierString = String::stringWithUTF8Format("%s@%s:%u", MCUTF8(mUsername), MCUTF8(mHostname), mPort);
identifier = strdup(identifierString->UTF8Characters());
mailstream_low_set_identifier(low, identifier);
if (mImap->imap_response != NULL) {
MC_SAFE_REPLACE_RETAIN(String, mWelcomeString, String::stringWithUTF8Characters(mImap->imap_response));
mYahooServer = (mWelcomeString->locationOfString(MCSTR("yahoo.com")) != -1);
#ifdef LIBETPAN_HAS_MAILIMAP_163_WORKAROUND
if (mWelcomeString->locationOfString(MCSTR("Coremail System IMap Server Ready")) != -1)
mailimap_set_163_workaround_enabled(mImap, 1);
#endif
if (mWelcomeString->locationOfString(MCSTR("Courier-IMAP")) != -1) {
LOCK();
mIdleEnabled = true;
UNLOCK();
mNamespaceEnabled = true;
}
mRamblerRuServer = (mHostname->locationOfString(MCSTR(".rambler.ru")) != -1);
mHermesServer = (mWelcomeString->locationOfString(MCSTR("Hermes")) != -1);
mQipServer = (mWelcomeString->locationOfString(MCSTR("QIP IMAP server")) != -1);
}
mState = STATE_CONNECTED;
if (isAutomaticConfigurationEnabled()) {
if (mCurrentCapabilities != NULL) {
applyCapabilities(mCurrentCapabilities);
} else {
IndexSet *capabilities = capability(pError);
if (* pError != ErrorNone) {
MCLog("capabilities failed");
goto close;
} else {
MC_SAFE_REPLACE_RETAIN(IndexSet, mCurrentCapabilities, capabilities);
applyCapabilities(mCurrentCapabilities);
}
}
}
* pError = ErrorNone;
MCLog("connect ok");
return;
close:
unsetup();
}
void IMAPSession::connectIfNeeded(ErrorCode * pError)
{
if (mShouldDisconnect) {
disconnect();
mShouldDisconnect = false;
}
if (mState == STATE_DISCONNECTED) {
connect(pError);
}
else {
* pError = ErrorNone;
}
}
void IMAPSession::loginIfNeeded(ErrorCode * pError)
{
connectIfNeeded(pError);
if (* pError != ErrorNone)
return;
if (mState == STATE_CONNECTED) {
login(pError);
}
else {
* pError = ErrorNone;
}
}
void IMAPSession::login(ErrorCode * pError)
{
int r;
MCLog("login");
MCAssert(mState == STATE_CONNECTED);
MC_SAFE_RELEASE(mLoginResponse);
MC_SAFE_RELEASE(mUnparsedResponseData);
const char * utf8username;
const char * utf8password;
utf8username = MCUTF8(mUsername);
utf8password = MCUTF8(mPassword);
if (utf8username == NULL) {
utf8username = "";
}
if (utf8password == NULL) {
utf8password = "";
}
switch (mAuthType) {
case 0:
default:
r = mailimap_login(mImap, utf8username, utf8password);
break;
case AuthTypeSASLCRAMMD5:
r = mailimap_authenticate(mImap, "CRAM-MD5",
MCUTF8(mHostname),
NULL,
NULL,
utf8username, utf8username,
utf8password, NULL);
break;
case AuthTypeSASLPlain:
r = mailimap_authenticate(mImap, "PLAIN",
MCUTF8(mHostname),
NULL,
NULL,
utf8username, utf8username,
utf8password, NULL);
break;
case AuthTypeSASLGSSAPI:
// needs to be tested
r = mailimap_authenticate(mImap, "GSSAPI",
MCUTF8(mHostname),
NULL,
NULL,
utf8username, utf8username,
utf8password, NULL /* realm */);
break;
case AuthTypeSASLDIGESTMD5:
r = mailimap_authenticate(mImap, "DIGEST-MD5",
MCUTF8(mHostname),
NULL,
NULL,
utf8username, utf8username,
utf8password, NULL);
break;
case AuthTypeSASLLogin:
r = mailimap_authenticate(mImap, "LOGIN",
MCUTF8(mHostname),
NULL,
NULL,
utf8username, utf8username,
utf8password, NULL);
break;
case AuthTypeSASLSRP:
r = mailimap_authenticate(mImap, "SRP",
MCUTF8(mHostname),
NULL,
NULL,
utf8username, utf8username,
utf8password, NULL);
break;
case AuthTypeSASLNTLM:
r = mailimap_authenticate(mImap, "NTLM",
MCUTF8(mHostname),
NULL,
NULL,
utf8username, utf8username,
utf8password, NULL/* realm */);
break;
case AuthTypeSASLKerberosV4:
r = mailimap_authenticate(mImap, "KERBEROS_V4",
MCUTF8(mHostname),
NULL,
NULL,
utf8username, utf8username,
utf8password, NULL/* realm */);
break;
case AuthTypeXOAuth2:
case AuthTypeXOAuth2Outlook:
if (mOAuth2Token == NULL) {
r = MAILIMAP_ERROR_STREAM;
}
else {
r = mailimap_oauth2_authenticate(mImap, utf8username, MCUTF8(mOAuth2Token));
}
break;
}
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
Data * unparsed_response = Data::data();
if (mImap->imap_stream_buffer != NULL) {
unparsed_response = Data::dataWithBytes(mImap->imap_stream_buffer->str, (unsigned int) mImap->imap_stream_buffer->len);
}
MC_SAFE_REPLACE_RETAIN(Data, mUnparsedResponseData, unparsed_response);
return;
}
else if (hasError(r)) {
String * response;
response = MCSTR("");
if (mImap->imap_response != NULL) {
response = String::stringWithUTF8Characters(mImap->imap_response);
}
MC_SAFE_REPLACE_COPY(String, mLoginResponse, response);
if (response->locationOfString(MCSTR("not enabled for IMAP use")) != -1) {
* pError = ErrorGmailIMAPNotEnabled;
}
else if (response->locationOfString(MCSTR("IMAP access is disabled")) != -1) {
* pError = ErrorGmailIMAPNotEnabled;
}
else if (response->locationOfString(MCSTR("bandwidth limits")) != -1) {
* pError = ErrorGmailExceededBandwidthLimit;
}
else if (response->locationOfString(MCSTR("Too many simultaneous connections")) != -1) {
* pError = ErrorGmailTooManySimultaneousConnections;
}
else if (response->locationOfString(MCSTR("Maximum number of connections")) != -1) {
* pError = ErrorGmailTooManySimultaneousConnections;
}
else if (response->locationOfString(MCSTR("Application-specific password required")) != -1) {
* pError = ErrorGmailApplicationSpecificPasswordRequired;
}
else if (response->locationOfString(MCSTR("http://me.com/move")) != -1) {
* pError = ErrorMobileMeMoved;
}
else if (response->locationOfString(MCSTR("OCF12")) != -1) {
* pError = ErrorYahooUnavailable;
}
else if (response->locationOfString(MCSTR("Login to your account via a web browser")) != -1) {
* pError = ErrorOutlookLoginViaWebBrowser;
}
else if (response->locationOfString(MCSTR("Service temporarily unavailable")) != -1) {
mShouldDisconnect = true;
* pError = ErrorConnection;
}
else {
* pError = ErrorAuthentication;
}
return;
}
String * loginResponse = MCSTR("");
if (mIsGmail) {
if (mImap->imap_response != NULL) {
loginResponse = String::stringWithUTF8Characters(mImap->imap_response);
int location = loginResponse->locationOfString(MCSTR(" authenticated (Success)"));
if (location != -1) {
String * emailAndName = loginResponse->substringToIndex(location);
location = emailAndName->locationOfString(MCSTR(" "));
MC_SAFE_RELEASE(mGmailUserDisplayName);
mGmailUserDisplayName = emailAndName->substringFromIndex(location + 1);
mGmailUserDisplayName->retain();
}
}
}
MC_SAFE_REPLACE_COPY(String, mLoginResponse, loginResponse);
mState = STATE_LOGGEDIN;
if (isAutomaticConfigurationEnabled()) {
if (mCurrentCapabilities != NULL) {
applyCapabilities(mCurrentCapabilities);
} else {
IndexSet *capabilities = capability(pError);
if (* pError != ErrorNone) {
MCLog("capabilities failed");
return;
} else {
MC_SAFE_REPLACE_RETAIN(IndexSet, mCurrentCapabilities, capabilities);
applyCapabilities(mCurrentCapabilities);
}
}
}
else {
// TODO: capabilities should be shared with other sessions for non automatic capabilities sessions.
}
enableFeatures();
if (isAutomaticConfigurationEnabled()) {
bool hasDefaultNamespace = false;
if (isNamespaceEnabled()) {
IMAPNamespace * personalNamespace = NULL;
if (mFetchedNamespace != NULL) {
personalNamespace = mFetchedNamespace;
} else {
HashMap * result = fetchNamespace(pError);
if (* pError != ErrorNone) {
MCLog("fetch namespace failed");
return;
}
personalNamespace = (IMAPNamespace *) result->objectForKey(IMAPNamespacePersonal);
}
if (personalNamespace != NULL) {
setDefaultNamespace(personalNamespace);
mDelimiter = defaultNamespace()->mainDelimiter();
if (mFetchedNamespace != personalNamespace) {
MC_SAFE_REPLACE_RETAIN(IMAPNamespace, mFetchedNamespace, personalNamespace);
}
hasDefaultNamespace = true;
}
}
if (!hasDefaultNamespace) {
clist * imap_folders;
IMAPFolder * folder;
Array * folders;
r = mailimap_list(mImap, "", "", &imap_folders);
folders = resultsWithError(r, imap_folders, pError);
if (* pError != ErrorNone)
return;
if (folders->count() > 0) {
folder = (IMAPFolder *) folders->objectAtIndex(0);
}
else {
folder = NULL;
}
if (folder == NULL) {
* pError = ErrorNonExistantFolder;
return;
}
mDelimiter = folder->delimiter();
IMAPNamespace * defaultNamespace = IMAPNamespace::namespaceWithPrefix(MCSTR(""), folder->delimiter());
setDefaultNamespace(defaultNamespace);
}
if (isIdentityEnabled()) {
// IMAPIdentity * serverIdentity = NULL;
// if (mFetchedIdentity) {
// serverIdentity = mFetchedIdentity;
// } else {
// serverIdentity = identity(clientIdentity(), pError);
// }
// if (* pError != ErrorNone) {
// // Ignore identity errors
// MCLog("fetch identity failed");
// }
// else {
// if (mFetchedIdentity != serverIdentity) {
// MC_SAFE_REPLACE_RETAIN(IMAPIdentity, mFetchedIdentity, serverIdentity);
// }
// MC_SAFE_REPLACE_RETAIN(IMAPIdentity, mServerIdentity, serverIdentity);
// }
}
}
else {
// TODO: namespace should be shared with other sessions for non automatic namespace.
}
mAutomaticConfigurationDone = true;
* pError = ErrorNone;
MCLog("login ok");
}
void IMAPSession::setNeedsReselect()
{
mNeedsReselect = true;
}
void IMAPSession::setNeedsReconnect()
{
mShouldDisconnect = true;
}
void IMAPSession::selectIfNeeded(String * folder, ErrorCode * pError)
{
loginIfNeeded(pError);
if (* pError != ErrorNone)
return;
if (folder == NULL) {
* pError = ErrorMissingFolder;
return;
}
if (mNeedsReselect) {
mNeedsReselect = false;
select(folder, pError);
}
else if (mState == STATE_SELECTED) {
MCAssert(mCurrentFolder != NULL);
if (mCurrentFolder->caseInsensitiveCompare(folder) != 0) {
select(folder, pError);
}
}
else if (mState == STATE_LOGGEDIN) {
select(folder, pError);
}
else {
* pError = ErrorNone;
}
}
static uint64_t get_mod_sequence_value(mailimap * session)
{
uint64_t mod_sequence_value;
clistiter * cur;
mod_sequence_value = 0;
for(cur = clist_begin(session->imap_response_info->rsp_extension_list) ; cur != NULL ; cur = clist_next(cur)) {
struct mailimap_extension_data * ext_data;
struct mailimap_condstore_resptextcode * resptextcode;
ext_data = (struct mailimap_extension_data *) clist_content(cur);
if (ext_data->ext_extension->ext_id != MAILIMAP_EXTENSION_CONDSTORE) {
continue;
}
if (ext_data->ext_type != MAILIMAP_CONDSTORE_TYPE_RESP_TEXT_CODE) {
continue;
}
resptextcode = (struct mailimap_condstore_resptextcode *) ext_data->ext_data;
switch (resptextcode->cs_type) {
case MAILIMAP_CONDSTORE_RESPTEXTCODE_HIGHESTMODSEQ:
mod_sequence_value = resptextcode->cs_data.cs_modseq_value;
break;
case MAILIMAP_CONDSTORE_RESPTEXTCODE_NOMODSEQ:
mod_sequence_value = 0;
break;
}
}
return mod_sequence_value;
}
String * IMAPSession::customCommand(String * command, ErrorCode * pError)
{
int r;
loginIfNeeded(pError);
if (* pError != ErrorNone)
return NULL;
r = mailimap_custom_command(mImap, MCUTF8(command));
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return NULL;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return NULL;
}
else if (hasError(r)) {
* pError = ErrorCustomCommand;
return NULL;
}
String *response = String::stringWithUTF8Characters(mImap->imap_response);
return response;
}
void IMAPSession::select(String * folder, ErrorCode * pError)
{
int r;
MCLog("select");
MCAssert(mState == STATE_LOGGEDIN || mState == STATE_SELECTED);
r = mailimap_select(mImap, MCUTF8(folder));
MCLog("select error : %i", r);
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
MCLog("select error : %s %i", MCUTF8DESC(this), * pError);
return;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return;
}
else if (hasError(r)) {
* pError = ErrorNonExistantFolder;
mState = STATE_LOGGEDIN;
MC_SAFE_RELEASE(mCurrentFolder);
return;
}
MC_SAFE_REPLACE_COPY(String, mCurrentFolder, folder);
if (mImap->imap_selection_info != NULL) {
mUIDValidity = mImap->imap_selection_info->sel_uidvalidity;
mUIDNext = mImap->imap_selection_info->sel_uidnext;
if (mImap->imap_selection_info->sel_has_exists) {
mFolderMsgCount = (unsigned int) (mImap->imap_selection_info->sel_exists);
} else {
mFolderMsgCount = -1;
}
if (mImap->imap_selection_info->sel_first_unseen) {
mFirstUnseenUid = mImap->imap_selection_info->sel_first_unseen;
} else {
mFirstUnseenUid = 0;
}
if (mImap->imap_selection_info->sel_unseen) {
mUnseenCount = mImap->imap_selection_info->sel_unseen;
} else {
mUnseenCount = 0;
}
if (mImap->imap_selection_info->sel_perm_flags) {
clistiter * cur;
struct mailimap_flag_perm * perm_flag;
for(cur = clist_end(mImap->imap_selection_info->sel_perm_flags) ; cur != NULL ;
cur = clist_previous(cur)) {
perm_flag = (struct mailimap_flag_perm *)clist_content(cur);
mAllowsNewPermanentFlags = perm_flag->fl_type == MAILIMAP_FLAG_PERM_ALL;
if (mAllowsNewPermanentFlags) {
break;
}
}
}
mModSequenceValue = get_mod_sequence_value(mImap);
}
mState = STATE_SELECTED;
* pError = ErrorNone;
MCLog("select ok");
}
IMAPFolderStatus * IMAPSession::folderStatus(String * folder, ErrorCode * pError)
{
int r;
MCLog("status");
if (mState != STATE_LOGGEDIN && mState != STATE_SELECTED) {
* pError = ErrorFolderState;
MCLog("trying to fetch status in bad state");
IMAPFolderStatus * empty;
empty = new IMAPFolderStatus();
empty->autorelease();
return empty;
}
if (folder == NULL) {
* pError = ErrorMissingFolder;
MCLog("trying to fetch status without folder");
IMAPFolderStatus * empty;
empty = new IMAPFolderStatus();
empty->autorelease();
return empty;
}
if (mImap == NULL) {
* pError = ErrorDisconnected;
MCLog("trying to fetch status without connection");
IMAPFolderStatus * empty;
empty = new IMAPFolderStatus();
empty->autorelease();
return empty;
}
struct mailimap_mailbox_data_status * status;
struct mailimap_status_att_list * status_att_list;
status_att_list = mailimap_status_att_list_new_empty();
mailimap_status_att_list_add(status_att_list, MAILIMAP_STATUS_ATT_UNSEEN);
mailimap_status_att_list_add(status_att_list, MAILIMAP_STATUS_ATT_MESSAGES);
mailimap_status_att_list_add(status_att_list, MAILIMAP_STATUS_ATT_RECENT);
mailimap_status_att_list_add(status_att_list, MAILIMAP_STATUS_ATT_UIDNEXT);
mailimap_status_att_list_add(status_att_list, MAILIMAP_STATUS_ATT_UIDVALIDITY);
if (mCondstoreEnabled || mXYMHighestModseqEnabled) {
mailimap_status_att_list_add(status_att_list, MAILIMAP_STATUS_ATT_HIGHESTMODSEQ);
}
r = mailimap_status(mImap, MCUTF8(folder), status_att_list, &status);
IMAPFolderStatus * fs;
fs = new IMAPFolderStatus();
fs->autorelease();
MCLog("status error : %i", r);
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
MCLog("status error : %s %i", MCUTF8DESC(this), * pError);
mailimap_status_att_list_free(status_att_list);
return fs;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
mailimap_status_att_list_free(status_att_list);
return fs;
}
else if (hasError(r)) {
* pError = ErrorNonExistantFolder;
mailimap_status_att_list_free(status_att_list);
return fs;
}
clistiter * cur;
if (status != NULL) {
struct mailimap_status_info * status_info;
for(cur = clist_begin(status->st_info_list) ; cur != NULL ;
cur = clist_next(cur)) {
status_info = (struct mailimap_status_info *) clist_content(cur);
switch (status_info->st_att) {
case MAILIMAP_STATUS_ATT_UNSEEN:
fs->setUnseenCount(status_info->st_value);
break;
case MAILIMAP_STATUS_ATT_MESSAGES:
fs->setMessageCount(status_info->st_value);
break;
case MAILIMAP_STATUS_ATT_RECENT:
fs->setRecentCount(status_info->st_value);
break;
case MAILIMAP_STATUS_ATT_UIDNEXT:
fs->setUidNext(status_info->st_value);
break;
case MAILIMAP_STATUS_ATT_UIDVALIDITY:
fs->setUidValidity(status_info->st_value);
break;
case MAILIMAP_STATUS_ATT_EXTENSION: {
struct mailimap_extension_data * ext_data = status_info->st_ext_data;
if (ext_data->ext_extension == &mailimap_extension_condstore) {
struct mailimap_condstore_status_info * status_info = (struct mailimap_condstore_status_info *) ext_data->ext_data;
fs->setHighestModSeqValue(status_info->cs_highestmodseq_value);
}
break;
}
}
}
mailimap_mailbox_data_status_free(status);
}
mailimap_status_att_list_free(status_att_list);
return fs;
}
void IMAPSession::noop(ErrorCode * pError)
{
int r;
if (mImap == NULL)
return;
MCLog("connect");
loginIfNeeded(pError);
if (* pError != ErrorNone) {
return;
}
if (mImap->imap_stream != NULL) {
r = mailimap_noop(mImap);
if (r == MAILIMAP_ERROR_STREAM) {
* pError = ErrorConnection;
}
if (r == MAILIMAP_ERROR_NOOP) {
* pError = ErrorNoop;
}
}
}
#pragma mark mailbox flags conversion
static struct {
const char * name;
int flag;
} mb_keyword_flag[] = {
{"Inbox", IMAPFolderFlagInbox},
{"AllMail", IMAPFolderFlagAllMail},
{"Sent", IMAPFolderFlagSentMail},
{"Spam", IMAPFolderFlagSpam},
{"Starred", IMAPFolderFlagStarred},
{"Trash", IMAPFolderFlagTrash},
{"Important", IMAPFolderFlagImportant},
{"Drafts", IMAPFolderFlagDrafts},
{"Archive", IMAPFolderFlagArchive},
{"All", IMAPFolderFlagAll},
{"Junk", IMAPFolderFlagJunk},
{"Flagged", IMAPFolderFlagFlagged},
};
static int imap_mailbox_flags_to_flags(struct mailimap_mbx_list_flags * imap_flags)
{
int flags;
clistiter * cur;
flags = 0;
if (imap_flags->mbf_type == MAILIMAP_MBX_LIST_FLAGS_SFLAG) {
switch (imap_flags->mbf_sflag) {
case MAILIMAP_MBX_LIST_SFLAG_MARKED:
flags |= IMAPFolderFlagMarked;
break;
case MAILIMAP_MBX_LIST_SFLAG_NOSELECT:
flags |= IMAPFolderFlagNoSelect;
break;
case MAILIMAP_MBX_LIST_SFLAG_UNMARKED:
flags |= IMAPFolderFlagUnmarked;
break;
}
}
for(cur = clist_begin(imap_flags->mbf_oflags) ; cur != NULL ;
cur = clist_next(cur)) {
struct mailimap_mbx_list_oflag * oflag;
oflag = (struct mailimap_mbx_list_oflag *) clist_content(cur);
switch (oflag->of_type) {
case MAILIMAP_MBX_LIST_OFLAG_NOINFERIORS:
flags |= IMAPFolderFlagNoInferiors;
break;
case MAILIMAP_MBX_LIST_OFLAG_FLAG_EXT:
for(unsigned int i = 0 ; i < sizeof(mb_keyword_flag) / sizeof(mb_keyword_flag[0]) ; i ++) {
if (strcasecmp(mb_keyword_flag[i].name, oflag->of_flag_ext) == 0) {
flags |= mb_keyword_flag[i].flag;
}
}
break;
}
}
return flags;
}
static Array * resultsWithError(int r, clist * list, ErrorCode * pError)
{
clistiter * cur;
Array * result;
result = Array::array();
if (r == MAILIMAP_ERROR_STREAM) {
* pError = ErrorConnection;
return NULL;
}
else if (r == MAILIMAP_ERROR_PARSE) {
* pError = ErrorParse;
return NULL;
}
else if (hasError(r)) {
* pError = ErrorNonExistantFolder;
return NULL;
}
for(cur = clist_begin(list) ; cur != NULL ; cur = cur->next) {
struct mailimap_mailbox_list * mb_list;
IMAPFolderFlag flags;
IMAPFolder * folder;
String * path;
mb_list = (struct mailimap_mailbox_list *) cur->data;
flags = IMAPFolderFlagNone;
if (mb_list->mb_flag != NULL)
flags = (IMAPFolderFlag) imap_mailbox_flags_to_flags(mb_list->mb_flag);
folder = new IMAPFolder();
path = String::stringWithUTF8Characters(mb_list->mb_name);
if (path->uppercaseString()->isEqual(MCSTR("INBOX"))) {
folder->setPath(MCSTR("INBOX"));
}
else {
folder->setPath(path);
}
folder->setDelimiter(mb_list->mb_delimiter);
folder->setFlags(flags);
result->addObject(folder);
folder->release();
}
mailimap_list_result_free(list);
* pError = ErrorNone;
return result;
}
// Deprecated
char IMAPSession::fetchDelimiterIfNeeded(char defaultDelimiter, ErrorCode * pError)
{
int r;
clist * imap_folders;
IMAPFolder * folder;
Array * folders;
if (defaultDelimiter != 0)
return defaultDelimiter;
r = mailimap_list(mImap, "", "", &imap_folders);
folders = resultsWithError(r, imap_folders, pError);
if (* pError == ErrorConnection || * pError == ErrorParse)
mShouldDisconnect = true;
if (* pError != ErrorNone)
return 0;
if (folders->count() > 0) {
folder = (IMAPFolder *) folders->objectAtIndex(0);
}
else {
folder = NULL;
}
if (folder == NULL)
return 0;
* pError = ErrorNone;
return folder->delimiter();
}
Array * /* IMAPFolder */ IMAPSession::fetchSubscribedFolders(ErrorCode * pError)
{
int r;
clist * imap_folders;
MCLog("fetch subscribed");
loginIfNeeded(pError);
if (* pError != ErrorNone)
return NULL;
if (mDelimiter == 0) {
char delimiter;
delimiter = fetchDelimiterIfNeeded(mDelimiter, pError);
if (* pError != ErrorNone)
return NULL;
//setDelimiter(delimiter);
mDelimiter = delimiter;
}
String * prefix;
prefix = defaultNamespace()->mainPrefix();
if (prefix == NULL) {
prefix = MCSTR("");
}
if (prefix->length() > 0) {
if (!prefix->hasSuffix(String::stringWithUTF8Format("%c", mDelimiter))) {
prefix = prefix->stringByAppendingUTF8Format("%c", mDelimiter);
}
}
r = mailimap_lsub(mImap, MCUTF8(prefix), "*", &imap_folders);
MCLog("fetch subscribed %u", r);
Array * result = resultsWithError(r, imap_folders, pError);
if (* pError == ErrorConnection || * pError == ErrorParse)
mShouldDisconnect = true;
return result;
}
Array * /* IMAPFolder */ IMAPSession::fetchAllFolders(ErrorCode * pError)
{
int r;
clist * imap_folders;
loginIfNeeded(pError);
if (* pError != ErrorNone)
return NULL;
if (mDelimiter == 0) {
char delimiter;
delimiter = fetchDelimiterIfNeeded(mDelimiter, pError);
if (* pError != ErrorNone)
return NULL;
//setDelimiter(delimiter);
mDelimiter = delimiter;
}
String * prefix = NULL;
if (defaultNamespace()) {
prefix = defaultNamespace()->mainPrefix();
}
if (prefix == NULL) {
prefix = MCSTR("");
}
if (prefix->length() > 0) {
if (!prefix->hasSuffix(String::stringWithUTF8Format("%c", mDelimiter))) {
prefix = prefix->stringByAppendingUTF8Format("%c", mDelimiter);
}
}
if (mXListEnabled) {
r = mailimap_xlist(mImap, MCUTF8(prefix), "*", &imap_folders);
}
else {
r = mailimap_list(mImap, MCUTF8(prefix), "*", &imap_folders);
}
Array * result = resultsWithError(r, imap_folders, pError);
if (* pError == ErrorConnection || * pError == ErrorParse)
mShouldDisconnect = true;
if (result != NULL) {
bool hasInbox = false;
mc_foreacharray(IMAPFolder, folder, result) {
if (folder->path()->isEqual(MCSTR("INBOX"))) {
hasInbox = true;
}
}
if (!hasInbox) {
mc_foreacharray(IMAPFolder, folder, result) {
if (folder->flags() & IMAPFolderFlagInbox) {
// some mail providers use non-standart name for inbox folder
hasInbox = true;
folder->setPath(MCSTR("INBOX"));
break;
}
}
if (!hasInbox) {
r = mailimap_list(mImap, "", "INBOX", &imap_folders);
Array * inboxResult = resultsWithError(r, imap_folders, pError);
if (* pError == ErrorConnection || * pError == ErrorParse)
mShouldDisconnect = true;
result->addObjectsFromArray(inboxResult);
hasInbox = true;
}
}
}
return result;
}
void IMAPSession::renameFolder(String * folder, String * otherName, ErrorCode * pError)
{
int r;
selectIfNeeded(MCSTR("INBOX"), pError);
if (* pError != ErrorNone)
return;
r = mailimap_rename(mImap, MCUTF8(folder), MCUTF8(otherName));
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return;
}
else if (hasError(r)) {
* pError = ErrorRename;
return;
}
* pError = ErrorNone;
}
void IMAPSession::deleteFolder(String * folder, ErrorCode * pError)
{
int r;
selectIfNeeded(MCSTR("INBOX"), pError);
if (* pError != ErrorNone)
return;
r = mailimap_delete(mImap, MCUTF8(folder));
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return;
}
else if (hasError(r)) {
* pError = ErrorDelete;
return;
}
* pError = ErrorNone;
}
void IMAPSession::createFolder(String * folder, ErrorCode * pError)
{
int r;
selectIfNeeded(MCSTR("INBOX"), pError);
if (* pError != ErrorNone)
return;
r = mailimap_create(mImap, MCUTF8(folder));
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return;
}
else if (hasError(r)) {
* pError = ErrorCreate;
return;
}
* pError = ErrorNone;
subscribeFolder(folder, pError);
}
void IMAPSession::subscribeFolder(String * folder, ErrorCode * pError)
{
int r;
selectIfNeeded(MCSTR("INBOX"), pError);
if (* pError != ErrorNone)
return;
r = mailimap_subscribe(mImap, MCUTF8(folder));
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return;
}
else if (hasError(r)) {
* pError = ErrorSubscribe;
return;
}
* pError = ErrorNone;
}
void IMAPSession::unsubscribeFolder(String * folder, ErrorCode * pError)
{
int r;
selectIfNeeded(MCSTR("INBOX"), pError);
if (* pError != ErrorNone)
return;
r = mailimap_unsubscribe(mImap, MCUTF8(folder));
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return;
}
else if (hasError(r)) {
* pError = ErrorSubscribe;
return;
}
* pError = ErrorNone;
}
void IMAPSession::appendMessage(String * folder, Data * messageData, MessageFlag flags,
IMAPProgressCallback * progressCallback, uint32_t * createdUID, ErrorCode * pError)
{
this->appendMessageWithCustomFlags(folder, messageData, flags, NULL, progressCallback, createdUID, pError);
}
void IMAPSession::appendMessageWithCustomFlags(String * folder, Data * messageData, MessageFlag flags, Array * customFlags,
IMAPProgressCallback * progressCallback, uint32_t * createdUID, ErrorCode * pError)
{
this->appendMessageWithCustomFlagsAndDate(folder, messageData, flags, NULL, (time_t) -1, progressCallback, createdUID, pError);
}
void IMAPSession::appendMessageWithCustomFlagsAndDate(String * folder, Data * messageData, MessageFlag flags, Array * customFlags, time_t date,
IMAPProgressCallback * progressCallback, uint32_t * createdUID, ErrorCode * pError)
{
int r;
struct mailimap_flag_list * flag_list;
uint32_t uidvalidity;
uint32_t uidresult;
selectIfNeeded(folder, pError);
if (* pError != ErrorNone)
return;
mProgressCallback = progressCallback;
bodyProgress(0, messageData->length());
flag_list = flags_to_lep(flags);
if (customFlags != NULL) {
for (unsigned int i = 0 ; i < customFlags->count() ; i ++) {
struct mailimap_flag * f;
String * customFlag = (String *) customFlags->objectAtIndex(i);
f = mailimap_flag_new_flag_keyword(strdup(customFlag->UTF8Characters()));
mailimap_flag_list_add(flag_list, f);
}
}
struct mailimap_date_time * imap_date = NULL;
if (date != (time_t) -1) {
imap_date = imapDateFromTimestamp(date);
}
r = mailimap_uidplus_append(mImap, MCUTF8(folder), flag_list, imap_date, messageData->bytes(), messageData->length(),
&uidvalidity, &uidresult);
if (imap_date != NULL) {
mailimap_date_time_free(imap_date);
}
mailimap_flag_list_free(flag_list);
bodyProgress(messageData->length(), messageData->length());
mProgressCallback = NULL;
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return;
}
else if (hasError(r)) {
* pError = ErrorAppend;
return;
}
* createdUID = uidresult;
* pError = ErrorNone;
}
void IMAPSession::appendMessageWithCustomFlagsAndDate(String * folder, String * messagePath, MessageFlag flags, Array * customFlags, time_t date,
IMAPProgressCallback * progressCallback, uint32_t * createdUID, ErrorCode * pError)
{
Data * messageData = Data::dataWithContentsOfFile(messagePath);
if (!messageData) {
* pError = ErrorFile;
return;
}
return appendMessageWithCustomFlagsAndDate(folder, messageData, flags, customFlags, date, progressCallback, createdUID, pError);
}
void IMAPSession::copyMessages(String * folder, IndexSet * uidSet, String * destFolder,
HashMap ** pUidMapping, ErrorCode * pError)
{
int r;
struct mailimap_set * set;
struct mailimap_set * src_uid;
struct mailimap_set * dest_uid;
uint32_t uidvalidity;
clist * setList;
IndexSet * uidSetResult;
HashMap * uidMapping = NULL;
selectIfNeeded(folder, pError);
if (* pError != ErrorNone)
return;
set = setFromIndexSet(uidSet);
if (clist_count(set->set_list) == 0) {
mailimap_set_free(set);
return;
}
setList = splitSet(set, 10);
uidSetResult = NULL;
for(clistiter * iter = clist_begin(setList) ; iter != NULL ; iter = clist_next(iter)) {
struct mailimap_set * current_set;
current_set = (struct mailimap_set *) clist_content(iter);
r = mailimap_uidplus_uid_copy(mImap, current_set, MCUTF8(destFolder),
&uidvalidity, &src_uid, &dest_uid);
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
goto release;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
goto release;
}
else if (hasError(r)) {
* pError = ErrorCopy;
goto release;
}
if ((src_uid != NULL) && (dest_uid != NULL)) {
if (uidMapping == NULL) {
uidMapping = HashMap::hashMap();
}
Array * srcUidsArray = arrayFromSet(src_uid);
Array * destUidsArray = arrayFromSet(dest_uid);
for(int i = 0 ; i < srcUidsArray->count() && i < destUidsArray->count() ; i ++) {
uidMapping->setObjectForKey(srcUidsArray->objectAtIndex(i), destUidsArray->objectAtIndex(i));
}
}
if (src_uid != NULL) {
mailimap_set_free(src_uid);
}
if (dest_uid != NULL) {
mailimap_set_free(dest_uid);
}
}
if (pUidMapping != NULL) {
* pUidMapping = uidMapping;
}
* pError = ErrorNone;
release:
for(clistiter * iter = clist_begin(setList) ; iter != NULL ; iter = clist_next(iter)) {
struct mailimap_set * current_set;
current_set = (struct mailimap_set *) clist_content(iter);
mailimap_set_free(current_set);
}
clist_free(setList);
mailimap_set_free(set);
}
void IMAPSession::moveMessages(String * folder, IndexSet * uidSet, String * destFolder,
HashMap ** pUidMapping, ErrorCode * pError)
{
int r;
struct mailimap_set * set;
struct mailimap_set * src_uid;
struct mailimap_set * dest_uid;
uint32_t uidvalidity;
clist * setList;
IndexSet * uidSetResult;
HashMap * uidMapping = NULL;
selectIfNeeded(folder, pError);
if (* pError != ErrorNone)
return;
set = setFromIndexSet(uidSet);
if (clist_count(set->set_list) == 0) {
mailimap_set_free(set);
return;
}
setList = splitSet(set, 10);
uidSetResult = NULL;
for(clistiter * iter = clist_begin(setList) ; iter != NULL ; iter = clist_next(iter)) {
struct mailimap_set * current_set;
current_set = (struct mailimap_set *) clist_content(iter);
r = mailimap_uidplus_uid_move(mImap, current_set, MCUTF8(destFolder),
&uidvalidity, &src_uid, &dest_uid);
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
goto release;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
goto release;
}
else if (hasError(r)) {
* pError = ErrorCopy;
goto release;
}
if ((src_uid != NULL) && (dest_uid != NULL)) {
if (uidMapping == NULL) {
uidMapping = HashMap::hashMap();
}
Array * srcUidsArray = arrayFromSet(src_uid);
Array * destUidsArray = arrayFromSet(dest_uid);
for(int i = 0 ; i < srcUidsArray->count() && i < destUidsArray->count() ; i ++) {
uidMapping->setObjectForKey(srcUidsArray->objectAtIndex(i), destUidsArray->objectAtIndex(i));
}
}
if (src_uid != NULL) {
mailimap_set_free(src_uid);
}
if (dest_uid != NULL) {
mailimap_set_free(dest_uid);
}
}
if (pUidMapping != NULL) {
* pUidMapping = uidMapping;
}
* pError = ErrorNone;
release:
for(clistiter * iter = clist_begin(setList) ; iter != NULL ; iter = clist_next(iter)) {
struct mailimap_set * current_set;
current_set = (struct mailimap_set *) clist_content(iter);
mailimap_set_free(current_set);
}
clist_free(setList);
mailimap_set_free(set);
}
void IMAPSession::expunge(String * folder, ErrorCode * pError)
{
int r;
selectIfNeeded(folder, pError);
if (* pError != ErrorNone)
return;
r = mailimap_expunge(mImap);
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return;
}
else if (hasError(r)) {
* pError = ErrorExpunge;
return;
}
* pError = ErrorNone;
}
static int
fetch_imap(mailimap * imap, bool identifier_is_uid, uint32_t identifier,
struct mailimap_fetch_type * fetch_type,
char ** result, size_t * result_len)
{
int r;
struct mailimap_msg_att * msg_att;
struct mailimap_msg_att_item * msg_att_item;
clist * fetch_result;
struct mailimap_set * set;
char * text;
size_t text_length;
clistiter * cur;
set = mailimap_set_new_single(identifier);
if (identifier_is_uid) {
r = mailimap_uid_fetch(imap, set, fetch_type, &fetch_result);
}
else {
r = mailimap_fetch(imap, set, fetch_type, &fetch_result);
}
mailimap_set_free(set);
switch (r) {
case MAILIMAP_NO_ERROR:
break;
default:
return r;
}
if (clist_isempty(fetch_result)) {
mailimap_fetch_list_free(fetch_result);
return MAILIMAP_ERROR_FETCH;
}
msg_att = (struct mailimap_msg_att *) clist_begin(fetch_result)->data;
text = NULL;
text_length = 0;
for(cur = clist_begin(msg_att->att_list) ; cur != NULL ;
cur = clist_next(cur)) {
msg_att_item = (struct mailimap_msg_att_item *) clist_content(cur);
if (msg_att_item->att_type != MAILIMAP_MSG_ATT_ITEM_STATIC) {
continue;
}
if (msg_att_item->att_data.att_static->att_type !=
MAILIMAP_MSG_ATT_BODY_SECTION) {
continue;
}
text = msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part;
msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part = NULL;
text_length = msg_att_item->att_data.att_static->att_data.att_body_section->sec_length;
}
mailimap_fetch_list_free(fetch_result);
if (text == NULL)
return MAILIMAP_ERROR_FETCH;
* result = text;
* result_len = text_length;
return MAILIMAP_NO_ERROR;
}
HashMap * IMAPSession::fetchMessageNumberUIDMapping(String * folder, uint32_t fromUID, uint32_t toUID,
ErrorCode * pError)
{
struct mailimap_set * imap_set;
struct mailimap_fetch_type * fetch_type;
clist * fetch_result;
HashMap * result;
struct mailimap_fetch_att * fetch_att;
int r;
clistiter * iter;
selectIfNeeded(folder, pError);
if (* pError != ErrorNone)
return NULL;
result = HashMap::hashMap();
imap_set = mailimap_set_new_interval(fromUID, toUID);
fetch_type = mailimap_fetch_type_new_fetch_att_list_empty();
fetch_att = mailimap_fetch_att_new_uid();
mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
r = mailimap_uid_fetch(mImap, imap_set, fetch_type, &fetch_result);
mailimap_fetch_type_free(fetch_type);
mailimap_set_free(imap_set);
if (r == MAILIMAP_ERROR_STREAM) {
MCLog("error stream");
mShouldDisconnect = true;
* pError = ErrorConnection;
return NULL;
}
else if (r == MAILIMAP_ERROR_PARSE) {
MCLog("error parse");
mShouldDisconnect = true;
* pError = ErrorParse;
return NULL;
}
else if (hasError(r)) {
MCLog("error fetch");
* pError = ErrorFetch;
return NULL;
}
for(iter = clist_begin(fetch_result) ; iter != NULL ; iter = clist_next(iter)) {
struct mailimap_msg_att * msg_att;
clistiter * item_iter;
uint32_t uid;
msg_att = (struct mailimap_msg_att *) clist_content(iter);
uid = 0;
for(item_iter = clist_begin(msg_att->att_list) ; item_iter != NULL ; item_iter = clist_next(item_iter)) {
struct mailimap_msg_att_item * att_item;
att_item = (struct mailimap_msg_att_item *) clist_content(item_iter);
if (att_item->att_type == MAILIMAP_MSG_ATT_ITEM_STATIC) {
struct mailimap_msg_att_static * att_static;
att_static = att_item->att_data.att_static;
if (att_static->att_type == MAILIMAP_MSG_ATT_UID) {
uid = att_static->att_data.att_uid;
}
}
}
if (uid < fromUID) {
uid = 0;
}
if (uid != 0) {
result->setObjectForKey(Value::valueWithUnsignedLongValue(msg_att->att_number),
Value::valueWithUnsignedLongValue(uid));
}
}
mailimap_fetch_list_free(fetch_result);
* pError = ErrorNone;
return result;
}
struct msg_att_handler_data {
IndexSet * uidsFilter;
IndexSet * numbersFilter;
bool fetchByUID;
Array * result;
IMAPMessagesRequestKind requestKind;
uint32_t mLastFetchedSequenceNumber;
HashMap * mapping;
bool needsHeader;
bool needsBody;
bool needsFlags;
bool needsGmailLabels;
bool needsGmailMessageID;
bool needsGmailThreadID;
};
static void msg_att_handler(struct mailimap_msg_att * msg_att, void * context)
{
clistiter * item_iter;
uint32_t uid;
IMAPMessage * msg;
bool hasHeader;
bool hasBody;
bool hasFlags;
bool hasGmailLabels;
bool hasGmailMessageID;
bool hasGmailThreadID;
struct msg_att_handler_data * msg_att_context;
bool fetchByUID;
Array * result;
IMAPMessagesRequestKind requestKind;
uint32_t mLastFetchedSequenceNumber;
HashMap * mapping;
bool needsHeader;
bool needsBody;
bool needsFlags;
bool needsGmailLabels;
bool needsGmailMessageID;
bool needsGmailThreadID;
IndexSet * uidsFilter;
IndexSet * numbersFilter;
msg_att_context = (struct msg_att_handler_data *) context;
uidsFilter = msg_att_context->uidsFilter;
numbersFilter = msg_att_context->numbersFilter;
fetchByUID = msg_att_context->fetchByUID;
result = msg_att_context->result;
requestKind = msg_att_context->requestKind;
mapping = msg_att_context->mapping;
needsHeader = msg_att_context->needsHeader;
needsBody = msg_att_context->needsBody;
needsFlags = msg_att_context->needsFlags;
needsGmailLabels = msg_att_context->needsGmailLabels;
needsGmailMessageID = msg_att_context->needsGmailMessageID;
needsGmailThreadID = msg_att_context->needsGmailThreadID;
hasHeader = false;
hasBody = false;
hasFlags = false;
hasGmailLabels = false;
hasGmailMessageID = false;
hasGmailThreadID = false;
if (numbersFilter != NULL) {
if (!numbersFilter->containsIndex((uint64_t) msg_att->att_number)) {
return;
}
}
msg = new IMAPMessage();
uid = 0;
mLastFetchedSequenceNumber = msg_att->att_number;
if (mapping != NULL) {
uid = (uint32_t) ((Value *) mapping->objectForKey(Value::valueWithUnsignedLongValue(msg_att->att_number)))->longLongValue();
}
msg->setSequenceNumber(msg_att->att_number);
for(item_iter = clist_begin(msg_att->att_list) ; item_iter != NULL ; item_iter = clist_next(item_iter)) {
struct mailimap_msg_att_item * att_item;
att_item = (struct mailimap_msg_att_item *) clist_content(item_iter);
if (att_item->att_type == MAILIMAP_MSG_ATT_ITEM_DYNAMIC) {
MessageFlag flags;
flags = flags_from_lep_att_dynamic(att_item->att_data.att_dyn);
msg->setFlags(flags);
msg->setOriginalFlags(flags);
hasFlags = true;
Array * customFlags;
customFlags = custom_flags_from_lep_att_dynamic(att_item->att_data.att_dyn);
msg->setCustomFlags(customFlags);
}
else if (att_item->att_type == MAILIMAP_MSG_ATT_ITEM_STATIC) {
struct mailimap_msg_att_static * att_static;
att_static = att_item->att_data.att_static;
if (att_static->att_type == MAILIMAP_MSG_ATT_UID) {
uid = att_static->att_data.att_uid;
}
else if (att_static->att_type == MAILIMAP_MSG_ATT_ENVELOPE) {
struct mailimap_envelope * env;
MCLog("parse envelope %lu", (unsigned long) uid);
env = att_static->att_data.att_env;
if ((requestKind & IMAPMessagesRequestKindMessageId) != 0) {
msg->header()->importPartialIMAPEnvelope(env);
} else {
msg->header()->importIMAPEnvelope(env);
}
hasHeader = true;
}
else if (att_static->att_type == MAILIMAP_MSG_ATT_BODY_SECTION) {
if ((requestKind & IMAPMessagesRequestKindFullHeaders) != 0 ||
(requestKind & IMAPMessagesRequestKindExtraHeaders) != 0) {
char * bytes;
size_t length;
bytes = att_static->att_data.att_body_section->sec_body_part;
length = att_static->att_data.att_body_section->sec_length;
msg->header()->importHeadersData(Data::dataWithBytes(bytes, (unsigned int) length));
hasHeader = true;
}
else {
char * references;
size_t ref_size;
// references
references = att_static->att_data.att_body_section->sec_body_part;
ref_size = att_static->att_data.att_body_section->sec_length;
msg->header()->importIMAPReferences(Data::dataWithBytes(references, (unsigned int) ref_size));
}
}
else if (att_static->att_type == MAILIMAP_MSG_ATT_BODYSTRUCTURE) {
AbstractPart * mainPart;
// bodystructure
mainPart = IMAPPart::attachmentWithIMAPBody(att_static->att_data.att_body);
msg->setMainPart(mainPart);
hasBody = true;
}
}
else if (att_item->att_type == MAILIMAP_MSG_ATT_ITEM_EXTENSION) {
struct mailimap_extension_data * ext_data;
ext_data = att_item->att_data.att_extension_data;
if (ext_data->ext_extension == &mailimap_extension_condstore) {
struct mailimap_condstore_fetch_mod_resp * fetch_data;
fetch_data = (struct mailimap_condstore_fetch_mod_resp *) ext_data->ext_data;
msg->setModSeqValue(fetch_data->cs_modseq_value);
}
else if (ext_data->ext_extension == &mailimap_extension_xgmlabels) {
struct mailimap_msg_att_xgmlabels * cLabels;
Array * labels;
clistiter * cur;
labels = new Array();
hasGmailLabels = true;
cLabels = (struct mailimap_msg_att_xgmlabels *) ext_data->ext_data;
for(cur = clist_begin(cLabels->att_labels) ; cur != NULL ; cur = clist_next(cur)) {
char * cLabel;
String * label;
cLabel = (char *) clist_content(cur);
label = String::stringWithUTF8Characters(cLabel);
labels->addObject(label);
}
if (labels->count() > 0) {
msg->setGmailLabels(labels);
}
labels->release();
}
else if (ext_data->ext_extension == &mailimap_extension_xgmthrid) {
uint64_t * threadID;
threadID = (uint64_t *) ext_data->ext_data;
msg->setGmailThreadID(*threadID);
hasGmailThreadID = true;
}
else if (ext_data->ext_extension == &mailimap_extension_xgmmsgid) {
uint64_t * msgID;
msgID = (uint64_t *) ext_data->ext_data;
msg->setGmailMessageID(*msgID);
hasGmailMessageID = true;
}
}
}
for(item_iter = clist_begin(msg_att->att_list) ; item_iter != NULL ; item_iter = clist_next(item_iter)) {
struct mailimap_msg_att_item * att_item;
att_item = (struct mailimap_msg_att_item *) clist_content(item_iter);
if (att_item->att_type == MAILIMAP_MSG_ATT_ITEM_STATIC) {
struct mailimap_msg_att_static * att_static;
att_static = att_item->att_data.att_static;
if (att_static->att_type == MAILIMAP_MSG_ATT_INTERNALDATE) {
msg->header()->importIMAPInternalDate(att_static->att_data.att_internal_date);
} else if (att_static->att_type == MAILIMAP_MSG_ATT_RFC822_SIZE) {
msg->setSize(att_static->att_data.att_rfc822_size);
}
}
}
if (needsBody && !hasBody) {
msg->release();
return;
}
if (needsHeader && !hasHeader) {
msg->release();
return;
}
if (needsFlags && !hasFlags) {
msg->release();
return;
}
if (needsGmailThreadID && !hasGmailThreadID) {
msg->release();
return;
}
if (needsGmailMessageID && !hasGmailMessageID) {
msg->release();
return;
}
if (needsGmailLabels && !hasGmailLabels) {
msg->release();
return;
}
if (uid != 0) {
msg->setUid(uid);
}
else {
msg->release();
return;
}
if (uidsFilter != NULL) {
if (!uidsFilter->containsIndex((uint64_t) uid)) {
msg->release();
return;
}
}
result->addObject(msg);
msg->release();
msg_att_context->mLastFetchedSequenceNumber = mLastFetchedSequenceNumber;
}
IMAPSyncResult * IMAPSession::fetchMessages(String * folder, IMAPMessagesRequestKind requestKind, bool fetchByUID,
struct mailimap_set * imapset, IndexSet * uidsFilter, IndexSet * numbersFilter,
uint64_t modseq, HashMap * mapping,
IMAPProgressCallback * progressCallback, Array * extraHeaders, ErrorCode * pError)
{
struct mailimap_fetch_type * fetch_type;
clist * fetch_result;
struct mailimap_qresync_vanished * vanished;
struct mailimap_fetch_att * fetch_att;
int r;
bool needsHeader;
bool needsBody;
bool needsFlags;
bool needsGmailLabels;
bool needsGmailMessageID;
bool needsGmailThreadID;
Array * messages;
IndexSet * vanishedMessages;
selectIfNeeded(folder, pError);
if (* pError != ErrorNone)
return NULL;
if (mNeedsMboxMailWorkaround && ((requestKind & IMAPMessagesRequestKindHeaders) != 0)) {
requestKind = (IMAPMessagesRequestKind) (requestKind & ~IMAPMessagesRequestKindHeaders);
requestKind = (IMAPMessagesRequestKind) (requestKind | IMAPMessagesRequestKindFullHeaders);
}
if (extraHeaders != NULL) {
requestKind = (IMAPMessagesRequestKind) (requestKind | IMAPMessagesRequestKindExtraHeaders);
}
if ((requestKind & IMAPMessagesRequestKindHeaders) != 0) {
mProgressItemsCount = 0;
mProgressCallback = progressCallback;
}
messages = Array::array();
needsHeader = false;
needsBody = false;
needsFlags = false;
needsGmailLabels = false;
needsGmailMessageID = false;
needsGmailThreadID = false;
clist * hdrlist = clist_new();
fetch_type = mailimap_fetch_type_new_fetch_att_list_empty();
fetch_att = mailimap_fetch_att_new_uid();
mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
if ((requestKind & IMAPMessagesRequestKindFlags) != 0) {
MCLog("request flags");
fetch_att = mailimap_fetch_att_new_flags();
mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
needsFlags = true;
}
if ((requestKind & IMAPMessagesRequestKindGmailLabels) != 0) {
MCLog("request flags");
fetch_att = mailimap_fetch_att_new_xgmlabels();
mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
needsGmailLabels = true;
}
if ((requestKind & IMAPMessagesRequestKindGmailThreadID) != 0) {
fetch_att = mailimap_fetch_att_new_xgmthrid();
mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
needsGmailThreadID = true;
}
if ((requestKind & IMAPMessagesRequestKindGmailMessageID) != 0) {
fetch_att = mailimap_fetch_att_new_xgmmsgid();
mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
needsGmailMessageID = true;
}
if ((requestKind & IMAPMessagesRequestKindFullHeaders) != 0) {
char * header;
MCLog("request envelope");
// most important header
header = strdup("Date");
clist_append(hdrlist, header);
header = strdup("Subject");
clist_append(hdrlist, header);
header = strdup("From");
clist_append(hdrlist, header);
header = strdup("Sender");
clist_append(hdrlist, header);
header = strdup("Reply-To");
clist_append(hdrlist, header);
header = strdup("To");
clist_append(hdrlist, header);
header = strdup("Cc");
clist_append(hdrlist, header);
header = strdup("Message-ID");
clist_append(hdrlist, header);
header = strdup("References");
clist_append(hdrlist, header);
header = strdup("In-Reply-To");
clist_append(hdrlist, header);
}
if ((requestKind & IMAPMessagesRequestKindMessageId) != 0) {
char * header;
// envelope
fetch_att = mailimap_fetch_att_new_envelope();
mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
MCLog("request envelope");
header = strdup("Message-ID");
clist_append(hdrlist, header);
header = strdup("Subject");
clist_append(hdrlist, header);
}
if ((requestKind & IMAPMessagesRequestKindHeaders) != 0) {
char * header;
MCLog("request envelope");
// envelope
fetch_att = mailimap_fetch_att_new_envelope();
mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
// references header
header = strdup("References");
clist_append(hdrlist, header);
if ((requestKind & IMAPMessagesRequestKindHeaderSubject) != 0) {
header = strdup("Subject");
clist_append(hdrlist, header);
}
}
if ((requestKind & IMAPMessagesRequestKindSize) != 0) {
// message structure
MCLog("request size");
fetch_att = mailimap_fetch_att_new_rfc822_size();
mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
}
if ((requestKind & IMAPMessagesRequestKindStructure) != 0) {
// message structure
MCLog("request bodystructure");
fetch_att = mailimap_fetch_att_new_bodystructure();
mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
needsBody = true;
}
if ((requestKind & IMAPMessagesRequestKindInternalDate) != 0) {
// internal date
fetch_att = mailimap_fetch_att_new_internaldate();
mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
}
if ((requestKind & IMAPMessagesRequestKindBody) != 0) {
fetch_att = mailimap_fetch_att_new_body_peek_section(mailimap_section_new(NULL));
mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
}
if ((requestKind & IMAPMessagesRequestKindExtraHeaders) != 0) {
// custom header request
char * header;
if (extraHeaders && extraHeaders->count() > 0) {
for (unsigned int i = 0; i < extraHeaders->count(); i++) {
String * headerString = (String *)extraHeaders->objectAtIndex(i);
header = strdup(headerString->UTF8Characters());
clist_append(hdrlist, header);
}
}
}
if (clist_begin(hdrlist) != NULL) {
struct mailimap_header_list * imap_hdrlist;
struct mailimap_section * section;
imap_hdrlist = mailimap_header_list_new(hdrlist);
section = mailimap_section_new_header_fields(imap_hdrlist);
fetch_att = mailimap_fetch_att_new_body_peek_section(section);
mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
needsHeader = true;
}
else {
clist_free(hdrlist);
}
struct msg_att_handler_data msg_att_data;
memset(&msg_att_data, 0, sizeof(msg_att_data));
msg_att_data.uidsFilter = uidsFilter;
msg_att_data.numbersFilter = numbersFilter;
msg_att_data.fetchByUID = fetchByUID;
msg_att_data.result = messages;
msg_att_data.requestKind = requestKind;
msg_att_data.mLastFetchedSequenceNumber = mLastFetchedSequenceNumber;
msg_att_data.mapping = mapping;
msg_att_data.needsHeader = needsHeader;
msg_att_data.needsBody = needsBody;
msg_att_data.needsFlags = needsFlags;
msg_att_data.needsGmailLabels = needsGmailLabels;
msg_att_data.needsGmailMessageID = needsGmailMessageID;
msg_att_data.needsGmailThreadID = needsGmailThreadID;
mailimap_set_msg_att_handler(mImap, msg_att_handler, &msg_att_data);
mBodyProgressEnabled = false;
vanished = NULL;
if (fetchByUID) {
if ((modseq != 0) && (mCondstoreEnabled || mQResyncEnabled)) {
if (mQResyncEnabled) {
r = mailimap_uid_fetch_qresync(mImap, imapset, fetch_type, modseq,
&fetch_result, &vanished);
}
else { /* condstore */
r = mailimap_uid_fetch_changedsince(mImap, imapset, fetch_type, modseq,
&fetch_result);
}
}
else {
r = mailimap_uid_fetch(mImap, imapset, fetch_type, &fetch_result);
}
} else {
if ((modseq != 0) && (mCondstoreEnabled || mQResyncEnabled)) {
if (mQResyncEnabled) {
r = mailimap_fetch_qresync(mImap, imapset, fetch_type, modseq,
&fetch_result, &vanished);
}
else { /* condstore */
r = mailimap_fetch_changedsince(mImap, imapset, fetch_type, modseq,
&fetch_result);
}
}
else {
r = mailimap_fetch(mImap, imapset, fetch_type, &fetch_result);
}
}
vanishedMessages = NULL;
if (vanished != NULL) {
vanishedMessages = indexSetFromSet(vanished->qr_known_uids);
}
mBodyProgressEnabled = true;
mProgressCallback = NULL;
mLastFetchedSequenceNumber = msg_att_data.mLastFetchedSequenceNumber;
mailimap_fetch_type_free(fetch_type);
mailimap_set_msg_att_handler(mImap, NULL, NULL);
if (r == MAILIMAP_ERROR_STREAM) {
MCLog("error stream");
mShouldDisconnect = true;
* pError = ErrorConnection;
return NULL;
}
else if (r == MAILIMAP_ERROR_PARSE) {
MCLog("error parse");
mShouldDisconnect = true;
* pError = ErrorParse;
return NULL;
}
else if (hasError(r)) {
MCLog("error fetch");
* pError = ErrorFetch;
return NULL;
}
IMAPSyncResult * result;
result = new IMAPSyncResult();
result->setModifiedOrAddedMessages(messages);
result->setVanishedMessages(vanishedMessages);
result->autorelease();
if ((requestKind & IMAPMessagesRequestKindHeaders) != 0) {
if (messages->count() == 0) {
unsigned int count;
count = clist_count(fetch_result);
if (count > 0) {
requestKind = (IMAPMessagesRequestKind) (requestKind & ~IMAPMessagesRequestKindHeaders);
requestKind = (IMAPMessagesRequestKind) (requestKind | IMAPMessagesRequestKindFullHeaders);
result = fetchMessages(folder, requestKind, fetchByUID,
imapset, uidsFilter, numbersFilter,
modseq, NULL, progressCallback, extraHeaders, pError);
if (result != NULL) {
if (result->modifiedOrAddedMessages() != NULL) {
if (result->modifiedOrAddedMessages()->count() > 0) {
mNeedsMboxMailWorkaround = true;
}
}
}
}
}
}
mailimap_fetch_list_free(fetch_result);
* pError = ErrorNone;
return result;
}
Array * IMAPSession::fetchMessagesByUID(String * folder, IMAPMessagesRequestKind requestKind,
IndexSet * uids, IMAPProgressCallback * progressCallback, ErrorCode * pError)
{
return fetchMessagesByUIDWithExtraHeaders(folder, requestKind, uids, progressCallback, NULL, pError);
}
Array * IMAPSession::fetchMessagesByUIDWithExtraHeaders(String * folder, IMAPMessagesRequestKind requestKind,
IndexSet * uids, IMAPProgressCallback * progressCallback,
Array * extraHeaders, ErrorCode * pError)
{
struct mailimap_set * imapset = setFromIndexSet(uids);
IMAPSyncResult * syncResult = fetchMessages(folder, requestKind, true, imapset, uids, NULL, 0, NULL,
progressCallback, extraHeaders, pError);
if (syncResult == NULL) {
mailimap_set_free(imapset);
return NULL;
}
Array * result = syncResult->modifiedOrAddedMessages();
result->retain()->autorelease();
mailimap_set_free(imapset);
return result;
}
Array * IMAPSession::fetchMessagesByNumber(String * folder, IMAPMessagesRequestKind requestKind,
IndexSet * numbers, IMAPProgressCallback * progressCallback,
ErrorCode * pError)
{
return fetchMessagesByNumberWithExtraHeaders(folder, requestKind, numbers, progressCallback, NULL, pError);
}
Array * IMAPSession::fetchMessagesByNumberWithExtraHeaders(String * folder, IMAPMessagesRequestKind requestKind,
IndexSet * numbers, IMAPProgressCallback * progressCallback,
Array * extraHeaders, ErrorCode * pError)
{
struct mailimap_set * imapset = setFromIndexSet(numbers);
IMAPSyncResult * syncResult = fetchMessages(folder, requestKind, false, imapset, NULL, numbers, 0, NULL,
progressCallback, extraHeaders, pError);
if (syncResult == NULL) {
mailimap_set_free(imapset);
return NULL;
}
Array * result = syncResult->modifiedOrAddedMessages();
result->retain()->autorelease();
mailimap_set_free(imapset);
return result;
}
static int fetch_rfc822(mailimap * session, bool identifier_is_uid,
uint32_t identifier, char ** result, size_t * result_len)
{
struct mailimap_section * section;
struct mailimap_fetch_att * fetch_att;
struct mailimap_fetch_type * fetch_type;
section = mailimap_section_new(NULL);
fetch_att = mailimap_fetch_att_new_body_peek_section(section);
fetch_type = mailimap_fetch_type_new_fetch_att(fetch_att);
int r = fetch_imap(session, identifier_is_uid, identifier,
fetch_type, result, result_len);
mailimap_fetch_type_free(fetch_type);
return r;
#if 0
int r;
clist * fetch_list;
struct mailimap_section * section;
struct mailimap_fetch_att * fetch_att;
struct mailimap_fetch_type * fetch_type;
struct mailimap_set * set;
struct mailimap_msg_att * msg_att;
struct mailimap_msg_att_item * item;
int res;
clistiter * cur;
section = mailimap_section_new(NULL);
fetch_att = mailimap_fetch_att_new_body_peek_section(section);
fetch_type = mailimap_fetch_type_new_fetch_att(fetch_att);
set = mailimap_set_new_single(identifier);
if (identifier_is_uid) {
r = mailimap_uid_fetch(session, set, fetch_type, &fetch_list);
}
else {
r = mailimap_fetch(session, set, fetch_type, &fetch_list);
}
mailimap_set_free(set);
mailimap_fetch_type_free(fetch_type);
if (r != MAILIMAP_NO_ERROR) {
res = r;
goto err;
}
if (clist_isempty(fetch_list)) {
res = MAILIMAP_ERROR_FETCH;
goto free;
}
msg_att = (struct mailimap_msg_att *) clist_begin(fetch_list)->data;
for(cur = clist_begin(msg_att->att_list) ; cur != NULL ; cur = clist_next(cur)) {
item = (struct mailimap_msg_att_item *) clist_content(cur);
if (item->att_type != MAILIMAP_MSG_ATT_ITEM_STATIC) {
continue;
}
if (item->att_data.att_static->att_type != MAILIMAP_MSG_ATT_BODY_SECTION) {
continue;
}
* result = item->att_data.att_static->att_data.att_body_section->sec_body_part;
item->att_data.att_static->att_data.att_body_section->sec_body_part = NULL;
mailimap_fetch_list_free(fetch_list);
return MAILIMAP_NO_ERROR;
}
res = MAILIMAP_ERROR_FETCH;
free:
mailimap_fetch_list_free(fetch_list);
err:
return res;
#endif
}
Data * IMAPSession::fetchMessageByUID(String * folder, uint32_t uid,
IMAPProgressCallback * progressCallback, ErrorCode * pError)
{
return fetchMessage(folder, true, uid, progressCallback, pError);
}
Data * IMAPSession::fetchMessageByNumber(String * folder, uint32_t number,
IMAPProgressCallback * progressCallback, ErrorCode * pError)
{
return fetchMessage(folder, false, number, progressCallback, pError);
}
Data * IMAPSession::fetchMessage(String * folder, bool identifier_is_uid, uint32_t identifier,
IMAPProgressCallback * progressCallback, ErrorCode * pError)
{
char * rfc822;
size_t rfc822_len;
int r;
Data * data;
selectIfNeeded(folder, pError);
if (* pError != ErrorNone)
return NULL;
mProgressItemsCount = 0;
mProgressCallback = progressCallback;
rfc822 = NULL;
r = fetch_rfc822(mImap, identifier_is_uid, identifier, &rfc822, &rfc822_len);
if (r == MAILIMAP_NO_ERROR) {
size_t len;
len = 0;
if (rfc822 != NULL) {
len = strlen(rfc822);
}
bodyProgress((unsigned int) len, (unsigned int) len);
}
mProgressCallback = NULL;
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return NULL;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return NULL;
}
else if (hasError(r)) {
* pError = ErrorFetch;
return NULL;
}
if (rfc822 == NULL) {
data = Data::data();
}
else {
data = Data::dataWithBytes(rfc822, (unsigned int) rfc822_len);
}
mailimap_nstring_free(rfc822);
* pError = ErrorNone;
return data;
}
static void nstringDeallocator(char * bytes, unsigned int length) {
mailimap_nstring_free(bytes);
};
Data * IMAPSession::fetchNonDecodedMessageAttachment(String * folder, bool identifier_is_uid,
uint32_t identifier, String * partID,
bool wholePart, uint32_t offset, uint32_t length,
Encoding encoding, IMAPProgressCallback * progressCallback, ErrorCode * pError)
{
struct mailimap_fetch_type * fetch_type;
struct mailimap_fetch_att * fetch_att;
struct mailimap_section * section;
struct mailimap_section_part * section_part;
clist * sec_list;
Array * partIDArray;
int r;
char * text = NULL;
size_t text_length = 0;
Data * data;
selectIfNeeded(folder, pError);
if (* pError != ErrorNone)
return NULL;
mProgressItemsCount = 0;
mProgressCallback = progressCallback;
bodyProgress(0, 0);
partIDArray = partID->componentsSeparatedByString(MCSTR("."));
sec_list = clist_new();
for(unsigned int i = 0 ; i < partIDArray->count() ; i ++) {
uint32_t * value;
String * element;
element = (String *) partIDArray->objectAtIndex(i);
value = (uint32_t *) malloc(sizeof(* value));
* value = element->intValue();
clist_append(sec_list, value);
}
section_part = mailimap_section_part_new(sec_list);
section = mailimap_section_new_part(section_part);
if (wholePart) {
fetch_att = mailimap_fetch_att_new_body_peek_section(section);
}
else {
fetch_att = mailimap_fetch_att_new_body_peek_section_partial(section, offset, length);
}
fetch_type = mailimap_fetch_type_new_fetch_att(fetch_att);
#ifdef LIBETPAN_HAS_MAILIMAP_RAMBLER_WORKAROUND
if (mRamblerRuServer && (encoding == EncodingBase64 || encoding == EncodingUUEncode)) {
mailimap_set_rambler_workaround_enabled(mImap, 1);
}
#endif
r = fetch_imap(mImap, identifier_is_uid, identifier, fetch_type, &text, &text_length);
mailimap_fetch_type_free(fetch_type);
#ifdef LIBETPAN_HAS_MAILIMAP_RAMBLER_WORKAROUND
mailimap_set_rambler_workaround_enabled(mImap, 0);
#endif
mProgressCallback = NULL;
MCLog("had error : %i", r);
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return NULL;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return NULL;
}
else if (hasError(r)) {
* pError = ErrorFetch;
return NULL;
}
data = Data::data();
data->takeBytesOwnership(text, (unsigned int) text_length, nstringDeallocator);
* pError = ErrorNone;
return data;
}
Data * IMAPSession::fetchMessageAttachment(String * folder, bool identifier_is_uid,
uint32_t identifier, String * partID,
Encoding encoding, IMAPProgressCallback * progressCallback, ErrorCode * pError)
{
Data * data = fetchNonDecodedMessageAttachment(folder, identifier_is_uid, identifier, partID, true, 0, 0, encoding, progressCallback, pError);
if (data) {
data = data->decodedDataUsingEncoding(encoding);
}
return data;
}
Data * IMAPSession::fetchMessageAttachmentByUID(String * folder, uint32_t uid, String * partID,
Encoding encoding, IMAPProgressCallback * progressCallback, ErrorCode * pError)
{
return fetchMessageAttachment(folder, true, uid, partID, encoding, progressCallback, pError);
}
Data * IMAPSession::fetchMessageAttachmentByNumber(String * folder, uint32_t number, String * partID,
Encoding encoding, IMAPProgressCallback * progressCallback, ErrorCode * pError)
{
return fetchMessageAttachment(folder, false, number, partID, encoding, progressCallback, pError);
}
void IMAPSession::fetchMessageAttachmentToFileByChunksByUID(String * folder, uint32_t uid, String * partID,
uint32_t estimatedSize, Encoding encoding,
String * outputFile, uint32_t chunkSize,
IMAPProgressCallback * progressCallback, ErrorCode * pError)
{
DataStreamDecoder * decoder = new DataStreamDecoder();
decoder->setEncoding(encoding);
decoder->setFilename(outputFile);
int nRetries = 0;
int const maxRetries = 3;
ErrorCode error = ErrorNone;
uint32_t offset = 0;
while (1) {
AutoreleasePool * pool = new AutoreleasePool();
LoadByChunkProgress * chunkProgressCallback = new LoadByChunkProgress();
chunkProgressCallback->setOffset(offset);
chunkProgressCallback->setEstimatedSize(estimatedSize);
chunkProgressCallback->setProgressCallback(progressCallback);
Data * data = fetchNonDecodedMessageAttachment(folder, true, uid, partID, false, offset, chunkSize, encoding, chunkProgressCallback, &error);
MC_SAFE_RELEASE(chunkProgressCallback);
if (error != ErrorNone) {
pool->release();
if ((error == ErrorConnection || error == ErrorParse) && nRetries < maxRetries) {
error = ErrorNone;
nRetries++;
continue;
}
break;
} else {
nRetries = 0;
}
if (data == NULL) {
break;
}
uint32_t encodedSize = data->length();
if (encodedSize == 0) {
pool->release();
break;
}
error = decoder->appendData(data);
pool->release();
if (error != ErrorNone) {
break;
}
offset += encodedSize;
// Try detect is this chunk last.
// Estimated size (extracted from BODYSTRUCTURE info) may be incorrect.
// Also, server may return chunk with size less than requested.
// So this detection is some tricky.
bool endOfPart = ((encodedSize == 0) ||
(estimatedSize > 0 && (estimatedSize <= offset) && (encodedSize != chunkSize)) ||
(estimatedSize == 0 && encodedSize < chunkSize));
if (endOfPart) {
break;
}
}
if (error == ErrorNone) {
decoder->flushData();
}
MC_SAFE_RELEASE(decoder);
* pError = error;
}
static bool msg_body_handler(int msg_att_type, struct mailimap_msg_att_body_section * section,
const char * bytes, size_t len, void * context)
{
DataStreamDecoder * decoder = (DataStreamDecoder *)context;
AutoreleasePool * pool = new AutoreleasePool();
Data * data = Data::dataWithBytes(bytes, (unsigned int) len);
ErrorCode error = decoder->appendData(data);
pool->release();
return error == ErrorNone;
}
void IMAPSession::fetchMessageAttachmentToFileByUID(String * folder, uint32_t uid, String * partID,
Encoding encoding, String * outputFile,
IMAPProgressCallback * progressCallback, ErrorCode * pError)
{
DataStreamDecoder * decoder = new DataStreamDecoder();
decoder->setEncoding(encoding);
decoder->setFilename(outputFile);
ErrorCode error = ErrorNone;
selectIfNeeded(folder, &error);
if (error != ErrorNone) {
* pError = error;
return;
}
mailimap_set_msg_body_handler(mImap, msg_body_handler, decoder);
fetchNonDecodedMessageAttachment(folder, true, uid, partID, true, 0, 0, encoding, progressCallback, &error);
mailimap_set_msg_body_handler(mImap, NULL, NULL);
if (error == ErrorNone) {
error = decoder->flushData();
}
MC_SAFE_RELEASE(decoder);
* pError = error;
}
IndexSet * IMAPSession::search(String * folder, IMAPSearchKind kind, String * searchString, ErrorCode * pError)
{
IMAPSearchExpression * expr;
expr = NULL;
switch (kind) {
case IMAPSearchKindAll:
{
expr = IMAPSearchExpression::searchAll();
break;
}
case IMAPSearchKindFrom:
{
expr = IMAPSearchExpression::searchFrom(searchString);
break;
}
case IMAPSearchKindTo:
{
expr = IMAPSearchExpression::searchTo(searchString);
break;
}
case IMAPSearchKindCc:
{
expr = IMAPSearchExpression::searchCc(searchString);
break;
}
case IMAPSearchKindBcc:
{
expr = IMAPSearchExpression::searchBcc(searchString);
break;
}
case IMAPSearchKindRecipient:
{
expr = IMAPSearchExpression::searchRecipient(searchString);
break;
}
case IMAPSearchKindSubject:
{
expr = IMAPSearchExpression::searchSubject(searchString);
break;
}
case IMAPSearchKindContent:
{
expr = IMAPSearchExpression::searchContent(searchString);
break;
}
case IMAPSearchKindBody:
{
expr = IMAPSearchExpression::searchBody(searchString);
break;
}
case IMAPSearchKindRead:
{
expr = IMAPSearchExpression::searchRead();
break;
}
case IMAPSearchKindUnread:
{
expr = IMAPSearchExpression::searchUnread();
break;
}
case IMAPSearchKindFlagged:
{
expr = IMAPSearchExpression::searchFlagged();
break;
}
case IMAPSearchKindUnflagged:
{
expr = IMAPSearchExpression::searchUnflagged();
break;
}
case IMAPSearchKindAnswered:
{
expr = IMAPSearchExpression::searchAnswered();
break;
}
case IMAPSearchKindUnanswered:
{
expr = IMAPSearchExpression::searchUnanswered();
break;
}
case IMAPSearchKindDraft:
{
expr = IMAPSearchExpression::searchDraft();
break;
}
case IMAPSearchKindUndraft:
{
expr = IMAPSearchExpression::searchUndraft();
break;
}
case IMAPSearchKindDeleted:
{
expr = IMAPSearchExpression::searchDeleted();
break;
}
case IMAPSearchKindSpam:
{
expr = IMAPSearchExpression::searchSpam();
break;
}
case IMAPSearchKindHeader:
{
String *header = new String("Message-ID");
expr = IMAPSearchExpression::searchHeader(header, searchString);
break;
}
default:
{
MCAssert(0);
break;
}
}
return search(folder, expr, pError);
}
static struct mailimap_search_key * searchKeyFromSearchExpression(IMAPSearchExpression * expression)
{
switch (expression->kind()) {
case IMAPSearchKindAll:
{
return mailimap_search_key_new_all();
}
case IMAPSearchKindFrom:
{
return mailimap_search_key_new_from(strdup(expression->value()->UTF8Characters()));
}
case IMAPSearchKindTo:
{
return mailimap_search_key_new_to(strdup(expression->value()->UTF8Characters()));
}
case IMAPSearchKindCc:
{
return mailimap_search_key_new_cc(strdup(expression->value()->UTF8Characters()));
}
case IMAPSearchKindBcc:
{
return mailimap_search_key_new_bcc(strdup(expression->value()->UTF8Characters()));
}
case IMAPSearchKindRecipient:
{
struct mailimap_search_key * to_search;
struct mailimap_search_key * cc_search;
struct mailimap_search_key * bcc_search;
struct mailimap_search_key * or_search1;
struct mailimap_search_key * or_search2;
to_search = mailimap_search_key_new_to(strdup(expression->value()->UTF8Characters()));
cc_search = mailimap_search_key_new_cc(strdup(expression->value()->UTF8Characters()));
bcc_search = mailimap_search_key_new_bcc(strdup(expression->value()->UTF8Characters()));
or_search1 = mailimap_search_key_new_or(to_search, cc_search);
or_search2 = mailimap_search_key_new_or(or_search1, bcc_search);
return or_search2;
}
case IMAPSearchKindSubject:
{
return mailimap_search_key_new_subject(strdup(expression->value()->UTF8Characters()));
}
case IMAPSearchKindContent:
{
return mailimap_search_key_new_text(strdup(expression->value()->UTF8Characters()));
}
case IMAPSearchKindBody:
{
return mailimap_search_key_new_body(strdup(expression->value()->UTF8Characters()));
}
case IMAPSearchKindUIDs:
{
return mailimap_search_key_new_uid(setFromIndexSet(expression->uids()));
}
case IMAPSearchKindNumbers:
{
return mailimap_search_key_new_set(setFromIndexSet(expression->numbers()));
}
case IMAPSearchKindHeader:
{
return mailimap_search_key_new_header(strdup(expression->header()->UTF8Characters()), strdup(expression->value()->UTF8Characters()));
}
case IMAPSearchKindBeforeDate:
{
time_t date = expression->date();
struct tm timeinfo;
localtime_r(&date, &timeinfo);
return mailimap_search_key_new_sentbefore(mailimap_date_new(timeinfo.tm_mday, timeinfo.tm_mon+1, timeinfo.tm_year+1900));
}
case IMAPSearchKindOnDate:
{
time_t date = expression->date();
struct tm timeinfo;
localtime_r(&date, &timeinfo);
return mailimap_search_key_new_senton(mailimap_date_new(timeinfo.tm_mday, timeinfo.tm_mon+1, timeinfo.tm_year+1900));
}
case IMAPSearchKindSinceDate:
{
time_t date = expression->date();
struct tm timeinfo;
localtime_r(&date, &timeinfo);
return mailimap_search_key_new_sentsince(mailimap_date_new(timeinfo.tm_mday, timeinfo.tm_mon+1, timeinfo.tm_year+1900));
}
case IMAPSearchKindBeforeReceivedDate:
{
time_t date = expression->date();
struct tm timeinfo;
localtime_r(&date, &timeinfo);
return mailimap_search_key_new_before(mailimap_date_new(timeinfo.tm_mday, timeinfo.tm_mon+1, timeinfo.tm_year+1900));
}
case IMAPSearchKindOnReceivedDate:
{
time_t date = expression->date();
struct tm timeinfo;
localtime_r(&date, &timeinfo);
return mailimap_search_key_new_on(mailimap_date_new(timeinfo.tm_mday, timeinfo.tm_mon+1, timeinfo.tm_year+1900));
}
case IMAPSearchKindSinceReceivedDate:
{
time_t date = expression->date();
struct tm timeinfo;
localtime_r(&date, &timeinfo);
return mailimap_search_key_new_since(mailimap_date_new(timeinfo.tm_mday, timeinfo.tm_mon+1, timeinfo.tm_year+1900));
}
case IMAPSearchKindGmailThreadID:
{
return mailimap_search_key_new_xgmthrid(expression->longNumber());
}
case IMAPSearchKindGmailMessageID:
{
return mailimap_search_key_new_xgmmsgid(expression->longNumber());
}
case IMAPSearchKindRead:
{
return mailimap_search_key_new(MAILIMAP_SEARCH_KEY_SEEN,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, 0,
NULL, NULL, NULL, NULL, NULL,
NULL, 0, NULL, NULL, NULL);
}
case IMAPSearchKindUnread:
{
return mailimap_search_key_new(MAILIMAP_SEARCH_KEY_UNSEEN,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, 0,
NULL, NULL, NULL, NULL, NULL,
NULL, 0, NULL, NULL, NULL);
}
case IMAPSearchKindFlagged:
{
return mailimap_search_key_new(MAILIMAP_SEARCH_KEY_FLAGGED,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, 0,
NULL, NULL, NULL, NULL, NULL,
NULL, 0, NULL, NULL, NULL);
}
case IMAPSearchKindUnflagged:
{
return mailimap_search_key_new(MAILIMAP_SEARCH_KEY_UNFLAGGED,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, 0,
NULL, NULL, NULL, NULL, NULL,
NULL, 0, NULL, NULL, NULL);
}
case IMAPSearchKindAnswered:
{
return mailimap_search_key_new(MAILIMAP_SEARCH_KEY_ANSWERED,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, 0,
NULL, NULL, NULL, NULL, NULL,
NULL, 0, NULL, NULL, NULL);
}
case IMAPSearchKindUnanswered:
{
return mailimap_search_key_new(MAILIMAP_SEARCH_KEY_UNANSWERED,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, 0,
NULL, NULL, NULL, NULL, NULL,
NULL, 0, NULL, NULL, NULL);
}
case IMAPSearchKindDraft:
{
return mailimap_search_key_new(MAILIMAP_SEARCH_KEY_DRAFT,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, 0,
NULL, NULL, NULL, NULL, NULL,
NULL, 0, NULL, NULL, NULL);
}
case IMAPSearchKindUndraft:
{
return mailimap_search_key_new(MAILIMAP_SEARCH_KEY_UNDRAFT,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, 0,
NULL, NULL, NULL, NULL, NULL,
NULL, 0, NULL, NULL, NULL);
}
case IMAPSearchKindDeleted:
{
return mailimap_search_key_new(MAILIMAP_SEARCH_KEY_DELETED,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, 0,
NULL, NULL, NULL, NULL, NULL,
NULL, 0, NULL, NULL, NULL);
}
case IMAPSearchKindSpam:
{
return mailimap_search_key_new(MAILIMAP_SEARCH_KEY_KEYWORD,
NULL, NULL, NULL, NULL, NULL,
strdup("Junk"), NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, 0,
NULL, NULL, NULL, NULL, NULL,
NULL, 0, NULL, NULL, NULL);
}
case IMAPSearchKindSizeLarger:
{
return mailimap_search_key_new_larger( (uint32_t) expression->longNumber());
}
case IMAPSearchKindSizeSmaller:
{
return mailimap_search_key_new_smaller( (uint32_t) expression->longNumber());
}
case IMAPSearchKindGmailRaw:
{
return mailimap_search_key_new_xgmraw(strdup(expression->value()->UTF8Characters()));
}
case IMAPSearchKindOr:
{
return mailimap_search_key_new_or(searchKeyFromSearchExpression(expression->leftExpression()), searchKeyFromSearchExpression(expression->rightExpression()));
}
case IMAPSearchKindAnd:
{
clist * list;
list = clist_new();
clist_append(list, searchKeyFromSearchExpression(expression->leftExpression()));
clist_append(list, searchKeyFromSearchExpression(expression->rightExpression()));
return mailimap_search_key_new_multiple(list);
}
case IMAPSearchKindNot:
{
return mailimap_search_key_new_not(searchKeyFromSearchExpression(expression->leftExpression()));
}
default:
MCAssert(0);
return NULL;
}
}
IndexSet * IMAPSession::search(String * folder, IMAPSearchExpression * expression, ErrorCode * pError)
{
struct mailimap_search_key * key;
selectIfNeeded(folder, pError);
if (* pError != ErrorNone)
return NULL;
clist * result_list = NULL;
const char * charset = "utf-8";
if (mYahooServer) {
charset = NULL;
}
int r;
key = searchKeyFromSearchExpression(expression);
if (mIsGmail) {
r = mailimap_uid_search_literalplus(mImap, charset, key, &result_list);
}
else {
r = mailimap_uid_search(mImap, charset, key, &result_list);
}
mailimap_search_key_free(key);
MCLog("had error : %i", r);
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return NULL;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return NULL;
}
else if (hasError(r)) {
* pError = ErrorFetch;
return NULL;
}
IndexSet * result = IndexSet::indexSet();
for(clistiter * cur = clist_begin(result_list) ; cur != NULL ; cur = clist_next(cur)) {
uint32_t * uid = (uint32_t *) clist_content(cur);
result->addIndex(* uid);
}
mailimap_search_result_free(result_list);
* pError = ErrorNone;
return result;
}
void IMAPSession::getQuota(uint32_t *usage, uint32_t *limit, ErrorCode * pError)
{
mailimap_quota_complete_data *quota_data;
int r = mailimap_quota_getquotaroot(mImap, "INBOX", "a_data);
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return;
}
else if (hasError(r)) {
* pError = ErrorFetch;
return;
}
for(clistiter * cur = clist_begin(quota_data->quota_list); cur != NULL; cur = clist_next(cur)) {
mailimap_quota_quota_data *quota = (mailimap_quota_quota_data*)clist_content(cur);
for (clistiter *cur2 = clist_begin(quota->quota_list); cur2 != NULL; cur2 = clist_next(cur2)) {
mailimap_quota_quota_resource *res = (mailimap_quota_quota_resource*)clist_content(cur2);
if (!strcasecmp("STORAGE", res->resource_name)) {
*usage = res->usage;
*limit = res->limit;
}
}
}
mailimap_quota_complete_data_free(quota_data);
}
bool IMAPSession::setupIdle()
{
// main thread
LOCK();
bool canIdle = mIdleEnabled;
if (mIdleEnabled) {
mailstream_setup_idle(mImap->imap_stream);
}
UNLOCK();
return canIdle;
}
void IMAPSession::idle(String * folder, uint32_t lastKnownUID, Data ** response, ErrorCode * pError)
{
int r;
setNeedsReselect();
// connection thread
selectIfNeeded(folder, pError);
if (* pError != ErrorNone)
return;
if (lastKnownUID != 0) {
Array * msgs;
msgs = fetchMessagesByUID(folder, IMAPMessagesRequestKindUid, IndexSet::indexSetWithRange(RangeMake(lastKnownUID, UINT64_MAX)),
NULL, pError);
if (* pError != ErrorNone)
return;
if (msgs->count() > 0) {
IMAPMessage * msg;
msg = (IMAPMessage *) msgs->objectAtIndex(0);
if (msg->uid() > lastKnownUID) {
MCLog("found msg UID %u %u", (unsigned int) msg->uid(), (unsigned int) lastKnownUID);
return;
}
}
}
r = mailimap_idle(mImap);
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return;
}
else if (hasError(r)) {
* pError = ErrorIdle;
return;
}
if (!mImap->imap_selection_info->sel_has_exists && !mImap->imap_selection_info->sel_has_recent) {
int r;
r = mailstream_wait_idle(mImap->imap_stream, MAX_IDLE_DELAY);
switch (r) {
case MAILSTREAM_IDLE_ERROR:
case MAILSTREAM_IDLE_CANCELLED:
{
mShouldDisconnect = true;
* pError = ErrorConnection;
MCLog("error or cancelled");
return;
}
case MAILSTREAM_IDLE_INTERRUPTED:
* pError = ErrorIdleInterrupted;
MCLog("interrupted by user");
break;
case MAILSTREAM_IDLE_HASDATA:
MCLog("something on the socket");
break;
case MAILSTREAM_IDLE_TIMEOUT:
MCLog("idle timeout");
break;
}
}
else {
MCLog("found info before idling");
}
r = mailimap_idle_done(mImap);
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return;
}
else if (hasError(r)) {
* pError = ErrorIdle;
return;
}
* pError = ErrorNone;
}
void IMAPSession::interruptIdle()
{
// main thread
LOCK();
if (mIdleEnabled) {
mailstream_interrupt_idle(mImap->imap_stream);
}
UNLOCK();
}
void IMAPSession::unsetupIdle()
{
// main thread
LOCK();
if (mIdleEnabled) {
mailstream_unsetup_idle(mImap->imap_stream);
}
UNLOCK();
}
void IMAPSession::disconnect()
{
unsetup();
}
void IMAPSession::reconnect(ErrorCode * pError)
{
mShouldDisconnect = true;
connectIfNeeded(pError);
}
IMAPIdentity * IMAPSession::identity(IMAPIdentity * clientIdentity, ErrorCode * pError)
{
connectIfNeeded(pError);
if (* pError != ErrorNone)
return NULL;
struct mailimap_id_params_list * client_identification;
client_identification = mailimap_id_params_list_new_empty();
mc_foreacharray(String, key, clientIdentity->allInfoKeys()) {
MMAPString * mmap_str_name = mmap_string_new(key->UTF8Characters());
MMAPString * mmap_str_value = mmap_string_new(clientIdentity->infoForKey(key)->UTF8Characters());
mmap_string_ref(mmap_str_name);
mmap_string_ref(mmap_str_value);
mailimap_id_params_list_add_name_value(client_identification, mmap_str_name->str, mmap_str_value->str);
}
int r;
struct mailimap_id_params_list * server_identification;
r = mailimap_id(mImap, client_identification, &server_identification);
mailimap_id_params_list_free(client_identification);
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return NULL;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return NULL;
}
else if (hasError(r)) {
* pError = ErrorIdentity;
return NULL;
}
IMAPIdentity * result = new IMAPIdentity();
clistiter * cur;
for(cur = clist_begin(server_identification->idpa_list) ; cur != NULL ; cur = clist_next(cur)) {
struct mailimap_id_param * param;
param = (struct mailimap_id_param *) clist_content(cur);
String * responseKey;
String * responseValue;
responseKey = String::stringWithUTF8Characters(param->idpa_name);
responseValue = String::stringWithUTF8Characters(param->idpa_value);
result->setInfoForKey(responseKey, responseValue);
}
mailimap_id_params_list_free(server_identification);
* pError = ErrorNone;
result->autorelease();
return result;
}
void IMAPSession::bodyProgress(unsigned int current, unsigned int maximum)
{
if (!mBodyProgressEnabled)
return;
if (mProgressCallback != NULL) {
mProgressCallback->bodyProgress(this, current, maximum);
}
}
void IMAPSession::itemsProgress(unsigned int current, unsigned int maximum)
{
mProgressItemsCount ++;
if (mProgressCallback != NULL) {
mProgressCallback->itemsProgress(this, mProgressItemsCount, maximum);
}
}
IMAPNamespace * IMAPSession::defaultNamespace()
{
return mDefaultNamespace;
}
void IMAPSession::setDefaultNamespace(IMAPNamespace * ns)
{
MC_SAFE_REPLACE_RETAIN(IMAPNamespace, mDefaultNamespace, ns);
}
IMAPIdentity * IMAPSession::serverIdentity()
{
return mServerIdentity;
}
IMAPIdentity * IMAPSession::clientIdentity()
{
return mClientIdentity;
}
void IMAPSession::setClientIdentity(IMAPIdentity * identity)
{
MC_SAFE_REPLACE_COPY(IMAPIdentity, mClientIdentity, identity);
}
HashMap * IMAPSession::fetchNamespace(ErrorCode * pError)
{
HashMap * result;
struct mailimap_namespace_data * namespace_data;
int r;
loginIfNeeded(pError);
if (* pError != ErrorNone)
return NULL;
result = HashMap::hashMap();
r = mailimap_namespace(mImap, &namespace_data);
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return NULL;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return NULL;
}
else if (hasError(r)) {
* pError = ErrorNamespace;
return NULL;
}
IMAPNamespace * ns;
if (namespace_data->ns_personal != NULL) {
ns = new IMAPNamespace();
ns->importIMAPNamespace(namespace_data->ns_personal);
result->setObjectForKey(IMAPNamespacePersonal, ns);
ns->release();
}
if (namespace_data->ns_other != NULL) {
ns = new IMAPNamespace();
ns->importIMAPNamespace(namespace_data->ns_other);
result->setObjectForKey(IMAPNamespaceOther, ns);
ns->release();
}
if (namespace_data->ns_shared != NULL) {
ns = new IMAPNamespace();
ns->importIMAPNamespace(namespace_data->ns_shared);
result->setObjectForKey(IMAPNamespaceShared, ns);
ns->release();
}
mailimap_namespace_data_free(namespace_data);
* pError = ErrorNone;
return result;
}
void IMAPSession::storeFlagsByUID(String * folder, IndexSet * uids, IMAPStoreFlagsRequestKind kind, MessageFlag flags, ErrorCode * pError)
{
this->storeFlagsAndCustomFlagsByUID(folder, uids, kind, flags, NULL, pError);
}
void IMAPSession::storeFlagsAndCustomFlagsByUID(String * folder, IndexSet * uids, IMAPStoreFlagsRequestKind kind, MessageFlag flags, Array * customFlags, ErrorCode * pError)
{
storeFlagsAndCustomFlags(folder, true, uids, kind, flags, customFlags, pError);
}
void IMAPSession::storeFlagsAndCustomFlags(String * folder, bool identifier_is_uid, IndexSet * identifiers,
IMAPStoreFlagsRequestKind kind, MessageFlag flags, Array * customFlags, ErrorCode * pError)
{
struct mailimap_set * imap_set;
struct mailimap_store_att_flags * store_att_flags;
struct mailimap_flag_list * flag_list;
int r;
clist * setList;
selectIfNeeded(folder, pError);
if (* pError != ErrorNone)
return;
imap_set = setFromIndexSet(identifiers);
if (clist_count(imap_set->set_list) == 0) {
mailimap_set_free(imap_set);
return;
}
setList = splitSet(imap_set, 50);
flag_list = mailimap_flag_list_new_empty();
if ((flags & MessageFlagSeen) != 0) {
struct mailimap_flag * f;
f = mailimap_flag_new_seen();
mailimap_flag_list_add(flag_list, f);
}
if ((flags & MessageFlagAnswered) != 0) {
struct mailimap_flag * f;
f = mailimap_flag_new_answered();
mailimap_flag_list_add(flag_list, f);
}
if ((flags & MessageFlagFlagged) != 0) {
struct mailimap_flag * f;
f = mailimap_flag_new_flagged();
mailimap_flag_list_add(flag_list, f);
}
if ((flags & MessageFlagDeleted) != 0) {
struct mailimap_flag * f;
f = mailimap_flag_new_deleted();
mailimap_flag_list_add(flag_list, f);
}
if ((flags & MessageFlagDraft) != 0) {
struct mailimap_flag * f;
f = mailimap_flag_new_draft();
mailimap_flag_list_add(flag_list, f);
}
if ((flags & MessageFlagMDNSent) != 0) {
struct mailimap_flag * f;
f = mailimap_flag_new_flag_keyword(strdup("$MDNSent"));
mailimap_flag_list_add(flag_list, f);
}
if ((flags & MessageFlagForwarded) != 0) {
struct mailimap_flag * f;
f = mailimap_flag_new_flag_keyword(strdup("$Forwarded"));
mailimap_flag_list_add(flag_list, f);
}
if ((flags & MessageFlagSubmitPending) != 0) {
struct mailimap_flag * f;
f = mailimap_flag_new_flag_keyword(strdup("$SubmitPending"));
mailimap_flag_list_add(flag_list, f);
}
if ((flags & MessageFlagSubmitted) != 0) {
struct mailimap_flag * f;
f = mailimap_flag_new_flag_keyword(strdup("$Submitted"));
mailimap_flag_list_add(flag_list, f);
}
if (customFlags != NULL) {
for (unsigned int i = 0 ; i < customFlags->count() ; i ++) {
struct mailimap_flag * f;
String * customFlag = (String *) customFlags->objectAtIndex(i);
f = mailimap_flag_new_flag_keyword(strdup(customFlag->UTF8Characters()));
mailimap_flag_list_add(flag_list, f);
}
}
store_att_flags = NULL;
for(clistiter * iter = clist_begin(setList) ; iter != NULL ; iter = clist_next(iter)) {
struct mailimap_set * current_set;
current_set = (struct mailimap_set *) clist_content(iter);
switch (kind) {
case IMAPStoreFlagsRequestKindRemove:
store_att_flags = mailimap_store_att_flags_new_remove_flags_silent(flag_list);
break;
case IMAPStoreFlagsRequestKindAdd:
store_att_flags = mailimap_store_att_flags_new_add_flags_silent(flag_list);
break;
case IMAPStoreFlagsRequestKindSet:
store_att_flags = mailimap_store_att_flags_new_set_flags_silent(flag_list);
break;
}
#ifdef LIBETPAN_HAS_MAILIMAP_QIP_WORKAROUND
if (mQipServer) {
mailimap_set_qip_workaround_enabled(mImap, 1);
}
#endif
if (identifier_is_uid) {
r = mailimap_uid_store(mImap, current_set, store_att_flags);
}
else {
r = mailimap_store(mImap, current_set, store_att_flags);
}
#ifdef LIBETPAN_HAS_MAILIMAP_QIP_WORKAROUND
mailimap_set_qip_workaround_enabled(mImap, 0);
#endif
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
goto release;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
goto release;
}
else if (hasError(r)) {
* pError = ErrorStore;
goto release;
}
}
* pError = ErrorNone;
release:
for(clistiter * iter = clist_begin(setList) ; iter != NULL ; iter = clist_next(iter)) {
struct mailimap_set * current_set;
current_set = (struct mailimap_set *) clist_content(iter);
mailimap_set_free(current_set);
}
clist_free(setList);
mailimap_store_att_flags_free(store_att_flags);
mailimap_set_free(imap_set);
}
void IMAPSession::storeFlagsByNumber(String * folder, IndexSet * numbers, IMAPStoreFlagsRequestKind kind, MessageFlag flags, ErrorCode * pError)
{
this->storeFlagsAndCustomFlagsByNumber(folder, numbers, kind, flags, NULL, pError);
}
void IMAPSession::storeFlagsAndCustomFlagsByNumber(String * folder, IndexSet * numbers, IMAPStoreFlagsRequestKind kind, MessageFlag flags, Array * customFlags, ErrorCode * pError)
{
storeFlagsAndCustomFlags(folder, false, numbers, kind, flags, customFlags, pError);
}
void IMAPSession::storeLabelsByUID(String * folder, IndexSet * uids, IMAPStoreFlagsRequestKind kind, Array * labels, ErrorCode * pError)
{
storeLabels(folder, true, uids, kind, labels, pError);
}
void IMAPSession::storeLabelsByNumber(String * folder, IndexSet * numbers, IMAPStoreFlagsRequestKind kind, Array * labels, ErrorCode * pError)
{
storeLabels(folder, false, numbers, kind, labels, pError);
}
void IMAPSession::storeLabels(String * folder, bool identifier_is_uid, IndexSet * identifiers, IMAPStoreFlagsRequestKind kind, Array * labels, ErrorCode * pError)
{
struct mailimap_set * imap_set;
struct mailimap_msg_att_xgmlabels * xgmlabels;
int r;
clist * setList;
selectIfNeeded(folder, pError);
if (* pError != ErrorNone)
return;
imap_set = setFromIndexSet(identifiers);
if (clist_count(imap_set->set_list) == 0) {
mailimap_set_free(imap_set);
return;
}
setList = splitSet(imap_set, 10);
xgmlabels = mailimap_msg_att_xgmlabels_new_empty();
for(unsigned int i = 0 ; i < labels->count() ; i ++) {
String * label = (String *) labels->objectAtIndex(i);
mailimap_msg_att_xgmlabels_add(xgmlabels, strdup(label->UTF8Characters()));
}
for(clistiter * iter = clist_begin(setList) ; iter != NULL ; iter = clist_next(iter)) {
struct mailimap_set * current_set;
int fl_sign;
current_set = (struct mailimap_set *) clist_content(iter);
switch (kind) {
case IMAPStoreFlagsRequestKindRemove:
fl_sign = -1;
break;
case IMAPStoreFlagsRequestKindAdd:
fl_sign = 1;
break;
case IMAPStoreFlagsRequestKindSet:
fl_sign = 0;
break;
}
if (identifier_is_uid) {
r = mailimap_uid_store_xgmlabels(mImap, current_set, fl_sign, 1, xgmlabels);
}
else {
r = mailimap_store_xgmlabels(mImap, current_set, fl_sign, 1, xgmlabels);
}
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
goto release;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
goto release;
}
else if (hasError(r)) {
* pError = ErrorStore;
goto release;
}
}
* pError = ErrorNone;
release:
for(clistiter * iter = clist_begin(setList) ; iter != NULL ; iter = clist_next(iter)) {
struct mailimap_set * current_set;
current_set = (struct mailimap_set *) clist_content(iter);
mailimap_set_free(current_set);
}
clist_free(setList);
mailimap_msg_att_xgmlabels_free(xgmlabels);
mailimap_set_free(imap_set);
}
uint32_t IMAPSession::uidValidity()
{
return mUIDValidity;
}
uint32_t IMAPSession::uidNext()
{
return mUIDNext;
}
uint64_t IMAPSession::modSequenceValue()
{
return mModSequenceValue;
}
unsigned int IMAPSession::lastFolderMessageCount()
{
return mFolderMsgCount;
}
uint32_t IMAPSession::firstUnseenUid()
{
return mFirstUnseenUid;
}
uint32_t IMAPSession::unseenCount()
{
return mUnseenCount;
}
IMAPSyncResult * IMAPSession::syncMessagesByUID(String * folder, IMAPMessagesRequestKind requestKind,
IndexSet * uids, uint64_t modseq,
IMAPProgressCallback * progressCallback, ErrorCode * pError)
{
return syncMessagesByUIDWithExtraHeaders(folder, requestKind, uids, modseq, progressCallback, NULL, pError);
}
IMAPSyncResult * IMAPSession::syncMessagesByUIDWithExtraHeaders(String * folder, IMAPMessagesRequestKind requestKind,
IndexSet * uids, uint64_t modseq,
IMAPProgressCallback * progressCallback, Array * extraHeaders,
ErrorCode * pError)
{
struct mailimap_set * imapset = setFromIndexSet(uids);
IMAPSyncResult * result = fetchMessages(folder, requestKind, true, imapset,
uids, NULL,
modseq, NULL,
progressCallback, extraHeaders, pError);
mailimap_set_free(imapset);
return result;
}
IndexSet * IMAPSession::capability(ErrorCode * pError)
{
int r;
struct mailimap_capability_data * cap;
connectIfNeeded(pError);
if (* pError != ErrorNone)
return NULL;
r = mailimap_capability(mImap, &cap);
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return NULL;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return NULL;
}
else if (hasError(r)) {
* pError = ErrorCapability;
return NULL;
}
mailimap_capability_data_free(cap);
IndexSet * result = new IndexSet();
capabilitySetWithSessionState(result);
* pError = ErrorNone;
result->autorelease();
return result;
}
void IMAPSession::capabilitySetWithSessionState(IndexSet * capabilities)
{
if (mailimap_has_extension(mImap, (char *)"STARTTLS")) {
capabilities->addIndex(IMAPCapabilityStartTLS);
}
if (mailimap_has_authentication(mImap, (char *)"PLAIN")) {
capabilities->addIndex(IMAPCapabilityAuthPlain);
}
if (mailimap_has_authentication(mImap, (char *)"LOGIN")) {
capabilities->addIndex(IMAPCapabilityAuthLogin);
}
if (mailimap_has_idle(mImap)) {
capabilities->addIndex(IMAPCapabilityIdle);
}
if (mailimap_has_id(mImap)) {
capabilities->addIndex(IMAPCapabilityId);
}
if (mailimap_has_xlist(mImap)) {
capabilities->addIndex(IMAPCapabilityXList);
}
if (mailimap_has_extension(mImap, (char *) "X-GM-EXT-1")) {
// Disable use of XLIST if this is the Gmail IMAP server because it implements
// RFC 6154.
capabilities->addIndex(IMAPCapabilityGmail);
}
if (mailimap_has_condstore(mImap)) {
capabilities->addIndex(IMAPCapabilityCondstore);
}
if (mailimap_has_qresync(mImap)) {
capabilities->addIndex(IMAPCapabilityQResync);
}
if (mailimap_has_xoauth2(mImap)) {
capabilities->addIndex(IMAPCapabilityXOAuth2);
}
if (mailimap_has_namespace(mImap)) {
capabilities->addIndex(IMAPCapabilityNamespace);
}
if (mailimap_has_compress_deflate(mImap)) {
capabilities->addIndex(IMAPCapabilityCompressDeflate);
}
if (mailimap_has_extension(mImap, (char *)"CHILDREN")) {
capabilities->addIndex(IMAPCapabilityChildren);
}
if (mailimap_has_extension(mImap, (char *)"MOVE")) {
capabilities->addIndex(IMAPCapabilityMove);
}
if (mailimap_has_extension(mImap, (char *)"XYMHIGHESTMODSEQ")) {
capabilities->addIndex(IMAPCapabilityXYMHighestModseq);
}
applyCapabilities(capabilities);
}
IndexSet * IMAPSession::storedCapabilities() {
return (IndexSet *)MC_SAFE_COPY(mCurrentCapabilities);
}
void IMAPSession::applyCapabilities(IndexSet * capabilities)
{
if (capabilities->containsIndex(IMAPCapabilityId)) {
mIdentityEnabled = true;
}
if (capabilities->containsIndex(IMAPCapabilityXList)) {
mXListEnabled = true;
}
if (capabilities->containsIndex(IMAPCapabilityGmail)) {
mXListEnabled = false;
mCondstoreEnabled = true;
mIsGmail = true;
}
if (capabilities->containsIndex(IMAPCapabilityIdle)) {
LOCK();
mIdleEnabled = true;
UNLOCK();
}
if (capabilities->containsIndex(IMAPCapabilityCondstore)) {
mCondstoreEnabled = true;
}
if (capabilities->containsIndex(IMAPCapabilityQResync)) {
mQResyncEnabled = true;
}
if (capabilities->containsIndex(IMAPCapabilityXYMHighestModseq)) {
mXYMHighestModseqEnabled = true;
}
if (capabilities->containsIndex(IMAPCapabilityXOAuth2)) {
mXOauth2Enabled = true;
}
if (mHermesServer) {
// Hermes server improperly advertise a namespace capability.
}
else {
if (capabilities->containsIndex(IMAPCapabilityNamespace)) {
mNamespaceEnabled = true;
}
}
if (capabilities->containsIndex(IMAPCapabilityCompressDeflate)) {
mCompressionEnabled = true;
}
}
bool IMAPSession::isIdleEnabled()
{
LOCK();
bool idleEnabled = mIdleEnabled;
UNLOCK();
return idleEnabled;
}
bool IMAPSession::isXListEnabled()
{
return mXListEnabled;
}
bool IMAPSession::isCondstoreEnabled()
{
return mCondstoreEnabled;
}
bool IMAPSession::isQResyncEnabled()
{
return mQResyncEnabled;
}
bool IMAPSession::isIdentityEnabled()
{
return mIdentityEnabled;
}
bool IMAPSession::isXOAuthEnabled()
{
return mXOauth2Enabled;
}
bool IMAPSession::isNamespaceEnabled()
{
return mNamespaceEnabled;
}
bool IMAPSession::isCompressionEnabled()
{
return mCompressionEnabled;
}
bool IMAPSession::allowsNewPermanentFlags() {
return mAllowsNewPermanentFlags;
}
bool IMAPSession::isDisconnected()
{
return mState == STATE_DISCONNECTED;
}
void IMAPSession::setConnectionLogger(ConnectionLogger * logger)
{
lockConnectionLogger();
mConnectionLogger = logger;
unlockConnectionLogger();
}
ConnectionLogger * IMAPSession::connectionLogger()
{
ConnectionLogger * result;
lockConnectionLogger();
result = mConnectionLogger;
unlockConnectionLogger();
return result;
}
void IMAPSession::lockConnectionLogger()
{
pthread_mutex_lock(&mConnectionLoggerLock);
}
void IMAPSession::unlockConnectionLogger()
{
pthread_mutex_unlock(&mConnectionLoggerLock);
}
ConnectionLogger * IMAPSession::connectionLoggerNoLock()
{
return mConnectionLogger;
}
String * IMAPSession::htmlRendering(IMAPMessage * message, String * folder, ErrorCode * pError)
{
HTMLRendererIMAPDataCallback * dataCallback = new HTMLRendererIMAPDataCallback(this, message->uid());
String * htmlString = HTMLRenderer::htmlForIMAPMessage(folder,
message,
dataCallback,
NULL);
* pError = dataCallback->error();
MC_SAFE_RELEASE(dataCallback);
if (* pError != ErrorNone) {
return NULL;
}
return htmlString;
}
String * IMAPSession::htmlBodyRendering(IMAPMessage * message, String * folder, ErrorCode * pError)
{
MCAssert(folder != NULL);
HTMLRendererIMAPDataCallback * dataCallback = new HTMLRendererIMAPDataCallback(this, message->uid());
HTMLBodyRendererTemplateCallback * htmlCallback = new HTMLBodyRendererTemplateCallback();
String * htmlBodyString = HTMLRenderer::htmlForIMAPMessage(folder,
message,
dataCallback,
htmlCallback);
* pError = dataCallback->error();
MC_SAFE_RELEASE(dataCallback);
MC_SAFE_RELEASE(htmlCallback);
if (* pError != ErrorNone) {
return NULL;
}
return htmlBodyString;
}
String * IMAPSession::plainTextRendering(IMAPMessage * message, String * folder, ErrorCode * pError)
{
String * htmlString = htmlRendering(message, folder, pError);
if (* pError != ErrorNone) {
return NULL;
}
String * plainTextString = htmlString->flattenHTML();
return plainTextString;
}
String * IMAPSession::plainTextBodyRendering(IMAPMessage * message, String * folder, bool stripWhitespace, ErrorCode * pError)
{
MCAssert(folder != NULL);
String * htmlBodyString = htmlBodyRendering(message, folder, pError);
if (* pError != ErrorNone) {
return NULL;
}
String * plainTextBodyString = htmlBodyString->flattenHTML();
if (stripWhitespace) {
return plainTextBodyString->stripWhitespace();
}
return plainTextBodyString;
}
void IMAPSession::setAutomaticConfigurationEnabled(bool enabled)
{
mAutomaticConfigurationEnabled = enabled;
}
bool IMAPSession::isAutomaticConfigurationEnabled()
{
return mAutomaticConfigurationEnabled;
}
bool IMAPSession::enableFeature(String * feature)
{
struct mailimap_capability_data * caps;
clist * cap_list;
struct mailimap_capability * cap;
int r;
cap_list = clist_new();
cap = mailimap_capability_new(MAILIMAP_CAPABILITY_NAME, NULL, strdup(MCUTF8(feature)));
clist_append(cap_list, cap);
caps = mailimap_capability_data_new(cap_list);
struct mailimap_capability_data * result;
r = mailimap_enable(mImap, caps, &result);
mailimap_capability_data_free(caps);
if (r != MAILIMAP_NO_ERROR)
return false;
mailimap_capability_data_free(result);
return true;
}
void IMAPSession::enableFeatures()
{
if (isCompressionEnabled()) {
ErrorCode error;
enableCompression(&error);
if (error != ErrorNone) {
MCLog("could not enable compression");
}
}
if (isQResyncEnabled()) {
enableFeature(MCSTR("QRESYNC"));
}
else if (isCondstoreEnabled()) {
enableFeature(MCSTR("CONDSTORE"));
}
}
void IMAPSession::enableCompression(ErrorCode * pError)
{
int r;
r = mailimap_compress(mImap);
if (r == MAILIMAP_ERROR_STREAM) {
mShouldDisconnect = true;
* pError = ErrorConnection;
return;
}
else if (r == MAILIMAP_ERROR_PARSE) {
mShouldDisconnect = true;
* pError = ErrorParse;
return;
}
else if (hasError(r)) {
* pError = ErrorCompression;
return;
}
* pError = ErrorNone;
}
bool IMAPSession::isAutomaticConfigurationDone()
{
return mAutomaticConfigurationDone;
}
void IMAPSession::resetAutomaticConfigurationDone()
{
mAutomaticConfigurationDone = false;
}
String * IMAPSession::gmailUserDisplayName()
{
return mGmailUserDisplayName;
}
| ./CrossVul/dataset_final_sorted/CWE-295/cpp/good_1981_0 |
crossvul-cpp_data_bad_4031_1 | #include <pichi/config.hpp>
// Include config.hpp first
#include <array>
#include <boost/asio/connect.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/spawn2.hpp>
#include <boost/asio/write.hpp>
#include <pichi/api/balancer.hpp>
#include <pichi/api/vos.hpp>
#include <pichi/asserts.hpp>
#include <pichi/common.hpp>
#include <pichi/crypto/key.hpp>
#include <pichi/net/adapter.hpp>
#include <pichi/net/asio.hpp>
#include <pichi/net/common.hpp>
#include <pichi/net/direct.hpp>
#include <pichi/net/helpers.hpp>
#include <pichi/net/http.hpp>
#include <pichi/net/reject.hpp>
#include <pichi/net/socks5.hpp>
#include <pichi/net/ssaead.hpp>
#include <pichi/net/ssstream.hpp>
#include <pichi/net/tunnel.hpp>
#include <pichi/test/socket.hpp>
#ifdef ENABLE_TLS
#include <boost/asio/ssl/context.hpp>
#include <boost/asio/ssl/stream.hpp>
#endif // ENABLE_TLS
using namespace std;
namespace asio = boost::asio;
namespace ip = asio::ip;
namespace ssl = asio::ssl;
namespace sys = boost::system;
using ip::tcp;
using pichi::crypto::CryptoMethod;
using TcpSocket = tcp::socket;
using TlsSocket = ssl::stream<TcpSocket>;
namespace pichi::net {
#ifdef ENABLE_TLS
static auto createTlsContext(api::IngressVO const& vo)
{
auto ctx = ssl::context{ssl::context::tls_server};
ctx.use_certificate_chain_file(*vo.certFile_);
ctx.use_private_key_file(*vo.keyFile_, ssl::context::pem);
return ctx;
}
static auto createTlsContext(api::EgressVO const& vo)
{
auto ctx = ssl::context{ssl::context::tls_client};
if (*vo.insecure_) {
ctx.set_verify_mode(ssl::context::verify_none);
}
else {
ctx.set_verify_mode(ssl::context::verify_peer);
ctx.set_default_verify_paths();
if (vo.caFile_.has_value()) ctx.load_verify_file(*vo.caFile_);
}
return ctx;
}
#endif // ENABLE_TLS
template <typename Socket, typename Yield>
void connect(Endpoint const& endpoint, Socket& s, Yield yield)
{
suppressC4100(yield);
#ifdef ENABLE_TLS
if constexpr (IsSslStreamV<Socket>) {
connect(endpoint, s.next_layer(), yield);
s.async_handshake(ssl::stream_base::handshake_type::client, yield);
}
else
#endif // ENABLE_TLS
#ifdef BUILD_TEST
if constexpr (is_same_v<Socket, pichi::test::Stream>) {
s.connect();
}
else
#endif // BUILD_TEST
asio::async_connect(s,
tcp::resolver{s.get_executor()
#ifndef RESOLVER_CONSTRUCTED_FROM_EXECUTOR
.context()
#endif // RESOLVER_CONSTRUCTED_FROM_EXECUTOR
}
.async_resolve(endpoint.host_, endpoint.port_, yield),
yield);
}
template <typename Socket, typename Yield>
void read(Socket& s, MutableBuffer<uint8_t> buf, Yield yield)
{
suppressC4100(yield);
#ifdef BUILD_TEST
if constexpr (is_same_v<Socket, pichi::test::Stream>)
asio::read(s, asio::buffer(buf));
else
#endif // BUILD_TEST
asio::async_read(s, asio::buffer(buf), yield);
}
template <typename Socket, typename Yield>
size_t readSome(Socket& s, MutableBuffer<uint8_t> buf, Yield yield)
{
suppressC4100(yield);
#ifdef BUILD_TEST
if constexpr (is_same_v<Socket, pichi::test::Stream>)
return s.read_some(asio::buffer(buf));
else
#endif // BUILD_TEST
return s.async_read_some(asio::buffer(buf), yield);
}
template <typename Socket, typename Yield>
void write(Socket& s, ConstBuffer<uint8_t> buf, Yield yield)
{
suppressC4100(yield);
#ifdef BUILD_TEST
if constexpr (is_same_v<Socket, pichi::test::Stream>)
asio::write(s, asio::buffer(buf));
else
#endif // BUILD_TEST
asio::async_write(s, asio::buffer(buf), yield);
}
template <typename Socket, typename Yield> void close(Socket& s, Yield yield)
{
// This function is supposed to be 'noexcept' because it's always invoked in the desturctors.
// TODO log it
auto ec = sys::error_code{};
if constexpr (IsSslStreamV<Socket>) {
s.async_shutdown(yield[ec]);
close(s.next_layer(), yield);
}
else {
suppressC4100(yield);
s.close(ec);
}
}
template <typename Socket> bool isOpen(Socket const& s)
{
if constexpr (IsSslStreamV<Socket>) {
return isOpen(s.next_layer());
}
else {
return s.is_open();
}
}
template <typename Socket> unique_ptr<Ingress> makeIngress(api::IngressHolder& holder, Socket&& s)
{
auto container = array<uint8_t, 1024>{0};
auto psk = MutableBuffer<uint8_t>{container};
auto& vo = holder.vo_;
switch (vo.type_) {
case AdapterType::HTTP:
#ifdef ENABLE_TLS
if (*vo.tls_) {
auto ctx = createTlsContext(vo);
return make_unique<HttpIngress<TlsSocket>>(vo.credentials_, forward<Socket>(s), ctx);
}
else
#endif // ENABLE_TLS
return make_unique<HttpIngress<TcpSocket>>(vo.credentials_, forward<Socket>(s));
case AdapterType::SOCKS5:
#ifdef ENABLE_TLS
if (*vo.tls_) {
auto ctx = createTlsContext(vo);
return make_unique<Socks5Ingress<TlsSocket>>(vo.credentials_, forward<Socket>(s), ctx);
}
else
#endif // ENABLE_TLS
return make_unique<Socks5Ingress<TcpSocket>>(vo.credentials_, forward<Socket>(s));
case AdapterType::SS:
psk = {container, generateKey(*vo.method_, ConstBuffer<uint8_t>{*vo.password_}, container)};
switch (*vo.method_) {
case CryptoMethod::RC4_MD5:
return make_unique<SSStreamAdapter<CryptoMethod::RC4_MD5, Socket>>(psk, forward<Socket>(s));
case CryptoMethod::BF_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::BF_CFB, Socket>>(psk, forward<Socket>(s));
case CryptoMethod::AES_128_CTR:
return make_unique<SSStreamAdapter<CryptoMethod::AES_128_CTR, Socket>>(psk,
forward<Socket>(s));
case CryptoMethod::AES_192_CTR:
return make_unique<SSStreamAdapter<CryptoMethod::AES_192_CTR, Socket>>(psk,
forward<Socket>(s));
case CryptoMethod::AES_256_CTR:
return make_unique<SSStreamAdapter<CryptoMethod::AES_256_CTR, Socket>>(psk,
forward<Socket>(s));
case CryptoMethod::AES_128_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::AES_128_CFB, Socket>>(psk,
forward<Socket>(s));
case CryptoMethod::AES_192_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::AES_192_CFB, Socket>>(psk,
forward<Socket>(s));
case CryptoMethod::AES_256_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::AES_256_CFB, Socket>>(psk,
forward<Socket>(s));
case CryptoMethod::CAMELLIA_128_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::CAMELLIA_128_CFB, Socket>>(
psk, forward<Socket>(s));
case CryptoMethod::CAMELLIA_192_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::CAMELLIA_192_CFB, Socket>>(
psk, forward<Socket>(s));
case CryptoMethod::CAMELLIA_256_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::CAMELLIA_256_CFB, Socket>>(
psk, forward<Socket>(s));
case CryptoMethod::CHACHA20:
return make_unique<SSStreamAdapter<CryptoMethod::CHACHA20, Socket>>(psk, forward<Socket>(s));
case CryptoMethod::SALSA20:
return make_unique<SSStreamAdapter<CryptoMethod::SALSA20, Socket>>(psk, forward<Socket>(s));
case CryptoMethod::CHACHA20_IETF:
return make_unique<SSStreamAdapter<CryptoMethod::CHACHA20_IETF, Socket>>(psk,
forward<Socket>(s));
case CryptoMethod::AES_128_GCM:
return make_unique<SSAeadAdapter<CryptoMethod::AES_128_GCM, Socket>>(psk, forward<Socket>(s));
case CryptoMethod::AES_192_GCM:
return make_unique<SSAeadAdapter<CryptoMethod::AES_192_GCM, Socket>>(psk, forward<Socket>(s));
case CryptoMethod::AES_256_GCM:
return make_unique<SSAeadAdapter<CryptoMethod::AES_256_GCM, Socket>>(psk, forward<Socket>(s));
case CryptoMethod::CHACHA20_IETF_POLY1305:
return make_unique<SSAeadAdapter<CryptoMethod::CHACHA20_IETF_POLY1305, Socket>>(
psk, forward<Socket>(s));
case CryptoMethod::XCHACHA20_IETF_POLY1305:
return make_unique<SSAeadAdapter<CryptoMethod::XCHACHA20_IETF_POLY1305, Socket>>(
psk, forward<Socket>(s));
default:
fail(PichiError::BAD_PROTO);
}
case AdapterType::TUNNEL:
return make_unique<TunnelIngress<api::IngressIterator, Socket>>(*holder.balancer_,
forward<Socket>(s));
default:
fail(PichiError::BAD_PROTO);
}
}
unique_ptr<Egress> makeEgress(api::EgressVO const& vo, asio::io_context& io)
{
auto container = array<uint8_t, 1024>{0};
auto psk = MutableBuffer<uint8_t>{container};
switch (vo.type_) {
case AdapterType::HTTP:
#ifdef ENABLE_TLS
if (*vo.tls_) {
auto ctx = createTlsContext(vo);
return make_unique<HttpEgress<TlsSocket>>(vo.credential_, io, ctx);
}
else
#endif // ENABLE_TLS
return make_unique<HttpEgress<TcpSocket>>(vo.credential_, io);
case AdapterType::SOCKS5:
#ifdef ENABLE_TLS
if (*vo.tls_) {
auto ctx = createTlsContext(vo);
return make_unique<Socks5Egress<ssl::stream<tcp::socket>>>(vo.credential_, io, ctx);
}
else
#endif // ENABLE_TLS
return make_unique<Socks5Egress<tcp::socket>>(vo.credential_, io);
case AdapterType::DIRECT:
return make_unique<DirectAdapter>(io);
case AdapterType::REJECT:
switch (*vo.mode_) {
case api::DelayMode::RANDOM:
return make_unique<RejectEgress>(io);
case api::DelayMode::FIXED:
return make_unique<RejectEgress>(io, *vo.delay_);
default:
fail(PichiError::BAD_PROTO);
}
case AdapterType::SS:
psk = {container, generateKey(*vo.method_, ConstBuffer<uint8_t>{*vo.password_}, container)};
switch (*vo.method_) {
case CryptoMethod::RC4_MD5:
return make_unique<SSStreamAdapter<CryptoMethod::RC4_MD5, TcpSocket>>(psk, io);
case CryptoMethod::BF_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::BF_CFB, TcpSocket>>(psk, io);
case CryptoMethod::AES_128_CTR:
return make_unique<SSStreamAdapter<CryptoMethod::AES_128_CTR, TcpSocket>>(psk, io);
case CryptoMethod::AES_192_CTR:
return make_unique<SSStreamAdapter<CryptoMethod::AES_192_CTR, TcpSocket>>(psk, io);
case CryptoMethod::AES_256_CTR:
return make_unique<SSStreamAdapter<CryptoMethod::AES_256_CTR, TcpSocket>>(psk, io);
case CryptoMethod::AES_128_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::AES_128_CFB, TcpSocket>>(psk, io);
case CryptoMethod::AES_192_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::AES_192_CFB, TcpSocket>>(psk, io);
case CryptoMethod::AES_256_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::AES_256_CFB, TcpSocket>>(psk, io);
case CryptoMethod::CAMELLIA_128_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::CAMELLIA_128_CFB, TcpSocket>>(psk, io);
case CryptoMethod::CAMELLIA_192_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::CAMELLIA_192_CFB, TcpSocket>>(psk, io);
case CryptoMethod::CAMELLIA_256_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::CAMELLIA_256_CFB, TcpSocket>>(psk, io);
case CryptoMethod::CHACHA20:
return make_unique<SSStreamAdapter<CryptoMethod::CHACHA20, TcpSocket>>(psk, io);
case CryptoMethod::SALSA20:
return make_unique<SSStreamAdapter<CryptoMethod::SALSA20, TcpSocket>>(psk, io);
case CryptoMethod::CHACHA20_IETF:
return make_unique<SSStreamAdapter<CryptoMethod::CHACHA20_IETF, TcpSocket>>(psk, io);
case CryptoMethod::AES_128_GCM:
return make_unique<SSAeadAdapter<CryptoMethod::AES_128_GCM, TcpSocket>>(psk, io);
case CryptoMethod::AES_192_GCM:
return make_unique<SSAeadAdapter<CryptoMethod::AES_192_GCM, TcpSocket>>(psk, io);
case CryptoMethod::AES_256_GCM:
return make_unique<SSAeadAdapter<CryptoMethod::AES_256_GCM, TcpSocket>>(psk, io);
case CryptoMethod::CHACHA20_IETF_POLY1305:
return make_unique<SSAeadAdapter<CryptoMethod::CHACHA20_IETF_POLY1305, TcpSocket>>(psk, io);
case CryptoMethod::XCHACHA20_IETF_POLY1305:
return make_unique<SSAeadAdapter<CryptoMethod::XCHACHA20_IETF_POLY1305, TcpSocket>>(psk, io);
default:
fail(PichiError::BAD_PROTO);
}
default:
fail(PichiError::BAD_PROTO);
}
}
using Yield = asio::yield_context;
template void connect<>(Endpoint const&, TcpSocket&, Yield);
template void read<>(TcpSocket&, MutableBuffer<uint8_t>, Yield);
template size_t readSome<>(TcpSocket&, MutableBuffer<uint8_t>, Yield);
template void write<>(TcpSocket&, ConstBuffer<uint8_t>, Yield);
template void close<>(TcpSocket&, Yield);
template bool isOpen<>(TcpSocket const&);
#ifdef ENABLE_TLS
template void connect<>(Endpoint const&, TlsSocket&, Yield);
template void read<>(TlsSocket&, MutableBuffer<uint8_t>, Yield);
template size_t readSome<>(TlsSocket&, MutableBuffer<uint8_t>, Yield);
template void write<>(TlsSocket&, ConstBuffer<uint8_t>, Yield);
template void close<>(TlsSocket&, Yield);
template bool isOpen<>(TlsSocket const&);
#endif // ENABLE_TLS
#ifdef BUILD_TEST
template void connect<>(Endpoint const&, pichi::test::Stream&, Yield);
template void read<>(pichi::test::Stream&, MutableBuffer<uint8_t>, Yield);
template size_t readSome<>(pichi::test::Stream&, MutableBuffer<uint8_t>, Yield);
template void write<>(pichi::test::Stream&, ConstBuffer<uint8_t>, Yield);
template void close<>(pichi::test::Stream&, Yield);
template bool isOpen<>(pichi::test::Stream const&);
#endif // BUILD_TEST
template unique_ptr<Ingress> makeIngress<>(api::IngressHolder&, TcpSocket&&);
} // namespace pichi::net
| ./CrossVul/dataset_final_sorted/CWE-295/cpp/bad_4031_1 |
crossvul-cpp_data_good_4031_1 | #include <pichi/config.hpp>
// Include config.hpp first
#include <array>
#include <boost/asio/connect.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/spawn2.hpp>
#include <boost/asio/write.hpp>
#include <pichi/api/balancer.hpp>
#include <pichi/api/vos.hpp>
#include <pichi/asserts.hpp>
#include <pichi/common.hpp>
#include <pichi/crypto/key.hpp>
#include <pichi/net/adapter.hpp>
#include <pichi/net/asio.hpp>
#include <pichi/net/common.hpp>
#include <pichi/net/direct.hpp>
#include <pichi/net/helpers.hpp>
#include <pichi/net/http.hpp>
#include <pichi/net/reject.hpp>
#include <pichi/net/socks5.hpp>
#include <pichi/net/ssaead.hpp>
#include <pichi/net/ssstream.hpp>
#include <pichi/net/tunnel.hpp>
#include <pichi/test/socket.hpp>
#ifdef ENABLE_TLS
#include <boost/asio/ssl/context.hpp>
#include <boost/asio/ssl/rfc2818_verification.hpp>
#include <boost/asio/ssl/stream.hpp>
#endif // ENABLE_TLS
using namespace std;
namespace asio = boost::asio;
namespace ip = asio::ip;
namespace ssl = asio::ssl;
namespace sys = boost::system;
using ip::tcp;
using pichi::crypto::CryptoMethod;
using TcpSocket = tcp::socket;
using TlsSocket = ssl::stream<TcpSocket>;
namespace pichi::net {
#ifdef ENABLE_TLS
static auto createTlsContext(api::IngressVO const& vo)
{
auto ctx = ssl::context{ssl::context::tls_server};
ctx.use_certificate_chain_file(*vo.certFile_);
ctx.use_private_key_file(*vo.keyFile_, ssl::context::pem);
return ctx;
}
static auto createTlsContext(api::EgressVO const& vo)
{
auto ctx = ssl::context{ssl::context::tls_client};
if (*vo.insecure_) {
ctx.set_verify_mode(ssl::context::verify_none);
return ctx;
}
ctx.set_verify_mode(ssl::context::verify_peer);
if (vo.caFile_.has_value())
ctx.load_verify_file(*vo.caFile_);
else {
ctx.set_default_verify_paths();
ctx.set_verify_callback(ssl::rfc2818_verification{*vo.host_});
}
return ctx;
}
#endif // ENABLE_TLS
template <typename Socket, typename Yield>
void connect(Endpoint const& endpoint, Socket& s, Yield yield)
{
suppressC4100(yield);
#ifdef ENABLE_TLS
if constexpr (IsSslStreamV<Socket>) {
connect(endpoint, s.next_layer(), yield);
s.async_handshake(ssl::stream_base::handshake_type::client, yield);
}
else
#endif // ENABLE_TLS
#ifdef BUILD_TEST
if constexpr (is_same_v<Socket, pichi::test::Stream>) {
s.connect();
}
else
#endif // BUILD_TEST
asio::async_connect(s,
tcp::resolver{s.get_executor()
#ifndef RESOLVER_CONSTRUCTED_FROM_EXECUTOR
.context()
#endif // RESOLVER_CONSTRUCTED_FROM_EXECUTOR
}
.async_resolve(endpoint.host_, endpoint.port_, yield),
yield);
}
template <typename Socket, typename Yield>
void read(Socket& s, MutableBuffer<uint8_t> buf, Yield yield)
{
suppressC4100(yield);
#ifdef BUILD_TEST
if constexpr (is_same_v<Socket, pichi::test::Stream>)
asio::read(s, asio::buffer(buf));
else
#endif // BUILD_TEST
asio::async_read(s, asio::buffer(buf), yield);
}
template <typename Socket, typename Yield>
size_t readSome(Socket& s, MutableBuffer<uint8_t> buf, Yield yield)
{
suppressC4100(yield);
#ifdef BUILD_TEST
if constexpr (is_same_v<Socket, pichi::test::Stream>)
return s.read_some(asio::buffer(buf));
else
#endif // BUILD_TEST
return s.async_read_some(asio::buffer(buf), yield);
}
template <typename Socket, typename Yield>
void write(Socket& s, ConstBuffer<uint8_t> buf, Yield yield)
{
suppressC4100(yield);
#ifdef BUILD_TEST
if constexpr (is_same_v<Socket, pichi::test::Stream>)
asio::write(s, asio::buffer(buf));
else
#endif // BUILD_TEST
asio::async_write(s, asio::buffer(buf), yield);
}
template <typename Socket, typename Yield> void close(Socket& s, Yield yield)
{
// This function is supposed to be 'noexcept' because it's always invoked in the desturctors.
// TODO log it
auto ec = sys::error_code{};
if constexpr (IsSslStreamV<Socket>) {
s.async_shutdown(yield[ec]);
close(s.next_layer(), yield);
}
else {
suppressC4100(yield);
s.close(ec);
}
}
template <typename Socket> bool isOpen(Socket const& s)
{
if constexpr (IsSslStreamV<Socket>) {
return isOpen(s.next_layer());
}
else {
return s.is_open();
}
}
template <typename Socket> unique_ptr<Ingress> makeIngress(api::IngressHolder& holder, Socket&& s)
{
auto container = array<uint8_t, 1024>{0};
auto psk = MutableBuffer<uint8_t>{container};
auto& vo = holder.vo_;
switch (vo.type_) {
case AdapterType::HTTP:
#ifdef ENABLE_TLS
if (*vo.tls_) {
auto ctx = createTlsContext(vo);
return make_unique<HttpIngress<TlsSocket>>(vo.credentials_, forward<Socket>(s), ctx);
}
else
#endif // ENABLE_TLS
return make_unique<HttpIngress<TcpSocket>>(vo.credentials_, forward<Socket>(s));
case AdapterType::SOCKS5:
#ifdef ENABLE_TLS
if (*vo.tls_) {
auto ctx = createTlsContext(vo);
return make_unique<Socks5Ingress<TlsSocket>>(vo.credentials_, forward<Socket>(s), ctx);
}
else
#endif // ENABLE_TLS
return make_unique<Socks5Ingress<TcpSocket>>(vo.credentials_, forward<Socket>(s));
case AdapterType::SS:
psk = {container, generateKey(*vo.method_, ConstBuffer<uint8_t>{*vo.password_}, container)};
switch (*vo.method_) {
case CryptoMethod::RC4_MD5:
return make_unique<SSStreamAdapter<CryptoMethod::RC4_MD5, Socket>>(psk, forward<Socket>(s));
case CryptoMethod::BF_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::BF_CFB, Socket>>(psk, forward<Socket>(s));
case CryptoMethod::AES_128_CTR:
return make_unique<SSStreamAdapter<CryptoMethod::AES_128_CTR, Socket>>(psk,
forward<Socket>(s));
case CryptoMethod::AES_192_CTR:
return make_unique<SSStreamAdapter<CryptoMethod::AES_192_CTR, Socket>>(psk,
forward<Socket>(s));
case CryptoMethod::AES_256_CTR:
return make_unique<SSStreamAdapter<CryptoMethod::AES_256_CTR, Socket>>(psk,
forward<Socket>(s));
case CryptoMethod::AES_128_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::AES_128_CFB, Socket>>(psk,
forward<Socket>(s));
case CryptoMethod::AES_192_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::AES_192_CFB, Socket>>(psk,
forward<Socket>(s));
case CryptoMethod::AES_256_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::AES_256_CFB, Socket>>(psk,
forward<Socket>(s));
case CryptoMethod::CAMELLIA_128_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::CAMELLIA_128_CFB, Socket>>(
psk, forward<Socket>(s));
case CryptoMethod::CAMELLIA_192_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::CAMELLIA_192_CFB, Socket>>(
psk, forward<Socket>(s));
case CryptoMethod::CAMELLIA_256_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::CAMELLIA_256_CFB, Socket>>(
psk, forward<Socket>(s));
case CryptoMethod::CHACHA20:
return make_unique<SSStreamAdapter<CryptoMethod::CHACHA20, Socket>>(psk, forward<Socket>(s));
case CryptoMethod::SALSA20:
return make_unique<SSStreamAdapter<CryptoMethod::SALSA20, Socket>>(psk, forward<Socket>(s));
case CryptoMethod::CHACHA20_IETF:
return make_unique<SSStreamAdapter<CryptoMethod::CHACHA20_IETF, Socket>>(psk,
forward<Socket>(s));
case CryptoMethod::AES_128_GCM:
return make_unique<SSAeadAdapter<CryptoMethod::AES_128_GCM, Socket>>(psk, forward<Socket>(s));
case CryptoMethod::AES_192_GCM:
return make_unique<SSAeadAdapter<CryptoMethod::AES_192_GCM, Socket>>(psk, forward<Socket>(s));
case CryptoMethod::AES_256_GCM:
return make_unique<SSAeadAdapter<CryptoMethod::AES_256_GCM, Socket>>(psk, forward<Socket>(s));
case CryptoMethod::CHACHA20_IETF_POLY1305:
return make_unique<SSAeadAdapter<CryptoMethod::CHACHA20_IETF_POLY1305, Socket>>(
psk, forward<Socket>(s));
case CryptoMethod::XCHACHA20_IETF_POLY1305:
return make_unique<SSAeadAdapter<CryptoMethod::XCHACHA20_IETF_POLY1305, Socket>>(
psk, forward<Socket>(s));
default:
fail(PichiError::BAD_PROTO);
}
case AdapterType::TUNNEL:
return make_unique<TunnelIngress<api::IngressIterator, Socket>>(*holder.balancer_,
forward<Socket>(s));
default:
fail(PichiError::BAD_PROTO);
}
}
unique_ptr<Egress> makeEgress(api::EgressVO const& vo, asio::io_context& io)
{
auto container = array<uint8_t, 1024>{0};
auto psk = MutableBuffer<uint8_t>{container};
switch (vo.type_) {
case AdapterType::HTTP:
#ifdef ENABLE_TLS
if (*vo.tls_) {
auto ctx = createTlsContext(vo);
return make_unique<HttpEgress<TlsSocket>>(vo.credential_, io, ctx);
}
else
#endif // ENABLE_TLS
return make_unique<HttpEgress<TcpSocket>>(vo.credential_, io);
case AdapterType::SOCKS5:
#ifdef ENABLE_TLS
if (*vo.tls_) {
auto ctx = createTlsContext(vo);
return make_unique<Socks5Egress<ssl::stream<tcp::socket>>>(vo.credential_, io, ctx);
}
else
#endif // ENABLE_TLS
return make_unique<Socks5Egress<tcp::socket>>(vo.credential_, io);
case AdapterType::DIRECT:
return make_unique<DirectAdapter>(io);
case AdapterType::REJECT:
switch (*vo.mode_) {
case api::DelayMode::RANDOM:
return make_unique<RejectEgress>(io);
case api::DelayMode::FIXED:
return make_unique<RejectEgress>(io, *vo.delay_);
default:
fail(PichiError::BAD_PROTO);
}
case AdapterType::SS:
psk = {container, generateKey(*vo.method_, ConstBuffer<uint8_t>{*vo.password_}, container)};
switch (*vo.method_) {
case CryptoMethod::RC4_MD5:
return make_unique<SSStreamAdapter<CryptoMethod::RC4_MD5, TcpSocket>>(psk, io);
case CryptoMethod::BF_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::BF_CFB, TcpSocket>>(psk, io);
case CryptoMethod::AES_128_CTR:
return make_unique<SSStreamAdapter<CryptoMethod::AES_128_CTR, TcpSocket>>(psk, io);
case CryptoMethod::AES_192_CTR:
return make_unique<SSStreamAdapter<CryptoMethod::AES_192_CTR, TcpSocket>>(psk, io);
case CryptoMethod::AES_256_CTR:
return make_unique<SSStreamAdapter<CryptoMethod::AES_256_CTR, TcpSocket>>(psk, io);
case CryptoMethod::AES_128_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::AES_128_CFB, TcpSocket>>(psk, io);
case CryptoMethod::AES_192_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::AES_192_CFB, TcpSocket>>(psk, io);
case CryptoMethod::AES_256_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::AES_256_CFB, TcpSocket>>(psk, io);
case CryptoMethod::CAMELLIA_128_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::CAMELLIA_128_CFB, TcpSocket>>(psk, io);
case CryptoMethod::CAMELLIA_192_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::CAMELLIA_192_CFB, TcpSocket>>(psk, io);
case CryptoMethod::CAMELLIA_256_CFB:
return make_unique<SSStreamAdapter<CryptoMethod::CAMELLIA_256_CFB, TcpSocket>>(psk, io);
case CryptoMethod::CHACHA20:
return make_unique<SSStreamAdapter<CryptoMethod::CHACHA20, TcpSocket>>(psk, io);
case CryptoMethod::SALSA20:
return make_unique<SSStreamAdapter<CryptoMethod::SALSA20, TcpSocket>>(psk, io);
case CryptoMethod::CHACHA20_IETF:
return make_unique<SSStreamAdapter<CryptoMethod::CHACHA20_IETF, TcpSocket>>(psk, io);
case CryptoMethod::AES_128_GCM:
return make_unique<SSAeadAdapter<CryptoMethod::AES_128_GCM, TcpSocket>>(psk, io);
case CryptoMethod::AES_192_GCM:
return make_unique<SSAeadAdapter<CryptoMethod::AES_192_GCM, TcpSocket>>(psk, io);
case CryptoMethod::AES_256_GCM:
return make_unique<SSAeadAdapter<CryptoMethod::AES_256_GCM, TcpSocket>>(psk, io);
case CryptoMethod::CHACHA20_IETF_POLY1305:
return make_unique<SSAeadAdapter<CryptoMethod::CHACHA20_IETF_POLY1305, TcpSocket>>(psk, io);
case CryptoMethod::XCHACHA20_IETF_POLY1305:
return make_unique<SSAeadAdapter<CryptoMethod::XCHACHA20_IETF_POLY1305, TcpSocket>>(psk, io);
default:
fail(PichiError::BAD_PROTO);
}
default:
fail(PichiError::BAD_PROTO);
}
}
using Yield = asio::yield_context;
template void connect<>(Endpoint const&, TcpSocket&, Yield);
template void read<>(TcpSocket&, MutableBuffer<uint8_t>, Yield);
template size_t readSome<>(TcpSocket&, MutableBuffer<uint8_t>, Yield);
template void write<>(TcpSocket&, ConstBuffer<uint8_t>, Yield);
template void close<>(TcpSocket&, Yield);
template bool isOpen<>(TcpSocket const&);
#ifdef ENABLE_TLS
template void connect<>(Endpoint const&, TlsSocket&, Yield);
template void read<>(TlsSocket&, MutableBuffer<uint8_t>, Yield);
template size_t readSome<>(TlsSocket&, MutableBuffer<uint8_t>, Yield);
template void write<>(TlsSocket&, ConstBuffer<uint8_t>, Yield);
template void close<>(TlsSocket&, Yield);
template bool isOpen<>(TlsSocket const&);
#endif // ENABLE_TLS
#ifdef BUILD_TEST
template void connect<>(Endpoint const&, pichi::test::Stream&, Yield);
template void read<>(pichi::test::Stream&, MutableBuffer<uint8_t>, Yield);
template size_t readSome<>(pichi::test::Stream&, MutableBuffer<uint8_t>, Yield);
template void write<>(pichi::test::Stream&, ConstBuffer<uint8_t>, Yield);
template void close<>(pichi::test::Stream&, Yield);
template bool isOpen<>(pichi::test::Stream const&);
#endif // BUILD_TEST
template unique_ptr<Ingress> makeIngress<>(api::IngressHolder&, TcpSocket&&);
} // namespace pichi::net
| ./CrossVul/dataset_final_sorted/CWE-295/cpp/good_4031_1 |
crossvul-cpp_data_bad_4600_1 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-295/c/bad_4600_1 |
crossvul-cpp_data_bad_4599_0 | /*
* Copyright (C) 2015 Adrien Vergé
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* In addition, as a special exception, the copyright holders give permission
* to link the code of portions of this program with the OpenSSL library under
* certain conditions as described in each individual source file, and
* distribute linked combinations including the two.
* You must obey the GNU General Public License in all respects for all of the
* code used other than OpenSSL. If you modify file(s) with this exception,
* you may extend this exception to your version of the file(s), but you are
* not obligated to do so. If you do not wish to do so, delete this exception
* statement from your version. If you delete this exception statement from
* all source files in the program, then also delete it here.
*/
#include "tunnel.h"
#include "http.h"
#include "log.h"
#include <unistd.h>
#include <fcntl.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <errno.h>
#include <string.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <openssl/err.h>
#include <openssl/x509v3.h>
#include <openssl/engine.h>
#if HAVE_PTY_H
#include <pty.h>
#elif HAVE_UTIL_H
#include <util.h>
#endif
#include <termios.h>
#include <signal.h>
#include <sys/wait.h>
#if HAVE_SYSTEMD
#include <systemd/sd-daemon.h>
#endif
// we use this constant in the source, so define a fallback if not defined
#ifndef OPENSSL_API_COMPAT
#define OPENSSL_API_COMPAT 0x0908000L
#endif
struct ofv_varr {
unsigned int cap; // current capacity
unsigned int off; // next slot to write, always < max(cap - 1, 1)
const char **data; // NULL terminated
};
static int ofv_append_varr(struct ofv_varr *p, const char *x)
{
if (p->off + 1 >= p->cap) {
const char **ndata;
unsigned int ncap = (p->off + 1) * 2;
if (p->off + 1 >= ncap) {
log_error("%s: ncap exceeded\n", __func__);
return 1;
};
ndata = realloc(p->data, ncap * sizeof(const char *));
if (ndata) {
p->data = ndata;
p->cap = ncap;
} else {
log_error("realloc: %s\n", strerror(errno));
return 1;
}
}
if (p->data == NULL) {
log_error("%s: NULL data\n", __func__);
return 1;
}
if (p->off + 1 >= p->cap) {
log_error("%s: cap exceeded in p\n", __func__);
return 1;
}
p->data[p->off] = x;
p->data[++p->off] = NULL;
return 0;
}
static int on_ppp_if_up(struct tunnel *tunnel)
{
log_info("Interface %s is UP.\n", tunnel->ppp_iface);
if (tunnel->config->set_routes) {
int ret;
log_info("Setting new routes...\n");
ret = ipv4_set_tunnel_routes(tunnel);
if (ret != 0)
log_warn("Adding route table is incomplete. Please check route table.\n");
}
if (tunnel->config->set_dns) {
log_info("Adding VPN nameservers...\n");
ipv4_add_nameservers_to_resolv_conf(tunnel);
}
log_info("Tunnel is up and running.\n");
#if HAVE_SYSTEMD
sd_notify(0, "READY=1");
#endif
return 0;
}
static int on_ppp_if_down(struct tunnel *tunnel)
{
log_info("Setting ppp interface down.\n");
if (tunnel->config->set_routes) {
log_info("Restoring routes...\n");
ipv4_restore_routes(tunnel);
}
if (tunnel->config->set_dns) {
log_info("Removing VPN nameservers...\n");
ipv4_del_nameservers_from_resolv_conf(tunnel);
}
return 0;
}
static int pppd_run(struct tunnel *tunnel)
{
pid_t pid;
int amaster;
int slave_stderr;
#ifdef HAVE_STRUCT_TERMIOS
struct termios termp = {
.c_cflag = B9600,
.c_cc[VTIME] = 0,
.c_cc[VMIN] = 1
};
#endif
static const char ppp_path[] = PPP_PATH;
if (access(ppp_path, F_OK) != 0) {
log_error("%s: %s.\n", ppp_path, strerror(errno));
return 1;
}
log_debug("ppp_path: %s\n", ppp_path);
slave_stderr = dup(STDERR_FILENO);
if (slave_stderr < 0) {
log_error("slave stderr %s\n", strerror(errno));
return 1;
}
#ifdef HAVE_STRUCT_TERMIOS
pid = forkpty(&amaster, NULL, &termp, NULL);
#else
pid = forkpty(&amaster, NULL, NULL, NULL);
#endif
if (pid == 0) { // child process
struct ofv_varr pppd_args = { 0, 0, NULL };
dup2(slave_stderr, STDERR_FILENO);
close(slave_stderr);
#if HAVE_USR_SBIN_PPP
/*
* assume there is a default configuration to start.
* Support for taking options from the command line
* e.g. the name of the configuration or options
* to send interactively to ppp will be added later
*/
static const char *const v[] = {
ppp_path,
"-direct"
};
for (unsigned int i = 0; i < ARRAY_SIZE(v); i++)
if (ofv_append_varr(&pppd_args, v[i]))
return 1;
#endif
#if HAVE_USR_SBIN_PPPD
if (tunnel->config->pppd_call) {
if (ofv_append_varr(&pppd_args, ppp_path))
return 1;
if (ofv_append_varr(&pppd_args, "call"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_call))
return 1;
} else {
static const char *const v[] = {
ppp_path,
"115200", // speed
":192.0.2.1", // <local_IP_address>:<remote_IP_address>
"noipdefault",
"noaccomp",
"noauth",
"default-asyncmap",
"nopcomp",
"receive-all",
"nodefaultroute",
"nodetach",
"lcp-max-configure", "40",
"mru", "1354"
};
for (unsigned int i = 0; i < ARRAY_SIZE(v); i++)
if (ofv_append_varr(&pppd_args, v[i]))
return 1;
}
if (tunnel->config->pppd_use_peerdns)
if (ofv_append_varr(&pppd_args, "usepeerdns"))
return 1;
if (tunnel->config->pppd_log) {
if (ofv_append_varr(&pppd_args, "debug"))
return 1;
if (ofv_append_varr(&pppd_args, "logfile"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_log))
return 1;
} else {
/*
* pppd defaults to logging to fd=1, clobbering the
* actual PPP data
*/
if (ofv_append_varr(&pppd_args, "logfd"))
return 1;
if (ofv_append_varr(&pppd_args, "2"))
return 1;
}
if (tunnel->config->pppd_plugin) {
if (ofv_append_varr(&pppd_args, "plugin"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_plugin))
return 1;
}
if (tunnel->config->pppd_ipparam) {
if (ofv_append_varr(&pppd_args, "ipparam"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_ipparam))
return 1;
}
if (tunnel->config->pppd_ifname) {
if (ofv_append_varr(&pppd_args, "ifname"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_ifname))
return 1;
}
#endif
#if HAVE_USR_SBIN_PPP
if (tunnel->config->ppp_system) {
if (ofv_append_varr(&pppd_args, tunnel->config->ppp_system))
return 1;
}
#endif
close(tunnel->ssl_socket);
execv(pppd_args.data[0], (char *const *)pppd_args.data);
free(pppd_args.data);
fprintf(stderr, "execvp: %s\n", strerror(errno));
_exit(EXIT_FAILURE);
} else {
close(slave_stderr);
if (pid == -1) {
log_error("forkpty: %s\n", strerror(errno));
return 1;
}
}
// Set non-blocking
int flags = fcntl(amaster, F_GETFL, 0);
if (flags == -1)
flags = 0;
if (fcntl(amaster, F_SETFL, flags | O_NONBLOCK) == -1) {
log_error("fcntl: %s\n", strerror(errno));
return 1;
}
tunnel->pppd_pid = pid;
tunnel->pppd_pty = amaster;
return 0;
}
static const char * const pppd_message[] = {
"Has detached, or otherwise the connection was successfully established and terminated at the peer's request.",
"An immediately fatal error of some kind occurred, such as an essential system call failing, or running out of virtual memory.",
"An error was detected in processing the options given, such as two mutually exclusive options being used.",
"Is not setuid-root and the invoking user is not root.",
"The kernel does not support PPP, for example, the PPP kernel driver is not included or cannot be loaded.",
"Terminated because it was sent a SIGINT, SIGTERM or SIGHUP signal.",
"The serial port could not be locked.",
"The serial port could not be opened.",
"The connect script failed (returned a non-zero exit status).",
"The command specified as the argument to the pty option could not be run.",
"The PPP negotiation failed, that is, it didn't reach the point where at least one network protocol (e.g. IP) was running.",
"The peer system failed (or refused) to authenticate itself.",
"The link was established successfully and terminated because it was idle.",
"The link was established successfully and terminated because the connect time limit was reached.",
"Callback was negotiated and an incoming call should arrive shortly.",
"The link was terminated because the peer is not responding to echo requests.",
"The link was terminated by the modem hanging up.",
"The PPP negotiation failed because serial loopback was detected.",
"The init script failed (returned a non-zero exit status).",
"We failed to authenticate ourselves to the peer."
};
static int pppd_terminate(struct tunnel *tunnel)
{
close(tunnel->pppd_pty);
log_debug("Waiting for %s to exit...\n", PPP_DAEMON);
int status;
if (waitpid(tunnel->pppd_pid, &status, 0) == -1) {
log_error("waitpid: %s\n", strerror(errno));
return 1;
}
if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
log_debug("waitpid: %s exit status code %d\n",
PPP_DAEMON, exit_status);
#if HAVE_USR_SBIN_PPPD
if (exit_status >= ARRAY_SIZE(pppd_message) || exit_status < 0) {
log_error("%s: Returned an unknown exit status: %d\n",
PPP_DAEMON, exit_status);
} else {
switch (exit_status) {
case 0: // success
log_debug("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
case 16: // emitted when exiting normally
log_info("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
default:
log_error("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
}
}
#else
// ppp exit codes in the FreeBSD case
switch (exit_status) {
case 0: // success and EX_NORMAL as defined in ppp source directly
log_debug("%s: %s\n", PPP_DAEMON, pppd_message[exit_status]);
break;
case 1:
case 127:
case 255: // abnormal exit with hard-coded error codes in ppp
log_error("%s: exited with return value of %d\n",
PPP_DAEMON, exit_status);
break;
default:
log_error("%s: %s (%d)\n", PPP_DAEMON, strerror(exit_status),
exit_status);
break;
}
#endif
} else if (WIFSIGNALED(status)) {
int signal_number = WTERMSIG(status);
log_debug("waitpid: %s terminated by signal %d\n",
PPP_DAEMON, signal_number);
log_error("%s: terminated by signal: %s\n",
PPP_DAEMON, strsignal(signal_number));
}
return 0;
}
int ppp_interface_is_up(struct tunnel *tunnel)
{
struct ifaddrs *ifap, *ifa;
log_debug("Got Address: %s\n", inet_ntoa(tunnel->ipv4.ip_addr));
if (getifaddrs(&ifap)) {
log_error("getifaddrs: %s\n", strerror(errno));
return 0;
}
for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
if ((
#if HAVE_USR_SBIN_PPPD
(tunnel->config->pppd_ifname
&& strstr(ifa->ifa_name, tunnel->config->pppd_ifname)
!= NULL)
|| strstr(ifa->ifa_name, "ppp") != NULL
#endif
#if HAVE_USR_SBIN_PPP
strstr(ifa->ifa_name, "tun") != NULL
#endif
) && ifa->ifa_flags & IFF_UP) {
if (&(ifa->ifa_addr->sa_family) != NULL
&& ifa->ifa_addr->sa_family == AF_INET) {
struct in_addr if_ip_addr =
cast_addr(ifa->ifa_addr)->sin_addr;
log_debug("Interface Name: %s\n", ifa->ifa_name);
log_debug("Interface Addr: %s\n", inet_ntoa(if_ip_addr));
if (tunnel->ipv4.ip_addr.s_addr == if_ip_addr.s_addr) {
strncpy(tunnel->ppp_iface, ifa->ifa_name,
ROUTE_IFACE_LEN - 1);
freeifaddrs(ifap);
return 1;
}
}
}
}
freeifaddrs(ifap);
return 0;
}
static int get_gateway_host_ip(struct tunnel *tunnel)
{
const struct addrinfo hints = { .ai_family = AF_INET };
struct addrinfo *result = NULL;
int ret = getaddrinfo(tunnel->config->gateway_host, NULL, &hints, &result);
if (ret) {
if (ret == EAI_SYSTEM)
log_error("getaddrinfo: %s\n", strerror(errno));
else
log_error("getaddrinfo: %s\n", gai_strerror(ret));
return 1;
}
tunnel->config->gateway_ip = ((struct sockaddr_in *)
result->ai_addr)->sin_addr;
freeaddrinfo(result);
setenv("VPN_GATEWAY", inet_ntoa(tunnel->config->gateway_ip), 0);
return 0;
}
/*
* Establish a regular TCP connection.
*/
static int tcp_connect(struct tunnel *tunnel)
{
int ret, handle;
struct sockaddr_in server;
char *env_proxy;
handle = socket(AF_INET, SOCK_STREAM, 0);
if (handle == -1) {
log_error("socket: %s\n", strerror(errno));
goto err_socket;
}
env_proxy = getenv("https_proxy");
if (env_proxy == NULL)
env_proxy = getenv("HTTPS_PROXY");
if (env_proxy == NULL)
env_proxy = getenv("all_proxy");
if (env_proxy == NULL)
env_proxy = getenv("ALL_PROXY");
if (env_proxy != NULL) {
char *proxy_host, *proxy_port;
// protect the original environment from modifications
env_proxy = strdup(env_proxy);
if (env_proxy == NULL) {
log_error("strdup: %s\n", strerror(errno));
goto err_strdup;
}
// get rid of a trailing slash
if (*env_proxy && env_proxy[strlen(env_proxy) - 1] == '/')
env_proxy[strlen(env_proxy) - 1] = '\0';
// get rid of a http(s):// prefix in env_proxy
proxy_host = strstr(env_proxy, "://");
if (proxy_host == NULL)
proxy_host = env_proxy;
else
proxy_host += 3;
// split host and port
proxy_port = index(proxy_host, ':');
if (proxy_port != NULL) {
proxy_port[0] = '\0';
proxy_port++;
server.sin_port = htons(strtoul(proxy_port, NULL, 10));
} else {
server.sin_port = htons(tunnel->config->gateway_port);
}
// get rid of a trailing slash
if (*proxy_host && proxy_host[strlen(proxy_host) - 1] == '/')
proxy_host[strlen(proxy_host) - 1] = '\0';
log_debug("proxy_host: %s\n", proxy_host);
log_debug("proxy_port: %s\n", proxy_port);
server.sin_addr.s_addr = inet_addr(proxy_host);
// if host is given as a FQDN we have to do a DNS lookup
if (server.sin_addr.s_addr == INADDR_NONE) {
const struct addrinfo hints = { .ai_family = AF_INET };
struct addrinfo *result = NULL;
ret = getaddrinfo(proxy_host, NULL, &hints, &result);
if (ret) {
if (ret == EAI_SYSTEM)
log_error("getaddrinfo: %s\n", strerror(errno));
else
log_error("getaddrinfo: %s\n", gai_strerror(ret));
goto err_connect;
}
server.sin_addr = ((struct sockaddr_in *)
result->ai_addr)->sin_addr;
freeaddrinfo(result);
}
} else {
server.sin_port = htons(tunnel->config->gateway_port);
server.sin_addr = tunnel->config->gateway_ip;
}
log_debug("server_addr: %s\n", inet_ntoa(server.sin_addr));
log_debug("server_port: %u\n", ntohs(server.sin_port));
server.sin_family = AF_INET;
memset(&(server.sin_zero), '\0', 8);
log_debug("gateway_addr: %s\n", inet_ntoa(tunnel->config->gateway_ip));
log_debug("gateway_port: %u\n", tunnel->config->gateway_port);
ret = connect(handle, (struct sockaddr *) &server, sizeof(server));
if (ret) {
log_error("connect: %s\n", strerror(errno));
goto err_connect;
}
if (env_proxy != NULL) {
char request[128];
// https://tools.ietf.org/html/rfc7231#section-4.3.6
sprintf(request, "CONNECT %s:%u HTTP/1.1\r\nHost: %s:%u\r\n\r\n",
inet_ntoa(tunnel->config->gateway_ip),
tunnel->config->gateway_port,
inet_ntoa(tunnel->config->gateway_ip),
tunnel->config->gateway_port);
ssize_t bytes_written = write(handle, request, strlen(request));
if (bytes_written != strlen(request)) {
log_error("write error while talking to proxy: %s\n",
strerror(errno));
goto err_connect;
}
// wait for a "200 OK" reply from the proxy,
// be careful not to fetch too many bytes at once
const char *response = NULL;
memset(&(request), '\0', sizeof(request));
for (int j = 0; response == NULL; j++) {
/*
* Coverity detected a defect:
* CID 200508: String not null terminated (STRING_NULL)
*
* It is actually a false positive:
* • Function memset() initializes 'request' with '\0'
* • Function read() gets a single char into: request[j]
* • The final '\0' cannot be overwritten because:
* j < ARRAY_SIZE(request) - 1
*/
ssize_t bytes_read = read(handle, &(request[j]), 1);
if (bytes_read < 1) {
log_error("Proxy response is unexpectedly large and cannot fit in the %lu-bytes buffer.\n",
ARRAY_SIZE(request));
goto err_proxy_response;
}
// detect "200"
static const char HTTP_STATUS_200[] = "200";
response = strstr(request, HTTP_STATUS_200);
// detect end-of-line after "200"
if (response != NULL) {
/*
* RFC2616 states in section 2.2 Basic Rules:
* CR = <US-ASCII CR, carriage return (13)>
* LF = <US-ASCII LF, linefeed (10)>
* HTTP/1.1 defines the sequence CR LF as the
* end-of-line marker for all protocol elements
* except the entity-body (see appendix 19.3
* for tolerant applications).
* CRLF = CR LF
*
* RFC2616 states in section 19.3 Tolerant Applications:
* The line terminator for message-header fields
* is the sequence CRLF. However, we recommend
* that applications, when parsing such headers,
* recognize a single LF as a line terminator
* and ignore the leading CR.
*/
static const char *const HTTP_EOL[] = {
"\r\n\r\n",
"\n\n"
};
const char *eol = NULL;
for (int i = 0; (i < ARRAY_SIZE(HTTP_EOL)) &&
(eol == NULL); i++)
eol = strstr(response, HTTP_EOL[i]);
response = eol;
}
if (j > ARRAY_SIZE(request) - 2) {
log_error("Proxy response does not contain \"%s\" as expected.\n",
HTTP_STATUS_200);
goto err_proxy_response;
}
}
free(env_proxy); // release memory allocated by strdup()
}
return handle;
err_proxy_response:
err_connect:
free(env_proxy); // release memory allocated by strdup()
err_strdup:
close(handle);
err_socket:
return -1;
}
static int ssl_verify_cert(struct tunnel *tunnel)
{
int ret = -1;
int cert_valid = 0;
unsigned char digest[SHA256LEN];
unsigned int len;
struct x509_digest *elem;
char digest_str[SHA256STRLEN], *subject, *issuer;
char *line;
int i;
X509_NAME *subj;
char common_name[FIELD_SIZE + 1];
SSL_set_verify(tunnel->ssl_handle, SSL_VERIFY_PEER, NULL);
X509 *cert = SSL_get_peer_certificate(tunnel->ssl_handle);
if (cert == NULL) {
log_error("Unable to get gateway certificate.\n");
return 1;
}
subj = X509_get_subject_name(cert);
#ifdef HAVE_X509_CHECK_HOST
// Use OpenSSL native host validation if v >= 1.0.2.
// correctly check return value of X509_check_host
if (X509_check_host(cert, common_name, FIELD_SIZE, 0, NULL) == 1)
cert_valid = 1;
#else
// Use explicit Common Name check if native validation not available.
// Note: this will ignore Subject Alternative Name fields.
if (subj
&& X509_NAME_get_text_by_NID(subj, NID_commonName, common_name,
FIELD_SIZE) > 0
&& strncasecmp(common_name, tunnel->config->gateway_host,
FIELD_SIZE) == 0)
cert_valid = 1;
#endif
// Try to validate certificate using local PKI
if (cert_valid
&& SSL_get_verify_result(tunnel->ssl_handle) == X509_V_OK) {
log_debug("Gateway certificate validation succeeded.\n");
ret = 0;
goto free_cert;
}
log_debug("Gateway certificate validation failed.\n");
// If validation failed, check if cert is in the white list
if (X509_digest(cert, EVP_sha256(), digest, &len) <= 0
|| len != SHA256LEN) {
log_error("Could not compute certificate sha256 digest.\n");
goto free_cert;
}
// Encode digest in base16
for (i = 0; i < SHA256LEN; i++)
sprintf(&digest_str[2 * i], "%02x", digest[i]);
digest_str[SHA256STRLEN - 1] = '\0';
// Is it in whitelist?
for (elem = tunnel->config->cert_whitelist; elem != NULL;
elem = elem->next)
if (memcmp(digest_str, elem->data, SHA256STRLEN - 1) == 0)
break;
if (elem != NULL) { // break before end of loop
log_debug("Gateway certificate digest found in white list.\n");
ret = 0;
goto free_cert;
}
subject = X509_NAME_oneline(subj, NULL, 0);
issuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
log_error("Gateway certificate validation failed, and the certificate digest in not in the local whitelist. If you trust it, rerun with:\n");
log_error(" --trusted-cert %s\n", digest_str);
log_error("or add this line to your config file:\n");
log_error(" trusted-cert = %s\n", digest_str);
log_error("Gateway certificate:\n");
log_error(" subject:\n");
for (line = strtok(subject, "/"); line != NULL;
line = strtok(NULL, "/"))
log_error(" %s\n", line);
log_error(" issuer:\n");
for (line = strtok(issuer, "/"); line != NULL;
line = strtok(NULL, "/"))
log_error(" %s\n", line);
log_error(" sha256 digest:\n");
log_error(" %s\n", digest_str);
free_cert:
X509_free(cert);
return ret;
}
/*
* Destroy and free the SSL connection to the gateway.
*/
static void ssl_disconnect(struct tunnel *tunnel)
{
if (!tunnel->ssl_handle)
return;
SSL_shutdown(tunnel->ssl_handle);
SSL_free(tunnel->ssl_handle);
SSL_CTX_free(tunnel->ssl_context);
close(tunnel->ssl_socket);
tunnel->ssl_handle = NULL;
tunnel->ssl_context = NULL;
}
/*
* Connects to the gateway and initiate an SSL session.
*/
int ssl_connect(struct tunnel *tunnel)
{
ssl_disconnect(tunnel);
tunnel->ssl_socket = tcp_connect(tunnel);
if (tunnel->ssl_socket == -1)
return 1;
// registration is deprecated from OpenSSL 1.1.0 onward
#if OPENSSL_API_COMPAT < 0x10100000L
// Register the error strings for libcrypto & libssl
SSL_load_error_strings();
// Register the available ciphers and digests
SSL_library_init();
#endif
tunnel->ssl_context = SSL_CTX_new(SSLv23_client_method());
if (tunnel->ssl_context == NULL) {
log_error("SSL_CTX_new: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
// Load the OS default CA files
if (!SSL_CTX_set_default_verify_paths(tunnel->ssl_context))
log_error("Could not load OS OpenSSL files.\n");
if (tunnel->config->ca_file) {
if (!SSL_CTX_load_verify_locations(
tunnel->ssl_context,
tunnel->config->ca_file, NULL)) {
log_error("SSL_CTX_load_verify_locations: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
/* Use engine for PIV if user-cert config starts with pkcs11 URI: */
if (tunnel->config->use_engine > 0) {
ENGINE *e;
ENGINE_load_builtin_engines();
e = ENGINE_by_id("pkcs11");
if (!e) {
log_error("Could not load pkcs11 Engine: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!ENGINE_init(e)) {
log_error("Could not init pkcs11 Engine: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
ENGINE_free(e);
return 1;
}
if (!ENGINE_set_default_RSA(e))
abort();
ENGINE_finish(e);
ENGINE_free(e);
struct token parms;
parms.uri = tunnel->config->user_cert;
parms.cert = NULL;
if (!ENGINE_ctrl_cmd(e, "LOAD_CERT_CTRL", 0, &parms, NULL, 1)) {
log_error("PKCS11 ENGINE_ctrl_cmd: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_use_certificate(tunnel->ssl_context, parms.cert)) {
log_error("PKCS11 SSL_CTX_use_certificate: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
EVP_PKEY * privkey = ENGINE_load_private_key(
e, parms.uri, UI_OpenSSL(), NULL);
if (!privkey) {
log_error("PKCS11 ENGINE_load_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_use_PrivateKey(tunnel->ssl_context, privkey)) {
log_error("PKCS11 SSL_CTX_use_PrivateKey_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_check_private_key(tunnel->ssl_context)) {
log_error("PKCS11 SSL_CTX_check_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
} else { /* end PKCS11-engine */
if (tunnel->config->user_cert) {
if (!SSL_CTX_use_certificate_file(
tunnel->ssl_context, tunnel->config->user_cert,
SSL_FILETYPE_PEM)) {
log_error("SSL_CTX_use_certificate_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
if (tunnel->config->user_key) {
if (!SSL_CTX_use_PrivateKey_file(
tunnel->ssl_context, tunnel->config->user_key,
SSL_FILETYPE_PEM)) {
log_error("SSL_CTX_use_PrivateKey_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
if (tunnel->config->user_cert && tunnel->config->user_key) {
if (!SSL_CTX_check_private_key(tunnel->ssl_context)) {
log_error("SSL_CTX_check_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
}
if (!tunnel->config->insecure_ssl) {
long sslctxopt = SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
long checkopt;
checkopt = SSL_CTX_set_options(tunnel->ssl_context, sslctxopt);
if ((checkopt & sslctxopt) != sslctxopt) {
log_error("SSL_CTX_set_options didn't set opt: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
tunnel->ssl_handle = SSL_new(tunnel->ssl_context);
if (tunnel->ssl_handle == NULL) {
log_error("SSL_new: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!tunnel->config->insecure_ssl) {
if (!tunnel->config->cipher_list) {
const char *cipher_list;
if (tunnel->config->seclevel_1)
cipher_list = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4@SECLEVEL=1";
else
cipher_list = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4";
tunnel->config->cipher_list = strdup(cipher_list);
}
} else {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (tunnel->config->min_tls <= 0)
tunnel->config->min_tls = TLS1_VERSION;
#endif
if (!tunnel->config->cipher_list && tunnel->config->seclevel_1) {
const char *cipher_list = "DEFAULT@SECLEVEL=1";
tunnel->config->cipher_list = strdup(cipher_list);
}
}
if (tunnel->config->cipher_list) {
log_debug("Setting cipher list to: %s\n", tunnel->config->cipher_list);
if (!SSL_set_cipher_list(tunnel->ssl_handle,
tunnel->config->cipher_list)) {
log_error("SSL_set_cipher_list failed: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (tunnel->config->min_tls > 0) {
log_debug("Setting min proto version to: 0x%x\n",
tunnel->config->min_tls);
if (!SSL_set_min_proto_version(tunnel->ssl_handle,
tunnel->config->min_tls)) {
log_error("SSL_set_min_proto_version failed: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
#endif
if (!SSL_set_fd(tunnel->ssl_handle, tunnel->ssl_socket)) {
log_error("SSL_set_fd: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
SSL_set_mode(tunnel->ssl_handle, SSL_MODE_AUTO_RETRY);
// Initiate SSL handshake
if (SSL_connect(tunnel->ssl_handle) != 1) {
log_error("SSL_connect: %s\n"
"You might want to try --insecure-ssl or specify a different --cipher-list\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
SSL_set_mode(tunnel->ssl_handle, SSL_MODE_AUTO_RETRY);
if (ssl_verify_cert(tunnel))
return 1;
// Disable SIGPIPE (occurs when trying to write to an already-closed
// socket).
signal(SIGPIPE, SIG_IGN);
return 0;
}
int run_tunnel(struct vpn_config *config)
{
int ret;
struct tunnel tunnel = {
.config = config,
.state = STATE_DOWN,
.ssl_context = NULL,
.ssl_handle = NULL,
.ipv4.ns1_addr.s_addr = 0,
.ipv4.ns2_addr.s_addr = 0,
.ipv4.dns_suffix = NULL,
.on_ppp_if_up = on_ppp_if_up,
.on_ppp_if_down = on_ppp_if_down
};
// Step 0: get gateway host IP
log_debug("Resolving gateway host ip\n");
ret = get_gateway_host_ip(&tunnel);
if (ret)
goto err_tunnel;
// Step 1: open a SSL connection to the gateway
log_debug("Establishing ssl connection\n");
ret = ssl_connect(&tunnel);
if (ret)
goto err_tunnel;
log_info("Connected to gateway.\n");
// Step 2: connect to the HTTP interface and authenticate to get a
// cookie
ret = auth_log_in(&tunnel);
if (ret != 1) {
log_error("Could not authenticate to gateway. Please check the password, client certificate, etc.\n");
log_debug("%s %d\n", err_http_str(ret), ret);
ret = 1;
goto err_tunnel;
}
log_info("Authenticated.\n");
log_debug("Cookie: %s\n", tunnel.cookie);
ret = auth_request_vpn_allocation(&tunnel);
if (ret != 1) {
log_error("VPN allocation request failed (%s).\n",
err_http_str(ret));
ret = 1;
goto err_tunnel;
}
log_info("Remote gateway has allocated a VPN.\n");
ret = ssl_connect(&tunnel);
if (ret)
goto err_tunnel;
// Step 3: get configuration
log_debug("Retrieving configuration\n");
ret = auth_get_config(&tunnel);
if (ret != 1) {
log_error("Could not get VPN configuration (%s).\n",
err_http_str(ret));
ret = 1;
goto err_tunnel;
}
// Step 4: run a pppd process
log_debug("Establishing the tunnel\n");
ret = pppd_run(&tunnel);
if (ret)
goto err_tunnel;
// Step 5: ask gateway to start tunneling
log_debug("Switch to tunneling mode\n");
ret = http_send(&tunnel,
"GET /remote/sslvpn-tunnel HTTP/1.1\r\n"
"Host: sslvpn\r\n"
"Cookie: %s\r\n\r\n",
tunnel.cookie);
if (ret != 1) {
log_error("Could not start tunnel (%s).\n", err_http_str(ret));
ret = 1;
goto err_start_tunnel;
}
tunnel.state = STATE_CONNECTING;
ret = 0;
// Step 6: perform io between pppd and the gateway, while tunnel is up
log_debug("Starting IO through the tunnel\n");
io_loop(&tunnel);
log_debug("disconnecting\n");
if (tunnel.state == STATE_UP)
if (tunnel.on_ppp_if_down != NULL)
tunnel.on_ppp_if_down(&tunnel);
tunnel.state = STATE_DISCONNECTING;
err_start_tunnel:
pppd_terminate(&tunnel);
log_info("Terminated %s.\n", PPP_DAEMON);
err_tunnel:
log_info("Closed connection to gateway.\n");
tunnel.state = STATE_DOWN;
if (ssl_connect(&tunnel)) {
log_info("Could not log out.\n");
} else {
auth_log_out(&tunnel);
log_info("Logged out.\n");
}
// explicitly free the buffer allocated for split routes of the ipv4 config
if (tunnel.ipv4.split_rt != NULL) {
free(tunnel.ipv4.split_rt);
tunnel.ipv4.split_rt = NULL;
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-295/c/bad_4599_0 |
crossvul-cpp_data_bad_4597_0 | /*
* Copyright (C) 2015 Adrien Vergé
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* In addition, as a special exception, the copyright holders give permission
* to link the code of portions of this program with the OpenSSL library under
* certain conditions as described in each individual source file, and
* distribute linked combinations including the two.
* You must obey the GNU General Public License in all respects for all of the
* code used other than OpenSSL. If you modify file(s) with this exception,
* you may extend this exception to your version of the file(s), but you are
* not obligated to do so. If you do not wish to do so, delete this exception
* statement from your version. If you delete this exception statement from
* all source files in the program, then also delete it here.
*/
#include "tunnel.h"
#include "http.h"
#include "log.h"
#include <unistd.h>
#include <fcntl.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <errno.h>
#include <string.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <openssl/err.h>
#include <openssl/x509v3.h>
#include <openssl/engine.h>
#if HAVE_PTY_H
#include <pty.h>
#elif HAVE_UTIL_H
#include <util.h>
#endif
#include <termios.h>
#include <signal.h>
#include <sys/wait.h>
#if HAVE_SYSTEMD
#include <systemd/sd-daemon.h>
#endif
// we use this constant in the source, so define a fallback if not defined
#ifndef OPENSSL_API_COMPAT
#define OPENSSL_API_COMPAT 0x0908000L
#endif
struct ofv_varr {
unsigned int cap; // current capacity
unsigned int off; // next slot to write, always < max(cap - 1, 1)
const char **data; // NULL terminated
};
static int ofv_append_varr(struct ofv_varr *p, const char *x)
{
if (p->off + 1 >= p->cap) {
const char **ndata;
unsigned int ncap = (p->off + 1) * 2;
if (p->off + 1 >= ncap) {
log_error("%s: ncap exceeded\n", __func__);
return 1;
};
ndata = realloc(p->data, ncap * sizeof(const char *));
if (ndata) {
p->data = ndata;
p->cap = ncap;
} else {
log_error("realloc: %s\n", strerror(errno));
return 1;
}
}
if (p->data == NULL) {
log_error("%s: NULL data\n", __func__);
return 1;
}
if (p->off + 1 >= p->cap) {
log_error("%s: cap exceeded in p\n", __func__);
return 1;
}
p->data[p->off] = x;
p->data[++p->off] = NULL;
return 0;
}
static int on_ppp_if_up(struct tunnel *tunnel)
{
log_info("Interface %s is UP.\n", tunnel->ppp_iface);
if (tunnel->config->set_routes) {
int ret;
log_info("Setting new routes...\n");
ret = ipv4_set_tunnel_routes(tunnel);
if (ret != 0)
log_warn("Adding route table is incomplete. Please check route table.\n");
}
if (tunnel->config->set_dns) {
log_info("Adding VPN nameservers...\n");
ipv4_add_nameservers_to_resolv_conf(tunnel);
}
log_info("Tunnel is up and running.\n");
#if HAVE_SYSTEMD
sd_notify(0, "READY=1");
#endif
return 0;
}
static int on_ppp_if_down(struct tunnel *tunnel)
{
log_info("Setting ppp interface down.\n");
if (tunnel->config->set_routes) {
log_info("Restoring routes...\n");
ipv4_restore_routes(tunnel);
}
if (tunnel->config->set_dns) {
log_info("Removing VPN nameservers...\n");
ipv4_del_nameservers_from_resolv_conf(tunnel);
}
return 0;
}
static int pppd_run(struct tunnel *tunnel)
{
pid_t pid;
int amaster;
int slave_stderr;
#ifdef HAVE_STRUCT_TERMIOS
struct termios termp = {
.c_cflag = B9600,
.c_cc[VTIME] = 0,
.c_cc[VMIN] = 1
};
#endif
static const char ppp_path[] = PPP_PATH;
if (access(ppp_path, F_OK) != 0) {
log_error("%s: %s.\n", ppp_path, strerror(errno));
return 1;
}
log_debug("ppp_path: %s\n", ppp_path);
slave_stderr = dup(STDERR_FILENO);
if (slave_stderr < 0) {
log_error("slave stderr %s\n", strerror(errno));
return 1;
}
#ifdef HAVE_STRUCT_TERMIOS
pid = forkpty(&amaster, NULL, &termp, NULL);
#else
pid = forkpty(&amaster, NULL, NULL, NULL);
#endif
if (pid == 0) { // child process
struct ofv_varr pppd_args = { 0, 0, NULL };
dup2(slave_stderr, STDERR_FILENO);
close(slave_stderr);
#if HAVE_USR_SBIN_PPP
/*
* assume there is a default configuration to start.
* Support for taking options from the command line
* e.g. the name of the configuration or options
* to send interactively to ppp will be added later
*/
static const char *const v[] = {
ppp_path,
"-direct"
};
for (unsigned int i = 0; i < ARRAY_SIZE(v); i++)
if (ofv_append_varr(&pppd_args, v[i]))
return 1;
#endif
#if HAVE_USR_SBIN_PPPD
if (tunnel->config->pppd_call) {
if (ofv_append_varr(&pppd_args, ppp_path))
return 1;
if (ofv_append_varr(&pppd_args, "call"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_call))
return 1;
} else {
static const char *const v[] = {
ppp_path,
"115200", // speed
":192.0.2.1", // <local_IP_address>:<remote_IP_address>
"noipdefault",
"noaccomp",
"noauth",
"default-asyncmap",
"nopcomp",
"receive-all",
"nodefaultroute",
"nodetach",
"lcp-max-configure", "40",
"mru", "1354"
};
for (unsigned int i = 0; i < ARRAY_SIZE(v); i++)
if (ofv_append_varr(&pppd_args, v[i]))
return 1;
}
if (tunnel->config->pppd_use_peerdns)
if (ofv_append_varr(&pppd_args, "usepeerdns"))
return 1;
if (tunnel->config->pppd_log) {
if (ofv_append_varr(&pppd_args, "debug"))
return 1;
if (ofv_append_varr(&pppd_args, "logfile"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_log))
return 1;
} else {
/*
* pppd defaults to logging to fd=1, clobbering the
* actual PPP data
*/
if (ofv_append_varr(&pppd_args, "logfd"))
return 1;
if (ofv_append_varr(&pppd_args, "2"))
return 1;
}
if (tunnel->config->pppd_plugin) {
if (ofv_append_varr(&pppd_args, "plugin"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_plugin))
return 1;
}
if (tunnel->config->pppd_ipparam) {
if (ofv_append_varr(&pppd_args, "ipparam"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_ipparam))
return 1;
}
if (tunnel->config->pppd_ifname) {
if (ofv_append_varr(&pppd_args, "ifname"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_ifname))
return 1;
}
#endif
#if HAVE_USR_SBIN_PPP
if (tunnel->config->ppp_system) {
if (ofv_append_varr(&pppd_args, tunnel->config->ppp_system))
return 1;
}
#endif
close(tunnel->ssl_socket);
execv(pppd_args.data[0], (char *const *)pppd_args.data);
free(pppd_args.data);
fprintf(stderr, "execvp: %s\n", strerror(errno));
_exit(EXIT_FAILURE);
} else {
close(slave_stderr);
if (pid == -1) {
log_error("forkpty: %s\n", strerror(errno));
return 1;
}
}
// Set non-blocking
int flags = fcntl(amaster, F_GETFL, 0);
if (flags == -1)
flags = 0;
if (fcntl(amaster, F_SETFL, flags | O_NONBLOCK) == -1) {
log_error("fcntl: %s\n", strerror(errno));
return 1;
}
tunnel->pppd_pid = pid;
tunnel->pppd_pty = amaster;
return 0;
}
static const char * const pppd_message[] = {
"Has detached, or otherwise the connection was successfully established and terminated at the peer's request.",
"An immediately fatal error of some kind occurred, such as an essential system call failing, or running out of virtual memory.",
"An error was detected in processing the options given, such as two mutually exclusive options being used.",
"Is not setuid-root and the invoking user is not root.",
"The kernel does not support PPP, for example, the PPP kernel driver is not included or cannot be loaded.",
"Terminated because it was sent a SIGINT, SIGTERM or SIGHUP signal.",
"The serial port could not be locked.",
"The serial port could not be opened.",
"The connect script failed (returned a non-zero exit status).",
"The command specified as the argument to the pty option could not be run.",
"The PPP negotiation failed, that is, it didn't reach the point where at least one network protocol (e.g. IP) was running.",
"The peer system failed (or refused) to authenticate itself.",
"The link was established successfully and terminated because it was idle.",
"The link was established successfully and terminated because the connect time limit was reached.",
"Callback was negotiated and an incoming call should arrive shortly.",
"The link was terminated because the peer is not responding to echo requests.",
"The link was terminated by the modem hanging up.",
"The PPP negotiation failed because serial loopback was detected.",
"The init script failed (returned a non-zero exit status).",
"We failed to authenticate ourselves to the peer."
};
static int pppd_terminate(struct tunnel *tunnel)
{
close(tunnel->pppd_pty);
log_debug("Waiting for %s to exit...\n", PPP_DAEMON);
int status;
if (waitpid(tunnel->pppd_pid, &status, 0) == -1) {
log_error("waitpid: %s\n", strerror(errno));
return 1;
}
if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
log_debug("waitpid: %s exit status code %d\n",
PPP_DAEMON, exit_status);
#if HAVE_USR_SBIN_PPPD
if (exit_status >= ARRAY_SIZE(pppd_message) || exit_status < 0) {
log_error("%s: Returned an unknown exit status: %d\n",
PPP_DAEMON, exit_status);
} else {
switch (exit_status) {
case 0: // success
log_debug("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
case 16: // emitted when exiting normally
log_info("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
default:
log_error("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
}
}
#else
// ppp exit codes in the FreeBSD case
switch (exit_status) {
case 0: // success and EX_NORMAL as defined in ppp source directly
log_debug("%s: %s\n", PPP_DAEMON, pppd_message[exit_status]);
break;
case 1:
case 127:
case 255: // abnormal exit with hard-coded error codes in ppp
log_error("%s: exited with return value of %d\n",
PPP_DAEMON, exit_status);
break;
default:
log_error("%s: %s (%d)\n", PPP_DAEMON, strerror(exit_status),
exit_status);
break;
}
#endif
} else if (WIFSIGNALED(status)) {
int signal_number = WTERMSIG(status);
log_debug("waitpid: %s terminated by signal %d\n",
PPP_DAEMON, signal_number);
log_error("%s: terminated by signal: %s\n",
PPP_DAEMON, strsignal(signal_number));
}
return 0;
}
int ppp_interface_is_up(struct tunnel *tunnel)
{
struct ifaddrs *ifap, *ifa;
log_debug("Got Address: %s\n", inet_ntoa(tunnel->ipv4.ip_addr));
if (getifaddrs(&ifap)) {
log_error("getifaddrs: %s\n", strerror(errno));
return 0;
}
for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
if ((
#if HAVE_USR_SBIN_PPPD
(tunnel->config->pppd_ifname
&& strstr(ifa->ifa_name, tunnel->config->pppd_ifname)
!= NULL)
|| strstr(ifa->ifa_name, "ppp") != NULL
#endif
#if HAVE_USR_SBIN_PPP
strstr(ifa->ifa_name, "tun") != NULL
#endif
) && ifa->ifa_flags & IFF_UP) {
if (&(ifa->ifa_addr->sa_family) != NULL
&& ifa->ifa_addr->sa_family == AF_INET) {
struct in_addr if_ip_addr =
cast_addr(ifa->ifa_addr)->sin_addr;
log_debug("Interface Name: %s\n", ifa->ifa_name);
log_debug("Interface Addr: %s\n", inet_ntoa(if_ip_addr));
if (tunnel->ipv4.ip_addr.s_addr == if_ip_addr.s_addr) {
strncpy(tunnel->ppp_iface, ifa->ifa_name,
ROUTE_IFACE_LEN - 1);
freeifaddrs(ifap);
return 1;
}
}
}
}
freeifaddrs(ifap);
return 0;
}
static int get_gateway_host_ip(struct tunnel *tunnel)
{
const struct addrinfo hints = { .ai_family = AF_INET };
struct addrinfo *result = NULL;
int ret = getaddrinfo(tunnel->config->gateway_host, NULL, &hints, &result);
if (ret) {
if (ret == EAI_SYSTEM)
log_error("getaddrinfo: %s\n", strerror(errno));
else
log_error("getaddrinfo: %s\n", gai_strerror(ret));
return 1;
}
tunnel->config->gateway_ip = ((struct sockaddr_in *)
result->ai_addr)->sin_addr;
freeaddrinfo(result);
setenv("VPN_GATEWAY", inet_ntoa(tunnel->config->gateway_ip), 0);
return 0;
}
/*
* Establish a regular TCP connection.
*/
static int tcp_connect(struct tunnel *tunnel)
{
int ret, handle;
struct sockaddr_in server;
char *env_proxy;
handle = socket(AF_INET, SOCK_STREAM, 0);
if (handle == -1) {
log_error("socket: %s\n", strerror(errno));
goto err_socket;
}
env_proxy = getenv("https_proxy");
if (env_proxy == NULL)
env_proxy = getenv("HTTPS_PROXY");
if (env_proxy == NULL)
env_proxy = getenv("all_proxy");
if (env_proxy == NULL)
env_proxy = getenv("ALL_PROXY");
if (env_proxy != NULL) {
char *proxy_host, *proxy_port;
// protect the original environment from modifications
env_proxy = strdup(env_proxy);
if (env_proxy == NULL) {
log_error("strdup: %s\n", strerror(errno));
goto err_strdup;
}
// get rid of a trailing slash
if (*env_proxy && env_proxy[strlen(env_proxy) - 1] == '/')
env_proxy[strlen(env_proxy) - 1] = '\0';
// get rid of a http(s):// prefix in env_proxy
proxy_host = strstr(env_proxy, "://");
if (proxy_host == NULL)
proxy_host = env_proxy;
else
proxy_host += 3;
// split host and port
proxy_port = index(proxy_host, ':');
if (proxy_port != NULL) {
proxy_port[0] = '\0';
proxy_port++;
server.sin_port = htons(strtoul(proxy_port, NULL, 10));
} else {
server.sin_port = htons(tunnel->config->gateway_port);
}
// get rid of a trailing slash
if (*proxy_host && proxy_host[strlen(proxy_host) - 1] == '/')
proxy_host[strlen(proxy_host) - 1] = '\0';
log_debug("proxy_host: %s\n", proxy_host);
log_debug("proxy_port: %s\n", proxy_port);
server.sin_addr.s_addr = inet_addr(proxy_host);
// if host is given as a FQDN we have to do a DNS lookup
if (server.sin_addr.s_addr == INADDR_NONE) {
const struct addrinfo hints = { .ai_family = AF_INET };
struct addrinfo *result = NULL;
ret = getaddrinfo(proxy_host, NULL, &hints, &result);
if (ret) {
if (ret == EAI_SYSTEM)
log_error("getaddrinfo: %s\n", strerror(errno));
else
log_error("getaddrinfo: %s\n", gai_strerror(ret));
goto err_connect;
}
server.sin_addr = ((struct sockaddr_in *)
result->ai_addr)->sin_addr;
freeaddrinfo(result);
}
} else {
server.sin_port = htons(tunnel->config->gateway_port);
server.sin_addr = tunnel->config->gateway_ip;
}
log_debug("server_addr: %s\n", inet_ntoa(server.sin_addr));
log_debug("server_port: %u\n", ntohs(server.sin_port));
server.sin_family = AF_INET;
memset(&(server.sin_zero), '\0', 8);
log_debug("gateway_addr: %s\n", inet_ntoa(tunnel->config->gateway_ip));
log_debug("gateway_port: %u\n", tunnel->config->gateway_port);
ret = connect(handle, (struct sockaddr *) &server, sizeof(server));
if (ret) {
log_error("connect: %s\n", strerror(errno));
goto err_connect;
}
if (env_proxy != NULL) {
char request[128];
// https://tools.ietf.org/html/rfc7231#section-4.3.6
sprintf(request, "CONNECT %s:%u HTTP/1.1\r\nHost: %s:%u\r\n\r\n",
inet_ntoa(tunnel->config->gateway_ip),
tunnel->config->gateway_port,
inet_ntoa(tunnel->config->gateway_ip),
tunnel->config->gateway_port);
ssize_t bytes_written = write(handle, request, strlen(request));
if (bytes_written != strlen(request)) {
log_error("write error while talking to proxy: %s\n",
strerror(errno));
goto err_connect;
}
// wait for a "200 OK" reply from the proxy,
// be careful not to fetch too many bytes at once
const char *response = NULL;
memset(&(request), '\0', sizeof(request));
for (int j = 0; response == NULL; j++) {
/*
* Coverity detected a defect:
* CID 200508: String not null terminated (STRING_NULL)
*
* It is actually a false positive:
* • Function memset() initializes 'request' with '\0'
* • Function read() gets a single char into: request[j]
* • The final '\0' cannot be overwritten because:
* j < ARRAY_SIZE(request) - 1
*/
ssize_t bytes_read = read(handle, &(request[j]), 1);
if (bytes_read < 1) {
log_error("Proxy response is unexpectedly large and cannot fit in the %lu-bytes buffer.\n",
ARRAY_SIZE(request));
goto err_proxy_response;
}
// detect "200"
static const char HTTP_STATUS_200[] = "200";
response = strstr(request, HTTP_STATUS_200);
// detect end-of-line after "200"
if (response != NULL) {
/*
* RFC2616 states in section 2.2 Basic Rules:
* CR = <US-ASCII CR, carriage return (13)>
* LF = <US-ASCII LF, linefeed (10)>
* HTTP/1.1 defines the sequence CR LF as the
* end-of-line marker for all protocol elements
* except the entity-body (see appendix 19.3
* for tolerant applications).
* CRLF = CR LF
*
* RFC2616 states in section 19.3 Tolerant Applications:
* The line terminator for message-header fields
* is the sequence CRLF. However, we recommend
* that applications, when parsing such headers,
* recognize a single LF as a line terminator
* and ignore the leading CR.
*/
static const char *const HTTP_EOL[] = {
"\r\n\r\n",
"\n\n"
};
const char *eol = NULL;
for (int i = 0; (i < ARRAY_SIZE(HTTP_EOL)) &&
(eol == NULL); i++)
eol = strstr(response, HTTP_EOL[i]);
response = eol;
}
if (j > ARRAY_SIZE(request) - 2) {
log_error("Proxy response does not contain \"%s\" as expected.\n",
HTTP_STATUS_200);
goto err_proxy_response;
}
}
free(env_proxy); // release memory allocated by strdup()
}
return handle;
err_proxy_response:
err_connect:
free(env_proxy); // release memory allocated by strdup()
err_strdup:
close(handle);
err_socket:
return -1;
}
static int ssl_verify_cert(struct tunnel *tunnel)
{
int ret = -1;
int cert_valid = 0;
unsigned char digest[SHA256LEN];
unsigned int len;
struct x509_digest *elem;
char digest_str[SHA256STRLEN], *subject, *issuer;
char *line;
int i;
X509_NAME *subj;
char common_name[FIELD_SIZE + 1];
SSL_set_verify(tunnel->ssl_handle, SSL_VERIFY_PEER, NULL);
X509 *cert = SSL_get_peer_certificate(tunnel->ssl_handle);
if (cert == NULL) {
log_error("Unable to get gateway certificate.\n");
return 1;
}
subj = X509_get_subject_name(cert);
#ifdef HAVE_X509_CHECK_HOST
// Use OpenSSL native host validation if v >= 1.0.2.
if (X509_check_host(cert, common_name, FIELD_SIZE, 0, NULL))
cert_valid = 1;
#else
// Use explicit Common Name check if native validation not available.
// Note: this will ignore Subject Alternative Name fields.
if (subj
&& X509_NAME_get_text_by_NID(subj, NID_commonName, common_name,
FIELD_SIZE) > 0
&& strncasecmp(common_name, tunnel->config->gateway_host,
FIELD_SIZE) == 0)
cert_valid = 1;
#endif
// Try to validate certificate using local PKI
if (cert_valid
&& SSL_get_verify_result(tunnel->ssl_handle) == X509_V_OK) {
log_debug("Gateway certificate validation succeeded.\n");
ret = 0;
goto free_cert;
}
log_debug("Gateway certificate validation failed.\n");
// If validation failed, check if cert is in the white list
if (X509_digest(cert, EVP_sha256(), digest, &len) <= 0
|| len != SHA256LEN) {
log_error("Could not compute certificate sha256 digest.\n");
goto free_cert;
}
// Encode digest in base16
for (i = 0; i < SHA256LEN; i++)
sprintf(&digest_str[2 * i], "%02x", digest[i]);
digest_str[SHA256STRLEN - 1] = '\0';
// Is it in whitelist?
for (elem = tunnel->config->cert_whitelist; elem != NULL;
elem = elem->next)
if (memcmp(digest_str, elem->data, SHA256STRLEN - 1) == 0)
break;
if (elem != NULL) { // break before end of loop
log_debug("Gateway certificate digest found in white list.\n");
ret = 0;
goto free_cert;
}
subject = X509_NAME_oneline(subj, NULL, 0);
issuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
log_error("Gateway certificate validation failed, and the certificate digest in not in the local whitelist. If you trust it, rerun with:\n");
log_error(" --trusted-cert %s\n", digest_str);
log_error("or add this line to your config file:\n");
log_error(" trusted-cert = %s\n", digest_str);
log_error("Gateway certificate:\n");
log_error(" subject:\n");
for (line = strtok(subject, "/"); line != NULL;
line = strtok(NULL, "/"))
log_error(" %s\n", line);
log_error(" issuer:\n");
for (line = strtok(issuer, "/"); line != NULL;
line = strtok(NULL, "/"))
log_error(" %s\n", line);
log_error(" sha256 digest:\n");
log_error(" %s\n", digest_str);
free_cert:
X509_free(cert);
return ret;
}
/*
* Destroy and free the SSL connection to the gateway.
*/
static void ssl_disconnect(struct tunnel *tunnel)
{
if (!tunnel->ssl_handle)
return;
SSL_shutdown(tunnel->ssl_handle);
SSL_free(tunnel->ssl_handle);
SSL_CTX_free(tunnel->ssl_context);
close(tunnel->ssl_socket);
tunnel->ssl_handle = NULL;
tunnel->ssl_context = NULL;
}
/*
* Connects to the gateway and initiate an SSL session.
*/
int ssl_connect(struct tunnel *tunnel)
{
ssl_disconnect(tunnel);
tunnel->ssl_socket = tcp_connect(tunnel);
if (tunnel->ssl_socket == -1)
return 1;
// registration is deprecated from OpenSSL 1.1.0 onward
#if OPENSSL_API_COMPAT < 0x10100000L
// Register the error strings for libcrypto & libssl
SSL_load_error_strings();
// Register the available ciphers and digests
SSL_library_init();
#endif
tunnel->ssl_context = SSL_CTX_new(SSLv23_client_method());
if (tunnel->ssl_context == NULL) {
log_error("SSL_CTX_new: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
// Load the OS default CA files
if (!SSL_CTX_set_default_verify_paths(tunnel->ssl_context))
log_error("Could not load OS OpenSSL files.\n");
if (tunnel->config->ca_file) {
if (!SSL_CTX_load_verify_locations(
tunnel->ssl_context,
tunnel->config->ca_file, NULL)) {
log_error("SSL_CTX_load_verify_locations: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
/* Use engine for PIV if user-cert config starts with pkcs11 URI: */
if (tunnel->config->use_engine > 0) {
ENGINE *e;
ENGINE_load_builtin_engines();
e = ENGINE_by_id("pkcs11");
if (!e) {
log_error("Could not load pkcs11 Engine: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!ENGINE_init(e)) {
log_error("Could not init pkcs11 Engine: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
ENGINE_free(e);
return 1;
}
if (!ENGINE_set_default_RSA(e))
abort();
ENGINE_finish(e);
ENGINE_free(e);
struct token parms;
parms.uri = tunnel->config->user_cert;
parms.cert = NULL;
if (!ENGINE_ctrl_cmd(e, "LOAD_CERT_CTRL", 0, &parms, NULL, 1)) {
log_error("PKCS11 ENGINE_ctrl_cmd: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_use_certificate(tunnel->ssl_context, parms.cert)) {
log_error("PKCS11 SSL_CTX_use_certificate: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
EVP_PKEY * privkey = ENGINE_load_private_key(
e, parms.uri, UI_OpenSSL(), NULL);
if (!privkey) {
log_error("PKCS11 ENGINE_load_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_use_PrivateKey(tunnel->ssl_context, privkey)) {
log_error("PKCS11 SSL_CTX_use_PrivateKey_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_check_private_key(tunnel->ssl_context)) {
log_error("PKCS11 SSL_CTX_check_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
} else { /* end PKCS11-engine */
if (tunnel->config->user_cert) {
if (!SSL_CTX_use_certificate_file(
tunnel->ssl_context, tunnel->config->user_cert,
SSL_FILETYPE_PEM)) {
log_error("SSL_CTX_use_certificate_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
if (tunnel->config->user_key) {
if (!SSL_CTX_use_PrivateKey_file(
tunnel->ssl_context, tunnel->config->user_key,
SSL_FILETYPE_PEM)) {
log_error("SSL_CTX_use_PrivateKey_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
if (tunnel->config->user_cert && tunnel->config->user_key) {
if (!SSL_CTX_check_private_key(tunnel->ssl_context)) {
log_error("SSL_CTX_check_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
}
if (!tunnel->config->insecure_ssl) {
long sslctxopt = SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
long checkopt;
checkopt = SSL_CTX_set_options(tunnel->ssl_context, sslctxopt);
if ((checkopt & sslctxopt) != sslctxopt) {
log_error("SSL_CTX_set_options didn't set opt: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
tunnel->ssl_handle = SSL_new(tunnel->ssl_context);
if (tunnel->ssl_handle == NULL) {
log_error("SSL_new: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!tunnel->config->insecure_ssl) {
if (!tunnel->config->cipher_list) {
const char *cipher_list;
if (tunnel->config->seclevel_1)
cipher_list = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4@SECLEVEL=1";
else
cipher_list = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4";
tunnel->config->cipher_list = strdup(cipher_list);
}
} else {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (tunnel->config->min_tls <= 0)
tunnel->config->min_tls = TLS1_VERSION;
#endif
if (!tunnel->config->cipher_list && tunnel->config->seclevel_1) {
const char *cipher_list = "DEFAULT@SECLEVEL=1";
tunnel->config->cipher_list = strdup(cipher_list);
}
}
if (tunnel->config->cipher_list) {
log_debug("Setting cipher list to: %s\n", tunnel->config->cipher_list);
if (!SSL_set_cipher_list(tunnel->ssl_handle,
tunnel->config->cipher_list)) {
log_error("SSL_set_cipher_list failed: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (tunnel->config->min_tls > 0) {
log_debug("Setting min proto version to: 0x%x\n",
tunnel->config->min_tls);
if (!SSL_set_min_proto_version(tunnel->ssl_handle,
tunnel->config->min_tls)) {
log_error("SSL_set_min_proto_version failed: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
#endif
if (!SSL_set_fd(tunnel->ssl_handle, tunnel->ssl_socket)) {
log_error("SSL_set_fd: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
SSL_set_mode(tunnel->ssl_handle, SSL_MODE_AUTO_RETRY);
// Initiate SSL handshake
if (SSL_connect(tunnel->ssl_handle) != 1) {
log_error("SSL_connect: %s\n"
"You might want to try --insecure-ssl or specify a different --cipher-list\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
SSL_set_mode(tunnel->ssl_handle, SSL_MODE_AUTO_RETRY);
if (ssl_verify_cert(tunnel))
return 1;
// Disable SIGPIPE (occurs when trying to write to an already-closed
// socket).
signal(SIGPIPE, SIG_IGN);
return 0;
}
int run_tunnel(struct vpn_config *config)
{
int ret;
struct tunnel tunnel = {
.config = config,
.state = STATE_DOWN,
.ssl_context = NULL,
.ssl_handle = NULL,
.ipv4.ns1_addr.s_addr = 0,
.ipv4.ns2_addr.s_addr = 0,
.ipv4.dns_suffix = NULL,
.on_ppp_if_up = on_ppp_if_up,
.on_ppp_if_down = on_ppp_if_down
};
// Step 0: get gateway host IP
log_debug("Resolving gateway host ip\n");
ret = get_gateway_host_ip(&tunnel);
if (ret)
goto err_tunnel;
// Step 1: open a SSL connection to the gateway
log_debug("Establishing ssl connection\n");
ret = ssl_connect(&tunnel);
if (ret)
goto err_tunnel;
log_info("Connected to gateway.\n");
// Step 2: connect to the HTTP interface and authenticate to get a
// cookie
ret = auth_log_in(&tunnel);
if (ret != 1) {
log_error("Could not authenticate to gateway. Please check the password, client certificate, etc.\n");
log_debug("%s %d\n", err_http_str(ret), ret);
ret = 1;
goto err_tunnel;
}
log_info("Authenticated.\n");
log_debug("Cookie: %s\n", tunnel.cookie);
ret = auth_request_vpn_allocation(&tunnel);
if (ret != 1) {
log_error("VPN allocation request failed (%s).\n",
err_http_str(ret));
ret = 1;
goto err_tunnel;
}
log_info("Remote gateway has allocated a VPN.\n");
ret = ssl_connect(&tunnel);
if (ret)
goto err_tunnel;
// Step 3: get configuration
log_debug("Retrieving configuration\n");
ret = auth_get_config(&tunnel);
if (ret != 1) {
log_error("Could not get VPN configuration (%s).\n",
err_http_str(ret));
ret = 1;
goto err_tunnel;
}
// Step 4: run a pppd process
log_debug("Establishing the tunnel\n");
ret = pppd_run(&tunnel);
if (ret)
goto err_tunnel;
// Step 5: ask gateway to start tunneling
log_debug("Switch to tunneling mode\n");
ret = http_send(&tunnel,
"GET /remote/sslvpn-tunnel HTTP/1.1\r\n"
"Host: sslvpn\r\n"
"Cookie: %s\r\n\r\n",
tunnel.cookie);
if (ret != 1) {
log_error("Could not start tunnel (%s).\n", err_http_str(ret));
ret = 1;
goto err_start_tunnel;
}
tunnel.state = STATE_CONNECTING;
ret = 0;
// Step 6: perform io between pppd and the gateway, while tunnel is up
log_debug("Starting IO through the tunnel\n");
io_loop(&tunnel);
log_debug("disconnecting\n");
if (tunnel.state == STATE_UP)
if (tunnel.on_ppp_if_down != NULL)
tunnel.on_ppp_if_down(&tunnel);
tunnel.state = STATE_DISCONNECTING;
err_start_tunnel:
pppd_terminate(&tunnel);
log_info("Terminated %s.\n", PPP_DAEMON);
err_tunnel:
log_info("Closed connection to gateway.\n");
tunnel.state = STATE_DOWN;
if (ssl_connect(&tunnel)) {
log_info("Could not log out.\n");
} else {
auth_log_out(&tunnel);
log_info("Logged out.\n");
}
// explicitly free the buffer allocated for split routes of the ipv4 config
if (tunnel.ipv4.split_rt != NULL) {
free(tunnel.ipv4.split_rt);
tunnel.ipv4.split_rt = NULL;
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-295/c/bad_4597_0 |
crossvul-cpp_data_good_4599_0 | /*
* Copyright (C) 2015 Adrien Vergé
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* In addition, as a special exception, the copyright holders give permission
* to link the code of portions of this program with the OpenSSL library under
* certain conditions as described in each individual source file, and
* distribute linked combinations including the two.
* You must obey the GNU General Public License in all respects for all of the
* code used other than OpenSSL. If you modify file(s) with this exception,
* you may extend this exception to your version of the file(s), but you are
* not obligated to do so. If you do not wish to do so, delete this exception
* statement from your version. If you delete this exception statement from
* all source files in the program, then also delete it here.
*/
#include "tunnel.h"
#include "http.h"
#include "log.h"
#include <unistd.h>
#include <fcntl.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <errno.h>
#include <string.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <openssl/err.h>
#include <openssl/x509v3.h>
#include <openssl/engine.h>
#if HAVE_PTY_H
#include <pty.h>
#elif HAVE_UTIL_H
#include <util.h>
#endif
#include <termios.h>
#include <signal.h>
#include <sys/wait.h>
#if HAVE_SYSTEMD
#include <systemd/sd-daemon.h>
#endif
// we use this constant in the source, so define a fallback if not defined
#ifndef OPENSSL_API_COMPAT
#define OPENSSL_API_COMPAT 0x0908000L
#endif
struct ofv_varr {
unsigned int cap; // current capacity
unsigned int off; // next slot to write, always < max(cap - 1, 1)
const char **data; // NULL terminated
};
static int ofv_append_varr(struct ofv_varr *p, const char *x)
{
if (p->off + 1 >= p->cap) {
const char **ndata;
unsigned int ncap = (p->off + 1) * 2;
if (p->off + 1 >= ncap) {
log_error("%s: ncap exceeded\n", __func__);
return 1;
};
ndata = realloc(p->data, ncap * sizeof(const char *));
if (ndata) {
p->data = ndata;
p->cap = ncap;
} else {
log_error("realloc: %s\n", strerror(errno));
return 1;
}
}
if (p->data == NULL) {
log_error("%s: NULL data\n", __func__);
return 1;
}
if (p->off + 1 >= p->cap) {
log_error("%s: cap exceeded in p\n", __func__);
return 1;
}
p->data[p->off] = x;
p->data[++p->off] = NULL;
return 0;
}
static int on_ppp_if_up(struct tunnel *tunnel)
{
log_info("Interface %s is UP.\n", tunnel->ppp_iface);
if (tunnel->config->set_routes) {
int ret;
log_info("Setting new routes...\n");
ret = ipv4_set_tunnel_routes(tunnel);
if (ret != 0)
log_warn("Adding route table is incomplete. Please check route table.\n");
}
if (tunnel->config->set_dns) {
log_info("Adding VPN nameservers...\n");
ipv4_add_nameservers_to_resolv_conf(tunnel);
}
log_info("Tunnel is up and running.\n");
#if HAVE_SYSTEMD
sd_notify(0, "READY=1");
#endif
return 0;
}
static int on_ppp_if_down(struct tunnel *tunnel)
{
log_info("Setting ppp interface down.\n");
if (tunnel->config->set_routes) {
log_info("Restoring routes...\n");
ipv4_restore_routes(tunnel);
}
if (tunnel->config->set_dns) {
log_info("Removing VPN nameservers...\n");
ipv4_del_nameservers_from_resolv_conf(tunnel);
}
return 0;
}
static int pppd_run(struct tunnel *tunnel)
{
pid_t pid;
int amaster;
int slave_stderr;
#ifdef HAVE_STRUCT_TERMIOS
struct termios termp = {
.c_cflag = B9600,
.c_cc[VTIME] = 0,
.c_cc[VMIN] = 1
};
#endif
static const char ppp_path[] = PPP_PATH;
if (access(ppp_path, F_OK) != 0) {
log_error("%s: %s.\n", ppp_path, strerror(errno));
return 1;
}
log_debug("ppp_path: %s\n", ppp_path);
slave_stderr = dup(STDERR_FILENO);
if (slave_stderr < 0) {
log_error("slave stderr %s\n", strerror(errno));
return 1;
}
#ifdef HAVE_STRUCT_TERMIOS
pid = forkpty(&amaster, NULL, &termp, NULL);
#else
pid = forkpty(&amaster, NULL, NULL, NULL);
#endif
if (pid == 0) { // child process
struct ofv_varr pppd_args = { 0, 0, NULL };
dup2(slave_stderr, STDERR_FILENO);
close(slave_stderr);
#if HAVE_USR_SBIN_PPP
/*
* assume there is a default configuration to start.
* Support for taking options from the command line
* e.g. the name of the configuration or options
* to send interactively to ppp will be added later
*/
static const char *const v[] = {
ppp_path,
"-direct"
};
for (unsigned int i = 0; i < ARRAY_SIZE(v); i++)
if (ofv_append_varr(&pppd_args, v[i]))
return 1;
#endif
#if HAVE_USR_SBIN_PPPD
if (tunnel->config->pppd_call) {
if (ofv_append_varr(&pppd_args, ppp_path))
return 1;
if (ofv_append_varr(&pppd_args, "call"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_call))
return 1;
} else {
static const char *const v[] = {
ppp_path,
"115200", // speed
":192.0.2.1", // <local_IP_address>:<remote_IP_address>
"noipdefault",
"noaccomp",
"noauth",
"default-asyncmap",
"nopcomp",
"receive-all",
"nodefaultroute",
"nodetach",
"lcp-max-configure", "40",
"mru", "1354"
};
for (unsigned int i = 0; i < ARRAY_SIZE(v); i++)
if (ofv_append_varr(&pppd_args, v[i]))
return 1;
}
if (tunnel->config->pppd_use_peerdns)
if (ofv_append_varr(&pppd_args, "usepeerdns"))
return 1;
if (tunnel->config->pppd_log) {
if (ofv_append_varr(&pppd_args, "debug"))
return 1;
if (ofv_append_varr(&pppd_args, "logfile"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_log))
return 1;
} else {
/*
* pppd defaults to logging to fd=1, clobbering the
* actual PPP data
*/
if (ofv_append_varr(&pppd_args, "logfd"))
return 1;
if (ofv_append_varr(&pppd_args, "2"))
return 1;
}
if (tunnel->config->pppd_plugin) {
if (ofv_append_varr(&pppd_args, "plugin"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_plugin))
return 1;
}
if (tunnel->config->pppd_ipparam) {
if (ofv_append_varr(&pppd_args, "ipparam"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_ipparam))
return 1;
}
if (tunnel->config->pppd_ifname) {
if (ofv_append_varr(&pppd_args, "ifname"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_ifname))
return 1;
}
#endif
#if HAVE_USR_SBIN_PPP
if (tunnel->config->ppp_system) {
if (ofv_append_varr(&pppd_args, tunnel->config->ppp_system))
return 1;
}
#endif
close(tunnel->ssl_socket);
execv(pppd_args.data[0], (char *const *)pppd_args.data);
free(pppd_args.data);
fprintf(stderr, "execvp: %s\n", strerror(errno));
_exit(EXIT_FAILURE);
} else {
close(slave_stderr);
if (pid == -1) {
log_error("forkpty: %s\n", strerror(errno));
return 1;
}
}
// Set non-blocking
int flags = fcntl(amaster, F_GETFL, 0);
if (flags == -1)
flags = 0;
if (fcntl(amaster, F_SETFL, flags | O_NONBLOCK) == -1) {
log_error("fcntl: %s\n", strerror(errno));
return 1;
}
tunnel->pppd_pid = pid;
tunnel->pppd_pty = amaster;
return 0;
}
static const char * const pppd_message[] = {
"Has detached, or otherwise the connection was successfully established and terminated at the peer's request.",
"An immediately fatal error of some kind occurred, such as an essential system call failing, or running out of virtual memory.",
"An error was detected in processing the options given, such as two mutually exclusive options being used.",
"Is not setuid-root and the invoking user is not root.",
"The kernel does not support PPP, for example, the PPP kernel driver is not included or cannot be loaded.",
"Terminated because it was sent a SIGINT, SIGTERM or SIGHUP signal.",
"The serial port could not be locked.",
"The serial port could not be opened.",
"The connect script failed (returned a non-zero exit status).",
"The command specified as the argument to the pty option could not be run.",
"The PPP negotiation failed, that is, it didn't reach the point where at least one network protocol (e.g. IP) was running.",
"The peer system failed (or refused) to authenticate itself.",
"The link was established successfully and terminated because it was idle.",
"The link was established successfully and terminated because the connect time limit was reached.",
"Callback was negotiated and an incoming call should arrive shortly.",
"The link was terminated because the peer is not responding to echo requests.",
"The link was terminated by the modem hanging up.",
"The PPP negotiation failed because serial loopback was detected.",
"The init script failed (returned a non-zero exit status).",
"We failed to authenticate ourselves to the peer."
};
static int pppd_terminate(struct tunnel *tunnel)
{
close(tunnel->pppd_pty);
log_debug("Waiting for %s to exit...\n", PPP_DAEMON);
int status;
if (waitpid(tunnel->pppd_pid, &status, 0) == -1) {
log_error("waitpid: %s\n", strerror(errno));
return 1;
}
if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
log_debug("waitpid: %s exit status code %d\n",
PPP_DAEMON, exit_status);
#if HAVE_USR_SBIN_PPPD
if (exit_status >= ARRAY_SIZE(pppd_message) || exit_status < 0) {
log_error("%s: Returned an unknown exit status: %d\n",
PPP_DAEMON, exit_status);
} else {
switch (exit_status) {
case 0: // success
log_debug("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
case 16: // emitted when exiting normally
log_info("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
default:
log_error("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
}
}
#else
// ppp exit codes in the FreeBSD case
switch (exit_status) {
case 0: // success and EX_NORMAL as defined in ppp source directly
log_debug("%s: %s\n", PPP_DAEMON, pppd_message[exit_status]);
break;
case 1:
case 127:
case 255: // abnormal exit with hard-coded error codes in ppp
log_error("%s: exited with return value of %d\n",
PPP_DAEMON, exit_status);
break;
default:
log_error("%s: %s (%d)\n", PPP_DAEMON, strerror(exit_status),
exit_status);
break;
}
#endif
} else if (WIFSIGNALED(status)) {
int signal_number = WTERMSIG(status);
log_debug("waitpid: %s terminated by signal %d\n",
PPP_DAEMON, signal_number);
log_error("%s: terminated by signal: %s\n",
PPP_DAEMON, strsignal(signal_number));
}
return 0;
}
int ppp_interface_is_up(struct tunnel *tunnel)
{
struct ifaddrs *ifap, *ifa;
log_debug("Got Address: %s\n", inet_ntoa(tunnel->ipv4.ip_addr));
if (getifaddrs(&ifap)) {
log_error("getifaddrs: %s\n", strerror(errno));
return 0;
}
for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
if ((
#if HAVE_USR_SBIN_PPPD
(tunnel->config->pppd_ifname
&& strstr(ifa->ifa_name, tunnel->config->pppd_ifname)
!= NULL)
|| strstr(ifa->ifa_name, "ppp") != NULL
#endif
#if HAVE_USR_SBIN_PPP
strstr(ifa->ifa_name, "tun") != NULL
#endif
) && ifa->ifa_flags & IFF_UP) {
if (&(ifa->ifa_addr->sa_family) != NULL
&& ifa->ifa_addr->sa_family == AF_INET) {
struct in_addr if_ip_addr =
cast_addr(ifa->ifa_addr)->sin_addr;
log_debug("Interface Name: %s\n", ifa->ifa_name);
log_debug("Interface Addr: %s\n", inet_ntoa(if_ip_addr));
if (tunnel->ipv4.ip_addr.s_addr == if_ip_addr.s_addr) {
strncpy(tunnel->ppp_iface, ifa->ifa_name,
ROUTE_IFACE_LEN - 1);
freeifaddrs(ifap);
return 1;
}
}
}
}
freeifaddrs(ifap);
return 0;
}
static int get_gateway_host_ip(struct tunnel *tunnel)
{
const struct addrinfo hints = { .ai_family = AF_INET };
struct addrinfo *result = NULL;
int ret = getaddrinfo(tunnel->config->gateway_host, NULL, &hints, &result);
if (ret) {
if (ret == EAI_SYSTEM)
log_error("getaddrinfo: %s\n", strerror(errno));
else
log_error("getaddrinfo: %s\n", gai_strerror(ret));
return 1;
}
tunnel->config->gateway_ip = ((struct sockaddr_in *)
result->ai_addr)->sin_addr;
freeaddrinfo(result);
setenv("VPN_GATEWAY", inet_ntoa(tunnel->config->gateway_ip), 0);
return 0;
}
/*
* Establish a regular TCP connection.
*/
static int tcp_connect(struct tunnel *tunnel)
{
int ret, handle;
struct sockaddr_in server;
char *env_proxy;
handle = socket(AF_INET, SOCK_STREAM, 0);
if (handle == -1) {
log_error("socket: %s\n", strerror(errno));
goto err_socket;
}
env_proxy = getenv("https_proxy");
if (env_proxy == NULL)
env_proxy = getenv("HTTPS_PROXY");
if (env_proxy == NULL)
env_proxy = getenv("all_proxy");
if (env_proxy == NULL)
env_proxy = getenv("ALL_PROXY");
if (env_proxy != NULL) {
char *proxy_host, *proxy_port;
// protect the original environment from modifications
env_proxy = strdup(env_proxy);
if (env_proxy == NULL) {
log_error("strdup: %s\n", strerror(errno));
goto err_strdup;
}
// get rid of a trailing slash
if (*env_proxy && env_proxy[strlen(env_proxy) - 1] == '/')
env_proxy[strlen(env_proxy) - 1] = '\0';
// get rid of a http(s):// prefix in env_proxy
proxy_host = strstr(env_proxy, "://");
if (proxy_host == NULL)
proxy_host = env_proxy;
else
proxy_host += 3;
// split host and port
proxy_port = index(proxy_host, ':');
if (proxy_port != NULL) {
proxy_port[0] = '\0';
proxy_port++;
server.sin_port = htons(strtoul(proxy_port, NULL, 10));
} else {
server.sin_port = htons(tunnel->config->gateway_port);
}
// get rid of a trailing slash
if (*proxy_host && proxy_host[strlen(proxy_host) - 1] == '/')
proxy_host[strlen(proxy_host) - 1] = '\0';
log_debug("proxy_host: %s\n", proxy_host);
log_debug("proxy_port: %s\n", proxy_port);
server.sin_addr.s_addr = inet_addr(proxy_host);
// if host is given as a FQDN we have to do a DNS lookup
if (server.sin_addr.s_addr == INADDR_NONE) {
const struct addrinfo hints = { .ai_family = AF_INET };
struct addrinfo *result = NULL;
ret = getaddrinfo(proxy_host, NULL, &hints, &result);
if (ret) {
if (ret == EAI_SYSTEM)
log_error("getaddrinfo: %s\n", strerror(errno));
else
log_error("getaddrinfo: %s\n", gai_strerror(ret));
goto err_connect;
}
server.sin_addr = ((struct sockaddr_in *)
result->ai_addr)->sin_addr;
freeaddrinfo(result);
}
} else {
server.sin_port = htons(tunnel->config->gateway_port);
server.sin_addr = tunnel->config->gateway_ip;
}
log_debug("server_addr: %s\n", inet_ntoa(server.sin_addr));
log_debug("server_port: %u\n", ntohs(server.sin_port));
server.sin_family = AF_INET;
memset(&(server.sin_zero), '\0', 8);
log_debug("gateway_addr: %s\n", inet_ntoa(tunnel->config->gateway_ip));
log_debug("gateway_port: %u\n", tunnel->config->gateway_port);
ret = connect(handle, (struct sockaddr *) &server, sizeof(server));
if (ret) {
log_error("connect: %s\n", strerror(errno));
goto err_connect;
}
if (env_proxy != NULL) {
char request[128];
// https://tools.ietf.org/html/rfc7231#section-4.3.6
sprintf(request, "CONNECT %s:%u HTTP/1.1\r\nHost: %s:%u\r\n\r\n",
inet_ntoa(tunnel->config->gateway_ip),
tunnel->config->gateway_port,
inet_ntoa(tunnel->config->gateway_ip),
tunnel->config->gateway_port);
ssize_t bytes_written = write(handle, request, strlen(request));
if (bytes_written != strlen(request)) {
log_error("write error while talking to proxy: %s\n",
strerror(errno));
goto err_connect;
}
// wait for a "200 OK" reply from the proxy,
// be careful not to fetch too many bytes at once
const char *response = NULL;
memset(&(request), '\0', sizeof(request));
for (int j = 0; response == NULL; j++) {
/*
* Coverity detected a defect:
* CID 200508: String not null terminated (STRING_NULL)
*
* It is actually a false positive:
* • Function memset() initializes 'request' with '\0'
* • Function read() gets a single char into: request[j]
* • The final '\0' cannot be overwritten because:
* j < ARRAY_SIZE(request) - 1
*/
ssize_t bytes_read = read(handle, &(request[j]), 1);
if (bytes_read < 1) {
log_error("Proxy response is unexpectedly large and cannot fit in the %lu-bytes buffer.\n",
ARRAY_SIZE(request));
goto err_proxy_response;
}
// detect "200"
static const char HTTP_STATUS_200[] = "200";
response = strstr(request, HTTP_STATUS_200);
// detect end-of-line after "200"
if (response != NULL) {
/*
* RFC2616 states in section 2.2 Basic Rules:
* CR = <US-ASCII CR, carriage return (13)>
* LF = <US-ASCII LF, linefeed (10)>
* HTTP/1.1 defines the sequence CR LF as the
* end-of-line marker for all protocol elements
* except the entity-body (see appendix 19.3
* for tolerant applications).
* CRLF = CR LF
*
* RFC2616 states in section 19.3 Tolerant Applications:
* The line terminator for message-header fields
* is the sequence CRLF. However, we recommend
* that applications, when parsing such headers,
* recognize a single LF as a line terminator
* and ignore the leading CR.
*/
static const char *const HTTP_EOL[] = {
"\r\n\r\n",
"\n\n"
};
const char *eol = NULL;
for (int i = 0; (i < ARRAY_SIZE(HTTP_EOL)) &&
(eol == NULL); i++)
eol = strstr(response, HTTP_EOL[i]);
response = eol;
}
if (j > ARRAY_SIZE(request) - 2) {
log_error("Proxy response does not contain \"%s\" as expected.\n",
HTTP_STATUS_200);
goto err_proxy_response;
}
}
free(env_proxy); // release memory allocated by strdup()
}
return handle;
err_proxy_response:
err_connect:
free(env_proxy); // release memory allocated by strdup()
err_strdup:
close(handle);
err_socket:
return -1;
}
static int ssl_verify_cert(struct tunnel *tunnel)
{
int ret = -1;
int cert_valid = 0;
unsigned char digest[SHA256LEN];
unsigned int len;
struct x509_digest *elem;
char digest_str[SHA256STRLEN], *subject, *issuer;
char *line;
int i;
X509_NAME *subj;
SSL_set_verify(tunnel->ssl_handle, SSL_VERIFY_PEER, NULL);
X509 *cert = SSL_get_peer_certificate(tunnel->ssl_handle);
if (cert == NULL) {
log_error("Unable to get gateway certificate.\n");
return 1;
}
subj = X509_get_subject_name(cert);
#ifdef HAVE_X509_CHECK_HOST
// Use OpenSSL native host validation if v >= 1.0.2.
// compare against gateway_host and correctly check return value
// to fix piror Incorrect use of X509_check_host
if (X509_check_host(cert, tunnel->config->gateway_host,
0, 0, NULL) == 1)
cert_valid = 1;
#else
char common_name[FIELD_SIZE + 1];
// Use explicit Common Name check if native validation not available.
// Note: this will ignore Subject Alternative Name fields.
if (subj
&& X509_NAME_get_text_by_NID(subj, NID_commonName, common_name,
FIELD_SIZE) > 0
&& strncasecmp(common_name, tunnel->config->gateway_host,
FIELD_SIZE) == 0)
cert_valid = 1;
#endif
// Try to validate certificate using local PKI
if (cert_valid
&& SSL_get_verify_result(tunnel->ssl_handle) == X509_V_OK) {
log_debug("Gateway certificate validation succeeded.\n");
ret = 0;
goto free_cert;
}
log_debug("Gateway certificate validation failed.\n");
// If validation failed, check if cert is in the white list
if (X509_digest(cert, EVP_sha256(), digest, &len) <= 0
|| len != SHA256LEN) {
log_error("Could not compute certificate sha256 digest.\n");
goto free_cert;
}
// Encode digest in base16
for (i = 0; i < SHA256LEN; i++)
sprintf(&digest_str[2 * i], "%02x", digest[i]);
digest_str[SHA256STRLEN - 1] = '\0';
// Is it in whitelist?
for (elem = tunnel->config->cert_whitelist; elem != NULL;
elem = elem->next)
if (memcmp(digest_str, elem->data, SHA256STRLEN - 1) == 0)
break;
if (elem != NULL) { // break before end of loop
log_debug("Gateway certificate digest found in white list.\n");
ret = 0;
goto free_cert;
}
subject = X509_NAME_oneline(subj, NULL, 0);
issuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
log_error("Gateway certificate validation failed, and the certificate digest in not in the local whitelist. If you trust it, rerun with:\n");
log_error(" --trusted-cert %s\n", digest_str);
log_error("or add this line to your config file:\n");
log_error(" trusted-cert = %s\n", digest_str);
log_error("Gateway certificate:\n");
log_error(" subject:\n");
for (line = strtok(subject, "/"); line != NULL;
line = strtok(NULL, "/"))
log_error(" %s\n", line);
log_error(" issuer:\n");
for (line = strtok(issuer, "/"); line != NULL;
line = strtok(NULL, "/"))
log_error(" %s\n", line);
log_error(" sha256 digest:\n");
log_error(" %s\n", digest_str);
free_cert:
X509_free(cert);
return ret;
}
/*
* Destroy and free the SSL connection to the gateway.
*/
static void ssl_disconnect(struct tunnel *tunnel)
{
if (!tunnel->ssl_handle)
return;
SSL_shutdown(tunnel->ssl_handle);
SSL_free(tunnel->ssl_handle);
SSL_CTX_free(tunnel->ssl_context);
close(tunnel->ssl_socket);
tunnel->ssl_handle = NULL;
tunnel->ssl_context = NULL;
}
/*
* Connects to the gateway and initiate an SSL session.
*/
int ssl_connect(struct tunnel *tunnel)
{
ssl_disconnect(tunnel);
tunnel->ssl_socket = tcp_connect(tunnel);
if (tunnel->ssl_socket == -1)
return 1;
// registration is deprecated from OpenSSL 1.1.0 onward
#if OPENSSL_API_COMPAT < 0x10100000L
// Register the error strings for libcrypto & libssl
SSL_load_error_strings();
// Register the available ciphers and digests
SSL_library_init();
#endif
tunnel->ssl_context = SSL_CTX_new(SSLv23_client_method());
if (tunnel->ssl_context == NULL) {
log_error("SSL_CTX_new: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
// Load the OS default CA files
if (!SSL_CTX_set_default_verify_paths(tunnel->ssl_context))
log_error("Could not load OS OpenSSL files.\n");
if (tunnel->config->ca_file) {
if (!SSL_CTX_load_verify_locations(
tunnel->ssl_context,
tunnel->config->ca_file, NULL)) {
log_error("SSL_CTX_load_verify_locations: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
/* Use engine for PIV if user-cert config starts with pkcs11 URI: */
if (tunnel->config->use_engine > 0) {
ENGINE *e;
ENGINE_load_builtin_engines();
e = ENGINE_by_id("pkcs11");
if (!e) {
log_error("Could not load pkcs11 Engine: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!ENGINE_init(e)) {
log_error("Could not init pkcs11 Engine: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
ENGINE_free(e);
return 1;
}
if (!ENGINE_set_default_RSA(e))
abort();
ENGINE_finish(e);
ENGINE_free(e);
struct token parms;
parms.uri = tunnel->config->user_cert;
parms.cert = NULL;
if (!ENGINE_ctrl_cmd(e, "LOAD_CERT_CTRL", 0, &parms, NULL, 1)) {
log_error("PKCS11 ENGINE_ctrl_cmd: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_use_certificate(tunnel->ssl_context, parms.cert)) {
log_error("PKCS11 SSL_CTX_use_certificate: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
EVP_PKEY * privkey = ENGINE_load_private_key(
e, parms.uri, UI_OpenSSL(), NULL);
if (!privkey) {
log_error("PKCS11 ENGINE_load_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_use_PrivateKey(tunnel->ssl_context, privkey)) {
log_error("PKCS11 SSL_CTX_use_PrivateKey_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_check_private_key(tunnel->ssl_context)) {
log_error("PKCS11 SSL_CTX_check_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
} else { /* end PKCS11-engine */
if (tunnel->config->user_cert) {
if (!SSL_CTX_use_certificate_file(
tunnel->ssl_context, tunnel->config->user_cert,
SSL_FILETYPE_PEM)) {
log_error("SSL_CTX_use_certificate_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
if (tunnel->config->user_key) {
if (!SSL_CTX_use_PrivateKey_file(
tunnel->ssl_context, tunnel->config->user_key,
SSL_FILETYPE_PEM)) {
log_error("SSL_CTX_use_PrivateKey_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
if (tunnel->config->user_cert && tunnel->config->user_key) {
if (!SSL_CTX_check_private_key(tunnel->ssl_context)) {
log_error("SSL_CTX_check_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
}
if (!tunnel->config->insecure_ssl) {
long sslctxopt = SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
long checkopt;
checkopt = SSL_CTX_set_options(tunnel->ssl_context, sslctxopt);
if ((checkopt & sslctxopt) != sslctxopt) {
log_error("SSL_CTX_set_options didn't set opt: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
tunnel->ssl_handle = SSL_new(tunnel->ssl_context);
if (tunnel->ssl_handle == NULL) {
log_error("SSL_new: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!tunnel->config->insecure_ssl) {
if (!tunnel->config->cipher_list) {
const char *cipher_list;
if (tunnel->config->seclevel_1)
cipher_list = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4@SECLEVEL=1";
else
cipher_list = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4";
tunnel->config->cipher_list = strdup(cipher_list);
}
} else {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (tunnel->config->min_tls <= 0)
tunnel->config->min_tls = TLS1_VERSION;
#endif
if (!tunnel->config->cipher_list && tunnel->config->seclevel_1) {
const char *cipher_list = "DEFAULT@SECLEVEL=1";
tunnel->config->cipher_list = strdup(cipher_list);
}
}
if (tunnel->config->cipher_list) {
log_debug("Setting cipher list to: %s\n", tunnel->config->cipher_list);
if (!SSL_set_cipher_list(tunnel->ssl_handle,
tunnel->config->cipher_list)) {
log_error("SSL_set_cipher_list failed: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (tunnel->config->min_tls > 0) {
log_debug("Setting min proto version to: 0x%x\n",
tunnel->config->min_tls);
if (!SSL_set_min_proto_version(tunnel->ssl_handle,
tunnel->config->min_tls)) {
log_error("SSL_set_min_proto_version failed: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
#endif
if (!SSL_set_fd(tunnel->ssl_handle, tunnel->ssl_socket)) {
log_error("SSL_set_fd: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
SSL_set_mode(tunnel->ssl_handle, SSL_MODE_AUTO_RETRY);
// Initiate SSL handshake
if (SSL_connect(tunnel->ssl_handle) != 1) {
log_error("SSL_connect: %s\n"
"You might want to try --insecure-ssl or specify a different --cipher-list\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
SSL_set_mode(tunnel->ssl_handle, SSL_MODE_AUTO_RETRY);
if (ssl_verify_cert(tunnel))
return 1;
// Disable SIGPIPE (occurs when trying to write to an already-closed
// socket).
signal(SIGPIPE, SIG_IGN);
return 0;
}
int run_tunnel(struct vpn_config *config)
{
int ret;
struct tunnel tunnel = {
.config = config,
.state = STATE_DOWN,
.ssl_context = NULL,
.ssl_handle = NULL,
.ipv4.ns1_addr.s_addr = 0,
.ipv4.ns2_addr.s_addr = 0,
.ipv4.dns_suffix = NULL,
.on_ppp_if_up = on_ppp_if_up,
.on_ppp_if_down = on_ppp_if_down
};
// Step 0: get gateway host IP
log_debug("Resolving gateway host ip\n");
ret = get_gateway_host_ip(&tunnel);
if (ret)
goto err_tunnel;
// Step 1: open a SSL connection to the gateway
log_debug("Establishing ssl connection\n");
ret = ssl_connect(&tunnel);
if (ret)
goto err_tunnel;
log_info("Connected to gateway.\n");
// Step 2: connect to the HTTP interface and authenticate to get a
// cookie
ret = auth_log_in(&tunnel);
if (ret != 1) {
log_error("Could not authenticate to gateway. Please check the password, client certificate, etc.\n");
log_debug("%s %d\n", err_http_str(ret), ret);
ret = 1;
goto err_tunnel;
}
log_info("Authenticated.\n");
log_debug("Cookie: %s\n", tunnel.cookie);
ret = auth_request_vpn_allocation(&tunnel);
if (ret != 1) {
log_error("VPN allocation request failed (%s).\n",
err_http_str(ret));
ret = 1;
goto err_tunnel;
}
log_info("Remote gateway has allocated a VPN.\n");
ret = ssl_connect(&tunnel);
if (ret)
goto err_tunnel;
// Step 3: get configuration
log_debug("Retrieving configuration\n");
ret = auth_get_config(&tunnel);
if (ret != 1) {
log_error("Could not get VPN configuration (%s).\n",
err_http_str(ret));
ret = 1;
goto err_tunnel;
}
// Step 4: run a pppd process
log_debug("Establishing the tunnel\n");
ret = pppd_run(&tunnel);
if (ret)
goto err_tunnel;
// Step 5: ask gateway to start tunneling
log_debug("Switch to tunneling mode\n");
ret = http_send(&tunnel,
"GET /remote/sslvpn-tunnel HTTP/1.1\r\n"
"Host: sslvpn\r\n"
"Cookie: %s\r\n\r\n",
tunnel.cookie);
if (ret != 1) {
log_error("Could not start tunnel (%s).\n", err_http_str(ret));
ret = 1;
goto err_start_tunnel;
}
tunnel.state = STATE_CONNECTING;
ret = 0;
// Step 6: perform io between pppd and the gateway, while tunnel is up
log_debug("Starting IO through the tunnel\n");
io_loop(&tunnel);
log_debug("disconnecting\n");
if (tunnel.state == STATE_UP)
if (tunnel.on_ppp_if_down != NULL)
tunnel.on_ppp_if_down(&tunnel);
tunnel.state = STATE_DISCONNECTING;
err_start_tunnel:
pppd_terminate(&tunnel);
log_info("Terminated %s.\n", PPP_DAEMON);
err_tunnel:
log_info("Closed connection to gateway.\n");
tunnel.state = STATE_DOWN;
if (ssl_connect(&tunnel)) {
log_info("Could not log out.\n");
} else {
auth_log_out(&tunnel);
log_info("Logged out.\n");
}
// explicitly free the buffer allocated for split routes of the ipv4 config
if (tunnel.ipv4.split_rt != NULL) {
free(tunnel.ipv4.split_rt);
tunnel.ipv4.split_rt = NULL;
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-295/c/good_4599_0 |
crossvul-cpp_data_good_4597_0 | /*
* Copyright (C) 2015 Adrien Vergé
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* In addition, as a special exception, the copyright holders give permission
* to link the code of portions of this program with the OpenSSL library under
* certain conditions as described in each individual source file, and
* distribute linked combinations including the two.
* You must obey the GNU General Public License in all respects for all of the
* code used other than OpenSSL. If you modify file(s) with this exception,
* you may extend this exception to your version of the file(s), but you are
* not obligated to do so. If you do not wish to do so, delete this exception
* statement from your version. If you delete this exception statement from
* all source files in the program, then also delete it here.
*/
#include "tunnel.h"
#include "http.h"
#include "log.h"
#include <unistd.h>
#include <fcntl.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <errno.h>
#include <string.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <openssl/err.h>
#include <openssl/x509v3.h>
#include <openssl/engine.h>
#if HAVE_PTY_H
#include <pty.h>
#elif HAVE_UTIL_H
#include <util.h>
#endif
#include <termios.h>
#include <signal.h>
#include <sys/wait.h>
#if HAVE_SYSTEMD
#include <systemd/sd-daemon.h>
#endif
// we use this constant in the source, so define a fallback if not defined
#ifndef OPENSSL_API_COMPAT
#define OPENSSL_API_COMPAT 0x0908000L
#endif
struct ofv_varr {
unsigned int cap; // current capacity
unsigned int off; // next slot to write, always < max(cap - 1, 1)
const char **data; // NULL terminated
};
static int ofv_append_varr(struct ofv_varr *p, const char *x)
{
if (p->off + 1 >= p->cap) {
const char **ndata;
unsigned int ncap = (p->off + 1) * 2;
if (p->off + 1 >= ncap) {
log_error("%s: ncap exceeded\n", __func__);
return 1;
};
ndata = realloc(p->data, ncap * sizeof(const char *));
if (ndata) {
p->data = ndata;
p->cap = ncap;
} else {
log_error("realloc: %s\n", strerror(errno));
return 1;
}
}
if (p->data == NULL) {
log_error("%s: NULL data\n", __func__);
return 1;
}
if (p->off + 1 >= p->cap) {
log_error("%s: cap exceeded in p\n", __func__);
return 1;
}
p->data[p->off] = x;
p->data[++p->off] = NULL;
return 0;
}
static int on_ppp_if_up(struct tunnel *tunnel)
{
log_info("Interface %s is UP.\n", tunnel->ppp_iface);
if (tunnel->config->set_routes) {
int ret;
log_info("Setting new routes...\n");
ret = ipv4_set_tunnel_routes(tunnel);
if (ret != 0)
log_warn("Adding route table is incomplete. Please check route table.\n");
}
if (tunnel->config->set_dns) {
log_info("Adding VPN nameservers...\n");
ipv4_add_nameservers_to_resolv_conf(tunnel);
}
log_info("Tunnel is up and running.\n");
#if HAVE_SYSTEMD
sd_notify(0, "READY=1");
#endif
return 0;
}
static int on_ppp_if_down(struct tunnel *tunnel)
{
log_info("Setting ppp interface down.\n");
if (tunnel->config->set_routes) {
log_info("Restoring routes...\n");
ipv4_restore_routes(tunnel);
}
if (tunnel->config->set_dns) {
log_info("Removing VPN nameservers...\n");
ipv4_del_nameservers_from_resolv_conf(tunnel);
}
return 0;
}
static int pppd_run(struct tunnel *tunnel)
{
pid_t pid;
int amaster;
int slave_stderr;
#ifdef HAVE_STRUCT_TERMIOS
struct termios termp = {
.c_cflag = B9600,
.c_cc[VTIME] = 0,
.c_cc[VMIN] = 1
};
#endif
static const char ppp_path[] = PPP_PATH;
if (access(ppp_path, F_OK) != 0) {
log_error("%s: %s.\n", ppp_path, strerror(errno));
return 1;
}
log_debug("ppp_path: %s\n", ppp_path);
slave_stderr = dup(STDERR_FILENO);
if (slave_stderr < 0) {
log_error("slave stderr %s\n", strerror(errno));
return 1;
}
#ifdef HAVE_STRUCT_TERMIOS
pid = forkpty(&amaster, NULL, &termp, NULL);
#else
pid = forkpty(&amaster, NULL, NULL, NULL);
#endif
if (pid == 0) { // child process
struct ofv_varr pppd_args = { 0, 0, NULL };
dup2(slave_stderr, STDERR_FILENO);
close(slave_stderr);
#if HAVE_USR_SBIN_PPP
/*
* assume there is a default configuration to start.
* Support for taking options from the command line
* e.g. the name of the configuration or options
* to send interactively to ppp will be added later
*/
static const char *const v[] = {
ppp_path,
"-direct"
};
for (unsigned int i = 0; i < ARRAY_SIZE(v); i++)
if (ofv_append_varr(&pppd_args, v[i]))
return 1;
#endif
#if HAVE_USR_SBIN_PPPD
if (tunnel->config->pppd_call) {
if (ofv_append_varr(&pppd_args, ppp_path))
return 1;
if (ofv_append_varr(&pppd_args, "call"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_call))
return 1;
} else {
static const char *const v[] = {
ppp_path,
"115200", // speed
":192.0.2.1", // <local_IP_address>:<remote_IP_address>
"noipdefault",
"noaccomp",
"noauth",
"default-asyncmap",
"nopcomp",
"receive-all",
"nodefaultroute",
"nodetach",
"lcp-max-configure", "40",
"mru", "1354"
};
for (unsigned int i = 0; i < ARRAY_SIZE(v); i++)
if (ofv_append_varr(&pppd_args, v[i]))
return 1;
}
if (tunnel->config->pppd_use_peerdns)
if (ofv_append_varr(&pppd_args, "usepeerdns"))
return 1;
if (tunnel->config->pppd_log) {
if (ofv_append_varr(&pppd_args, "debug"))
return 1;
if (ofv_append_varr(&pppd_args, "logfile"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_log))
return 1;
} else {
/*
* pppd defaults to logging to fd=1, clobbering the
* actual PPP data
*/
if (ofv_append_varr(&pppd_args, "logfd"))
return 1;
if (ofv_append_varr(&pppd_args, "2"))
return 1;
}
if (tunnel->config->pppd_plugin) {
if (ofv_append_varr(&pppd_args, "plugin"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_plugin))
return 1;
}
if (tunnel->config->pppd_ipparam) {
if (ofv_append_varr(&pppd_args, "ipparam"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_ipparam))
return 1;
}
if (tunnel->config->pppd_ifname) {
if (ofv_append_varr(&pppd_args, "ifname"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_ifname))
return 1;
}
#endif
#if HAVE_USR_SBIN_PPP
if (tunnel->config->ppp_system) {
if (ofv_append_varr(&pppd_args, tunnel->config->ppp_system))
return 1;
}
#endif
close(tunnel->ssl_socket);
execv(pppd_args.data[0], (char *const *)pppd_args.data);
free(pppd_args.data);
fprintf(stderr, "execvp: %s\n", strerror(errno));
_exit(EXIT_FAILURE);
} else {
close(slave_stderr);
if (pid == -1) {
log_error("forkpty: %s\n", strerror(errno));
return 1;
}
}
// Set non-blocking
int flags = fcntl(amaster, F_GETFL, 0);
if (flags == -1)
flags = 0;
if (fcntl(amaster, F_SETFL, flags | O_NONBLOCK) == -1) {
log_error("fcntl: %s\n", strerror(errno));
return 1;
}
tunnel->pppd_pid = pid;
tunnel->pppd_pty = amaster;
return 0;
}
static const char * const pppd_message[] = {
"Has detached, or otherwise the connection was successfully established and terminated at the peer's request.",
"An immediately fatal error of some kind occurred, such as an essential system call failing, or running out of virtual memory.",
"An error was detected in processing the options given, such as two mutually exclusive options being used.",
"Is not setuid-root and the invoking user is not root.",
"The kernel does not support PPP, for example, the PPP kernel driver is not included or cannot be loaded.",
"Terminated because it was sent a SIGINT, SIGTERM or SIGHUP signal.",
"The serial port could not be locked.",
"The serial port could not be opened.",
"The connect script failed (returned a non-zero exit status).",
"The command specified as the argument to the pty option could not be run.",
"The PPP negotiation failed, that is, it didn't reach the point where at least one network protocol (e.g. IP) was running.",
"The peer system failed (or refused) to authenticate itself.",
"The link was established successfully and terminated because it was idle.",
"The link was established successfully and terminated because the connect time limit was reached.",
"Callback was negotiated and an incoming call should arrive shortly.",
"The link was terminated because the peer is not responding to echo requests.",
"The link was terminated by the modem hanging up.",
"The PPP negotiation failed because serial loopback was detected.",
"The init script failed (returned a non-zero exit status).",
"We failed to authenticate ourselves to the peer."
};
static int pppd_terminate(struct tunnel *tunnel)
{
close(tunnel->pppd_pty);
log_debug("Waiting for %s to exit...\n", PPP_DAEMON);
int status;
if (waitpid(tunnel->pppd_pid, &status, 0) == -1) {
log_error("waitpid: %s\n", strerror(errno));
return 1;
}
if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
log_debug("waitpid: %s exit status code %d\n",
PPP_DAEMON, exit_status);
#if HAVE_USR_SBIN_PPPD
if (exit_status >= ARRAY_SIZE(pppd_message) || exit_status < 0) {
log_error("%s: Returned an unknown exit status: %d\n",
PPP_DAEMON, exit_status);
} else {
switch (exit_status) {
case 0: // success
log_debug("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
case 16: // emitted when exiting normally
log_info("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
default:
log_error("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
}
}
#else
// ppp exit codes in the FreeBSD case
switch (exit_status) {
case 0: // success and EX_NORMAL as defined in ppp source directly
log_debug("%s: %s\n", PPP_DAEMON, pppd_message[exit_status]);
break;
case 1:
case 127:
case 255: // abnormal exit with hard-coded error codes in ppp
log_error("%s: exited with return value of %d\n",
PPP_DAEMON, exit_status);
break;
default:
log_error("%s: %s (%d)\n", PPP_DAEMON, strerror(exit_status),
exit_status);
break;
}
#endif
} else if (WIFSIGNALED(status)) {
int signal_number = WTERMSIG(status);
log_debug("waitpid: %s terminated by signal %d\n",
PPP_DAEMON, signal_number);
log_error("%s: terminated by signal: %s\n",
PPP_DAEMON, strsignal(signal_number));
}
return 0;
}
int ppp_interface_is_up(struct tunnel *tunnel)
{
struct ifaddrs *ifap, *ifa;
log_debug("Got Address: %s\n", inet_ntoa(tunnel->ipv4.ip_addr));
if (getifaddrs(&ifap)) {
log_error("getifaddrs: %s\n", strerror(errno));
return 0;
}
for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
if ((
#if HAVE_USR_SBIN_PPPD
(tunnel->config->pppd_ifname
&& strstr(ifa->ifa_name, tunnel->config->pppd_ifname)
!= NULL)
|| strstr(ifa->ifa_name, "ppp") != NULL
#endif
#if HAVE_USR_SBIN_PPP
strstr(ifa->ifa_name, "tun") != NULL
#endif
) && ifa->ifa_flags & IFF_UP) {
if (&(ifa->ifa_addr->sa_family) != NULL
&& ifa->ifa_addr->sa_family == AF_INET) {
struct in_addr if_ip_addr =
cast_addr(ifa->ifa_addr)->sin_addr;
log_debug("Interface Name: %s\n", ifa->ifa_name);
log_debug("Interface Addr: %s\n", inet_ntoa(if_ip_addr));
if (tunnel->ipv4.ip_addr.s_addr == if_ip_addr.s_addr) {
strncpy(tunnel->ppp_iface, ifa->ifa_name,
ROUTE_IFACE_LEN - 1);
freeifaddrs(ifap);
return 1;
}
}
}
}
freeifaddrs(ifap);
return 0;
}
static int get_gateway_host_ip(struct tunnel *tunnel)
{
const struct addrinfo hints = { .ai_family = AF_INET };
struct addrinfo *result = NULL;
int ret = getaddrinfo(tunnel->config->gateway_host, NULL, &hints, &result);
if (ret) {
if (ret == EAI_SYSTEM)
log_error("getaddrinfo: %s\n", strerror(errno));
else
log_error("getaddrinfo: %s\n", gai_strerror(ret));
return 1;
}
tunnel->config->gateway_ip = ((struct sockaddr_in *)
result->ai_addr)->sin_addr;
freeaddrinfo(result);
setenv("VPN_GATEWAY", inet_ntoa(tunnel->config->gateway_ip), 0);
return 0;
}
/*
* Establish a regular TCP connection.
*/
static int tcp_connect(struct tunnel *tunnel)
{
int ret, handle;
struct sockaddr_in server;
char *env_proxy;
handle = socket(AF_INET, SOCK_STREAM, 0);
if (handle == -1) {
log_error("socket: %s\n", strerror(errno));
goto err_socket;
}
env_proxy = getenv("https_proxy");
if (env_proxy == NULL)
env_proxy = getenv("HTTPS_PROXY");
if (env_proxy == NULL)
env_proxy = getenv("all_proxy");
if (env_proxy == NULL)
env_proxy = getenv("ALL_PROXY");
if (env_proxy != NULL) {
char *proxy_host, *proxy_port;
// protect the original environment from modifications
env_proxy = strdup(env_proxy);
if (env_proxy == NULL) {
log_error("strdup: %s\n", strerror(errno));
goto err_strdup;
}
// get rid of a trailing slash
if (*env_proxy && env_proxy[strlen(env_proxy) - 1] == '/')
env_proxy[strlen(env_proxy) - 1] = '\0';
// get rid of a http(s):// prefix in env_proxy
proxy_host = strstr(env_proxy, "://");
if (proxy_host == NULL)
proxy_host = env_proxy;
else
proxy_host += 3;
// split host and port
proxy_port = index(proxy_host, ':');
if (proxy_port != NULL) {
proxy_port[0] = '\0';
proxy_port++;
server.sin_port = htons(strtoul(proxy_port, NULL, 10));
} else {
server.sin_port = htons(tunnel->config->gateway_port);
}
// get rid of a trailing slash
if (*proxy_host && proxy_host[strlen(proxy_host) - 1] == '/')
proxy_host[strlen(proxy_host) - 1] = '\0';
log_debug("proxy_host: %s\n", proxy_host);
log_debug("proxy_port: %s\n", proxy_port);
server.sin_addr.s_addr = inet_addr(proxy_host);
// if host is given as a FQDN we have to do a DNS lookup
if (server.sin_addr.s_addr == INADDR_NONE) {
const struct addrinfo hints = { .ai_family = AF_INET };
struct addrinfo *result = NULL;
ret = getaddrinfo(proxy_host, NULL, &hints, &result);
if (ret) {
if (ret == EAI_SYSTEM)
log_error("getaddrinfo: %s\n", strerror(errno));
else
log_error("getaddrinfo: %s\n", gai_strerror(ret));
goto err_connect;
}
server.sin_addr = ((struct sockaddr_in *)
result->ai_addr)->sin_addr;
freeaddrinfo(result);
}
} else {
server.sin_port = htons(tunnel->config->gateway_port);
server.sin_addr = tunnel->config->gateway_ip;
}
log_debug("server_addr: %s\n", inet_ntoa(server.sin_addr));
log_debug("server_port: %u\n", ntohs(server.sin_port));
server.sin_family = AF_INET;
memset(&(server.sin_zero), '\0', 8);
log_debug("gateway_addr: %s\n", inet_ntoa(tunnel->config->gateway_ip));
log_debug("gateway_port: %u\n", tunnel->config->gateway_port);
ret = connect(handle, (struct sockaddr *) &server, sizeof(server));
if (ret) {
log_error("connect: %s\n", strerror(errno));
goto err_connect;
}
if (env_proxy != NULL) {
char request[128];
// https://tools.ietf.org/html/rfc7231#section-4.3.6
sprintf(request, "CONNECT %s:%u HTTP/1.1\r\nHost: %s:%u\r\n\r\n",
inet_ntoa(tunnel->config->gateway_ip),
tunnel->config->gateway_port,
inet_ntoa(tunnel->config->gateway_ip),
tunnel->config->gateway_port);
ssize_t bytes_written = write(handle, request, strlen(request));
if (bytes_written != strlen(request)) {
log_error("write error while talking to proxy: %s\n",
strerror(errno));
goto err_connect;
}
// wait for a "200 OK" reply from the proxy,
// be careful not to fetch too many bytes at once
const char *response = NULL;
memset(&(request), '\0', sizeof(request));
for (int j = 0; response == NULL; j++) {
/*
* Coverity detected a defect:
* CID 200508: String not null terminated (STRING_NULL)
*
* It is actually a false positive:
* • Function memset() initializes 'request' with '\0'
* • Function read() gets a single char into: request[j]
* • The final '\0' cannot be overwritten because:
* j < ARRAY_SIZE(request) - 1
*/
ssize_t bytes_read = read(handle, &(request[j]), 1);
if (bytes_read < 1) {
log_error("Proxy response is unexpectedly large and cannot fit in the %lu-bytes buffer.\n",
ARRAY_SIZE(request));
goto err_proxy_response;
}
// detect "200"
static const char HTTP_STATUS_200[] = "200";
response = strstr(request, HTTP_STATUS_200);
// detect end-of-line after "200"
if (response != NULL) {
/*
* RFC2616 states in section 2.2 Basic Rules:
* CR = <US-ASCII CR, carriage return (13)>
* LF = <US-ASCII LF, linefeed (10)>
* HTTP/1.1 defines the sequence CR LF as the
* end-of-line marker for all protocol elements
* except the entity-body (see appendix 19.3
* for tolerant applications).
* CRLF = CR LF
*
* RFC2616 states in section 19.3 Tolerant Applications:
* The line terminator for message-header fields
* is the sequence CRLF. However, we recommend
* that applications, when parsing such headers,
* recognize a single LF as a line terminator
* and ignore the leading CR.
*/
static const char *const HTTP_EOL[] = {
"\r\n\r\n",
"\n\n"
};
const char *eol = NULL;
for (int i = 0; (i < ARRAY_SIZE(HTTP_EOL)) &&
(eol == NULL); i++)
eol = strstr(response, HTTP_EOL[i]);
response = eol;
}
if (j > ARRAY_SIZE(request) - 2) {
log_error("Proxy response does not contain \"%s\" as expected.\n",
HTTP_STATUS_200);
goto err_proxy_response;
}
}
free(env_proxy); // release memory allocated by strdup()
}
return handle;
err_proxy_response:
err_connect:
free(env_proxy); // release memory allocated by strdup()
err_strdup:
close(handle);
err_socket:
return -1;
}
static int ssl_verify_cert(struct tunnel *tunnel)
{
int ret = -1;
int cert_valid = 0;
unsigned char digest[SHA256LEN];
unsigned int len;
struct x509_digest *elem;
char digest_str[SHA256STRLEN], *subject, *issuer;
char *line;
int i;
X509_NAME *subj;
char common_name[FIELD_SIZE + 1];
SSL_set_verify(tunnel->ssl_handle, SSL_VERIFY_PEER, NULL);
X509 *cert = SSL_get_peer_certificate(tunnel->ssl_handle);
if (cert == NULL) {
log_error("Unable to get gateway certificate.\n");
return 1;
}
subj = X509_get_subject_name(cert);
#ifdef HAVE_X509_CHECK_HOST
// Use OpenSSL native host validation if v >= 1.0.2.
// correctly check return value of X509_check_host
if (X509_check_host(cert, common_name, FIELD_SIZE, 0, NULL) == 1)
cert_valid = 1;
#else
// Use explicit Common Name check if native validation not available.
// Note: this will ignore Subject Alternative Name fields.
if (subj
&& X509_NAME_get_text_by_NID(subj, NID_commonName, common_name,
FIELD_SIZE) > 0
&& strncasecmp(common_name, tunnel->config->gateway_host,
FIELD_SIZE) == 0)
cert_valid = 1;
#endif
// Try to validate certificate using local PKI
if (cert_valid
&& SSL_get_verify_result(tunnel->ssl_handle) == X509_V_OK) {
log_debug("Gateway certificate validation succeeded.\n");
ret = 0;
goto free_cert;
}
log_debug("Gateway certificate validation failed.\n");
// If validation failed, check if cert is in the white list
if (X509_digest(cert, EVP_sha256(), digest, &len) <= 0
|| len != SHA256LEN) {
log_error("Could not compute certificate sha256 digest.\n");
goto free_cert;
}
// Encode digest in base16
for (i = 0; i < SHA256LEN; i++)
sprintf(&digest_str[2 * i], "%02x", digest[i]);
digest_str[SHA256STRLEN - 1] = '\0';
// Is it in whitelist?
for (elem = tunnel->config->cert_whitelist; elem != NULL;
elem = elem->next)
if (memcmp(digest_str, elem->data, SHA256STRLEN - 1) == 0)
break;
if (elem != NULL) { // break before end of loop
log_debug("Gateway certificate digest found in white list.\n");
ret = 0;
goto free_cert;
}
subject = X509_NAME_oneline(subj, NULL, 0);
issuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
log_error("Gateway certificate validation failed, and the certificate digest in not in the local whitelist. If you trust it, rerun with:\n");
log_error(" --trusted-cert %s\n", digest_str);
log_error("or add this line to your config file:\n");
log_error(" trusted-cert = %s\n", digest_str);
log_error("Gateway certificate:\n");
log_error(" subject:\n");
for (line = strtok(subject, "/"); line != NULL;
line = strtok(NULL, "/"))
log_error(" %s\n", line);
log_error(" issuer:\n");
for (line = strtok(issuer, "/"); line != NULL;
line = strtok(NULL, "/"))
log_error(" %s\n", line);
log_error(" sha256 digest:\n");
log_error(" %s\n", digest_str);
free_cert:
X509_free(cert);
return ret;
}
/*
* Destroy and free the SSL connection to the gateway.
*/
static void ssl_disconnect(struct tunnel *tunnel)
{
if (!tunnel->ssl_handle)
return;
SSL_shutdown(tunnel->ssl_handle);
SSL_free(tunnel->ssl_handle);
SSL_CTX_free(tunnel->ssl_context);
close(tunnel->ssl_socket);
tunnel->ssl_handle = NULL;
tunnel->ssl_context = NULL;
}
/*
* Connects to the gateway and initiate an SSL session.
*/
int ssl_connect(struct tunnel *tunnel)
{
ssl_disconnect(tunnel);
tunnel->ssl_socket = tcp_connect(tunnel);
if (tunnel->ssl_socket == -1)
return 1;
// registration is deprecated from OpenSSL 1.1.0 onward
#if OPENSSL_API_COMPAT < 0x10100000L
// Register the error strings for libcrypto & libssl
SSL_load_error_strings();
// Register the available ciphers and digests
SSL_library_init();
#endif
tunnel->ssl_context = SSL_CTX_new(SSLv23_client_method());
if (tunnel->ssl_context == NULL) {
log_error("SSL_CTX_new: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
// Load the OS default CA files
if (!SSL_CTX_set_default_verify_paths(tunnel->ssl_context))
log_error("Could not load OS OpenSSL files.\n");
if (tunnel->config->ca_file) {
if (!SSL_CTX_load_verify_locations(
tunnel->ssl_context,
tunnel->config->ca_file, NULL)) {
log_error("SSL_CTX_load_verify_locations: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
/* Use engine for PIV if user-cert config starts with pkcs11 URI: */
if (tunnel->config->use_engine > 0) {
ENGINE *e;
ENGINE_load_builtin_engines();
e = ENGINE_by_id("pkcs11");
if (!e) {
log_error("Could not load pkcs11 Engine: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!ENGINE_init(e)) {
log_error("Could not init pkcs11 Engine: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
ENGINE_free(e);
return 1;
}
if (!ENGINE_set_default_RSA(e))
abort();
ENGINE_finish(e);
ENGINE_free(e);
struct token parms;
parms.uri = tunnel->config->user_cert;
parms.cert = NULL;
if (!ENGINE_ctrl_cmd(e, "LOAD_CERT_CTRL", 0, &parms, NULL, 1)) {
log_error("PKCS11 ENGINE_ctrl_cmd: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_use_certificate(tunnel->ssl_context, parms.cert)) {
log_error("PKCS11 SSL_CTX_use_certificate: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
EVP_PKEY * privkey = ENGINE_load_private_key(
e, parms.uri, UI_OpenSSL(), NULL);
if (!privkey) {
log_error("PKCS11 ENGINE_load_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_use_PrivateKey(tunnel->ssl_context, privkey)) {
log_error("PKCS11 SSL_CTX_use_PrivateKey_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_check_private_key(tunnel->ssl_context)) {
log_error("PKCS11 SSL_CTX_check_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
} else { /* end PKCS11-engine */
if (tunnel->config->user_cert) {
if (!SSL_CTX_use_certificate_file(
tunnel->ssl_context, tunnel->config->user_cert,
SSL_FILETYPE_PEM)) {
log_error("SSL_CTX_use_certificate_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
if (tunnel->config->user_key) {
if (!SSL_CTX_use_PrivateKey_file(
tunnel->ssl_context, tunnel->config->user_key,
SSL_FILETYPE_PEM)) {
log_error("SSL_CTX_use_PrivateKey_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
if (tunnel->config->user_cert && tunnel->config->user_key) {
if (!SSL_CTX_check_private_key(tunnel->ssl_context)) {
log_error("SSL_CTX_check_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
}
if (!tunnel->config->insecure_ssl) {
long sslctxopt = SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
long checkopt;
checkopt = SSL_CTX_set_options(tunnel->ssl_context, sslctxopt);
if ((checkopt & sslctxopt) != sslctxopt) {
log_error("SSL_CTX_set_options didn't set opt: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
tunnel->ssl_handle = SSL_new(tunnel->ssl_context);
if (tunnel->ssl_handle == NULL) {
log_error("SSL_new: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!tunnel->config->insecure_ssl) {
if (!tunnel->config->cipher_list) {
const char *cipher_list;
if (tunnel->config->seclevel_1)
cipher_list = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4@SECLEVEL=1";
else
cipher_list = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4";
tunnel->config->cipher_list = strdup(cipher_list);
}
} else {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (tunnel->config->min_tls <= 0)
tunnel->config->min_tls = TLS1_VERSION;
#endif
if (!tunnel->config->cipher_list && tunnel->config->seclevel_1) {
const char *cipher_list = "DEFAULT@SECLEVEL=1";
tunnel->config->cipher_list = strdup(cipher_list);
}
}
if (tunnel->config->cipher_list) {
log_debug("Setting cipher list to: %s\n", tunnel->config->cipher_list);
if (!SSL_set_cipher_list(tunnel->ssl_handle,
tunnel->config->cipher_list)) {
log_error("SSL_set_cipher_list failed: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (tunnel->config->min_tls > 0) {
log_debug("Setting min proto version to: 0x%x\n",
tunnel->config->min_tls);
if (!SSL_set_min_proto_version(tunnel->ssl_handle,
tunnel->config->min_tls)) {
log_error("SSL_set_min_proto_version failed: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
#endif
if (!SSL_set_fd(tunnel->ssl_handle, tunnel->ssl_socket)) {
log_error("SSL_set_fd: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
SSL_set_mode(tunnel->ssl_handle, SSL_MODE_AUTO_RETRY);
// Initiate SSL handshake
if (SSL_connect(tunnel->ssl_handle) != 1) {
log_error("SSL_connect: %s\n"
"You might want to try --insecure-ssl or specify a different --cipher-list\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
SSL_set_mode(tunnel->ssl_handle, SSL_MODE_AUTO_RETRY);
if (ssl_verify_cert(tunnel))
return 1;
// Disable SIGPIPE (occurs when trying to write to an already-closed
// socket).
signal(SIGPIPE, SIG_IGN);
return 0;
}
int run_tunnel(struct vpn_config *config)
{
int ret;
struct tunnel tunnel = {
.config = config,
.state = STATE_DOWN,
.ssl_context = NULL,
.ssl_handle = NULL,
.ipv4.ns1_addr.s_addr = 0,
.ipv4.ns2_addr.s_addr = 0,
.ipv4.dns_suffix = NULL,
.on_ppp_if_up = on_ppp_if_up,
.on_ppp_if_down = on_ppp_if_down
};
// Step 0: get gateway host IP
log_debug("Resolving gateway host ip\n");
ret = get_gateway_host_ip(&tunnel);
if (ret)
goto err_tunnel;
// Step 1: open a SSL connection to the gateway
log_debug("Establishing ssl connection\n");
ret = ssl_connect(&tunnel);
if (ret)
goto err_tunnel;
log_info("Connected to gateway.\n");
// Step 2: connect to the HTTP interface and authenticate to get a
// cookie
ret = auth_log_in(&tunnel);
if (ret != 1) {
log_error("Could not authenticate to gateway. Please check the password, client certificate, etc.\n");
log_debug("%s %d\n", err_http_str(ret), ret);
ret = 1;
goto err_tunnel;
}
log_info("Authenticated.\n");
log_debug("Cookie: %s\n", tunnel.cookie);
ret = auth_request_vpn_allocation(&tunnel);
if (ret != 1) {
log_error("VPN allocation request failed (%s).\n",
err_http_str(ret));
ret = 1;
goto err_tunnel;
}
log_info("Remote gateway has allocated a VPN.\n");
ret = ssl_connect(&tunnel);
if (ret)
goto err_tunnel;
// Step 3: get configuration
log_debug("Retrieving configuration\n");
ret = auth_get_config(&tunnel);
if (ret != 1) {
log_error("Could not get VPN configuration (%s).\n",
err_http_str(ret));
ret = 1;
goto err_tunnel;
}
// Step 4: run a pppd process
log_debug("Establishing the tunnel\n");
ret = pppd_run(&tunnel);
if (ret)
goto err_tunnel;
// Step 5: ask gateway to start tunneling
log_debug("Switch to tunneling mode\n");
ret = http_send(&tunnel,
"GET /remote/sslvpn-tunnel HTTP/1.1\r\n"
"Host: sslvpn\r\n"
"Cookie: %s\r\n\r\n",
tunnel.cookie);
if (ret != 1) {
log_error("Could not start tunnel (%s).\n", err_http_str(ret));
ret = 1;
goto err_start_tunnel;
}
tunnel.state = STATE_CONNECTING;
ret = 0;
// Step 6: perform io between pppd and the gateway, while tunnel is up
log_debug("Starting IO through the tunnel\n");
io_loop(&tunnel);
log_debug("disconnecting\n");
if (tunnel.state == STATE_UP)
if (tunnel.on_ppp_if_down != NULL)
tunnel.on_ppp_if_down(&tunnel);
tunnel.state = STATE_DISCONNECTING;
err_start_tunnel:
pppd_terminate(&tunnel);
log_info("Terminated %s.\n", PPP_DAEMON);
err_tunnel:
log_info("Closed connection to gateway.\n");
tunnel.state = STATE_DOWN;
if (ssl_connect(&tunnel)) {
log_info("Could not log out.\n");
} else {
auth_log_out(&tunnel);
log_info("Logged out.\n");
}
// explicitly free the buffer allocated for split routes of the ipv4 config
if (tunnel.ipv4.split_rt != NULL) {
free(tunnel.ipv4.split_rt);
tunnel.ipv4.split_rt = NULL;
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-295/c/good_4597_0 |
crossvul-cpp_data_bad_3203_1 | /*
* Copyright (c) 1997-2008 Kungliga Tekniska Högskolan
* (Royal Institute of Technology, Stockholm, Sweden).
* 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 Institute 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 INSTITUTE 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 INSTITUTE 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.
*/
#include "kdc_locl.h"
/*
* return the realm of a krbtgt-ticket or NULL
*/
static Realm
get_krbtgt_realm(const PrincipalName *p)
{
if(p->name_string.len == 2
&& strcmp(p->name_string.val[0], KRB5_TGS_NAME) == 0)
return p->name_string.val[1];
else
return NULL;
}
/*
* The KDC might add a signed path to the ticket authorization data
* field. This is to avoid server impersonating clients and the
* request constrained delegation.
*
* This is done by storing a KRB5_AUTHDATA_IF_RELEVANT with a single
* entry of type KRB5SignedPath.
*/
static krb5_error_code
find_KRB5SignedPath(krb5_context context,
const AuthorizationData *ad,
krb5_data *data)
{
AuthorizationData child;
krb5_error_code ret;
int pos;
if (ad == NULL || ad->len == 0)
return KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
pos = ad->len - 1;
if (ad->val[pos].ad_type != KRB5_AUTHDATA_IF_RELEVANT)
return KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
ret = decode_AuthorizationData(ad->val[pos].ad_data.data,
ad->val[pos].ad_data.length,
&child,
NULL);
if (ret) {
krb5_set_error_message(context, ret, "Failed to decode "
"IF_RELEVANT with %d", ret);
return ret;
}
if (child.len != 1) {
free_AuthorizationData(&child);
return KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
}
if (child.val[0].ad_type != KRB5_AUTHDATA_SIGNTICKET) {
free_AuthorizationData(&child);
return KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
}
if (data)
ret = der_copy_octet_string(&child.val[0].ad_data, data);
free_AuthorizationData(&child);
return ret;
}
krb5_error_code
_kdc_add_KRB5SignedPath(krb5_context context,
krb5_kdc_configuration *config,
hdb_entry_ex *krbtgt,
krb5_enctype enctype,
krb5_principal client,
krb5_const_principal server,
krb5_principals principals,
EncTicketPart *tkt)
{
krb5_error_code ret;
KRB5SignedPath sp;
krb5_data data;
krb5_crypto crypto = NULL;
size_t size = 0;
if (server && principals) {
ret = add_Principals(principals, server);
if (ret)
return ret;
}
{
KRB5SignedPathData spd;
spd.client = client;
spd.authtime = tkt->authtime;
spd.delegated = principals;
spd.method_data = NULL;
ASN1_MALLOC_ENCODE(KRB5SignedPathData, data.data, data.length,
&spd, &size, ret);
if (ret)
return ret;
if (data.length != size)
krb5_abortx(context, "internal asn.1 encoder error");
}
{
Key *key;
ret = hdb_enctype2key(context, &krbtgt->entry, NULL, enctype, &key);
if (ret == 0)
ret = krb5_crypto_init(context, &key->key, 0, &crypto);
if (ret) {
free(data.data);
return ret;
}
}
/*
* Fill in KRB5SignedPath
*/
sp.etype = enctype;
sp.delegated = principals;
sp.method_data = NULL;
ret = krb5_create_checksum(context, crypto, KRB5_KU_KRB5SIGNEDPATH, 0,
data.data, data.length, &sp.cksum);
krb5_crypto_destroy(context, crypto);
free(data.data);
if (ret)
return ret;
ASN1_MALLOC_ENCODE(KRB5SignedPath, data.data, data.length, &sp, &size, ret);
free_Checksum(&sp.cksum);
if (ret)
return ret;
if (data.length != size)
krb5_abortx(context, "internal asn.1 encoder error");
/*
* Add IF-RELEVANT(KRB5SignedPath) to the last slot in
* authorization data field.
*/
ret = _kdc_tkt_add_if_relevant_ad(context, tkt,
KRB5_AUTHDATA_SIGNTICKET, &data);
krb5_data_free(&data);
return ret;
}
static krb5_error_code
check_KRB5SignedPath(krb5_context context,
krb5_kdc_configuration *config,
hdb_entry_ex *krbtgt,
krb5_principal cp,
EncTicketPart *tkt,
krb5_principals *delegated,
int *signedpath)
{
krb5_error_code ret;
krb5_data data;
krb5_crypto crypto = NULL;
if (delegated)
*delegated = NULL;
ret = find_KRB5SignedPath(context, tkt->authorization_data, &data);
if (ret == 0) {
KRB5SignedPathData spd;
KRB5SignedPath sp;
size_t size = 0;
ret = decode_KRB5SignedPath(data.data, data.length, &sp, NULL);
krb5_data_free(&data);
if (ret)
return ret;
spd.client = cp;
spd.authtime = tkt->authtime;
spd.delegated = sp.delegated;
spd.method_data = sp.method_data;
ASN1_MALLOC_ENCODE(KRB5SignedPathData, data.data, data.length,
&spd, &size, ret);
if (ret) {
free_KRB5SignedPath(&sp);
return ret;
}
if (data.length != size)
krb5_abortx(context, "internal asn.1 encoder error");
{
Key *key;
ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use correct kvno! */
sp.etype, &key);
if (ret == 0)
ret = krb5_crypto_init(context, &key->key, 0, &crypto);
if (ret) {
free(data.data);
free_KRB5SignedPath(&sp);
return ret;
}
}
ret = krb5_verify_checksum(context, crypto, KRB5_KU_KRB5SIGNEDPATH,
data.data, data.length,
&sp.cksum);
krb5_crypto_destroy(context, crypto);
free(data.data);
if (ret) {
free_KRB5SignedPath(&sp);
kdc_log(context, config, 5,
"KRB5SignedPath not signed correctly, not marking as signed");
return 0;
}
if (delegated && sp.delegated) {
*delegated = malloc(sizeof(*sp.delegated));
if (*delegated == NULL) {
free_KRB5SignedPath(&sp);
return ENOMEM;
}
ret = copy_Principals(*delegated, sp.delegated);
if (ret) {
free_KRB5SignedPath(&sp);
free(*delegated);
*delegated = NULL;
return ret;
}
}
free_KRB5SignedPath(&sp);
*signedpath = 1;
}
return 0;
}
/*
*
*/
static krb5_error_code
check_PAC(krb5_context context,
krb5_kdc_configuration *config,
const krb5_principal client_principal,
const krb5_principal delegated_proxy_principal,
hdb_entry_ex *client,
hdb_entry_ex *server,
hdb_entry_ex *krbtgt,
const EncryptionKey *server_check_key,
const EncryptionKey *server_sign_key,
const EncryptionKey *krbtgt_sign_key,
EncTicketPart *tkt,
krb5_data *rspac,
int *signedpath)
{
AuthorizationData *ad = tkt->authorization_data;
unsigned i, j;
krb5_error_code ret;
if (ad == NULL || ad->len == 0)
return 0;
for (i = 0; i < ad->len; i++) {
AuthorizationData child;
if (ad->val[i].ad_type != KRB5_AUTHDATA_IF_RELEVANT)
continue;
ret = decode_AuthorizationData(ad->val[i].ad_data.data,
ad->val[i].ad_data.length,
&child,
NULL);
if (ret) {
krb5_set_error_message(context, ret, "Failed to decode "
"IF_RELEVANT with %d", ret);
return ret;
}
for (j = 0; j < child.len; j++) {
if (child.val[j].ad_type == KRB5_AUTHDATA_WIN2K_PAC) {
int signed_pac = 0;
krb5_pac pac;
/* Found PAC */
ret = krb5_pac_parse(context,
child.val[j].ad_data.data,
child.val[j].ad_data.length,
&pac);
free_AuthorizationData(&child);
if (ret)
return ret;
ret = krb5_pac_verify(context, pac, tkt->authtime,
client_principal,
server_check_key, NULL);
if (ret) {
krb5_pac_free(context, pac);
return ret;
}
ret = _kdc_pac_verify(context, client_principal,
delegated_proxy_principal,
client, server, krbtgt, &pac, &signed_pac);
if (ret) {
krb5_pac_free(context, pac);
return ret;
}
/*
* Only re-sign PAC if we could verify it with the PAC
* function. The no-verify case happens when we get in
* a PAC from cross realm from a Windows domain and
* that there is no PAC verification function.
*/
if (signed_pac) {
*signedpath = 1;
ret = _krb5_pac_sign(context, pac, tkt->authtime,
client_principal,
server_sign_key, krbtgt_sign_key, rspac);
}
krb5_pac_free(context, pac);
return ret;
}
}
free_AuthorizationData(&child);
}
return 0;
}
/*
*
*/
static krb5_error_code
check_tgs_flags(krb5_context context,
krb5_kdc_configuration *config,
KDC_REQ_BODY *b, const EncTicketPart *tgt, EncTicketPart *et)
{
KDCOptions f = b->kdc_options;
if(f.validate){
if(!tgt->flags.invalid || tgt->starttime == NULL){
kdc_log(context, config, 0,
"Bad request to validate ticket");
return KRB5KDC_ERR_BADOPTION;
}
if(*tgt->starttime > kdc_time){
kdc_log(context, config, 0,
"Early request to validate ticket");
return KRB5KRB_AP_ERR_TKT_NYV;
}
/* XXX tkt = tgt */
et->flags.invalid = 0;
}else if(tgt->flags.invalid){
kdc_log(context, config, 0,
"Ticket-granting ticket has INVALID flag set");
return KRB5KRB_AP_ERR_TKT_INVALID;
}
if(f.forwardable){
if(!tgt->flags.forwardable){
kdc_log(context, config, 0,
"Bad request for forwardable ticket");
return KRB5KDC_ERR_BADOPTION;
}
et->flags.forwardable = 1;
}
if(f.forwarded){
if(!tgt->flags.forwardable){
kdc_log(context, config, 0,
"Request to forward non-forwardable ticket");
return KRB5KDC_ERR_BADOPTION;
}
et->flags.forwarded = 1;
et->caddr = b->addresses;
}
if(tgt->flags.forwarded)
et->flags.forwarded = 1;
if(f.proxiable){
if(!tgt->flags.proxiable){
kdc_log(context, config, 0,
"Bad request for proxiable ticket");
return KRB5KDC_ERR_BADOPTION;
}
et->flags.proxiable = 1;
}
if(f.proxy){
if(!tgt->flags.proxiable){
kdc_log(context, config, 0,
"Request to proxy non-proxiable ticket");
return KRB5KDC_ERR_BADOPTION;
}
et->flags.proxy = 1;
et->caddr = b->addresses;
}
if(tgt->flags.proxy)
et->flags.proxy = 1;
if(f.allow_postdate){
if(!tgt->flags.may_postdate){
kdc_log(context, config, 0,
"Bad request for post-datable ticket");
return KRB5KDC_ERR_BADOPTION;
}
et->flags.may_postdate = 1;
}
if(f.postdated){
if(!tgt->flags.may_postdate){
kdc_log(context, config, 0,
"Bad request for postdated ticket");
return KRB5KDC_ERR_BADOPTION;
}
if(b->from)
*et->starttime = *b->from;
et->flags.postdated = 1;
et->flags.invalid = 1;
}else if(b->from && *b->from > kdc_time + context->max_skew){
kdc_log(context, config, 0, "Ticket cannot be postdated");
return KRB5KDC_ERR_CANNOT_POSTDATE;
}
if(f.renewable){
if(!tgt->flags.renewable || tgt->renew_till == NULL){
kdc_log(context, config, 0,
"Bad request for renewable ticket");
return KRB5KDC_ERR_BADOPTION;
}
et->flags.renewable = 1;
ALLOC(et->renew_till);
_kdc_fix_time(&b->rtime);
*et->renew_till = *b->rtime;
}
if(f.renew){
time_t old_life;
if(!tgt->flags.renewable || tgt->renew_till == NULL){
kdc_log(context, config, 0,
"Request to renew non-renewable ticket");
return KRB5KDC_ERR_BADOPTION;
}
old_life = tgt->endtime;
if(tgt->starttime)
old_life -= *tgt->starttime;
else
old_life -= tgt->authtime;
et->endtime = *et->starttime + old_life;
if (et->renew_till != NULL)
et->endtime = min(*et->renew_till, et->endtime);
}
#if 0
/* checks for excess flags */
if(f.request_anonymous && !config->allow_anonymous){
kdc_log(context, config, 0,
"Request for anonymous ticket");
return KRB5KDC_ERR_BADOPTION;
}
#endif
return 0;
}
/*
* Determine if constrained delegation is allowed from this client to this server
*/
static krb5_error_code
check_constrained_delegation(krb5_context context,
krb5_kdc_configuration *config,
HDB *clientdb,
hdb_entry_ex *client,
hdb_entry_ex *server,
krb5_const_principal target)
{
const HDB_Ext_Constrained_delegation_acl *acl;
krb5_error_code ret;
size_t i;
/*
* constrained_delegation (S4U2Proxy) only works within
* the same realm. We use the already canonicalized version
* of the principals here, while "target" is the principal
* provided by the client.
*/
if(!krb5_realm_compare(context, client->entry.principal, server->entry.principal)) {
ret = KRB5KDC_ERR_BADOPTION;
kdc_log(context, config, 0,
"Bad request for constrained delegation");
return ret;
}
if (clientdb->hdb_check_constrained_delegation) {
ret = clientdb->hdb_check_constrained_delegation(context, clientdb, client, target);
if (ret == 0)
return 0;
} else {
/* if client delegates to itself, that ok */
if (krb5_principal_compare(context, client->entry.principal, server->entry.principal) == TRUE)
return 0;
ret = hdb_entry_get_ConstrainedDelegACL(&client->entry, &acl);
if (ret) {
krb5_clear_error_message(context);
return ret;
}
if (acl) {
for (i = 0; i < acl->len; i++) {
if (krb5_principal_compare(context, target, &acl->val[i]) == TRUE)
return 0;
}
}
ret = KRB5KDC_ERR_BADOPTION;
}
kdc_log(context, config, 0,
"Bad request for constrained delegation");
return ret;
}
/*
* Determine if s4u2self is allowed from this client to this server
*
* For example, regardless of the principal being impersonated, if the
* 'client' and 'server' are the same, then it's safe.
*/
static krb5_error_code
check_s4u2self(krb5_context context,
krb5_kdc_configuration *config,
HDB *clientdb,
hdb_entry_ex *client,
krb5_const_principal server)
{
krb5_error_code ret;
/* if client does a s4u2self to itself, that ok */
if (krb5_principal_compare(context, client->entry.principal, server) == TRUE)
return 0;
if (clientdb->hdb_check_s4u2self) {
ret = clientdb->hdb_check_s4u2self(context, clientdb, client, server);
if (ret == 0)
return 0;
} else {
ret = KRB5KDC_ERR_BADOPTION;
}
return ret;
}
/*
*
*/
static krb5_error_code
verify_flags (krb5_context context,
krb5_kdc_configuration *config,
const EncTicketPart *et,
const char *pstr)
{
if(et->endtime < kdc_time){
kdc_log(context, config, 0, "Ticket expired (%s)", pstr);
return KRB5KRB_AP_ERR_TKT_EXPIRED;
}
if(et->flags.invalid){
kdc_log(context, config, 0, "Ticket not valid (%s)", pstr);
return KRB5KRB_AP_ERR_TKT_NYV;
}
return 0;
}
/*
*
*/
static krb5_error_code
fix_transited_encoding(krb5_context context,
krb5_kdc_configuration *config,
krb5_boolean check_policy,
const TransitedEncoding *tr,
EncTicketPart *et,
const char *client_realm,
const char *server_realm,
const char *tgt_realm)
{
krb5_error_code ret = 0;
char **realms, **tmp;
unsigned int num_realms;
size_t i;
switch (tr->tr_type) {
case DOMAIN_X500_COMPRESS:
break;
case 0:
/*
* Allow empty content of type 0 because that is was Microsoft
* generates in their TGT.
*/
if (tr->contents.length == 0)
break;
kdc_log(context, config, 0,
"Transited type 0 with non empty content");
return KRB5KDC_ERR_TRTYPE_NOSUPP;
default:
kdc_log(context, config, 0,
"Unknown transited type: %u", tr->tr_type);
return KRB5KDC_ERR_TRTYPE_NOSUPP;
}
ret = krb5_domain_x500_decode(context,
tr->contents,
&realms,
&num_realms,
client_realm,
server_realm);
if(ret){
krb5_warn(context, ret,
"Decoding transited encoding");
return ret;
}
if(strcmp(client_realm, tgt_realm) && strcmp(server_realm, tgt_realm)) {
/* not us, so add the previous realm to transited set */
if (num_realms + 1 > UINT_MAX/sizeof(*realms)) {
ret = ERANGE;
goto free_realms;
}
tmp = realloc(realms, (num_realms + 1) * sizeof(*realms));
if(tmp == NULL){
ret = ENOMEM;
goto free_realms;
}
realms = tmp;
realms[num_realms] = strdup(tgt_realm);
if(realms[num_realms] == NULL){
ret = ENOMEM;
goto free_realms;
}
num_realms++;
}
if(num_realms == 0) {
if(strcmp(client_realm, server_realm))
kdc_log(context, config, 0,
"cross-realm %s -> %s", client_realm, server_realm);
} else {
size_t l = 0;
char *rs;
for(i = 0; i < num_realms; i++)
l += strlen(realms[i]) + 2;
rs = malloc(l);
if(rs != NULL) {
*rs = '\0';
for(i = 0; i < num_realms; i++) {
if(i > 0)
strlcat(rs, ", ", l);
strlcat(rs, realms[i], l);
}
kdc_log(context, config, 0,
"cross-realm %s -> %s via [%s]",
client_realm, server_realm, rs);
free(rs);
}
}
if(check_policy) {
ret = krb5_check_transited(context, client_realm,
server_realm,
realms, num_realms, NULL);
if(ret) {
krb5_warn(context, ret, "cross-realm %s -> %s",
client_realm, server_realm);
goto free_realms;
}
et->flags.transited_policy_checked = 1;
}
et->transited.tr_type = DOMAIN_X500_COMPRESS;
ret = krb5_domain_x500_encode(realms, num_realms, &et->transited.contents);
if(ret)
krb5_warn(context, ret, "Encoding transited encoding");
free_realms:
for(i = 0; i < num_realms; i++)
free(realms[i]);
free(realms);
return ret;
}
static krb5_error_code
tgs_make_reply(krb5_context context,
krb5_kdc_configuration *config,
KDC_REQ_BODY *b,
krb5_const_principal tgt_name,
const EncTicketPart *tgt,
const krb5_keyblock *replykey,
int rk_is_subkey,
const EncryptionKey *serverkey,
const krb5_keyblock *sessionkey,
krb5_kvno kvno,
AuthorizationData *auth_data,
hdb_entry_ex *server,
krb5_principal server_principal,
const char *server_name,
hdb_entry_ex *client,
krb5_principal client_principal,
hdb_entry_ex *krbtgt,
krb5_enctype krbtgt_etype,
krb5_principals spp,
const krb5_data *rspac,
const METHOD_DATA *enc_pa_data,
const char **e_text,
krb5_data *reply)
{
KDC_REP rep;
EncKDCRepPart ek;
EncTicketPart et;
KDCOptions f = b->kdc_options;
krb5_error_code ret;
int is_weak = 0;
memset(&rep, 0, sizeof(rep));
memset(&et, 0, sizeof(et));
memset(&ek, 0, sizeof(ek));
rep.pvno = 5;
rep.msg_type = krb_tgs_rep;
et.authtime = tgt->authtime;
_kdc_fix_time(&b->till);
et.endtime = min(tgt->endtime, *b->till);
ALLOC(et.starttime);
*et.starttime = kdc_time;
ret = check_tgs_flags(context, config, b, tgt, &et);
if(ret)
goto out;
/* We should check the transited encoding if:
1) the request doesn't ask not to be checked
2) globally enforcing a check
3) principal requires checking
4) we allow non-check per-principal, but principal isn't marked as allowing this
5) we don't globally allow this
*/
#define GLOBAL_FORCE_TRANSITED_CHECK \
(config->trpolicy == TRPOLICY_ALWAYS_CHECK)
#define GLOBAL_ALLOW_PER_PRINCIPAL \
(config->trpolicy == TRPOLICY_ALLOW_PER_PRINCIPAL)
#define GLOBAL_ALLOW_DISABLE_TRANSITED_CHECK \
(config->trpolicy == TRPOLICY_ALWAYS_HONOUR_REQUEST)
/* these will consult the database in future release */
#define PRINCIPAL_FORCE_TRANSITED_CHECK(P) 0
#define PRINCIPAL_ALLOW_DISABLE_TRANSITED_CHECK(P) 0
ret = fix_transited_encoding(context, config,
!f.disable_transited_check ||
GLOBAL_FORCE_TRANSITED_CHECK ||
PRINCIPAL_FORCE_TRANSITED_CHECK(server) ||
!((GLOBAL_ALLOW_PER_PRINCIPAL &&
PRINCIPAL_ALLOW_DISABLE_TRANSITED_CHECK(server)) ||
GLOBAL_ALLOW_DISABLE_TRANSITED_CHECK),
&tgt->transited, &et,
krb5_principal_get_realm(context, client_principal),
krb5_principal_get_realm(context, server->entry.principal),
krb5_principal_get_realm(context, krbtgt->entry.principal));
if(ret)
goto out;
copy_Realm(&server_principal->realm, &rep.ticket.realm);
_krb5_principal2principalname(&rep.ticket.sname, server_principal);
copy_Realm(&tgt_name->realm, &rep.crealm);
/*
if (f.request_anonymous)
_kdc_make_anonymous_principalname (&rep.cname);
else */
copy_PrincipalName(&tgt_name->name, &rep.cname);
rep.ticket.tkt_vno = 5;
ek.caddr = et.caddr;
{
time_t life;
life = et.endtime - *et.starttime;
if(client && client->entry.max_life)
life = min(life, *client->entry.max_life);
if(server->entry.max_life)
life = min(life, *server->entry.max_life);
et.endtime = *et.starttime + life;
}
if(f.renewable_ok && tgt->flags.renewable &&
et.renew_till == NULL && et.endtime < *b->till &&
tgt->renew_till != NULL)
{
et.flags.renewable = 1;
ALLOC(et.renew_till);
*et.renew_till = *b->till;
}
if(et.renew_till){
time_t renew;
renew = *et.renew_till - *et.starttime;
if(client && client->entry.max_renew)
renew = min(renew, *client->entry.max_renew);
if(server->entry.max_renew)
renew = min(renew, *server->entry.max_renew);
*et.renew_till = *et.starttime + renew;
}
if(et.renew_till){
*et.renew_till = min(*et.renew_till, *tgt->renew_till);
*et.starttime = min(*et.starttime, *et.renew_till);
et.endtime = min(et.endtime, *et.renew_till);
}
*et.starttime = min(*et.starttime, et.endtime);
if(*et.starttime == et.endtime){
ret = KRB5KDC_ERR_NEVER_VALID;
goto out;
}
if(et.renew_till && et.endtime == *et.renew_till){
free(et.renew_till);
et.renew_till = NULL;
et.flags.renewable = 0;
}
et.flags.pre_authent = tgt->flags.pre_authent;
et.flags.hw_authent = tgt->flags.hw_authent;
et.flags.anonymous = tgt->flags.anonymous;
et.flags.ok_as_delegate = server->entry.flags.ok_as_delegate;
if(rspac->length) {
/*
* No not need to filter out the any PAC from the
* auth_data since it's signed by the KDC.
*/
ret = _kdc_tkt_add_if_relevant_ad(context, &et,
KRB5_AUTHDATA_WIN2K_PAC, rspac);
if (ret)
goto out;
}
if (auth_data) {
unsigned int i = 0;
/* XXX check authdata */
if (et.authorization_data == NULL) {
et.authorization_data = calloc(1, sizeof(*et.authorization_data));
if (et.authorization_data == NULL) {
ret = ENOMEM;
krb5_set_error_message(context, ret, "malloc: out of memory");
goto out;
}
}
for(i = 0; i < auth_data->len ; i++) {
ret = add_AuthorizationData(et.authorization_data, &auth_data->val[i]);
if (ret) {
krb5_set_error_message(context, ret, "malloc: out of memory");
goto out;
}
}
/* Filter out type KRB5SignedPath */
ret = find_KRB5SignedPath(context, et.authorization_data, NULL);
if (ret == 0) {
if (et.authorization_data->len == 1) {
free_AuthorizationData(et.authorization_data);
free(et.authorization_data);
et.authorization_data = NULL;
} else {
AuthorizationData *ad = et.authorization_data;
free_AuthorizationDataElement(&ad->val[ad->len - 1]);
ad->len--;
}
}
}
ret = krb5_copy_keyblock_contents(context, sessionkey, &et.key);
if (ret)
goto out;
et.crealm = tgt_name->realm;
et.cname = tgt_name->name;
ek.key = et.key;
/* MIT must have at least one last_req */
ek.last_req.val = calloc(1, sizeof(*ek.last_req.val));
if (ek.last_req.val == NULL) {
ret = ENOMEM;
goto out;
}
ek.last_req.len = 1; /* set after alloc to avoid null deref on cleanup */
ek.nonce = b->nonce;
ek.flags = et.flags;
ek.authtime = et.authtime;
ek.starttime = et.starttime;
ek.endtime = et.endtime;
ek.renew_till = et.renew_till;
ek.srealm = rep.ticket.realm;
ek.sname = rep.ticket.sname;
_kdc_log_timestamp(context, config, "TGS-REQ", et.authtime, et.starttime,
et.endtime, et.renew_till);
/* Don't sign cross realm tickets, they can't be checked anyway */
{
char *r = get_krbtgt_realm(&ek.sname);
if (r == NULL || strcmp(r, ek.srealm) == 0) {
ret = _kdc_add_KRB5SignedPath(context,
config,
krbtgt,
krbtgt_etype,
client_principal,
NULL,
spp,
&et);
if (ret)
goto out;
}
}
if (enc_pa_data->len) {
rep.padata = calloc(1, sizeof(*rep.padata));
if (rep.padata == NULL) {
ret = ENOMEM;
goto out;
}
ret = copy_METHOD_DATA(enc_pa_data, rep.padata);
if (ret)
goto out;
}
if (krb5_enctype_valid(context, serverkey->keytype) != 0
&& _kdc_is_weak_exception(server->entry.principal, serverkey->keytype))
{
krb5_enctype_enable(context, serverkey->keytype);
is_weak = 1;
}
/* It is somewhat unclear where the etype in the following
encryption should come from. What we have is a session
key in the passed tgt, and a list of preferred etypes
*for the new ticket*. Should we pick the best possible
etype, given the keytype in the tgt, or should we look
at the etype list here as well? What if the tgt
session key is DES3 and we want a ticket with a (say)
CAST session key. Should the DES3 etype be added to the
etype list, even if we don't want a session key with
DES3? */
ret = _kdc_encode_reply(context, config, NULL, 0,
&rep, &et, &ek, serverkey->keytype,
kvno,
serverkey, 0, replykey, rk_is_subkey,
e_text, reply);
if (is_weak)
krb5_enctype_disable(context, serverkey->keytype);
out:
free_TGS_REP(&rep);
free_TransitedEncoding(&et.transited);
if(et.starttime)
free(et.starttime);
if(et.renew_till)
free(et.renew_till);
if(et.authorization_data) {
free_AuthorizationData(et.authorization_data);
free(et.authorization_data);
}
free_LastReq(&ek.last_req);
memset(et.key.keyvalue.data, 0, et.key.keyvalue.length);
free_EncryptionKey(&et.key);
return ret;
}
static krb5_error_code
tgs_check_authenticator(krb5_context context,
krb5_kdc_configuration *config,
krb5_auth_context ac,
KDC_REQ_BODY *b,
const char **e_text,
krb5_keyblock *key)
{
krb5_authenticator auth;
size_t len = 0;
unsigned char *buf;
size_t buf_size;
krb5_error_code ret;
krb5_crypto crypto;
krb5_auth_con_getauthenticator(context, ac, &auth);
if(auth->cksum == NULL){
kdc_log(context, config, 0, "No authenticator in request");
ret = KRB5KRB_AP_ERR_INAPP_CKSUM;
goto out;
}
/*
* according to RFC1510 it doesn't need to be keyed,
* but according to the latest draft it needs to.
*/
if (
#if 0
!krb5_checksum_is_keyed(context, auth->cksum->cksumtype)
||
#endif
!krb5_checksum_is_collision_proof(context, auth->cksum->cksumtype)) {
kdc_log(context, config, 0, "Bad checksum type in authenticator: %d",
auth->cksum->cksumtype);
ret = KRB5KRB_AP_ERR_INAPP_CKSUM;
goto out;
}
/* XXX should not re-encode this */
ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, buf_size, b, &len, ret);
if(ret){
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0, "Failed to encode KDC-REQ-BODY: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
if(buf_size != len) {
free(buf);
kdc_log(context, config, 0, "Internal error in ASN.1 encoder");
*e_text = "KDC internal error";
ret = KRB5KRB_ERR_GENERIC;
goto out;
}
ret = krb5_crypto_init(context, key, 0, &crypto);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
free(buf);
kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
ret = krb5_verify_checksum(context,
crypto,
KRB5_KU_TGS_REQ_AUTH_CKSUM,
buf,
len,
auth->cksum);
free(buf);
krb5_crypto_destroy(context, crypto);
if(ret){
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0,
"Failed to verify authenticator checksum: %s", msg);
krb5_free_error_message(context, msg);
}
out:
free_Authenticator(auth);
free(auth);
return ret;
}
static krb5_boolean
need_referral(krb5_context context, krb5_kdc_configuration *config,
const KDCOptions * const options, krb5_principal server,
krb5_realm **realms)
{
const char *name;
if(!options->canonicalize && server->name.name_type != KRB5_NT_SRV_INST)
return FALSE;
if (server->name.name_string.len == 1)
name = server->name.name_string.val[0];
else if (server->name.name_string.len == 3) {
/*
This is used to give referrals for the
E3514235-4B06-11D1-AB04-00C04FC2DCD2/NTDSGUID/DNSDOMAIN
SPN form, which is used for inter-domain communication in AD
*/
name = server->name.name_string.val[2];
kdc_log(context, config, 0, "Giving 3 part referral for %s", name);
*realms = malloc(sizeof(char *)*2);
if (*realms == NULL) {
krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
return FALSE;
}
(*realms)[0] = strdup(name);
(*realms)[1] = NULL;
return TRUE;
} else if (server->name.name_string.len > 1)
name = server->name.name_string.val[1];
else
return FALSE;
kdc_log(context, config, 0, "Searching referral for %s", name);
return _krb5_get_host_realm_int(context, name, FALSE, realms) == 0;
}
static krb5_error_code
tgs_parse_request(krb5_context context,
krb5_kdc_configuration *config,
KDC_REQ_BODY *b,
const PA_DATA *tgs_req,
hdb_entry_ex **krbtgt,
krb5_enctype *krbtgt_etype,
krb5_ticket **ticket,
const char **e_text,
const char *from,
const struct sockaddr *from_addr,
time_t **csec,
int **cusec,
AuthorizationData **auth_data,
krb5_keyblock **replykey,
int *rk_is_subkey)
{
static char failed[] = "<unparse_name failed>";
krb5_ap_req ap_req;
krb5_error_code ret;
krb5_principal princ;
krb5_auth_context ac = NULL;
krb5_flags ap_req_options;
krb5_flags verify_ap_req_flags;
krb5_crypto crypto;
krb5uint32 krbtgt_kvno; /* kvno used for the PA-TGS-REQ AP-REQ Ticket */
krb5uint32 krbtgt_kvno_try;
int kvno_search_tries = 4; /* number of kvnos to try when tkt_vno == 0 */
const Keys *krbtgt_keys;/* keyset for TGT tkt_vno */
Key *tkey;
krb5_keyblock *subkey = NULL;
unsigned usage;
*auth_data = NULL;
*csec = NULL;
*cusec = NULL;
*replykey = NULL;
memset(&ap_req, 0, sizeof(ap_req));
ret = krb5_decode_ap_req(context, &tgs_req->padata_value, &ap_req);
if(ret){
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0, "Failed to decode AP-REQ: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
if(!get_krbtgt_realm(&ap_req.ticket.sname)){
/* XXX check for ticket.sname == req.sname */
kdc_log(context, config, 0, "PA-DATA is not a ticket-granting ticket");
ret = KRB5KDC_ERR_POLICY; /* ? */
goto out;
}
_krb5_principalname2krb5_principal(context,
&princ,
ap_req.ticket.sname,
ap_req.ticket.realm);
krbtgt_kvno = ap_req.ticket.enc_part.kvno ? *ap_req.ticket.enc_part.kvno : 0;
ret = _kdc_db_fetch(context, config, princ, HDB_F_GET_KRBTGT,
&krbtgt_kvno, NULL, krbtgt);
if (ret == HDB_ERR_NOT_FOUND_HERE) {
/* XXX Factor out this unparsing of the same princ all over */
char *p;
ret = krb5_unparse_name(context, princ, &p);
if (ret != 0)
p = failed;
krb5_free_principal(context, princ);
kdc_log(context, config, 5,
"Ticket-granting ticket account %s does not have secrets at "
"this KDC, need to proxy", p);
if (ret == 0)
free(p);
ret = HDB_ERR_NOT_FOUND_HERE;
goto out;
} else if (ret == HDB_ERR_KVNO_NOT_FOUND) {
char *p;
ret = krb5_unparse_name(context, princ, &p);
if (ret != 0)
p = failed;
krb5_free_principal(context, princ);
kdc_log(context, config, 5,
"Ticket-granting ticket account %s does not have keys for "
"kvno %d at this KDC", p, krbtgt_kvno);
if (ret == 0)
free(p);
ret = HDB_ERR_KVNO_NOT_FOUND;
goto out;
} else if (ret == HDB_ERR_NO_MKEY) {
char *p;
ret = krb5_unparse_name(context, princ, &p);
if (ret != 0)
p = failed;
krb5_free_principal(context, princ);
kdc_log(context, config, 5,
"Missing master key for decrypting keys for ticket-granting "
"ticket account %s with kvno %d at this KDC", p, krbtgt_kvno);
if (ret == 0)
free(p);
ret = HDB_ERR_KVNO_NOT_FOUND;
goto out;
} else if (ret) {
const char *msg = krb5_get_error_message(context, ret);
char *p;
ret = krb5_unparse_name(context, princ, &p);
if (ret != 0)
p = failed;
krb5_free_principal(context, princ);
kdc_log(context, config, 0,
"Ticket-granting ticket not found in database: %s", msg);
krb5_free_error_message(context, msg);
if (ret == 0)
free(p);
ret = KRB5KRB_AP_ERR_NOT_US;
goto out;
}
krbtgt_kvno_try = krbtgt_kvno ? krbtgt_kvno : (*krbtgt)->entry.kvno;
*krbtgt_etype = ap_req.ticket.enc_part.etype;
next_kvno:
krbtgt_keys = hdb_kvno2keys(context, &(*krbtgt)->entry, krbtgt_kvno_try);
ret = hdb_enctype2key(context, &(*krbtgt)->entry, krbtgt_keys,
ap_req.ticket.enc_part.etype, &tkey);
if (ret && krbtgt_kvno == 0 && kvno_search_tries > 0) {
kvno_search_tries--;
krbtgt_kvno_try--;
goto next_kvno;
} else if (ret) {
char *str = NULL, *p = NULL;
krb5_enctype_to_string(context, ap_req.ticket.enc_part.etype, &str);
krb5_unparse_name(context, princ, &p);
kdc_log(context, config, 0,
"No server key with enctype %s found for %s",
str ? str : "<unknown enctype>",
p ? p : "<unparse_name failed>");
free(str);
free(p);
ret = KRB5KRB_AP_ERR_BADKEYVER;
goto out;
}
if (b->kdc_options.validate)
verify_ap_req_flags = KRB5_VERIFY_AP_REQ_IGNORE_INVALID;
else
verify_ap_req_flags = 0;
ret = krb5_verify_ap_req2(context,
&ac,
&ap_req,
princ,
&tkey->key,
verify_ap_req_flags,
&ap_req_options,
ticket,
KRB5_KU_TGS_REQ_AUTH);
if (ret == KRB5KRB_AP_ERR_BAD_INTEGRITY && kvno_search_tries > 0) {
kvno_search_tries--;
krbtgt_kvno_try--;
goto next_kvno;
}
krb5_free_principal(context, princ);
if(ret) {
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0, "Failed to verify AP-REQ: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
{
krb5_authenticator auth;
ret = krb5_auth_con_getauthenticator(context, ac, &auth);
if (ret == 0) {
*csec = malloc(sizeof(**csec));
if (*csec == NULL) {
krb5_free_authenticator(context, &auth);
kdc_log(context, config, 0, "malloc failed");
goto out;
}
**csec = auth->ctime;
*cusec = malloc(sizeof(**cusec));
if (*cusec == NULL) {
krb5_free_authenticator(context, &auth);
kdc_log(context, config, 0, "malloc failed");
goto out;
}
**cusec = auth->cusec;
krb5_free_authenticator(context, &auth);
}
}
ret = tgs_check_authenticator(context, config,
ac, b, e_text, &(*ticket)->ticket.key);
if (ret) {
krb5_auth_con_free(context, ac);
goto out;
}
usage = KRB5_KU_TGS_REQ_AUTH_DAT_SUBKEY;
*rk_is_subkey = 1;
ret = krb5_auth_con_getremotesubkey(context, ac, &subkey);
if(ret){
const char *msg = krb5_get_error_message(context, ret);
krb5_auth_con_free(context, ac);
kdc_log(context, config, 0, "Failed to get remote subkey: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
if(subkey == NULL){
usage = KRB5_KU_TGS_REQ_AUTH_DAT_SESSION;
*rk_is_subkey = 0;
ret = krb5_auth_con_getkey(context, ac, &subkey);
if(ret) {
const char *msg = krb5_get_error_message(context, ret);
krb5_auth_con_free(context, ac);
kdc_log(context, config, 0, "Failed to get session key: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
}
if(subkey == NULL){
krb5_auth_con_free(context, ac);
kdc_log(context, config, 0,
"Failed to get key for enc-authorization-data");
ret = KRB5KRB_AP_ERR_BAD_INTEGRITY; /* ? */
goto out;
}
*replykey = subkey;
if (b->enc_authorization_data) {
krb5_data ad;
ret = krb5_crypto_init(context, subkey, 0, &crypto);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
krb5_auth_con_free(context, ac);
kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
ret = krb5_decrypt_EncryptedData (context,
crypto,
usage,
b->enc_authorization_data,
&ad);
krb5_crypto_destroy(context, crypto);
if(ret){
krb5_auth_con_free(context, ac);
kdc_log(context, config, 0,
"Failed to decrypt enc-authorization-data");
ret = KRB5KRB_AP_ERR_BAD_INTEGRITY; /* ? */
goto out;
}
ALLOC(*auth_data);
if (*auth_data == NULL) {
krb5_auth_con_free(context, ac);
ret = KRB5KRB_AP_ERR_BAD_INTEGRITY; /* ? */
goto out;
}
ret = decode_AuthorizationData(ad.data, ad.length, *auth_data, NULL);
if(ret){
krb5_auth_con_free(context, ac);
free(*auth_data);
*auth_data = NULL;
kdc_log(context, config, 0, "Failed to decode authorization data");
ret = KRB5KRB_AP_ERR_BAD_INTEGRITY; /* ? */
goto out;
}
}
krb5_auth_con_free(context, ac);
out:
free_AP_REQ(&ap_req);
return ret;
}
static krb5_error_code
build_server_referral(krb5_context context,
krb5_kdc_configuration *config,
krb5_crypto session,
krb5_const_realm referred_realm,
const PrincipalName *true_principal_name,
const PrincipalName *requested_principal,
krb5_data *outdata)
{
PA_ServerReferralData ref;
krb5_error_code ret;
EncryptedData ed;
krb5_data data;
size_t size = 0;
memset(&ref, 0, sizeof(ref));
if (referred_realm) {
ALLOC(ref.referred_realm);
if (ref.referred_realm == NULL)
goto eout;
*ref.referred_realm = strdup(referred_realm);
if (*ref.referred_realm == NULL)
goto eout;
}
if (true_principal_name) {
ALLOC(ref.true_principal_name);
if (ref.true_principal_name == NULL)
goto eout;
ret = copy_PrincipalName(true_principal_name, ref.true_principal_name);
if (ret)
goto eout;
}
if (requested_principal) {
ALLOC(ref.requested_principal_name);
if (ref.requested_principal_name == NULL)
goto eout;
ret = copy_PrincipalName(requested_principal,
ref.requested_principal_name);
if (ret)
goto eout;
}
ASN1_MALLOC_ENCODE(PA_ServerReferralData,
data.data, data.length,
&ref, &size, ret);
free_PA_ServerReferralData(&ref);
if (ret)
return ret;
if (data.length != size)
krb5_abortx(context, "internal asn.1 encoder error");
ret = krb5_encrypt_EncryptedData(context, session,
KRB5_KU_PA_SERVER_REFERRAL,
data.data, data.length,
0 /* kvno */, &ed);
free(data.data);
if (ret)
return ret;
ASN1_MALLOC_ENCODE(EncryptedData,
outdata->data, outdata->length,
&ed, &size, ret);
free_EncryptedData(&ed);
if (ret)
return ret;
if (outdata->length != size)
krb5_abortx(context, "internal asn.1 encoder error");
return 0;
eout:
free_PA_ServerReferralData(&ref);
krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
return ENOMEM;
}
static krb5_error_code
tgs_build_reply(krb5_context context,
krb5_kdc_configuration *config,
KDC_REQ *req,
KDC_REQ_BODY *b,
hdb_entry_ex *krbtgt,
krb5_enctype krbtgt_etype,
const krb5_keyblock *replykey,
int rk_is_subkey,
krb5_ticket *ticket,
krb5_data *reply,
const char *from,
const char **e_text,
AuthorizationData **auth_data,
const struct sockaddr *from_addr)
{
krb5_error_code ret;
krb5_principal cp = NULL, sp = NULL, rsp = NULL, tp = NULL, dp = NULL;
krb5_principal krbtgt_out_principal = NULL;
char *spn = NULL, *cpn = NULL, *tpn = NULL, *dpn = NULL, *krbtgt_out_n = NULL;
hdb_entry_ex *server = NULL, *client = NULL, *s4u2self_impersonated_client = NULL;
HDB *clientdb, *s4u2self_impersonated_clientdb;
krb5_realm ref_realm = NULL;
EncTicketPart *tgt = &ticket->ticket;
krb5_principals spp = NULL;
const EncryptionKey *ekey;
krb5_keyblock sessionkey;
krb5_kvno kvno;
krb5_data rspac;
const char *our_realm = /* Realm of this KDC */
krb5_principal_get_comp_string(context, krbtgt->entry.principal, 1);
char **capath = NULL;
size_t num_capath = 0;
hdb_entry_ex *krbtgt_out = NULL;
METHOD_DATA enc_pa_data;
PrincipalName *s;
Realm r;
EncTicketPart adtkt;
char opt_str[128];
int signedpath = 0;
Key *tkey_check;
Key *tkey_sign;
int flags = HDB_F_FOR_TGS_REQ;
memset(&sessionkey, 0, sizeof(sessionkey));
memset(&adtkt, 0, sizeof(adtkt));
krb5_data_zero(&rspac);
memset(&enc_pa_data, 0, sizeof(enc_pa_data));
s = b->sname;
r = b->realm;
/*
* Always to do CANON, see comment below about returned server principal (rsp).
*/
flags |= HDB_F_CANON;
if(b->kdc_options.enc_tkt_in_skey){
Ticket *t;
hdb_entry_ex *uu;
krb5_principal p;
Key *uukey;
krb5uint32 second_kvno = 0;
krb5uint32 *kvno_ptr = NULL;
if(b->additional_tickets == NULL ||
b->additional_tickets->len == 0){
ret = KRB5KDC_ERR_BADOPTION; /* ? */
kdc_log(context, config, 0,
"No second ticket present in request");
goto out;
}
t = &b->additional_tickets->val[0];
if(!get_krbtgt_realm(&t->sname)){
kdc_log(context, config, 0,
"Additional ticket is not a ticket-granting ticket");
ret = KRB5KDC_ERR_POLICY;
goto out;
}
_krb5_principalname2krb5_principal(context, &p, t->sname, t->realm);
if(t->enc_part.kvno){
second_kvno = *t->enc_part.kvno;
kvno_ptr = &second_kvno;
}
ret = _kdc_db_fetch(context, config, p,
HDB_F_GET_KRBTGT, kvno_ptr,
NULL, &uu);
krb5_free_principal(context, p);
if(ret){
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
goto out;
}
ret = hdb_enctype2key(context, &uu->entry, NULL,
t->enc_part.etype, &uukey);
if(ret){
_kdc_free_ent(context, uu);
ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */
goto out;
}
ret = krb5_decrypt_ticket(context, t, &uukey->key, &adtkt, 0);
_kdc_free_ent(context, uu);
if(ret)
goto out;
ret = verify_flags(context, config, &adtkt, spn);
if (ret)
goto out;
s = &adtkt.cname;
r = adtkt.crealm;
}
_krb5_principalname2krb5_principal(context, &sp, *s, r);
ret = krb5_unparse_name(context, sp, &spn);
if (ret)
goto out;
_krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crealm);
ret = krb5_unparse_name(context, cp, &cpn);
if (ret)
goto out;
unparse_flags (KDCOptions2int(b->kdc_options),
asn1_KDCOptions_units(),
opt_str, sizeof(opt_str));
if(*opt_str)
kdc_log(context, config, 0,
"TGS-REQ %s from %s for %s [%s]",
cpn, from, spn, opt_str);
else
kdc_log(context, config, 0,
"TGS-REQ %s from %s for %s", cpn, from, spn);
/*
* Fetch server
*/
server_lookup:
ret = _kdc_db_fetch(context, config, sp, HDB_F_GET_SERVER | flags,
NULL, NULL, &server);
if (ret == HDB_ERR_NOT_FOUND_HERE) {
kdc_log(context, config, 5, "target %s does not have secrets at this KDC, need to proxy", sp);
goto out;
} else if (ret == HDB_ERR_WRONG_REALM) {
free(ref_realm);
ref_realm = strdup(server->entry.principal->realm);
if (ref_realm == NULL) {
ret = krb5_enomem(context);
goto out;
}
kdc_log(context, config, 5,
"Returning a referral to realm %s for "
"server %s.",
ref_realm, spn);
krb5_free_principal(context, sp);
sp = NULL;
ret = krb5_make_principal(context, &sp, r, KRB5_TGS_NAME,
ref_realm, NULL);
if (ret)
goto out;
free(spn);
spn = NULL;
ret = krb5_unparse_name(context, sp, &spn);
if (ret)
goto out;
goto server_lookup;
} else if (ret) {
const char *new_rlm, *msg;
Realm req_rlm;
krb5_realm *realms;
if ((req_rlm = get_krbtgt_realm(&sp->name)) != NULL) {
if (capath == NULL) {
/* With referalls, hierarchical capaths are always enabled */
ret = _krb5_find_capath(context, tgt->crealm, our_realm,
req_rlm, TRUE, &capath, &num_capath);
if (ret)
goto out;
}
new_rlm = num_capath > 0 ? capath[--num_capath] : NULL;
if (new_rlm) {
kdc_log(context, config, 5, "krbtgt from %s via %s for "
"realm %s not found, trying %s", tgt->crealm,
our_realm, req_rlm, new_rlm);
free(ref_realm);
ref_realm = strdup(new_rlm);
if (ref_realm == NULL) {
ret = krb5_enomem(context);
goto out;
}
krb5_free_principal(context, sp);
sp = NULL;
krb5_make_principal(context, &sp, r,
KRB5_TGS_NAME, ref_realm, NULL);
free(spn);
spn = NULL;
ret = krb5_unparse_name(context, sp, &spn);
if (ret)
goto out;
goto server_lookup;
}
} else if (need_referral(context, config, &b->kdc_options, sp, &realms)) {
if (strcmp(realms[0], sp->realm) != 0) {
kdc_log(context, config, 5,
"Returning a referral to realm %s for "
"server %s that was not found",
realms[0], spn);
krb5_free_principal(context, sp);
sp = NULL;
krb5_make_principal(context, &sp, r, KRB5_TGS_NAME,
realms[0], NULL);
free(spn);
spn = NULL;
ret = krb5_unparse_name(context, sp, &spn);
if (ret) {
krb5_free_host_realm(context, realms);
goto out;
}
free(ref_realm);
ref_realm = strdup(realms[0]);
krb5_free_host_realm(context, realms);
goto server_lookup;
}
krb5_free_host_realm(context, realms);
}
msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0,
"Server not found in database: %s: %s", spn, msg);
krb5_free_error_message(context, msg);
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
goto out;
}
/* the name returned to the client depend on what was asked for,
* return canonical name if kdc_options.canonicalize was set, the
* client wants the true name of the principal, if not it just
* wants the name its asked for.
*/
if (b->kdc_options.canonicalize)
rsp = server->entry.principal;
else
rsp = sp;
/*
* Select enctype, return key and kvno.
*/
{
krb5_enctype etype;
if(b->kdc_options.enc_tkt_in_skey) {
size_t i;
ekey = &adtkt.key;
for(i = 0; i < b->etype.len; i++)
if (b->etype.val[i] == adtkt.key.keytype)
break;
if(i == b->etype.len) {
kdc_log(context, config, 0,
"Addition ticket have not matching etypes");
krb5_clear_error_message(context);
ret = KRB5KDC_ERR_ETYPE_NOSUPP;
goto out;
}
etype = b->etype.val[i];
kvno = 0;
} else {
Key *skey;
ret = _kdc_find_etype(context,
krb5_principal_is_krbtgt(context, sp) ?
config->tgt_use_strongest_session_key :
config->svc_use_strongest_session_key, FALSE,
server, b->etype.val, b->etype.len, &etype,
NULL);
if(ret) {
kdc_log(context, config, 0,
"Server (%s) has no support for etypes", spn);
goto out;
}
ret = _kdc_get_preferred_key(context, config, server, spn,
NULL, &skey);
if(ret) {
kdc_log(context, config, 0,
"Server (%s) has no supported etypes", spn);
goto out;
}
ekey = &skey->key;
kvno = server->entry.kvno;
}
ret = krb5_generate_random_keyblock(context, etype, &sessionkey);
if (ret)
goto out;
}
/*
* Check that service is in the same realm as the krbtgt. If it's
* not the same, it's someone that is using a uni-directional trust
* backward.
*/
/*
* Validate authoriation data
*/
ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use the right kvno! */
krbtgt_etype, &tkey_check);
if(ret) {
kdc_log(context, config, 0,
"Failed to find key for krbtgt PAC check");
goto out;
}
/*
* Now refetch the primary krbtgt, and get the current kvno (the
* sign check may have been on an old kvno, and the server may
* have been an incoming trust)
*/
ret = krb5_make_principal(context,
&krbtgt_out_principal,
our_realm,
KRB5_TGS_NAME,
our_realm,
NULL);
if (ret) {
kdc_log(context, config, 0,
"Failed to make krbtgt principal name object for "
"authz-data signatures");
goto out;
}
ret = krb5_unparse_name(context, krbtgt_out_principal, &krbtgt_out_n);
if (ret) {
kdc_log(context, config, 0,
"Failed to make krbtgt principal name object for "
"authz-data signatures");
goto out;
}
ret = _kdc_db_fetch(context, config, krbtgt_out_principal,
HDB_F_GET_KRBTGT, NULL, NULL, &krbtgt_out);
if (ret) {
char *ktpn = NULL;
ret = krb5_unparse_name(context, krbtgt->entry.principal, &ktpn);
kdc_log(context, config, 0,
"No such principal %s (needed for authz-data signature keys) "
"while processing TGS-REQ for service %s with krbtg %s",
krbtgt_out_n, spn, (ret == 0) ? ktpn : "<unknown>");
free(ktpn);
ret = KRB5KRB_AP_ERR_NOT_US;
goto out;
}
/*
* The first realm is the realm of the service, the second is
* krbtgt/<this>/@REALM component of the krbtgt DN the request was
* encrypted to. The redirection via the krbtgt_out entry allows
* the DB to possibly correct the case of the realm (Samba4 does
* this) before the strcmp()
*/
if (strcmp(krb5_principal_get_realm(context, server->entry.principal),
krb5_principal_get_realm(context, krbtgt_out->entry.principal)) != 0) {
char *ktpn;
ret = krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn);
kdc_log(context, config, 0,
"Request with wrong krbtgt: %s",
(ret == 0) ? ktpn : "<unknown>");
if(ret == 0)
free(ktpn);
ret = KRB5KRB_AP_ERR_NOT_US;
goto out;
}
ret = _kdc_get_preferred_key(context, config, krbtgt_out, krbtgt_out_n,
NULL, &tkey_sign);
if (ret) {
kdc_log(context, config, 0,
"Failed to find key for krbtgt PAC signature");
goto out;
}
ret = hdb_enctype2key(context, &krbtgt_out->entry, NULL,
tkey_sign->key.keytype, &tkey_sign);
if(ret) {
kdc_log(context, config, 0,
"Failed to find key for krbtgt PAC signature");
goto out;
}
ret = _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags,
NULL, &clientdb, &client);
if(ret == HDB_ERR_NOT_FOUND_HERE) {
/* This is OK, we are just trying to find out if they have
* been disabled or deleted in the meantime, missing secrets
* is OK */
} else if(ret){
const char *krbtgt_realm, *msg;
/*
* If the client belongs to the same realm as our krbtgt, it
* should exist in the local database.
*
*/
krbtgt_realm = krb5_principal_get_realm(context, krbtgt_out->entry.principal);
if(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) == 0) {
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
kdc_log(context, config, 1, "Client no longer in database: %s",
cpn);
goto out;
}
msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 1, "Client not found in database: %s", msg);
krb5_free_error_message(context, msg);
}
ret = check_PAC(context, config, cp, NULL,
client, server, krbtgt,
&tkey_check->key,
ekey, &tkey_sign->key,
tgt, &rspac, &signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0,
"Verify PAC failed for %s (%s) from %s with %s",
spn, cpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
/* also check the krbtgt for signature */
ret = check_KRB5SignedPath(context,
config,
krbtgt,
cp,
tgt,
&spp,
&signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0,
"KRB5SignedPath check failed for %s (%s) from %s with %s",
spn, cpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
/*
* Process request
*/
/* by default the tgt principal matches the client principal */
tp = cp;
tpn = cpn;
if (client) {
const PA_DATA *sdata;
int i = 0;
sdata = _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER);
if (sdata) {
krb5_crypto crypto;
krb5_data datack;
PA_S4U2Self self;
const char *str;
ret = decode_PA_S4U2Self(sdata->padata_value.data,
sdata->padata_value.length,
&self, NULL);
if (ret) {
kdc_log(context, config, 0, "Failed to decode PA-S4U2Self");
goto out;
}
ret = _krb5_s4u2self_to_checksumdata(context, &self, &datack);
if (ret)
goto out;
ret = krb5_crypto_init(context, &tgt->key, 0, &crypto);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
free_PA_S4U2Self(&self);
krb5_data_free(&datack);
kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
ret = krb5_verify_checksum(context,
crypto,
KRB5_KU_OTHER_CKSUM,
datack.data,
datack.length,
&self.cksum);
krb5_data_free(&datack);
krb5_crypto_destroy(context, crypto);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
free_PA_S4U2Self(&self);
kdc_log(context, config, 0,
"krb5_verify_checksum failed for S4U2Self: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
ret = _krb5_principalname2krb5_principal(context,
&tp,
self.name,
self.realm);
free_PA_S4U2Self(&self);
if (ret)
goto out;
ret = krb5_unparse_name(context, tp, &tpn);
if (ret)
goto out;
/* If we were about to put a PAC into the ticket, we better fix it to be the right PAC */
if(rspac.data) {
krb5_pac p = NULL;
krb5_data_free(&rspac);
ret = _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags,
NULL, &s4u2self_impersonated_clientdb, &s4u2self_impersonated_client);
if (ret) {
const char *msg;
/*
* If the client belongs to the same realm as our krbtgt, it
* should exist in the local database.
*
*/
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 1,
"S2U4Self principal to impersonate %s not found in database: %s",
tpn, msg);
krb5_free_error_message(context, msg);
goto out;
}
ret = _kdc_pac_generate(context, s4u2self_impersonated_client, &p);
if (ret) {
kdc_log(context, config, 0, "PAC generation failed for -- %s",
tpn);
goto out;
}
if (p != NULL) {
ret = _krb5_pac_sign(context, p, ticket->ticket.authtime,
s4u2self_impersonated_client->entry.principal,
ekey, &tkey_sign->key,
&rspac);
krb5_pac_free(context, p);
if (ret) {
kdc_log(context, config, 0, "PAC signing failed for -- %s",
tpn);
goto out;
}
}
}
/*
* Check that service doing the impersonating is
* requesting a ticket to it-self.
*/
ret = check_s4u2self(context, config, clientdb, client, sp);
if (ret) {
kdc_log(context, config, 0, "S4U2Self: %s is not allowed "
"to impersonate to service "
"(tried for user %s to service %s)",
cpn, tpn, spn);
goto out;
}
/*
* If the service isn't trusted for authentication to
* delegation, remove the forward flag.
*/
if (client->entry.flags.trusted_for_delegation) {
str = "[forwardable]";
} else {
b->kdc_options.forwardable = 0;
str = "";
}
kdc_log(context, config, 0, "s4u2self %s impersonating %s to "
"service %s %s", cpn, tpn, spn, str);
}
}
/*
* Constrained delegation
*/
if (client != NULL
&& b->additional_tickets != NULL
&& b->additional_tickets->len != 0
&& b->kdc_options.enc_tkt_in_skey == 0)
{
int ad_signedpath = 0;
Key *clientkey;
Ticket *t;
/*
* Require that the KDC have issued the service's krbtgt (not
* self-issued ticket with kimpersonate(1).
*/
if (!signedpath) {
ret = KRB5KDC_ERR_BADOPTION;
kdc_log(context, config, 0,
"Constrained delegation done on service ticket %s/%s",
cpn, spn);
goto out;
}
t = &b->additional_tickets->val[0];
ret = hdb_enctype2key(context, &client->entry,
hdb_kvno2keys(context, &client->entry,
t->enc_part.kvno ? * t->enc_part.kvno : 0),
t->enc_part.etype, &clientkey);
if(ret){
ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */
goto out;
}
ret = krb5_decrypt_ticket(context, t, &clientkey->key, &adtkt, 0);
if (ret) {
kdc_log(context, config, 0,
"failed to decrypt ticket for "
"constrained delegation from %s to %s ", cpn, spn);
goto out;
}
ret = _krb5_principalname2krb5_principal(context,
&tp,
adtkt.cname,
adtkt.crealm);
if (ret)
goto out;
ret = krb5_unparse_name(context, tp, &tpn);
if (ret)
goto out;
ret = _krb5_principalname2krb5_principal(context,
&dp,
t->sname,
t->realm);
if (ret)
goto out;
ret = krb5_unparse_name(context, dp, &dpn);
if (ret)
goto out;
/* check that ticket is valid */
if (adtkt.flags.forwardable == 0) {
kdc_log(context, config, 0,
"Missing forwardable flag on ticket for "
"constrained delegation from %s (%s) as %s to %s ",
cpn, dpn, tpn, spn);
ret = KRB5KDC_ERR_BADOPTION;
goto out;
}
ret = check_constrained_delegation(context, config, clientdb,
client, server, sp);
if (ret) {
kdc_log(context, config, 0,
"constrained delegation from %s (%s) as %s to %s not allowed",
cpn, dpn, tpn, spn);
goto out;
}
ret = verify_flags(context, config, &adtkt, tpn);
if (ret) {
goto out;
}
krb5_data_free(&rspac);
/*
* generate the PAC for the user.
*
* TODO: pass in t->sname and t->realm and build
* a S4U_DELEGATION_INFO blob to the PAC.
*/
ret = check_PAC(context, config, tp, dp,
client, server, krbtgt,
&clientkey->key,
ekey, &tkey_sign->key,
&adtkt, &rspac, &ad_signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0,
"Verify delegated PAC failed to %s for client"
"%s (%s) as %s from %s with %s",
spn, cpn, dpn, tpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
/*
* Check that the KDC issued the user's ticket.
*/
ret = check_KRB5SignedPath(context,
config,
krbtgt,
cp,
&adtkt,
NULL,
&ad_signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0,
"KRB5SignedPath check from service %s failed "
"for delegation to %s for client %s (%s)"
"from %s failed with %s",
spn, tpn, dpn, cpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
if (!ad_signedpath) {
ret = KRB5KDC_ERR_BADOPTION;
kdc_log(context, config, 0,
"Ticket not signed with PAC nor SignedPath service %s failed "
"for delegation to %s for client %s (%s)"
"from %s",
spn, tpn, dpn, cpn, from);
goto out;
}
kdc_log(context, config, 0, "constrained delegation for %s "
"from %s (%s) to %s", tpn, cpn, dpn, spn);
}
/*
* Check flags
*/
ret = kdc_check_flags(context, config,
client, cpn,
server, spn,
FALSE);
if(ret)
goto out;
if((b->kdc_options.validate || b->kdc_options.renew) &&
!krb5_principal_compare(context,
krbtgt->entry.principal,
server->entry.principal)){
kdc_log(context, config, 0, "Inconsistent request.");
ret = KRB5KDC_ERR_SERVER_NOMATCH;
goto out;
}
/* check for valid set of addresses */
if(!_kdc_check_addresses(context, config, tgt->caddr, from_addr)) {
ret = KRB5KRB_AP_ERR_BADADDR;
kdc_log(context, config, 0, "Request from wrong address");
goto out;
}
/*
* If this is an referral, add server referral data to the
* auth_data reply .
*/
if (ref_realm) {
PA_DATA pa;
krb5_crypto crypto;
kdc_log(context, config, 0,
"Adding server referral to %s", ref_realm);
ret = krb5_crypto_init(context, &sessionkey, 0, &crypto);
if (ret)
goto out;
ret = build_server_referral(context, config, crypto, ref_realm,
NULL, s, &pa.padata_value);
krb5_crypto_destroy(context, crypto);
if (ret) {
kdc_log(context, config, 0,
"Failed building server referral");
goto out;
}
pa.padata_type = KRB5_PADATA_SERVER_REFERRAL;
ret = add_METHOD_DATA(&enc_pa_data, &pa);
krb5_data_free(&pa.padata_value);
if (ret) {
kdc_log(context, config, 0,
"Add server referral METHOD-DATA failed");
goto out;
}
}
/*
*
*/
ret = tgs_make_reply(context,
config,
b,
tp,
tgt,
replykey,
rk_is_subkey,
ekey,
&sessionkey,
kvno,
*auth_data,
server,
rsp,
spn,
client,
cp,
krbtgt_out,
tkey_sign->key.keytype,
spp,
&rspac,
&enc_pa_data,
e_text,
reply);
out:
if (tpn != cpn)
free(tpn);
free(spn);
free(cpn);
free(dpn);
free(krbtgt_out_n);
_krb5_free_capath(context, capath);
krb5_data_free(&rspac);
krb5_free_keyblock_contents(context, &sessionkey);
if(krbtgt_out)
_kdc_free_ent(context, krbtgt_out);
if(server)
_kdc_free_ent(context, server);
if(client)
_kdc_free_ent(context, client);
if(s4u2self_impersonated_client)
_kdc_free_ent(context, s4u2self_impersonated_client);
if (tp && tp != cp)
krb5_free_principal(context, tp);
krb5_free_principal(context, cp);
krb5_free_principal(context, dp);
krb5_free_principal(context, sp);
krb5_free_principal(context, krbtgt_out_principal);
free(ref_realm);
free_METHOD_DATA(&enc_pa_data);
free_EncTicketPart(&adtkt);
return ret;
}
/*
*
*/
krb5_error_code
_kdc_tgs_rep(krb5_context context,
krb5_kdc_configuration *config,
KDC_REQ *req,
krb5_data *data,
const char *from,
struct sockaddr *from_addr,
int datagram_reply)
{
AuthorizationData *auth_data = NULL;
krb5_error_code ret;
int i = 0;
const PA_DATA *tgs_req;
hdb_entry_ex *krbtgt = NULL;
krb5_ticket *ticket = NULL;
const char *e_text = NULL;
krb5_enctype krbtgt_etype = ETYPE_NULL;
krb5_keyblock *replykey = NULL;
int rk_is_subkey = 0;
time_t *csec = NULL;
int *cusec = NULL;
if(req->padata == NULL){
ret = KRB5KDC_ERR_PREAUTH_REQUIRED; /* XXX ??? */
kdc_log(context, config, 0,
"TGS-REQ from %s without PA-DATA", from);
goto out;
}
tgs_req = _kdc_find_padata(req, &i, KRB5_PADATA_TGS_REQ);
if(tgs_req == NULL){
ret = KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
kdc_log(context, config, 0,
"TGS-REQ from %s without PA-TGS-REQ", from);
goto out;
}
ret = tgs_parse_request(context, config,
&req->req_body, tgs_req,
&krbtgt,
&krbtgt_etype,
&ticket,
&e_text,
from, from_addr,
&csec, &cusec,
&auth_data,
&replykey,
&rk_is_subkey);
if (ret == HDB_ERR_NOT_FOUND_HERE) {
/* kdc_log() is called in tgs_parse_request() */
goto out;
}
if (ret) {
kdc_log(context, config, 0,
"Failed parsing TGS-REQ from %s", from);
goto out;
}
{
const PA_DATA *pa = _kdc_find_padata(req, &i, KRB5_PADATA_FX_FAST);
if (pa)
kdc_log(context, config, 10, "Got TGS FAST request");
}
ret = tgs_build_reply(context,
config,
req,
&req->req_body,
krbtgt,
krbtgt_etype,
replykey,
rk_is_subkey,
ticket,
data,
from,
&e_text,
&auth_data,
from_addr);
if (ret) {
kdc_log(context, config, 0,
"Failed building TGS-REP to %s", from);
goto out;
}
/* */
if (datagram_reply && data->length > config->max_datagram_reply_length) {
krb5_data_free(data);
ret = KRB5KRB_ERR_RESPONSE_TOO_BIG;
e_text = "Reply packet too large";
}
out:
if (replykey)
krb5_free_keyblock(context, replykey);
if(ret && ret != HDB_ERR_NOT_FOUND_HERE && data->data == NULL){
/* XXX add fast wrapping on the error */
METHOD_DATA error_method = { 0, NULL };
kdc_log(context, config, 10, "tgs-req: sending error: %d to client", ret);
ret = _kdc_fast_mk_error(context, NULL,
&error_method,
NULL,
NULL,
ret, NULL,
NULL,
NULL, NULL,
csec, cusec,
data);
free_METHOD_DATA(&error_method);
}
free(csec);
free(cusec);
if (ticket)
krb5_free_ticket(context, ticket);
if(krbtgt)
_kdc_free_ent(context, krbtgt);
if (auth_data) {
free_AuthorizationData(auth_data);
free(auth_data);
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-295/c/bad_3203_1 |
crossvul-cpp_data_good_4600_1 | /* Obtained from: https://github.com/iSECPartners/ssl-conservatory */
/*
* Helper functions to perform basic hostname validation using OpenSSL.
*
* Author: Alban Diquet
*
* Copyright (C) 2012, iSEC Partners.
*
* 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.
*
*/
#include <strings.h>
#include <openssl/x509v3.h>
#include <openssl/ssl.h>
#define HOSTNAME_MAX_SIZE 255
#ifndef HAVE_X509_CHECK_HOST
#include "openssl_hostname_validation.h"
/**
* Tries to find a match for hostname in the certificate's Common Name field.
*
* Returns MatchFound if a match was found.
* Returns MatchNotFound if no matches were found.
* Returns MalformedCertificate if the Common Name had a NUL character embedded in it.
* Returns Error if the Common Name could not be extracted.
*/
static HostnameValidationResult matches_common_name(const char *hostname, const X509 *server_cert) {
int common_name_loc = -1;
X509_NAME_ENTRY *common_name_entry = NULL;
ASN1_STRING *common_name_asn1 = NULL;
char *common_name_str = NULL;
// Find the position of the CN field in the Subject field of the certificate
common_name_loc = X509_NAME_get_index_by_NID(X509_get_subject_name((X509 *) server_cert), NID_commonName, -1);
if (common_name_loc < 0) {
return Error;
}
// Extract the CN field
common_name_entry = X509_NAME_get_entry(X509_get_subject_name((X509 *) server_cert), common_name_loc);
if (common_name_entry == NULL) {
return Error;
}
// Convert the CN field to a C string
common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry);
if (common_name_asn1 == NULL) {
return Error;
}
common_name_str = (char *) ASN1_STRING_data(common_name_asn1);
// Make sure there isn't an embedded NUL character in the CN
if (ASN1_STRING_length(common_name_asn1) != strlen(common_name_str)) {
return MalformedCertificate;
}
// Compare expected hostname with the CN
if (strcasecmp(hostname, common_name_str) == 0) {
return MatchFound;
}
else {
return MatchNotFound;
}
}
/**
* Tries to find a match for hostname in the certificate's Subject Alternative Name extension.
*
* Returns MatchFound if a match was found.
* Returns MatchNotFound if no matches were found.
* Returns MalformedCertificate if any of the hostnames had a NUL character embedded in it.
* Returns NoSANPresent if the SAN extension was not present in the certificate.
*/
static HostnameValidationResult matches_subject_alternative_name(const char *hostname, const X509 *server_cert) {
HostnameValidationResult result = MatchNotFound;
int i;
int san_names_nb = -1;
STACK_OF(GENERAL_NAME) *san_names = NULL;
// Try to extract the names within the SAN extension from the certificate
san_names = X509_get_ext_d2i((X509 *) server_cert, NID_subject_alt_name, NULL, NULL);
if (san_names == NULL) {
return NoSANPresent;
}
san_names_nb = sk_GENERAL_NAME_num(san_names);
// Check each name within the extension
for (i=0; i<san_names_nb; i++) {
const GENERAL_NAME *current_name = sk_GENERAL_NAME_value(san_names, i);
if (current_name->type == GEN_DNS) {
// Current name is a DNS name, let's check it
char *dns_name = (char *) ASN1_STRING_data(current_name->d.dNSName);
// Make sure there isn't an embedded NUL character in the DNS name
if (ASN1_STRING_length(current_name->d.dNSName) != strlen(dns_name)) {
result = MalformedCertificate;
break;
}
else { // Compare expected hostname with the DNS name
if (strcasecmp(hostname, dns_name) == 0) {
result = MatchFound;
break;
}
}
}
}
sk_GENERAL_NAME_pop_free(san_names, GENERAL_NAME_free);
return result;
}
/**
* Validates the server's identity by looking for the expected hostname in the
* server's certificate. As described in RFC 6125, it first tries to find a match
* in the Subject Alternative Name extension. If the extension is not present in
* the certificate, it checks the Common Name instead.
*
* Returns MatchFound if a match was found.
* Returns MatchNotFound if no matches were found.
* Returns MalformedCertificate if any of the hostnames had a NUL character embedded in it.
* Returns Error if there was an error.
*/
HostnameValidationResult validate_hostname(const char *hostname, const X509 *server_cert) {
HostnameValidationResult result;
if((hostname == NULL) || (server_cert == NULL))
return Error;
// First try the Subject Alternative Names extension
result = matches_subject_alternative_name(hostname, server_cert);
if (result == NoSANPresent) {
// Extension was not found: try the Common Name
result = matches_common_name(hostname, server_cert);
}
return result;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-295/c/good_4600_1 |
crossvul-cpp_data_good_1607_0 | /* libinfinity - a GObject-based infinote implementation
* Copyright (C) 2007-2014 Armin Burgmeier <armin@arbur.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
/* TODO: Rename to InfGtkCertificateChecker */
/* TODO: Put the non-GUI-relevant parts of this code into libinfinity */
/* TODO: Support CRLs/OCSP */
#include <libinfgtk/inf-gtk-certificate-manager.h>
#include <libinfgtk/inf-gtk-certificate-dialog.h>
#include <libinfinity/common/inf-xml-connection.h>
#include <libinfinity/common/inf-cert-util.h>
#include <libinfinity/common/inf-file-util.h>
#include <libinfinity/common/inf-error.h>
#include <libinfinity/inf-i18n.h>
#include <libinfinity/inf-signals.h>
#include <gnutls/x509.h>
#include <string.h>
#include <errno.h>
typedef struct _InfGtkCertificateManagerQuery InfGtkCertificateManagerQuery;
struct _InfGtkCertificateManagerQuery {
InfGtkCertificateManager* manager;
GHashTable* known_hosts;
InfXmppConnection* connection;
InfGtkCertificateDialog* dialog;
GtkWidget* checkbutton;
InfCertificateChain* certificate_chain;
};
typedef struct _InfGtkCertificateManagerPrivate
InfGtkCertificateManagerPrivate;
struct _InfGtkCertificateManagerPrivate {
GtkWindow* parent_window;
InfXmppManager* xmpp_manager;
gchar* known_hosts_file;
GSList* queries;
};
typedef enum _InfGtkCertificateManagerError {
INF_GTK_CERTIFICATE_MANAGER_ERROR_DUPLICATE_HOST_ENTRY
} InfGtkCertificateManagerError;
enum {
PROP_0,
PROP_PARENT_WINDOW,
PROP_XMPP_MANAGER,
PROP_KNOWN_HOSTS_FILE
};
#define INF_GTK_CERTIFICATE_MANAGER_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), INF_GTK_TYPE_CERTIFICATE_MANAGER, InfGtkCertificateManagerPrivate))
G_DEFINE_TYPE_WITH_CODE(InfGtkCertificateManager, inf_gtk_certificate_manager, G_TYPE_OBJECT,
G_ADD_PRIVATE(InfGtkCertificateManager))
/* When a host presents a certificate different from one that we have pinned,
* usually we warn the user that something fishy is going on. However, if the
* pinned certificate has expired or will expire soon, then we kind of expect
* the certificate to change, and issue a less "flashy" warning message. This
* value defines how long before the pinned certificate expires we show a
* less dramatic warning message. */
static const unsigned int
INF_GTK_CERTIFICATE_MANAGER_EXPIRATION_TOLERANCE = 3 * 24 * 3600; /* 3 days */
/* memrchr does not seem to be available everywhere, so we implement it
* ourselves. */
static void*
inf_gtk_certificate_manager_memrchr(void* buf,
char c,
size_t len)
{
char* pos;
char* end;
pos = buf + len;
end = buf;
while(pos >= end)
{
if(*(pos - 1) == c)
return pos - 1;
--pos;
}
return NULL;
}
static GQuark
inf_gtk_certificate_manager_verify_error_quark(void)
{
return g_quark_from_static_string(
"INF_GTK_CERTIFICATE_MANAGER_VERIFY_ERROR"
);
}
#if 0
static InfGtkCertificateManagerQuery*
inf_gtk_certificate_manager_find_query(InfGtkCertificateManager* manager,
InfXmppConnection* connection)
{
InfGtkCertificateManagerPrivate* priv;
GSList* item;
InfGtkCertificateManagerQuery* query;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);
for(item = priv->queries; item != NULL; item == item->next)
{
query = (InfGtkCertificateManagerQuery*)item->data;
if(query->connection == connection)
return query;
}
return NULL;
}
#endif
static void
inf_gtk_certificate_manager_notify_status_cb(GObject* object,
GParamSpec* pspec,
gpointer user_data);
static void
inf_gtk_certificate_manager_query_free(InfGtkCertificateManagerQuery* query)
{
inf_signal_handlers_disconnect_by_func(
G_OBJECT(query->connection),
G_CALLBACK(inf_gtk_certificate_manager_notify_status_cb),
query
);
g_object_unref(query->connection);
inf_certificate_chain_unref(query->certificate_chain);
gtk_widget_destroy(GTK_WIDGET(query->dialog));
g_hash_table_unref(query->known_hosts);
g_slice_free(InfGtkCertificateManagerQuery, query);
}
static gboolean
inf_gtk_certificate_manager_compare_fingerprint(gnutls_x509_crt_t cert1,
gnutls_x509_crt_t cert2,
GError** error)
{
static const unsigned int SHA256_DIGEST_SIZE = 32;
size_t size;
guchar cert1_fingerprint[SHA256_DIGEST_SIZE];
guchar cert2_fingerprint[SHA256_DIGEST_SIZE];
int ret;
int cmp;
size = SHA256_DIGEST_SIZE;
ret = gnutls_x509_crt_get_fingerprint(
cert1,
GNUTLS_DIG_SHA256,
cert1_fingerprint,
&size
);
if(ret == GNUTLS_E_SUCCESS)
{
g_assert(size == SHA256_DIGEST_SIZE);
ret = gnutls_x509_crt_get_fingerprint(
cert2,
GNUTLS_DIG_SHA256,
cert2_fingerprint,
&size
);
}
if(ret != GNUTLS_E_SUCCESS)
{
inf_gnutls_set_error(error, ret);
return FALSE;
}
cmp = memcmp(cert1_fingerprint, cert2_fingerprint, SHA256_DIGEST_SIZE);
if(cmp != 0) return FALSE;
return TRUE;
}
static void
inf_gtk_certificate_manager_set_known_hosts(InfGtkCertificateManager* manager,
const gchar* known_hosts_file)
{
InfGtkCertificateManagerPrivate* priv;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);
/* TODO: If there are running queries, the we need to load the new hosts
* file and then change it in all queries. */
g_assert(priv->queries == NULL);
g_free(priv->known_hosts_file);
priv->known_hosts_file = g_strdup(known_hosts_file);
}
static GHashTable*
inf_gtk_certificate_manager_load_known_hosts(InfGtkCertificateManager* mgr,
GError** error)
{
InfGtkCertificateManagerPrivate* priv;
GHashTable* table;
gchar* content;
gsize size;
GError* local_error;
gchar* out_buf;
gsize out_buf_len;
gchar* pos;
gchar* prev;
gchar* next;
gchar* sep;
gsize len;
gsize out_len;
gint base64_state;
guint base64_save;
gnutls_datum_t data;
gnutls_x509_crt_t cert;
int res;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(mgr);
table = g_hash_table_new_full(
g_str_hash,
g_str_equal,
g_free,
(GDestroyNotify)gnutls_x509_crt_deinit
);
local_error = NULL;
g_file_get_contents(priv->known_hosts_file, &content, &size, &local_error);
if(local_error != NULL)
{
if(local_error->domain == G_FILE_ERROR &&
local_error->code == G_FILE_ERROR_NOENT)
{
return table;
}
g_propagate_prefixed_error(
error,
local_error,
_("Failed to open known hosts file \"%s\": "),
priv->known_hosts_file
);
g_hash_table_destroy(table);
return NULL;
}
out_buf = NULL;
out_buf_len = 0;
prev = content;
for(prev = content; prev != NULL; prev = next)
{
pos = strchr(prev, '\n');
next = NULL;
if(pos == NULL)
pos = content + size;
else
next = pos + 1;
sep = inf_gtk_certificate_manager_memrchr(prev, ':', pos - prev);
if(sep == NULL) continue; /* ignore line */
*sep = '\0';
if(g_hash_table_lookup(table, prev) != NULL)
{
g_set_error(
error,
g_quark_from_static_string("INF_GTK_CERTIFICATE_MANAGER_ERROR"),
INF_GTK_CERTIFICATE_MANAGER_ERROR_DUPLICATE_HOST_ENTRY,
_("Certificate for host \"%s\" appears twice in "
"known hosts file \"%s\""),
prev,
priv->known_hosts_file
);
g_hash_table_destroy(table);
g_free(out_buf);
g_free(content);
return NULL;
}
/* decode base64, import DER certificate */
len = (pos - (sep + 1));
out_len = len * 3 / 4;
if(out_len > out_buf_len)
{
out_buf = g_realloc(out_buf, out_len);
out_buf_len = out_len;
}
base64_state = 0;
base64_save = 0;
out_len = g_base64_decode_step(
sep + 1,
len,
out_buf,
&base64_state,
&base64_save
);
cert = NULL;
res = gnutls_x509_crt_init(&cert);
if(res == GNUTLS_E_SUCCESS)
{
data.data = out_buf;
data.size = out_len;
res = gnutls_x509_crt_import(cert, &data, GNUTLS_X509_FMT_DER);
}
if(res != GNUTLS_E_SUCCESS)
{
inf_gnutls_set_error(&local_error, res);
g_propagate_prefixed_error(
error,
local_error,
_("Failed to read certificate for host \"%s\" from "
"known hosts file \"%s\": "),
prev,
priv->known_hosts_file
);
if(cert != NULL)
gnutls_x509_crt_deinit(cert);
g_hash_table_destroy(table);
g_free(out_buf);
g_free(content);
return NULL;
}
g_hash_table_insert(table, g_strdup(prev), cert);
}
g_free(out_buf);
g_free(content);
return table;
}
static GHashTable*
inf_gtk_certificate_manager_ref_known_hosts(InfGtkCertificateManager* mgr,
GError** error)
{
InfGtkCertificateManagerPrivate* priv;
InfGtkCertificateManagerQuery* query;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(mgr);
if(priv->queries != NULL)
{
query = (InfGtkCertificateManagerQuery*)priv->queries->data;
g_hash_table_ref(query->known_hosts);
return query->known_hosts;
}
else
{
return inf_gtk_certificate_manager_load_known_hosts(mgr, error);
}
}
static gboolean
inf_gtk_certificate_manager_write_known_hosts(InfGtkCertificateManager* mgr,
GHashTable* table,
GError** error)
{
InfGtkCertificateManagerPrivate* priv;
gchar* dirname;
GIOChannel* channel;
GIOStatus status;
GHashTableIter iter;
gpointer key;
gpointer value;
const gchar* hostname;
gnutls_x509_crt_t cert;
size_t size;
int res;
gchar* buffer;
gchar* encoded_cert;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(mgr);
/* Note that we pin the whole certificate and not only the public key of
* our known hosts. This allows us to differentiate two cases when a
* host presents a new certificate:
* a) The old certificate has expired or is very close to expiration. In
* this case we still show a message to the user asking whether they
* trust the new certificate.
* b) The old certificate was perfectly valid. In this case we show a
* message saying that the certificate change was unexpected, and
* unless it was expected the host should not be trusted.
*/
dirname = g_path_get_dirname(priv->known_hosts_file);
if(!inf_file_util_create_directory(dirname, 0755, error))
{
g_free(dirname);
return FALSE;
}
g_free(dirname);
channel = g_io_channel_new_file(priv->known_hosts_file, "w", error);
if(channel == NULL) return FALSE;
status = g_io_channel_set_encoding(channel, NULL, error);
if(status != G_IO_STATUS_NORMAL)
{
g_io_channel_unref(channel);
return FALSE;
}
g_hash_table_iter_init(&iter, table);
while(g_hash_table_iter_next(&iter, &key, &value))
{
hostname = (const gchar*)key;
cert = (gnutls_x509_crt_t)value;
size = 0;
res = gnutls_x509_crt_export(cert, GNUTLS_X509_FMT_DER, NULL, &size);
g_assert(res != GNUTLS_E_SUCCESS);
buffer = NULL;
if(res == GNUTLS_E_SHORT_MEMORY_BUFFER)
{
buffer = g_malloc(size);
res = gnutls_x509_crt_export(cert, GNUTLS_X509_FMT_DER, buffer, &size);
}
if(res != GNUTLS_E_SUCCESS)
{
g_free(buffer);
g_io_channel_unref(channel);
inf_gnutls_set_error(error, res);
return FALSE;
}
encoded_cert = g_base64_encode(buffer, size);
g_free(buffer);
status = g_io_channel_write_chars(channel, hostname, strlen(hostname), NULL, error);
if(status == G_IO_STATUS_NORMAL)
status = g_io_channel_write_chars(channel, ":", 1, NULL, error);
if(status == G_IO_STATUS_NORMAL)
status = g_io_channel_write_chars(channel, encoded_cert, strlen(encoded_cert), NULL, error);
if(status == G_IO_STATUS_NORMAL)
status = g_io_channel_write_chars(channel, "\n", 1, NULL, error);
g_free(encoded_cert);
if(status != G_IO_STATUS_NORMAL)
{
g_io_channel_unref(channel);
return FALSE;
}
}
g_io_channel_unref(channel);
return TRUE;
}
static void
inf_gtk_certificate_manager_write_known_hosts_with_warning(
InfGtkCertificateManager* mgr,
GHashTable* table)
{
InfGtkCertificateManagerPrivate* priv;
GError* error;
gboolean result;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(mgr);
error = NULL;
result = inf_gtk_certificate_manager_write_known_hosts(
mgr,
table,
&error
);
if(error != NULL)
{
g_warning(
_("Failed to write file with known hosts \"%s\": %s"),
priv->known_hosts_file,
error->message
);
g_error_free(error);
}
}
static void
inf_gtk_certificate_manager_response_cb(GtkDialog* dialog,
int response_id,
gpointer user_data)
{
InfGtkCertificateManagerQuery* query;
InfGtkCertificateManagerPrivate* priv;
InfXmppConnection* connection;
gchar* hostname;
gnutls_x509_crt_t cert;
gnutls_x509_crt_t known_cert;
GError* error;
gboolean cert_equal;
query = (InfGtkCertificateManagerQuery*)user_data;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(query->manager);
connection = query->connection;
g_object_ref(connection);
switch(response_id)
{
case GTK_RESPONSE_ACCEPT:
g_object_get(
G_OBJECT(query->connection),
"remote-hostname", &hostname,
NULL
);
/* Add the certificate to the known hosts file, but only if it is not
* already, to avoid unnecessary disk I/O. */
cert =
inf_certificate_chain_get_own_certificate(query->certificate_chain);
known_cert = g_hash_table_lookup(query->known_hosts, hostname);
error = NULL;
cert_equal = FALSE;
if(known_cert != NULL)
{
cert_equal = inf_gtk_certificate_manager_compare_fingerprint(
cert,
known_cert,
&error
);
}
if(error != NULL)
{
g_warning(
_("Failed to add certificate to list of known hosts: %s"),
error->message
);
}
else if(!cert_equal)
{
cert = inf_cert_util_copy_certificate(cert, &error);
g_hash_table_insert(query->known_hosts, hostname, cert);
inf_gtk_certificate_manager_write_known_hosts_with_warning(
query->manager,
query->known_hosts
);
}
else
{
g_free(hostname);
}
priv->queries = g_slist_remove(priv->queries, query);
inf_gtk_certificate_manager_query_free(query);
inf_xmpp_connection_certificate_verify_continue(connection);
break;
case GTK_RESPONSE_REJECT:
case GTK_RESPONSE_DELETE_EVENT:
priv->queries = g_slist_remove(priv->queries, query);
inf_gtk_certificate_manager_query_free(query);
inf_xmpp_connection_certificate_verify_cancel(connection, NULL);
break;
default:
g_assert_not_reached();
break;
}
g_object_unref(connection);
}
static void
inf_gtk_certificate_manager_notify_status_cb(GObject* object,
GParamSpec* pspec,
gpointer user_data)
{
InfGtkCertificateManagerQuery* query;
InfGtkCertificateManagerPrivate* priv;
InfXmppConnection* connection;
InfXmlConnectionStatus status;
query = (InfGtkCertificateManagerQuery*)user_data;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(query->manager);
connection = INF_XMPP_CONNECTION(object);
g_object_get(G_OBJECT(connection), "status", &status, NULL);
if(status == INF_XML_CONNECTION_CLOSING ||
status == INF_XML_CONNECTION_CLOSED)
{
priv->queries = g_slist_remove(priv->queries, query);
inf_gtk_certificate_manager_query_free(query);
}
}
static void
inf_gtk_certificate_manager_certificate_func(InfXmppConnection* connection,
gnutls_session_t session,
InfCertificateChain* chain,
gpointer user_data)
{
InfGtkCertificateManager* manager;
InfGtkCertificateManagerPrivate* priv;
InfGtkCertificateDialogFlags flags;
gnutls_x509_crt_t presented_cert;
gnutls_x509_crt_t known_cert;
gchar* hostname;
gboolean match_hostname;
gboolean issuer_known;
gnutls_x509_crt_t root_cert;
int ret;
unsigned int verify;
GHashTable* table;
gboolean cert_equal;
time_t expiration_time;
InfGtkCertificateManagerQuery* query;
gchar* text;
GtkWidget* vbox;
GtkWidget* label;
GError* error;
manager = INF_GTK_CERTIFICATE_MANAGER(user_data);
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);
g_object_get(G_OBJECT(connection), "remote-hostname", &hostname, NULL);
presented_cert = inf_certificate_chain_get_own_certificate(chain);
match_hostname = gnutls_x509_crt_check_hostname(presented_cert, hostname);
/* First, validate the certificate */
ret = gnutls_certificate_verify_peers2(session, &verify);
error = NULL;
if(ret != GNUTLS_E_SUCCESS)
inf_gnutls_set_error(&error, ret);
/* Remove the GNUTLS_CERT_ISSUER_NOT_KNOWN flag from the verification
* result, and if the certificate is still invalid, then set an error. */
if(error == NULL)
{
issuer_known = TRUE;
if(verify & GNUTLS_CERT_SIGNER_NOT_FOUND)
{
issuer_known = FALSE;
/* Re-validate the certificate for other failure reasons --
* unfortunately the gnutls_certificate_verify_peers2() call
* does not tell us whether the certificate is otherwise invalid
* if a signer is not found already. */
/* TODO: Here it would be good to use the verify flags from the
* certificate credentials, but GnuTLS does not have API to
* retrieve them. */
root_cert = inf_certificate_chain_get_root_certificate(chain);
ret = gnutls_x509_crt_list_verify(
inf_certificate_chain_get_raw(chain),
inf_certificate_chain_get_n_certificates(chain),
&root_cert,
1,
NULL,
0,
GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT,
&verify
);
if(ret != GNUTLS_E_SUCCESS)
inf_gnutls_set_error(&error, ret);
}
if(error == NULL)
if(verify & GNUTLS_CERT_INVALID)
inf_gnutls_certificate_verification_set_error(&error, verify);
}
/* Look up the host in our database of pinned certificates if we could not
* fully verify the certificate, i.e. if either the issuer is not known or
* the hostname of the connection does not match the certificate. */
table = NULL;
if(error == NULL)
{
known_cert = NULL;
if(!match_hostname || !issuer_known)
{
/* If we cannot load the known host file, then cancel the connection.
* Otherwise it might happen that someone shows us a certificate that we
* tell the user we don't know, if though actually for that host we expect
* a different certificate. */
table = inf_gtk_certificate_manager_ref_known_hosts(manager, &error);
if(table != NULL)
known_cert = g_hash_table_lookup(table, hostname);
}
}
/* Next, configure the flags for the dialog to be shown based on the
* verification result, and on whether the pinned certificate matches
* the one presented by the host or not. */
flags = 0;
if(error == NULL)
{
if(known_cert != NULL)
{
cert_equal = inf_gtk_certificate_manager_compare_fingerprint(
known_cert,
presented_cert,
&error
);
if(error == NULL && cert_equal == FALSE)
{
if(!match_hostname)
flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_HOSTNAME_MISMATCH;
if(!issuer_known)
flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_ISSUER_NOT_KNOWN;
flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_UNEXPECTED;
expiration_time = gnutls_x509_crt_get_expiration_time(known_cert);
if(expiration_time != (time_t)(-1))
{
expiration_time -= INF_GTK_CERTIFICATE_MANAGER_EXPIRATION_TOLERANCE;
if(time(NULL) > expiration_time)
{
flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_OLD_EXPIRED;
}
}
}
}
else
{
if(!match_hostname)
flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_HOSTNAME_MISMATCH;
if(!issuer_known)
flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_ISSUER_NOT_KNOWN;
}
}
/* Now proceed either by accepting the connection, rejecting it, or
* bothering the user with an annoying dialog. */
if(error == NULL)
{
if(flags == 0)
{
if(match_hostname && issuer_known)
{
/* Remove the pinned entry if we now have a valid certificate for
* this host. */
if(table != NULL && g_hash_table_remove(table, hostname) == TRUE)
{
inf_gtk_certificate_manager_write_known_hosts_with_warning(
manager,
table
);
}
}
inf_xmpp_connection_certificate_verify_continue(connection);
}
else
{
query = g_slice_new(InfGtkCertificateManagerQuery);
query->manager = manager;
query->known_hosts = table;
query->connection = connection;
query->dialog = inf_gtk_certificate_dialog_new(
priv->parent_window,
0,
flags,
hostname,
chain
);
query->certificate_chain = chain;
table = NULL;
g_object_ref(query->connection);
inf_certificate_chain_ref(chain);
g_signal_connect(
G_OBJECT(connection),
"notify::status",
G_CALLBACK(inf_gtk_certificate_manager_notify_status_cb),
query
);
g_signal_connect(
G_OBJECT(query->dialog),
"response",
G_CALLBACK(inf_gtk_certificate_manager_response_cb),
query
);
gtk_dialog_add_button(
GTK_DIALOG(query->dialog),
_("_Cancel connection"),
GTK_RESPONSE_REJECT
);
gtk_dialog_add_button(
GTK_DIALOG(query->dialog),
_("C_ontinue connection"),
GTK_RESPONSE_ACCEPT
);
text = g_strdup_printf(
_("Do you want to continue the connection to host \"%s\"? If you "
"choose to continue, this certificate will be trusted in the "
"future when connecting to this host."),
hostname
);
label = gtk_label_new(text);
gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR);
gtk_label_set_max_width_chars(GTK_LABEL(label), 60);
gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
gtk_widget_show(label);
g_free(text);
vbox = gtk_dialog_get_content_area(GTK_DIALOG(query->dialog));
gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
priv->queries = g_slist_prepend(priv->queries, query);
gtk_window_present(GTK_WINDOW(query->dialog));
}
}
else
{
inf_xmpp_connection_certificate_verify_cancel(connection, error);
g_error_free(error);
}
if(table != NULL) g_hash_table_unref(table);
g_free(hostname);
}
static void
inf_gtk_certificate_manager_connection_added_cb(InfXmppManager* manager,
InfXmppConnection* connection,
gpointer user_data)
{
InfXmppConnectionSite site;
g_object_get(G_OBJECT(connection), "site", &site, NULL);
if(site == INF_XMPP_CONNECTION_CLIENT)
{
inf_xmpp_connection_set_certificate_callback(
connection,
GNUTLS_CERT_REQUIRE, /* require a server certificate */
inf_gtk_certificate_manager_certificate_func,
user_data,
NULL
);
}
}
static void
inf_gtk_certificate_manager_init(InfGtkCertificateManager* manager)
{
InfGtkCertificateManagerPrivate* priv;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);
priv->parent_window = NULL;
priv->xmpp_manager = NULL;
priv->known_hosts_file = NULL;
}
static void
inf_gtk_certificate_manager_dispose(GObject* object)
{
InfGtkCertificateManager* manager;
InfGtkCertificateManagerPrivate* priv;
GSList* item;
manager = INF_GTK_CERTIFICATE_MANAGER(object);
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);
if(priv->parent_window != NULL)
{
g_object_unref(priv->parent_window);
priv->parent_window = NULL;
}
if(priv->xmpp_manager != NULL)
{
g_object_unref(priv->xmpp_manager);
priv->xmpp_manager = NULL;
}
for(item = priv->queries; item != NULL; item = g_slist_next(item))
{
inf_gtk_certificate_manager_query_free(
(InfGtkCertificateManagerQuery*)item->data
);
}
g_slist_free(priv->queries);
priv->queries = NULL;
G_OBJECT_CLASS(inf_gtk_certificate_manager_parent_class)->dispose(object);
}
static void
inf_gtk_certificate_manager_finalize(GObject* object)
{
InfGtkCertificateManager* manager;
InfGtkCertificateManagerPrivate* priv;
manager = INF_GTK_CERTIFICATE_MANAGER(object);
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);
inf_gtk_certificate_manager_set_known_hosts(manager, NULL);
g_assert(priv->known_hosts_file == NULL);
G_OBJECT_CLASS(inf_gtk_certificate_manager_parent_class)->finalize(object);
}
static void
inf_gtk_certificate_manager_set_property(GObject* object,
guint prop_id,
const GValue* value,
GParamSpec* pspec)
{
InfGtkCertificateManager* manager;
InfGtkCertificateManagerPrivate* priv;
manager = INF_GTK_CERTIFICATE_MANAGER(object);
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);
switch(prop_id)
{
case PROP_PARENT_WINDOW:
g_assert(priv->parent_window == NULL); /* construct/only */
priv->parent_window = GTK_WINDOW(g_value_dup_object(value));
break;
case PROP_XMPP_MANAGER:
g_assert(priv->xmpp_manager == NULL); /* construct/only */
priv->xmpp_manager = INF_XMPP_MANAGER(g_value_dup_object(value));
g_signal_connect(
G_OBJECT(priv->xmpp_manager),
"connection-added",
G_CALLBACK(inf_gtk_certificate_manager_connection_added_cb),
manager
);
break;
case PROP_KNOWN_HOSTS_FILE:
inf_gtk_certificate_manager_set_known_hosts(
manager,
g_value_get_string(value)
);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
break;
}
}
static void
inf_gtk_certificate_manager_get_property(GObject* object,
guint prop_id,
GValue* value,
GParamSpec* pspec)
{
InfGtkCertificateManager* manager;
InfGtkCertificateManagerPrivate* priv;
manager = INF_GTK_CERTIFICATE_MANAGER(object);
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);
switch(prop_id)
{
case PROP_PARENT_WINDOW:
g_value_set_object(value, G_OBJECT(priv->parent_window));
break;
case PROP_XMPP_MANAGER:
g_value_set_object(value, G_OBJECT(priv->xmpp_manager));
break;
case PROP_KNOWN_HOSTS_FILE:
g_value_set_string(value, priv->known_hosts_file);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
break;
}
}
/*
* GType registration
*/
static void
inf_gtk_certificate_manager_class_init(
InfGtkCertificateManagerClass* certificate_manager_class)
{
GObjectClass* object_class;
object_class = G_OBJECT_CLASS(certificate_manager_class);
object_class->dispose = inf_gtk_certificate_manager_dispose;
object_class->finalize = inf_gtk_certificate_manager_finalize;
object_class->set_property = inf_gtk_certificate_manager_set_property;
object_class->get_property = inf_gtk_certificate_manager_get_property;
g_object_class_install_property(
object_class,
PROP_PARENT_WINDOW,
g_param_spec_object(
"parent-window",
"Parent window",
"The parent window for certificate approval dialogs",
GTK_TYPE_WINDOW,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY
)
);
g_object_class_install_property(
object_class,
PROP_XMPP_MANAGER,
g_param_spec_object(
"xmpp-manager",
"XMPP manager",
"The XMPP manager of registered connections",
INF_TYPE_XMPP_MANAGER,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY
)
);
g_object_class_install_property(
object_class,
PROP_KNOWN_HOSTS_FILE,
g_param_spec_string(
"known-hosts-file",
"Known hosts file",
"File containing certificates of known hosts",
NULL,
G_PARAM_READWRITE
)
);
}
/*
* Public API.
*/
/**
* inf_gtk_certificate_manager_new: (constructor)
* @parent_window: The #GtkWindow to which to make certificate approval
* dialogs transient to.
* @xmpp_manager: The #InfXmppManager whose #InfXmppConnection<!-- -->s to
* manage the certificates for.
* @known_hosts_file: (type filename) (allow-none): Path pointing to a file
* that contains certificates of known hosts, or %NULL.
*
* Creates a new #InfGtkCertificateManager. For each new client-side
* #InfXmppConnection in @xmpp_manager, the certificate manager will verify
* the server's certificate.
*
* If the certificate is contained in @known_hosts_file, then
* the certificate is accepted automatically. Otherwise, the user is asked for
* approval. If the user approves the certificate, then it is inserted into
* the @known_hosts_file.
*
* Returns: (transfer full): A new #InfGtkCertificateManager.
**/
InfGtkCertificateManager*
inf_gtk_certificate_manager_new(GtkWindow* parent_window,
InfXmppManager* xmpp_manager,
const gchar* known_hosts_file)
{
GObject* object;
object = g_object_new(
INF_GTK_TYPE_CERTIFICATE_MANAGER,
"parent-window", parent_window,
"xmpp-manager", xmpp_manager,
"known-hosts-file", known_hosts_file,
NULL
);
return INF_GTK_CERTIFICATE_MANAGER(object);
}
/* vim:set et sw=2 ts=2: */
| ./CrossVul/dataset_final_sorted/CWE-295/c/good_1607_0 |
crossvul-cpp_data_good_4600_3 | /*
* Copyright (C) 2015 Adrien Vergé
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* In addition, as a special exception, the copyright holders give permission
* to link the code of portions of this program with the OpenSSL library under
* certain conditions as described in each individual source file, and
* distribute linked combinations including the two.
* You must obey the GNU General Public License in all respects for all of the
* code used other than OpenSSL. If you modify file(s) with this exception,
* you may extend this exception to your version of the file(s), but you are
* not obligated to do so. If you do not wish to do so, delete this exception
* statement from your version. If you delete this exception statement from
* all source files in the program, then also delete it here.
*/
#include "tunnel.h"
#include "http.h"
#include "log.h"
#ifndef HAVE_X509_CHECK_HOST
#include "openssl_hostname_validation.h"
#endif
#include <unistd.h>
#include <fcntl.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <errno.h>
#include <string.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <openssl/err.h>
#include <openssl/x509v3.h>
#include <openssl/engine.h>
#if HAVE_PTY_H
#include <pty.h>
#elif HAVE_UTIL_H
#include <util.h>
#endif
#include <termios.h>
#include <signal.h>
#include <sys/wait.h>
#if HAVE_SYSTEMD
#include <systemd/sd-daemon.h>
#endif
// we use this constant in the source, so define a fallback if not defined
#ifndef OPENSSL_API_COMPAT
#define OPENSSL_API_COMPAT 0x0908000L
#endif
struct ofv_varr {
unsigned int cap; // current capacity
unsigned int off; // next slot to write, always < max(cap - 1, 1)
const char **data; // NULL terminated
};
static int ofv_append_varr(struct ofv_varr *p, const char *x)
{
if (p->off + 1 >= p->cap) {
const char **ndata;
unsigned int ncap = (p->off + 1) * 2;
if (p->off + 1 >= ncap) {
log_error("%s: ncap exceeded\n", __func__);
return 1;
};
ndata = realloc(p->data, ncap * sizeof(const char *));
if (ndata) {
p->data = ndata;
p->cap = ncap;
} else {
log_error("realloc: %s\n", strerror(errno));
return 1;
}
}
if (p->data == NULL) {
log_error("%s: NULL data\n", __func__);
return 1;
}
if (p->off + 1 >= p->cap) {
log_error("%s: cap exceeded in p\n", __func__);
return 1;
}
p->data[p->off] = x;
p->data[++p->off] = NULL;
return 0;
}
static int on_ppp_if_up(struct tunnel *tunnel)
{
log_info("Interface %s is UP.\n", tunnel->ppp_iface);
if (tunnel->config->set_routes) {
int ret;
log_info("Setting new routes...\n");
ret = ipv4_set_tunnel_routes(tunnel);
if (ret != 0)
log_warn("Adding route table is incomplete. Please check route table.\n");
}
if (tunnel->config->set_dns) {
log_info("Adding VPN nameservers...\n");
ipv4_add_nameservers_to_resolv_conf(tunnel);
}
log_info("Tunnel is up and running.\n");
#if HAVE_SYSTEMD
sd_notify(0, "READY=1");
#endif
return 0;
}
static int on_ppp_if_down(struct tunnel *tunnel)
{
log_info("Setting ppp interface down.\n");
if (tunnel->config->set_routes) {
log_info("Restoring routes...\n");
ipv4_restore_routes(tunnel);
}
if (tunnel->config->set_dns) {
log_info("Removing VPN nameservers...\n");
ipv4_del_nameservers_from_resolv_conf(tunnel);
}
return 0;
}
static int pppd_run(struct tunnel *tunnel)
{
pid_t pid;
int amaster;
int slave_stderr;
#ifdef HAVE_STRUCT_TERMIOS
struct termios termp = {
.c_cflag = B9600,
.c_cc[VTIME] = 0,
.c_cc[VMIN] = 1
};
#endif
static const char ppp_path[] = PPP_PATH;
if (access(ppp_path, F_OK) != 0) {
log_error("%s: %s.\n", ppp_path, strerror(errno));
return 1;
}
log_debug("ppp_path: %s\n", ppp_path);
slave_stderr = dup(STDERR_FILENO);
if (slave_stderr < 0) {
log_error("slave stderr %s\n", strerror(errno));
return 1;
}
#ifdef HAVE_STRUCT_TERMIOS
pid = forkpty(&amaster, NULL, &termp, NULL);
#else
pid = forkpty(&amaster, NULL, NULL, NULL);
#endif
if (pid == 0) { // child process
struct ofv_varr pppd_args = { 0, 0, NULL };
dup2(slave_stderr, STDERR_FILENO);
close(slave_stderr);
#if HAVE_USR_SBIN_PPP
/*
* assume there is a default configuration to start.
* Support for taking options from the command line
* e.g. the name of the configuration or options
* to send interactively to ppp will be added later
*/
static const char *const v[] = {
ppp_path,
"-direct"
};
for (unsigned int i = 0; i < ARRAY_SIZE(v); i++)
if (ofv_append_varr(&pppd_args, v[i]))
return 1;
#endif
#if HAVE_USR_SBIN_PPPD
if (tunnel->config->pppd_call) {
if (ofv_append_varr(&pppd_args, ppp_path))
return 1;
if (ofv_append_varr(&pppd_args, "call"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_call))
return 1;
} else {
static const char *const v[] = {
ppp_path,
"115200", // speed
":192.0.2.1", // <local_IP_address>:<remote_IP_address>
"noipdefault",
"noaccomp",
"noauth",
"default-asyncmap",
"nopcomp",
"receive-all",
"nodefaultroute",
"nodetach",
"lcp-max-configure", "40",
"mru", "1354"
};
for (unsigned int i = 0; i < ARRAY_SIZE(v); i++)
if (ofv_append_varr(&pppd_args, v[i]))
return 1;
}
if (tunnel->config->pppd_use_peerdns)
if (ofv_append_varr(&pppd_args, "usepeerdns"))
return 1;
if (tunnel->config->pppd_log) {
if (ofv_append_varr(&pppd_args, "debug"))
return 1;
if (ofv_append_varr(&pppd_args, "logfile"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_log))
return 1;
} else {
/*
* pppd defaults to logging to fd=1, clobbering the
* actual PPP data
*/
if (ofv_append_varr(&pppd_args, "logfd"))
return 1;
if (ofv_append_varr(&pppd_args, "2"))
return 1;
}
if (tunnel->config->pppd_plugin) {
if (ofv_append_varr(&pppd_args, "plugin"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_plugin))
return 1;
}
if (tunnel->config->pppd_ipparam) {
if (ofv_append_varr(&pppd_args, "ipparam"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_ipparam))
return 1;
}
if (tunnel->config->pppd_ifname) {
if (ofv_append_varr(&pppd_args, "ifname"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_ifname))
return 1;
}
#endif
#if HAVE_USR_SBIN_PPP
if (tunnel->config->ppp_system) {
if (ofv_append_varr(&pppd_args, tunnel->config->ppp_system))
return 1;
}
#endif
close(tunnel->ssl_socket);
execv(pppd_args.data[0], (char *const *)pppd_args.data);
free(pppd_args.data);
fprintf(stderr, "execvp: %s\n", strerror(errno));
_exit(EXIT_FAILURE);
} else {
close(slave_stderr);
if (pid == -1) {
log_error("forkpty: %s\n", strerror(errno));
return 1;
}
}
// Set non-blocking
int flags = fcntl(amaster, F_GETFL, 0);
if (flags == -1)
flags = 0;
if (fcntl(amaster, F_SETFL, flags | O_NONBLOCK) == -1) {
log_error("fcntl: %s\n", strerror(errno));
return 1;
}
tunnel->pppd_pid = pid;
tunnel->pppd_pty = amaster;
return 0;
}
static const char * const pppd_message[] = {
"Has detached, or otherwise the connection was successfully established and terminated at the peer's request.",
"An immediately fatal error of some kind occurred, such as an essential system call failing, or running out of virtual memory.",
"An error was detected in processing the options given, such as two mutually exclusive options being used.",
"Is not setuid-root and the invoking user is not root.",
"The kernel does not support PPP, for example, the PPP kernel driver is not included or cannot be loaded.",
"Terminated because it was sent a SIGINT, SIGTERM or SIGHUP signal.",
"The serial port could not be locked.",
"The serial port could not be opened.",
"The connect script failed (returned a non-zero exit status).",
"The command specified as the argument to the pty option could not be run.",
"The PPP negotiation failed, that is, it didn't reach the point where at least one network protocol (e.g. IP) was running.",
"The peer system failed (or refused) to authenticate itself.",
"The link was established successfully and terminated because it was idle.",
"The link was established successfully and terminated because the connect time limit was reached.",
"Callback was negotiated and an incoming call should arrive shortly.",
"The link was terminated because the peer is not responding to echo requests.",
"The link was terminated by the modem hanging up.",
"The PPP negotiation failed because serial loopback was detected.",
"The init script failed (returned a non-zero exit status).",
"We failed to authenticate ourselves to the peer."
};
static int pppd_terminate(struct tunnel *tunnel)
{
close(tunnel->pppd_pty);
log_debug("Waiting for %s to exit...\n", PPP_DAEMON);
int status;
if (waitpid(tunnel->pppd_pid, &status, 0) == -1) {
log_error("waitpid: %s\n", strerror(errno));
return 1;
}
if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
log_debug("waitpid: %s exit status code %d\n",
PPP_DAEMON, exit_status);
#if HAVE_USR_SBIN_PPPD
if (exit_status >= ARRAY_SIZE(pppd_message) || exit_status < 0) {
log_error("%s: Returned an unknown exit status: %d\n",
PPP_DAEMON, exit_status);
} else {
switch (exit_status) {
case 0: // success
log_debug("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
case 16: // emitted when exiting normally
log_info("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
default:
log_error("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
}
}
#else
// ppp exit codes in the FreeBSD case
switch (exit_status) {
case 0: // success and EX_NORMAL as defined in ppp source directly
log_debug("%s: %s\n", PPP_DAEMON, pppd_message[exit_status]);
break;
case 1:
case 127:
case 255: // abnormal exit with hard-coded error codes in ppp
log_error("%s: exited with return value of %d\n",
PPP_DAEMON, exit_status);
break;
default:
log_error("%s: %s (%d)\n", PPP_DAEMON, strerror(exit_status),
exit_status);
break;
}
#endif
} else if (WIFSIGNALED(status)) {
int signal_number = WTERMSIG(status);
log_debug("waitpid: %s terminated by signal %d\n",
PPP_DAEMON, signal_number);
log_error("%s: terminated by signal: %s\n",
PPP_DAEMON, strsignal(signal_number));
}
return 0;
}
int ppp_interface_is_up(struct tunnel *tunnel)
{
struct ifaddrs *ifap, *ifa;
log_debug("Got Address: %s\n", inet_ntoa(tunnel->ipv4.ip_addr));
if (getifaddrs(&ifap)) {
log_error("getifaddrs: %s\n", strerror(errno));
return 0;
}
for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
if ((
#if HAVE_USR_SBIN_PPPD
(tunnel->config->pppd_ifname
&& strstr(ifa->ifa_name, tunnel->config->pppd_ifname)
!= NULL)
|| strstr(ifa->ifa_name, "ppp") != NULL
#endif
#if HAVE_USR_SBIN_PPP
strstr(ifa->ifa_name, "tun") != NULL
#endif
) && ifa->ifa_flags & IFF_UP) {
if (&(ifa->ifa_addr->sa_family) != NULL
&& ifa->ifa_addr->sa_family == AF_INET) {
struct in_addr if_ip_addr =
cast_addr(ifa->ifa_addr)->sin_addr;
log_debug("Interface Name: %s\n", ifa->ifa_name);
log_debug("Interface Addr: %s\n", inet_ntoa(if_ip_addr));
if (tunnel->ipv4.ip_addr.s_addr == if_ip_addr.s_addr) {
strncpy(tunnel->ppp_iface, ifa->ifa_name,
ROUTE_IFACE_LEN - 1);
freeifaddrs(ifap);
return 1;
}
}
}
}
freeifaddrs(ifap);
return 0;
}
static int get_gateway_host_ip(struct tunnel *tunnel)
{
const struct addrinfo hints = { .ai_family = AF_INET };
struct addrinfo *result = NULL;
int ret = getaddrinfo(tunnel->config->gateway_host, NULL, &hints, &result);
if (ret) {
if (ret == EAI_SYSTEM)
log_error("getaddrinfo: %s\n", strerror(errno));
else
log_error("getaddrinfo: %s\n", gai_strerror(ret));
return 1;
}
tunnel->config->gateway_ip = ((struct sockaddr_in *)
result->ai_addr)->sin_addr;
freeaddrinfo(result);
setenv("VPN_GATEWAY", inet_ntoa(tunnel->config->gateway_ip), 0);
return 0;
}
/*
* Establish a regular TCP connection.
*/
static int tcp_connect(struct tunnel *tunnel)
{
int ret, handle;
struct sockaddr_in server;
char *env_proxy;
handle = socket(AF_INET, SOCK_STREAM, 0);
if (handle == -1) {
log_error("socket: %s\n", strerror(errno));
goto err_socket;
}
env_proxy = getenv("https_proxy");
if (env_proxy == NULL)
env_proxy = getenv("HTTPS_PROXY");
if (env_proxy == NULL)
env_proxy = getenv("all_proxy");
if (env_proxy == NULL)
env_proxy = getenv("ALL_PROXY");
if (env_proxy != NULL) {
char *proxy_host, *proxy_port;
// protect the original environment from modifications
env_proxy = strdup(env_proxy);
if (env_proxy == NULL) {
log_error("strdup: %s\n", strerror(errno));
goto err_strdup;
}
// get rid of a trailing slash
if (*env_proxy && env_proxy[strlen(env_proxy) - 1] == '/')
env_proxy[strlen(env_proxy) - 1] = '\0';
// get rid of a http(s):// prefix in env_proxy
proxy_host = strstr(env_proxy, "://");
if (proxy_host == NULL)
proxy_host = env_proxy;
else
proxy_host += 3;
// split host and port
proxy_port = index(proxy_host, ':');
if (proxy_port != NULL) {
proxy_port[0] = '\0';
proxy_port++;
server.sin_port = htons(strtoul(proxy_port, NULL, 10));
} else {
server.sin_port = htons(tunnel->config->gateway_port);
}
// get rid of a trailing slash
if (*proxy_host && proxy_host[strlen(proxy_host) - 1] == '/')
proxy_host[strlen(proxy_host) - 1] = '\0';
log_debug("proxy_host: %s\n", proxy_host);
log_debug("proxy_port: %s\n", proxy_port);
server.sin_addr.s_addr = inet_addr(proxy_host);
// if host is given as a FQDN we have to do a DNS lookup
if (server.sin_addr.s_addr == INADDR_NONE) {
const struct addrinfo hints = { .ai_family = AF_INET };
struct addrinfo *result = NULL;
ret = getaddrinfo(proxy_host, NULL, &hints, &result);
if (ret) {
if (ret == EAI_SYSTEM)
log_error("getaddrinfo: %s\n", strerror(errno));
else
log_error("getaddrinfo: %s\n", gai_strerror(ret));
goto err_connect;
}
server.sin_addr = ((struct sockaddr_in *)
result->ai_addr)->sin_addr;
freeaddrinfo(result);
}
} else {
server.sin_port = htons(tunnel->config->gateway_port);
server.sin_addr = tunnel->config->gateway_ip;
}
log_debug("server_addr: %s\n", inet_ntoa(server.sin_addr));
log_debug("server_port: %u\n", ntohs(server.sin_port));
server.sin_family = AF_INET;
memset(&(server.sin_zero), '\0', 8);
log_debug("gateway_addr: %s\n", inet_ntoa(tunnel->config->gateway_ip));
log_debug("gateway_port: %u\n", tunnel->config->gateway_port);
ret = connect(handle, (struct sockaddr *) &server, sizeof(server));
if (ret) {
log_error("connect: %s\n", strerror(errno));
goto err_connect;
}
if (env_proxy != NULL) {
char request[128];
// https://tools.ietf.org/html/rfc7231#section-4.3.6
sprintf(request, "CONNECT %s:%u HTTP/1.1\r\nHost: %s:%u\r\n\r\n",
inet_ntoa(tunnel->config->gateway_ip),
tunnel->config->gateway_port,
inet_ntoa(tunnel->config->gateway_ip),
tunnel->config->gateway_port);
ssize_t bytes_written = write(handle, request, strlen(request));
if (bytes_written != strlen(request)) {
log_error("write error while talking to proxy: %s\n",
strerror(errno));
goto err_connect;
}
// wait for a "200 OK" reply from the proxy,
// be careful not to fetch too many bytes at once
const char *response = NULL;
memset(&(request), '\0', sizeof(request));
for (int j = 0; response == NULL; j++) {
/*
* Coverity detected a defect:
* CID 200508: String not null terminated (STRING_NULL)
*
* It is actually a false positive:
* • Function memset() initializes 'request' with '\0'
* • Function read() gets a single char into: request[j]
* • The final '\0' cannot be overwritten because:
* j < ARRAY_SIZE(request) - 1
*/
ssize_t bytes_read = read(handle, &(request[j]), 1);
if (bytes_read < 1) {
log_error("Proxy response is unexpectedly large and cannot fit in the %lu-bytes buffer.\n",
ARRAY_SIZE(request));
goto err_proxy_response;
}
// detect "200"
static const char HTTP_STATUS_200[] = "200";
response = strstr(request, HTTP_STATUS_200);
// detect end-of-line after "200"
if (response != NULL) {
/*
* RFC2616 states in section 2.2 Basic Rules:
* CR = <US-ASCII CR, carriage return (13)>
* LF = <US-ASCII LF, linefeed (10)>
* HTTP/1.1 defines the sequence CR LF as the
* end-of-line marker for all protocol elements
* except the entity-body (see appendix 19.3
* for tolerant applications).
* CRLF = CR LF
*
* RFC2616 states in section 19.3 Tolerant Applications:
* The line terminator for message-header fields
* is the sequence CRLF. However, we recommend
* that applications, when parsing such headers,
* recognize a single LF as a line terminator
* and ignore the leading CR.
*/
static const char *const HTTP_EOL[] = {
"\r\n\r\n",
"\n\n"
};
const char *eol = NULL;
for (int i = 0; (i < ARRAY_SIZE(HTTP_EOL)) &&
(eol == NULL); i++)
eol = strstr(response, HTTP_EOL[i]);
response = eol;
}
if (j > ARRAY_SIZE(request) - 2) {
log_error("Proxy response does not contain \"%s\" as expected.\n",
HTTP_STATUS_200);
goto err_proxy_response;
}
}
free(env_proxy); // release memory allocated by strdup()
}
return handle;
err_proxy_response:
err_connect:
free(env_proxy); // release memory allocated by strdup()
err_strdup:
close(handle);
err_socket:
return -1;
}
static int ssl_verify_cert(struct tunnel *tunnel)
{
int ret = -1;
int cert_valid = 0;
unsigned char digest[SHA256LEN];
unsigned int len;
struct x509_digest *elem;
char digest_str[SHA256STRLEN], *subject, *issuer;
char *line;
int i;
X509_NAME *subj;
SSL_set_verify(tunnel->ssl_handle, SSL_VERIFY_PEER, NULL);
X509 *cert = SSL_get_peer_certificate(tunnel->ssl_handle);
if (cert == NULL) {
log_error("Unable to get gateway certificate.\n");
return 1;
}
subj = X509_get_subject_name(cert);
#ifdef HAVE_X509_CHECK_HOST
// Use OpenSSL native host validation if v >= 1.0.2.
// compare against gateway_host and correctly check return value
// to fix piror Incorrect use of X509_check_host
if (X509_check_host(cert, tunnel->config->gateway_host,
0, 0, NULL) == 1)
cert_valid = 1;
#else
// Use validate_hostname form iSECPartners if native validation not available
// in order to avoid TLS Certificate CommonName NULL Byte Vulnerability
if (validate_hostname(tunnel->config->gateway_host, cert) == MatchFound)
cert_valid = 1;
#endif
// Try to validate certificate using local PKI
if (cert_valid
&& SSL_get_verify_result(tunnel->ssl_handle) == X509_V_OK) {
log_debug("Gateway certificate validation succeeded.\n");
ret = 0;
goto free_cert;
}
log_debug("Gateway certificate validation failed.\n");
// If validation failed, check if cert is in the white list
if (X509_digest(cert, EVP_sha256(), digest, &len) <= 0
|| len != SHA256LEN) {
log_error("Could not compute certificate sha256 digest.\n");
goto free_cert;
}
// Encode digest in base16
for (i = 0; i < SHA256LEN; i++)
sprintf(&digest_str[2 * i], "%02x", digest[i]);
digest_str[SHA256STRLEN - 1] = '\0';
// Is it in whitelist?
for (elem = tunnel->config->cert_whitelist; elem != NULL;
elem = elem->next)
if (memcmp(digest_str, elem->data, SHA256STRLEN - 1) == 0)
break;
if (elem != NULL) { // break before end of loop
log_debug("Gateway certificate digest found in white list.\n");
ret = 0;
goto free_cert;
}
subject = X509_NAME_oneline(subj, NULL, 0);
issuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
log_error("Gateway certificate validation failed, and the certificate digest in not in the local whitelist. If you trust it, rerun with:\n");
log_error(" --trusted-cert %s\n", digest_str);
log_error("or add this line to your config file:\n");
log_error(" trusted-cert = %s\n", digest_str);
log_error("Gateway certificate:\n");
log_error(" subject:\n");
for (line = strtok(subject, "/"); line != NULL;
line = strtok(NULL, "/"))
log_error(" %s\n", line);
log_error(" issuer:\n");
for (line = strtok(issuer, "/"); line != NULL;
line = strtok(NULL, "/"))
log_error(" %s\n", line);
log_error(" sha256 digest:\n");
log_error(" %s\n", digest_str);
free_cert:
X509_free(cert);
return ret;
}
/*
* Destroy and free the SSL connection to the gateway.
*/
static void ssl_disconnect(struct tunnel *tunnel)
{
if (!tunnel->ssl_handle)
return;
SSL_shutdown(tunnel->ssl_handle);
SSL_free(tunnel->ssl_handle);
SSL_CTX_free(tunnel->ssl_context);
close(tunnel->ssl_socket);
tunnel->ssl_handle = NULL;
tunnel->ssl_context = NULL;
}
/*
* Connects to the gateway and initiate an SSL session.
*/
int ssl_connect(struct tunnel *tunnel)
{
ssl_disconnect(tunnel);
tunnel->ssl_socket = tcp_connect(tunnel);
if (tunnel->ssl_socket == -1)
return 1;
// registration is deprecated from OpenSSL 1.1.0 onward
#if OPENSSL_API_COMPAT < 0x10100000L
// Register the error strings for libcrypto & libssl
SSL_load_error_strings();
// Register the available ciphers and digests
SSL_library_init();
#endif
tunnel->ssl_context = SSL_CTX_new(SSLv23_client_method());
if (tunnel->ssl_context == NULL) {
log_error("SSL_CTX_new: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
// Load the OS default CA files
if (!SSL_CTX_set_default_verify_paths(tunnel->ssl_context))
log_error("Could not load OS OpenSSL files.\n");
if (tunnel->config->ca_file) {
if (!SSL_CTX_load_verify_locations(
tunnel->ssl_context,
tunnel->config->ca_file, NULL)) {
log_error("SSL_CTX_load_verify_locations: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
/* Use engine for PIV if user-cert config starts with pkcs11 URI: */
if (tunnel->config->use_engine > 0) {
ENGINE *e;
ENGINE_load_builtin_engines();
e = ENGINE_by_id("pkcs11");
if (!e) {
log_error("Could not load pkcs11 Engine: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!ENGINE_init(e)) {
log_error("Could not init pkcs11 Engine: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
ENGINE_free(e);
return 1;
}
if (!ENGINE_set_default_RSA(e))
abort();
ENGINE_finish(e);
ENGINE_free(e);
struct token parms;
parms.uri = tunnel->config->user_cert;
parms.cert = NULL;
if (!ENGINE_ctrl_cmd(e, "LOAD_CERT_CTRL", 0, &parms, NULL, 1)) {
log_error("PKCS11 ENGINE_ctrl_cmd: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_use_certificate(tunnel->ssl_context, parms.cert)) {
log_error("PKCS11 SSL_CTX_use_certificate: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
EVP_PKEY * privkey = ENGINE_load_private_key(
e, parms.uri, UI_OpenSSL(), NULL);
if (!privkey) {
log_error("PKCS11 ENGINE_load_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_use_PrivateKey(tunnel->ssl_context, privkey)) {
log_error("PKCS11 SSL_CTX_use_PrivateKey_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_check_private_key(tunnel->ssl_context)) {
log_error("PKCS11 SSL_CTX_check_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
} else { /* end PKCS11-engine */
if (tunnel->config->user_cert) {
if (!SSL_CTX_use_certificate_file(
tunnel->ssl_context, tunnel->config->user_cert,
SSL_FILETYPE_PEM)) {
log_error("SSL_CTX_use_certificate_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
if (tunnel->config->user_key) {
if (!SSL_CTX_use_PrivateKey_file(
tunnel->ssl_context, tunnel->config->user_key,
SSL_FILETYPE_PEM)) {
log_error("SSL_CTX_use_PrivateKey_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
if (tunnel->config->user_cert && tunnel->config->user_key) {
if (!SSL_CTX_check_private_key(tunnel->ssl_context)) {
log_error("SSL_CTX_check_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
}
if (!tunnel->config->insecure_ssl) {
long sslctxopt = SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
long checkopt;
checkopt = SSL_CTX_set_options(tunnel->ssl_context, sslctxopt);
if ((checkopt & sslctxopt) != sslctxopt) {
log_error("SSL_CTX_set_options didn't set opt: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
tunnel->ssl_handle = SSL_new(tunnel->ssl_context);
if (tunnel->ssl_handle == NULL) {
log_error("SSL_new: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!tunnel->config->insecure_ssl) {
if (!tunnel->config->cipher_list) {
const char *cipher_list;
if (tunnel->config->seclevel_1)
cipher_list = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4@SECLEVEL=1";
else
cipher_list = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4";
tunnel->config->cipher_list = strdup(cipher_list);
}
} else {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (tunnel->config->min_tls <= 0)
tunnel->config->min_tls = TLS1_VERSION;
#endif
if (!tunnel->config->cipher_list && tunnel->config->seclevel_1) {
const char *cipher_list = "DEFAULT@SECLEVEL=1";
tunnel->config->cipher_list = strdup(cipher_list);
}
}
if (tunnel->config->cipher_list) {
log_debug("Setting cipher list to: %s\n", tunnel->config->cipher_list);
if (!SSL_set_cipher_list(tunnel->ssl_handle,
tunnel->config->cipher_list)) {
log_error("SSL_set_cipher_list failed: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (tunnel->config->min_tls > 0) {
log_debug("Setting min proto version to: 0x%x\n",
tunnel->config->min_tls);
if (!SSL_set_min_proto_version(tunnel->ssl_handle,
tunnel->config->min_tls)) {
log_error("SSL_set_min_proto_version failed: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
#endif
if (!SSL_set_fd(tunnel->ssl_handle, tunnel->ssl_socket)) {
log_error("SSL_set_fd: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
SSL_set_mode(tunnel->ssl_handle, SSL_MODE_AUTO_RETRY);
// Initiate SSL handshake
if (SSL_connect(tunnel->ssl_handle) != 1) {
log_error("SSL_connect: %s\n"
"You might want to try --insecure-ssl or specify a different --cipher-list\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
SSL_set_mode(tunnel->ssl_handle, SSL_MODE_AUTO_RETRY);
if (ssl_verify_cert(tunnel))
return 1;
// Disable SIGPIPE (occurs when trying to write to an already-closed
// socket).
signal(SIGPIPE, SIG_IGN);
return 0;
}
int run_tunnel(struct vpn_config *config)
{
int ret;
struct tunnel tunnel = {
.config = config,
.state = STATE_DOWN,
.ssl_context = NULL,
.ssl_handle = NULL,
.ipv4.ns1_addr.s_addr = 0,
.ipv4.ns2_addr.s_addr = 0,
.ipv4.dns_suffix = NULL,
.on_ppp_if_up = on_ppp_if_up,
.on_ppp_if_down = on_ppp_if_down
};
// Step 0: get gateway host IP
log_debug("Resolving gateway host ip\n");
ret = get_gateway_host_ip(&tunnel);
if (ret)
goto err_tunnel;
// Step 1: open a SSL connection to the gateway
log_debug("Establishing ssl connection\n");
ret = ssl_connect(&tunnel);
if (ret)
goto err_tunnel;
log_info("Connected to gateway.\n");
// Step 2: connect to the HTTP interface and authenticate to get a
// cookie
ret = auth_log_in(&tunnel);
if (ret != 1) {
log_error("Could not authenticate to gateway. Please check the password, client certificate, etc.\n");
log_debug("%s %d\n", err_http_str(ret), ret);
ret = 1;
goto err_tunnel;
}
log_info("Authenticated.\n");
log_debug("Cookie: %s\n", tunnel.cookie);
ret = auth_request_vpn_allocation(&tunnel);
if (ret != 1) {
log_error("VPN allocation request failed (%s).\n",
err_http_str(ret));
ret = 1;
goto err_tunnel;
}
log_info("Remote gateway has allocated a VPN.\n");
ret = ssl_connect(&tunnel);
if (ret)
goto err_tunnel;
// Step 3: get configuration
log_debug("Retrieving configuration\n");
ret = auth_get_config(&tunnel);
if (ret != 1) {
log_error("Could not get VPN configuration (%s).\n",
err_http_str(ret));
ret = 1;
goto err_tunnel;
}
// Step 4: run a pppd process
log_debug("Establishing the tunnel\n");
ret = pppd_run(&tunnel);
if (ret)
goto err_tunnel;
// Step 5: ask gateway to start tunneling
log_debug("Switch to tunneling mode\n");
ret = http_send(&tunnel,
"GET /remote/sslvpn-tunnel HTTP/1.1\r\n"
"Host: sslvpn\r\n"
"Cookie: %s\r\n\r\n",
tunnel.cookie);
if (ret != 1) {
log_error("Could not start tunnel (%s).\n", err_http_str(ret));
ret = 1;
goto err_start_tunnel;
}
tunnel.state = STATE_CONNECTING;
ret = 0;
// Step 6: perform io between pppd and the gateway, while tunnel is up
log_debug("Starting IO through the tunnel\n");
io_loop(&tunnel);
log_debug("disconnecting\n");
if (tunnel.state == STATE_UP)
if (tunnel.on_ppp_if_down != NULL)
tunnel.on_ppp_if_down(&tunnel);
tunnel.state = STATE_DISCONNECTING;
err_start_tunnel:
pppd_terminate(&tunnel);
log_info("Terminated %s.\n", PPP_DAEMON);
err_tunnel:
log_info("Closed connection to gateway.\n");
tunnel.state = STATE_DOWN;
if (ssl_connect(&tunnel)) {
log_info("Could not log out.\n");
} else {
auth_log_out(&tunnel);
log_info("Logged out.\n");
}
// explicitly free the buffer allocated for split routes of the ipv4 config
if (tunnel.ipv4.split_rt != NULL) {
free(tunnel.ipv4.split_rt);
tunnel.ipv4.split_rt = NULL;
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-295/c/good_4600_3 |
crossvul-cpp_data_good_682_0 | /* $OpenBSD: x509_vpm.c,v 1.17 2018/03/22 15:54:46 beck Exp $ */
/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
* project 2004.
*/
/* ====================================================================
* Copyright (c) 2004 The OpenSSL Project. 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 acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS 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.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include <string.h>
#include <openssl/buffer.h>
#include <openssl/crypto.h>
#include <openssl/lhash.h>
#include <openssl/stack.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "vpm_int.h"
/* X509_VERIFY_PARAM functions */
int X509_VERIFY_PARAM_set1_email(X509_VERIFY_PARAM *param, const char *email,
size_t emaillen);
int X509_VERIFY_PARAM_set1_ip(X509_VERIFY_PARAM *param, const unsigned char *ip,
size_t iplen);
#define SET_HOST 0
#define ADD_HOST 1
static void
str_free(char *s)
{
free(s);
}
#define string_stack_free(sk) sk_OPENSSL_STRING_pop_free(sk, str_free)
/*
* Post 1.0.1 sk function "deep_copy". For the moment we simply make
* these take void * and use them directly without a glorious blob of
* obfuscating macros of dubious value in front of them. All this in
* preparation for a rototilling of safestack.h (likely inspired by
* this).
*/
static void *
sk_deep_copy(void *sk_void, void *copy_func_void, void *free_func_void)
{
_STACK *sk = sk_void;
void *(*copy_func)(void *) = copy_func_void;
void (*free_func)(void *) = free_func_void;
_STACK *ret = sk_dup(sk);
size_t i;
if (ret == NULL)
return NULL;
for (i = 0; i < ret->num; i++) {
if (ret->data[i] == NULL)
continue;
ret->data[i] = copy_func(ret->data[i]);
if (ret->data[i] == NULL) {
size_t j;
for (j = 0; j < i; j++) {
if (ret->data[j] != NULL)
free_func(ret->data[j]);
}
sk_free(ret);
return NULL;
}
}
return ret;
}
static int
int_x509_param_set_hosts(X509_VERIFY_PARAM_ID *id, int mode,
const char *name, size_t namelen)
{
char *copy;
if (name != NULL && namelen == 0)
namelen = strlen(name);
/*
* Refuse names with embedded NUL bytes.
* XXX: Do we need to push an error onto the error stack?
*/
if (name && memchr(name, '\0', namelen))
return 0;
if (mode == SET_HOST && id->hosts) {
string_stack_free(id->hosts);
id->hosts = NULL;
}
if (name == NULL || namelen == 0)
return 1;
copy = strndup(name, namelen);
if (copy == NULL)
return 0;
if (id->hosts == NULL &&
(id->hosts = sk_OPENSSL_STRING_new_null()) == NULL) {
free(copy);
return 0;
}
if (!sk_OPENSSL_STRING_push(id->hosts, copy)) {
free(copy);
if (sk_OPENSSL_STRING_num(id->hosts) == 0) {
sk_OPENSSL_STRING_free(id->hosts);
id->hosts = NULL;
}
return 0;
}
return 1;
}
static void
x509_verify_param_zero(X509_VERIFY_PARAM *param)
{
X509_VERIFY_PARAM_ID *paramid;
if (!param)
return;
param->name = NULL;
param->purpose = 0;
param->trust = 0;
/*param->inh_flags = X509_VP_FLAG_DEFAULT;*/
param->inh_flags = 0;
param->flags = 0;
param->depth = -1;
if (param->policies) {
sk_ASN1_OBJECT_pop_free(param->policies, ASN1_OBJECT_free);
param->policies = NULL;
}
paramid = param->id;
if (paramid->hosts) {
string_stack_free(paramid->hosts);
paramid->hosts = NULL;
}
free(paramid->peername);
paramid->peername = NULL;
free(paramid->email);
paramid->email = NULL;
paramid->emaillen = 0;
free(paramid->ip);
paramid->ip = NULL;
paramid->iplen = 0;
}
X509_VERIFY_PARAM *
X509_VERIFY_PARAM_new(void)
{
X509_VERIFY_PARAM *param;
X509_VERIFY_PARAM_ID *paramid;
param = calloc(1, sizeof(X509_VERIFY_PARAM));
if (param == NULL)
return NULL;
paramid = calloc (1, sizeof(X509_VERIFY_PARAM_ID));
if (paramid == NULL) {
free(param);
return NULL;
}
param->id = paramid;
x509_verify_param_zero(param);
return param;
}
void
X509_VERIFY_PARAM_free(X509_VERIFY_PARAM *param)
{
if (param == NULL)
return;
x509_verify_param_zero(param);
free(param->id);
free(param);
}
/* This function determines how parameters are "inherited" from one structure
* to another. There are several different ways this can happen.
*
* 1. If a child structure needs to have its values initialized from a parent
* they are simply copied across. For example SSL_CTX copied to SSL.
* 2. If the structure should take on values only if they are currently unset.
* For example the values in an SSL structure will take appropriate value
* for SSL servers or clients but only if the application has not set new
* ones.
*
* The "inh_flags" field determines how this function behaves.
*
* Normally any values which are set in the default are not copied from the
* destination and verify flags are ORed together.
*
* If X509_VP_FLAG_DEFAULT is set then anything set in the source is copied
* to the destination. Effectively the values in "to" become default values
* which will be used only if nothing new is set in "from".
*
* If X509_VP_FLAG_OVERWRITE is set then all value are copied across whether
* they are set or not. Flags is still Ored though.
*
* If X509_VP_FLAG_RESET_FLAGS is set then the flags value is copied instead
* of ORed.
*
* If X509_VP_FLAG_LOCKED is set then no values are copied.
*
* If X509_VP_FLAG_ONCE is set then the current inh_flags setting is zeroed
* after the next call.
*/
/* Macro to test if a field should be copied from src to dest */
#define test_x509_verify_param_copy(field, def) \
(to_overwrite || \
((src->field != def) && (to_default || (dest->field == def))))
/* As above but for ID fields */
#define test_x509_verify_param_copy_id(idf, def) \
test_x509_verify_param_copy(id->idf, def)
/* Macro to test and copy a field if necessary */
#define x509_verify_param_copy(field, def) \
if (test_x509_verify_param_copy(field, def)) \
dest->field = src->field
int
X509_VERIFY_PARAM_inherit(X509_VERIFY_PARAM *dest, const X509_VERIFY_PARAM *src)
{
unsigned long inh_flags;
int to_default, to_overwrite;
X509_VERIFY_PARAM_ID *id;
if (!src)
return 1;
id = src->id;
inh_flags = dest->inh_flags | src->inh_flags;
if (inh_flags & X509_VP_FLAG_ONCE)
dest->inh_flags = 0;
if (inh_flags & X509_VP_FLAG_LOCKED)
return 1;
if (inh_flags & X509_VP_FLAG_DEFAULT)
to_default = 1;
else
to_default = 0;
if (inh_flags & X509_VP_FLAG_OVERWRITE)
to_overwrite = 1;
else
to_overwrite = 0;
x509_verify_param_copy(purpose, 0);
x509_verify_param_copy(trust, 0);
x509_verify_param_copy(depth, -1);
/* If overwrite or check time not set, copy across */
if (to_overwrite || !(dest->flags & X509_V_FLAG_USE_CHECK_TIME)) {
dest->check_time = src->check_time;
dest->flags &= ~X509_V_FLAG_USE_CHECK_TIME;
/* Don't need to copy flag: that is done below */
}
if (inh_flags & X509_VP_FLAG_RESET_FLAGS)
dest->flags = 0;
dest->flags |= src->flags;
if (test_x509_verify_param_copy(policies, NULL)) {
if (!X509_VERIFY_PARAM_set1_policies(dest, src->policies))
return 0;
}
/* Copy the host flags if and only if we're copying the host list */
if (test_x509_verify_param_copy_id(hosts, NULL)) {
if (dest->id->hosts) {
string_stack_free(dest->id->hosts);
dest->id->hosts = NULL;
}
if (id->hosts) {
dest->id->hosts =
sk_deep_copy(id->hosts, strdup, str_free);
if (dest->id->hosts == NULL)
return 0;
dest->id->hostflags = id->hostflags;
}
}
if (test_x509_verify_param_copy_id(email, NULL)) {
if (!X509_VERIFY_PARAM_set1_email(dest, id->email,
id->emaillen))
return 0;
}
if (test_x509_verify_param_copy_id(ip, NULL)) {
if (!X509_VERIFY_PARAM_set1_ip(dest, id->ip, id->iplen))
return 0;
}
return 1;
}
int
X509_VERIFY_PARAM_set1(X509_VERIFY_PARAM *to, const X509_VERIFY_PARAM *from)
{
unsigned long save_flags = to->inh_flags;
int ret;
to->inh_flags |= X509_VP_FLAG_DEFAULT;
ret = X509_VERIFY_PARAM_inherit(to, from);
to->inh_flags = save_flags;
return ret;
}
static int
int_x509_param_set1(char **pdest, size_t *pdestlen, const char *src,
size_t srclen)
{
char *tmp;
if (src) {
if (srclen == 0) {
if ((tmp = strdup(src)) == NULL)
return 0;
srclen = strlen(src);
} else {
if ((tmp = malloc(srclen)) == NULL)
return 0;
memcpy(tmp, src, srclen);
}
} else {
tmp = NULL;
srclen = 0;
}
if (*pdest)
free(*pdest);
*pdest = tmp;
if (pdestlen)
*pdestlen = srclen;
return 1;
}
int
X509_VERIFY_PARAM_set1_name(X509_VERIFY_PARAM *param, const char *name)
{
free(param->name);
param->name = NULL;
if (name == NULL)
return 1;
param->name = strdup(name);
if (param->name)
return 1;
return 0;
}
int
X509_VERIFY_PARAM_set_flags(X509_VERIFY_PARAM *param, unsigned long flags)
{
param->flags |= flags;
if (flags & X509_V_FLAG_POLICY_MASK)
param->flags |= X509_V_FLAG_POLICY_CHECK;
return 1;
}
int
X509_VERIFY_PARAM_clear_flags(X509_VERIFY_PARAM *param, unsigned long flags)
{
param->flags &= ~flags;
return 1;
}
unsigned long
X509_VERIFY_PARAM_get_flags(X509_VERIFY_PARAM *param)
{
return param->flags;
}
int
X509_VERIFY_PARAM_set_purpose(X509_VERIFY_PARAM *param, int purpose)
{
return X509_PURPOSE_set(¶m->purpose, purpose);
}
int
X509_VERIFY_PARAM_set_trust(X509_VERIFY_PARAM *param, int trust)
{
return X509_TRUST_set(¶m->trust, trust);
}
void
X509_VERIFY_PARAM_set_depth(X509_VERIFY_PARAM *param, int depth)
{
param->depth = depth;
}
void
X509_VERIFY_PARAM_set_time(X509_VERIFY_PARAM *param, time_t t)
{
param->check_time = t;
param->flags |= X509_V_FLAG_USE_CHECK_TIME;
}
int
X509_VERIFY_PARAM_add0_policy(X509_VERIFY_PARAM *param, ASN1_OBJECT *policy)
{
if (!param->policies) {
param->policies = sk_ASN1_OBJECT_new_null();
if (!param->policies)
return 0;
}
if (!sk_ASN1_OBJECT_push(param->policies, policy))
return 0;
return 1;
}
int
X509_VERIFY_PARAM_set1_policies(X509_VERIFY_PARAM *param,
STACK_OF(ASN1_OBJECT) *policies)
{
int i;
ASN1_OBJECT *oid, *doid;
if (!param)
return 0;
if (param->policies)
sk_ASN1_OBJECT_pop_free(param->policies, ASN1_OBJECT_free);
if (!policies) {
param->policies = NULL;
return 1;
}
param->policies = sk_ASN1_OBJECT_new_null();
if (!param->policies)
return 0;
for (i = 0; i < sk_ASN1_OBJECT_num(policies); i++) {
oid = sk_ASN1_OBJECT_value(policies, i);
doid = OBJ_dup(oid);
if (!doid)
return 0;
if (!sk_ASN1_OBJECT_push(param->policies, doid)) {
ASN1_OBJECT_free(doid);
return 0;
}
}
param->flags |= X509_V_FLAG_POLICY_CHECK;
return 1;
}
int
X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param,
const char *name, size_t namelen)
{
return int_x509_param_set_hosts(param->id, SET_HOST, name, namelen);
}
int
X509_VERIFY_PARAM_add1_host(X509_VERIFY_PARAM *param,
const char *name, size_t namelen)
{
return int_x509_param_set_hosts(param->id, ADD_HOST, name, namelen);
}
void
X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param, unsigned int flags)
{
param->id->hostflags = flags;
}
char *
X509_VERIFY_PARAM_get0_peername(X509_VERIFY_PARAM *param)
{
return param->id->peername;
}
int
X509_VERIFY_PARAM_set1_email(X509_VERIFY_PARAM *param, const char *email,
size_t emaillen)
{
return int_x509_param_set1(¶m->id->email, ¶m->id->emaillen,
email, emaillen);
}
int
X509_VERIFY_PARAM_set1_ip(X509_VERIFY_PARAM *param, const unsigned char *ip,
size_t iplen)
{
if (iplen != 0 && iplen != 4 && iplen != 16)
return 0;
return int_x509_param_set1((char **)¶m->id->ip, ¶m->id->iplen,
(char *)ip, iplen);
}
int
X509_VERIFY_PARAM_set1_ip_asc(X509_VERIFY_PARAM *param, const char *ipasc)
{
unsigned char ipout[16];
size_t iplen;
iplen = (size_t)a2i_ipadd(ipout, ipasc);
if (iplen == 0)
return 0;
return X509_VERIFY_PARAM_set1_ip(param, ipout, iplen);
}
int
X509_VERIFY_PARAM_get_depth(const X509_VERIFY_PARAM *param)
{
return param->depth;
}
const char *
X509_VERIFY_PARAM_get0_name(const X509_VERIFY_PARAM *param)
{
return param->name;
}
static const X509_VERIFY_PARAM_ID _empty_id = { NULL };
#define vpm_empty_id (X509_VERIFY_PARAM_ID *)&_empty_id
/*
* Default verify parameters: these are used for various applications and can
* be overridden by the user specified table.
*/
static const X509_VERIFY_PARAM default_table[] = {
{
.name = "default",
.depth = 100,
.trust = 0, /* XXX This is not the default trust value */
.id = vpm_empty_id
},
{
.name = "pkcs7",
.purpose = X509_PURPOSE_SMIME_SIGN,
.trust = X509_TRUST_EMAIL,
.depth = -1,
.id = vpm_empty_id
},
{
.name = "smime_sign",
.purpose = X509_PURPOSE_SMIME_SIGN,
.trust = X509_TRUST_EMAIL,
.depth = -1,
.id = vpm_empty_id
},
{
.name = "ssl_client",
.purpose = X509_PURPOSE_SSL_CLIENT,
.trust = X509_TRUST_SSL_CLIENT,
.depth = -1,
.id = vpm_empty_id
},
{
.name = "ssl_server",
.purpose = X509_PURPOSE_SSL_SERVER,
.trust = X509_TRUST_SSL_SERVER,
.depth = -1,
.id = vpm_empty_id
}
};
static STACK_OF(X509_VERIFY_PARAM) *param_table = NULL;
static int
param_cmp(const X509_VERIFY_PARAM * const *a,
const X509_VERIFY_PARAM * const *b)
{
return strcmp((*a)->name, (*b)->name);
}
int
X509_VERIFY_PARAM_add0_table(X509_VERIFY_PARAM *param)
{
X509_VERIFY_PARAM *ptmp;
if (!param_table) {
param_table = sk_X509_VERIFY_PARAM_new(param_cmp);
if (!param_table)
return 0;
} else {
size_t idx;
if ((idx = sk_X509_VERIFY_PARAM_find(param_table, param))
!= -1) {
ptmp = sk_X509_VERIFY_PARAM_value(param_table,
idx);
X509_VERIFY_PARAM_free(ptmp);
(void)sk_X509_VERIFY_PARAM_delete(param_table,
idx);
}
}
if (!sk_X509_VERIFY_PARAM_push(param_table, param))
return 0;
return 1;
}
int
X509_VERIFY_PARAM_get_count(void)
{
int num = sizeof(default_table) / sizeof(X509_VERIFY_PARAM);
if (param_table)
num += sk_X509_VERIFY_PARAM_num(param_table);
return num;
}
const
X509_VERIFY_PARAM *X509_VERIFY_PARAM_get0(int id)
{
int num = sizeof(default_table) / sizeof(X509_VERIFY_PARAM);
if (id < num)
return default_table + id;
return sk_X509_VERIFY_PARAM_value(param_table, id - num);
}
const
X509_VERIFY_PARAM *X509_VERIFY_PARAM_lookup(const char *name)
{
X509_VERIFY_PARAM pm;
unsigned int i, limit;
pm.name = (char *)name;
if (param_table) {
size_t idx;
if ((idx = sk_X509_VERIFY_PARAM_find(param_table, &pm)) != -1)
return sk_X509_VERIFY_PARAM_value(param_table, idx);
}
limit = sizeof(default_table) / sizeof(X509_VERIFY_PARAM);
for (i = 0; i < limit; i++) {
if (strcmp(default_table[i].name, name) == 0) {
return &default_table[i];
}
}
return NULL;
}
void
X509_VERIFY_PARAM_table_cleanup(void)
{
if (param_table)
sk_X509_VERIFY_PARAM_pop_free(param_table,
X509_VERIFY_PARAM_free);
param_table = NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-295/c/good_682_0 |
crossvul-cpp_data_bad_4693_0 | /***
x509 modules for lua-openssl binding
create and manage x509 certificate
@module x509
@usage
x509 = require'openssl'.x509
*/
#include "openssl.h"
#include "private.h"
#define CRYPTO_LOCK_REF
#include "sk.h"
#define MYNAME "x509"
#define MYVERSION MYNAME " library for " LUA_VERSION " / Nov 2014 / "\
"based on OpenSSL " SHLIB_VERSION_NUMBER
#if OPENSSL_VERSION_NUMBER < 0x1010000fL || \
(defined(LIBRESSL_VERSION_NUMBER) && (LIBRESSL_VERSION_NUMBER < 0x20700000L))
#define X509_get0_notBefore X509_get_notBefore
#define X509_get0_notAfter X509_get_notAfter
#define X509_set1_notBefore X509_set_notBefore
#define X509_set1_notAfter X509_set_notAfter
#endif
static int openssl_push_purpose(lua_State*L, X509_PURPOSE* purpose)
{
lua_newtable(L);
AUXILIAR_SET(L, -1, "purpose", purpose->purpose, integer);
AUXILIAR_SET(L, -1, "trust", purpose->trust, integer);
AUXILIAR_SET(L, -1, "flags", purpose->flags, integer);
AUXILIAR_SET(L, -1, "name", purpose->name, string);
AUXILIAR_SET(L, -1, "sname", purpose->sname, string);
return 1;
};
/***
return all supported purpose as table
@function purpose
@treturn table
*/
/*
get special purpose info as table
@function purpose
@tparam number|string purpose id or short name
@treturn table
*/
static int openssl_x509_purpose(lua_State*L)
{
if (lua_isnone(L, 1))
{
int count = X509_PURPOSE_get_count();
int i;
lua_newtable(L);
for (i = 0; i < count; i++)
{
X509_PURPOSE* purpose = X509_PURPOSE_get0(i);
openssl_push_purpose(L, purpose);
lua_rawseti(L, -2, i + 1);
}
return 1;
}
else if (lua_isnumber(L, 1))
{
int idx = X509_PURPOSE_get_by_id(lua_tointeger(L, 1));
if (idx >= 0)
{
X509_PURPOSE* purpose = X509_PURPOSE_get0(idx);
openssl_push_purpose(L, purpose);
}
else
lua_pushnil(L);
return 1;
}
else if (lua_isstring(L, 1))
{
char* name = (char*)lua_tostring(L, 1);
int idx = X509_PURPOSE_get_by_sname(name);
if (idx >= 0)
{
X509_PURPOSE* purpose = X509_PURPOSE_get0(idx);
openssl_push_purpose(L, purpose);
}
else
lua_pushnil(L);
return 1;
}
else
luaL_argerror(L, 1, "only accpet none, string or number as nid or short name");
return 0;
};
static const char* usage_mode[] =
{
"standard",
"netscape",
"extend",
NULL
};
/***
get support certtypes
@function certtypes
@tparam[opt='standard'] string type support 'standard','netscape','extend'
@treturn table if type is 'standard' or 'netscape', contains node with {lname=...,sname=...,bitname=...},
if type is 'extend', contains node with {lname=...,sname=...,nid=...}
*/
static int openssl_x509_certtypes(lua_State*L)
{
int mode = luaL_checkoption(L, 1, "standard", usage_mode);
int i;
const BIT_STRING_BITNAME* bitname;
switch (mode)
{
case 0:
{
const static BIT_STRING_BITNAME key_usage_type_table[] =
{
{0, "Digital Signature", "digitalSignature"},
{1, "Non Repudiation", "nonRepudiation"},
{2, "Key Encipherment", "keyEncipherment"},
{3, "Data Encipherment", "dataEncipherment"},
{4, "Key Agreement", "keyAgreement"},
{5, "Certificate Sign", "keyCertSign"},
{6, "CRL Sign", "cRLSign"},
{7, "Encipher Only", "encipherOnly"},
{8, "Decipher Only", "decipherOnly"},
{ -1, NULL, NULL}
};
lua_newtable(L);
for (i = 0, bitname = &key_usage_type_table[i]; bitname->bitnum != -1; i++, bitname = &key_usage_type_table[i])
{
openssl_push_bit_string_bitname(L, bitname);
lua_rawseti(L, -2, i + 1);
}
return 1;
}
case 1:
{
const static BIT_STRING_BITNAME ns_cert_type_table[] =
{
{0, "SSL Client", "client"},
{1, "SSL Server", "server"},
{2, "S/MIME", "email"},
{3, "Object Signing", "objsign"},
{4, "Unused", "reserved"},
{5, "SSL CA", "sslCA"},
{6, "S/MIME CA", "emailCA"},
{7, "Object Signing CA", "objCA"},
{ -1, NULL, NULL}
};
lua_newtable(L);
for (i = 0, bitname = &ns_cert_type_table[i]; bitname->bitnum != -1; i++, bitname = &ns_cert_type_table[i])
{
openssl_push_bit_string_bitname(L, bitname);
lua_rawseti(L, -2, i + 1);
}
return 1;
}
case 2:
{
static const int ext_nids[] =
{
NID_server_auth,
NID_client_auth,
NID_email_protect,
NID_code_sign,
NID_ms_sgc,
NID_ns_sgc,
NID_OCSP_sign,
NID_time_stamp,
NID_dvcs,
NID_anyExtendedKeyUsage
};
int count = sizeof(ext_nids) / sizeof(int);
int nid;
lua_newtable(L);
for (i = 0; i < count; i++)
{
nid = ext_nids[i];
lua_newtable(L);
lua_pushstring(L, OBJ_nid2ln(nid));
lua_setfield(L, -2, "lname");
lua_pushstring(L, OBJ_nid2sn(nid));
lua_setfield(L, -2, "sname");
lua_pushinteger(L, nid);
lua_setfield(L, -2, "nid");
lua_rawseti(L, -2, i + 1);
};
return 1;
}
}
return 0;
}
/***
get certificate verify result string message
@function verify_cert_error_string
@tparam number verify_result
@treturn string result message
*/
static int openssl_verify_cert_error_string(lua_State*L)
{
int v = luaL_checkint(L, 1);
const char*s = X509_verify_cert_error_string(v);
lua_pushstring(L, s);
return 1;
}
/***
read x509 from string or bio input
@function read
@tparam bio|string input input data
@tparam[opt='auto'] string format support 'auto','pem','der'
@treturn x509 certificate object
*/
static LUA_FUNCTION(openssl_x509_read)
{
X509 *cert = NULL;
BIO *in = load_bio_object(L, 1);
int fmt = luaL_checkoption(L, 2, "auto", format);
if (fmt == FORMAT_AUTO)
{
fmt = bio_is_der(in) ? FORMAT_DER : FORMAT_PEM;
}
if (fmt == FORMAT_DER)
{
cert = d2i_X509_bio(in, NULL);
}
else if (fmt == FORMAT_PEM)
{
cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
}
BIO_free(in);
if (cert)
{
PUSH_OBJECT(cert, "openssl.x509");
return 1;
}
return openssl_pushresult(L, 0);
}
/***
create or generate a new x509 object.
@function new
@tparam[opt] openssl.bn serial serial number
@tparam[opt] x509_req csr,copy x509_name, pubkey and extension to new object
@tparam[opt] x509_name subject subject name set to x509_req
@tparam[opt] stack_of_x509_extension extensions add to x509
@tparam[opt] stack_of_x509_attribute attributes add to x509
@treturn x509 certificate object
*/
static int openssl_x509_new(lua_State* L)
{
int i = 1;
int ret = 1;
int n = lua_gettop(L);
X509 *x = X509_new();
ret = X509_set_version(x, 2);
if (ret == 1 && (
auxiliar_getclassudata(L, "openssl.bn", i) ||
lua_isstring(L, i) || lua_isnumber(L, i)
))
{
BIGNUM *bn = BN_get(L, i);
ASN1_INTEGER* ai = BN_to_ASN1_INTEGER(bn, NULL);
BN_free(bn);
ret = X509_set_serialNumber(x, ai);
ASN1_INTEGER_free(ai);
i++;
}
for (; i <= n; i++)
{
if (ret == 1 && auxiliar_getclassudata(L, "openssl.x509_req", i))
{
X509_REQ* csr = CHECK_OBJECT(i, X509_REQ, "openssl.x509_req");
X509_NAME* xn = X509_REQ_get_subject_name(csr);
ret = X509_set_subject_name(x, xn);
if (ret == 1)
{
STACK_OF(X509_EXTENSION) *exts = X509_REQ_get_extensions(csr);
int j, n1;
n1 = sk_X509_EXTENSION_num(exts);
for (j = 0; ret == 1 && j < n1; j++)
{
ret = X509_add_ext(x, sk_X509_EXTENSION_value(exts, j), j);
}
sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
}
if (ret == 1)
{
EVP_PKEY* pkey = X509_REQ_get_pubkey(csr);
ret = X509_set_pubkey(x, pkey);
EVP_PKEY_free(pkey);
}
i++;
};
if (ret == 1 && auxiliar_getclassudata(L, "openssl.x509_name", i))
{
X509_NAME *xn = CHECK_OBJECT(i, X509_NAME, "openssl.x509_name");
ret = X509_set_subject_name(x, xn);
i++;
}
}
if (ret == 1)
{
PUSH_OBJECT(x, "openssl.x509");
return 1;
}
else
{
X509_free(x);
return openssl_pushresult(L, ret);
}
};
static luaL_Reg R[] =
{
{"new", openssl_x509_new },
{"read", openssl_x509_read },
{"purpose", openssl_x509_purpose },
{"certtypes", openssl_x509_certtypes },
{"verify_cert_error_string", openssl_verify_cert_error_string },
{NULL, NULL}
};
int openssl_push_general_name(lua_State*L, const GENERAL_NAME* general_name)
{
if (general_name == NULL)
{
lua_pushnil(L);
return 1;
}
lua_newtable(L);
switch (general_name->type)
{
case GEN_OTHERNAME:
{
OTHERNAME *otherName = general_name->d.otherName;
lua_newtable(L);
openssl_push_asn1object(L, otherName->type_id);
PUSH_ASN1_STRING(L, otherName->value->value.asn1_string);
lua_settable(L, -3);
lua_setfield(L, -2, "otherName");
lua_pushstring(L, "otherName");
lua_setfield(L, -2, "type");
break;
}
case GEN_EMAIL:
PUSH_ASN1_STRING(L, general_name->d.rfc822Name);
lua_setfield(L, -2, "rfc822Name");
lua_pushstring(L, "rfc822Name");
lua_setfield(L, -2, "type");
break;
case GEN_DNS:
PUSH_ASN1_STRING(L, general_name->d.dNSName);
lua_setfield(L, -2, "dNSName");
lua_pushstring(L, "dNSName");
lua_setfield(L, -2, "type");
break;
case GEN_X400:
openssl_push_asn1type(L, general_name->d.x400Address);
lua_setfield(L, -2, "x400Address");
lua_pushstring(L, "x400Address");
lua_setfield(L, -2, "type");
break;
case GEN_DIRNAME:
{
X509_NAME* xn = general_name->d.directoryName;
openssl_push_xname_asobject(L, xn);
lua_setfield(L, -2, "directoryName");
lua_pushstring(L, "directoryName");
lua_setfield(L, -2, "type");
}
break;
case GEN_URI:
PUSH_ASN1_STRING(L, general_name->d.uniformResourceIdentifier);
lua_setfield(L, -2, "uniformResourceIdentifier");
lua_pushstring(L, "uniformResourceIdentifier");
lua_setfield(L, -2, "type");
break;
case GEN_IPADD:
lua_newtable(L);
PUSH_ASN1_OCTET_STRING(L, general_name->d.iPAddress);
lua_setfield(L, -2, "iPAddress");
lua_pushstring(L, "iPAddress");
lua_setfield(L, -2, "type");
break;
case GEN_EDIPARTY:
lua_newtable(L);
PUSH_ASN1_STRING(L, general_name->d.ediPartyName->nameAssigner);
lua_setfield(L, -2, "nameAssigner");
PUSH_ASN1_STRING(L, general_name->d.ediPartyName->partyName);
lua_setfield(L, -2, "partyName");
lua_setfield(L, -2, "ediPartyName");
lua_pushstring(L, "ediPartyName");
lua_setfield(L, -2, "type");
break;
case GEN_RID:
lua_newtable(L);
openssl_push_asn1object(L, general_name->d.registeredID);
lua_setfield(L, -2, "registeredID");
lua_pushstring(L, "registeredID");
lua_setfield(L, -2, "type");
break;
default:
lua_pushstring(L, "unsupport");
lua_setfield(L, -2, "type");
}
return 1;
};
static int check_cert(X509_STORE *ca, X509 *x, STACK_OF(X509) *untrustedchain, int purpose)
{
int ret = 0;
X509_STORE_CTX *csc = X509_STORE_CTX_new();
if (csc)
{
X509_STORE_set_flags(ca, X509_V_FLAG_CHECK_SS_SIGNATURE);
if (X509_STORE_CTX_init(csc, ca, x, untrustedchain) == 1)
{
if (purpose > 0)
{
X509_STORE_CTX_set_purpose(csc, purpose);
}
ret = X509_verify_cert(csc);
if (ret == 1)
ret = X509_V_OK;
else
ret = X509_STORE_CTX_get_error(csc);
}
X509_STORE_CTX_free(csc);
return ret;
}
return X509_V_ERR_OUT_OF_MEM;
}
/***
openssl.x509 object
@type x509
*/
/***
export x509_req to string
@function export
@tparam[opt='pem'] string format, 'der' or 'pem' default
@tparam[opt='true'] boolean noext not export extension
@treturn string
*/
static LUA_FUNCTION(openssl_x509_export)
{
X509 *cert = CHECK_OBJECT(1, X509, "openssl.x509");
int fmt = luaL_checkoption(L, 2, "pem", format);
int notext = lua_isnone(L, 3) ? 1 : lua_toboolean(L, 3);
BIO* out = NULL;
if (fmt != FORMAT_DER && fmt != FORMAT_PEM)
{
luaL_argerror(L, 2, "format only accept pem or der");
}
out = BIO_new(BIO_s_mem());
if (fmt == FORMAT_PEM)
{
if (!notext)
{
X509_print(out, cert);
}
if (PEM_write_bio_X509(out, cert))
{
BUF_MEM *bio_buf;
BIO_get_mem_ptr(out, &bio_buf);
lua_pushlstring(L, bio_buf->data, bio_buf->length);
}
else
lua_pushnil(L);
}
else
{
if (i2d_X509_bio(out, cert))
{
BUF_MEM *bio_buf;
BIO_get_mem_ptr(out, &bio_buf);
lua_pushlstring(L, bio_buf->data, bio_buf->length);
}
else
lua_pushnil(L);
}
BIO_free(out);
return 1;
};
/***
parse x509 object as table
@function parse
@tparam[opt=true] shortname default will use short object name
@treturn table result which all x509 information
*/
static LUA_FUNCTION(openssl_x509_parse)
{
int i;
X509 * cert = CHECK_OBJECT(1, X509, "openssl.x509");
X509_ALGOR* alg = 0;
lua_newtable(L);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
if (cert->name)
{
AUXILIAR_SET(L, -1, "name", cert->name, string);
}
AUXILIAR_SET(L, -1, "valid", cert->valid, boolean);
#endif
AUXILIAR_SET(L, -1, "version", X509_get_version(cert), integer);
openssl_push_xname_asobject(L, X509_get_subject_name(cert));
lua_setfield(L, -2, "subject");
openssl_push_xname_asobject(L, X509_get_issuer_name(cert));
lua_setfield(L, -2, "issuer");
{
char buf[32];
snprintf(buf, sizeof(buf), "%08lx", X509_subject_name_hash(cert));
AUXILIAR_SET(L, -1, "hash", buf, string);
}
PUSH_ASN1_INTEGER(L, X509_get0_serialNumber(cert));
lua_setfield(L, -2, "serialNumber");
PUSH_ASN1_TIME(L, X509_get0_notBefore(cert));
lua_setfield(L, -2, "notBefore");
PUSH_ASN1_TIME(L, X509_get0_notAfter(cert));
lua_setfield(L, -2, "notAfter");
{
CONSTIFY_X509_get0 X509_ALGOR *palg = NULL;
CONSTIFY_X509_get0 ASN1_BIT_STRING *psig = NULL;
X509_get0_signature(&psig, &palg, cert);
if (palg != NULL)
{
alg = X509_ALGOR_dup((X509_ALGOR*)palg);
PUSH_OBJECT(alg, "openssl.x509_algor");
lua_setfield(L, -2, "sig_alg");
}
if (psig != NULL)
{
lua_pushlstring(L, (const char *)psig->data, psig->length);
lua_setfield(L, -2, "sig");
}
}
{
int l = 0;
char* tmpstr = (char *)X509_alias_get0(cert, &l);
if (tmpstr)
{
AUXILIAR_SETLSTR(L, -1, "alias", tmpstr, l);
}
}
AUXILIAR_SET(L, -1, "ca", X509_check_ca(cert), boolean);
lua_newtable(L);
for (i = 0; i < X509_PURPOSE_get_count(); i++)
{
int set;
X509_PURPOSE *purp = X509_PURPOSE_get0(i);
int id = X509_PURPOSE_get_id(purp);
const char * pname = X509_PURPOSE_get0_sname(purp);
set = X509_check_purpose(cert, id, 0);
if (set)
{
AUXILIAR_SET(L, -1, pname, 1, boolean);
}
set = X509_check_purpose(cert, id, 1);
if (set)
{
lua_pushfstring(L, "%s CA", pname);
pname = lua_tostring(L, -1);
AUXILIAR_SET(L, -2, pname, 1, boolean);
lua_pop(L, 1);
}
}
lua_setfield(L, -2, "purposes");
{
int n = X509_get_ext_count(cert);
if (n > 0)
{
lua_pushstring(L, "extensions");
lua_newtable(L);
for (i = 0; i < n; i++)
{
X509_EXTENSION *ext = X509_get_ext(cert, i);
ext = X509_EXTENSION_dup(ext);
lua_pushinteger(L, i + 1);
PUSH_OBJECT(ext, "openssl.x509_extension");
lua_rawset(L, -3);
}
lua_rawset(L, -3);
}
}
return 1;
}
static LUA_FUNCTION(openssl_x509_free)
{
X509 *cert = CHECK_OBJECT(1, X509, "openssl.x509");
X509_free(cert);
return 0;
}
/***
get public key of x509
@function pubkey
@treturn evp_pkey public key
*/
/***
set public key of x509
@function pubkey
@tparam evp_pkey pubkey public key set to x509
@treturn boolean result, true for success
*/
static LUA_FUNCTION(openssl_x509_public_key)
{
X509 *cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
EVP_PKEY *pkey = X509_get_pubkey(cert);
PUSH_OBJECT(pkey, "openssl.evp_pkey");
return 1;
}
else
{
EVP_PKEY* pkey = CHECK_OBJECT(2, EVP_PKEY, "openssl.evp_pkey");
int ret = X509_set_pubkey(cert, pkey);
return openssl_pushresult(L, ret);
}
}
#if 0
static int verify_cb(int ok, X509_STORE_CTX *ctx)
{
int err;
X509 *err_cert;
/*
* it is ok to use a self signed certificate This case will catch both
* the initial ok == 0 and the final ok == 1 calls to this function
*/
err = X509_STORE_CTX_get_error(ctx);
if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
return 1;
/*
* BAD we should have gotten an error. Normally if everything worked
* X509_STORE_CTX_get_error(ctx) will still be set to
* DEPTH_ZERO_SELF_....
*/
if (ok)
{
//BIO_printf(bio_err, "error with certificate to be certified - should be self signed\n");
return 0;
}
else
{
err_cert = X509_STORE_CTX_get_current_cert(ctx);
//print_name(bio_err, NULL, X509_get_subject_name(err_cert), 0);
//BIO_printf(bio_err, "error with certificate - error %d at depth %d\n%s\n", err, X509_STORE_CTX_get_error_depth(ctx), X509_verify_cert_error_string(err));
return 1;
}
}
#endif
/***
check x509 with ca certchian and option purpose
purpose can be one of: ssl_client, ssl_server, ns_ssl_server, smime_sign, smime_encrypt, crl_sign, any, ocsp_helper, timestamp_sign
@function check
@tparam x509_store cacerts
@tparam x509_store untrusted certs containing a bunch of certs that are not trusted but may be useful in validating the certificate.
@tparam[opt] string purpose to check supported
@treturn boolean result true for check pass
@treturn integer verify result
@see verify_cert_error_string
*/
/***
check x509 with evp_pkey
@function check
@tparam evp_pkey pkey private key witch match with x509 pubkey
@treturn boolean result true for check pass
*/
static LUA_FUNCTION(openssl_x509_check)
{
X509 * cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (auxiliar_getclassudata(L, "openssl.evp_pkey", 2))
{
EVP_PKEY * key = CHECK_OBJECT(2, EVP_PKEY, "openssl.evp_pkey");
lua_pushboolean(L, X509_check_private_key(cert, key));
return 1;
}
else
{
X509_STORE* store = CHECK_OBJECT(2, X509_STORE, "openssl.x509_store");
STACK_OF(X509)* untrustedchain = lua_isnoneornil(L, 3) ? NULL : openssl_sk_x509_fromtable(L, 3);
int purpose = 0;
int ret = 0;
if (!lua_isnone(L, 4))
{
int purpose_id = X509_PURPOSE_get_by_sname((char*)luaL_optstring(L, 4, "any"));
if (purpose_id >= 0)
{
X509_PURPOSE* ppurpose = X509_PURPOSE_get0(purpose_id);
if (ppurpose)
{
purpose = ppurpose->purpose;
}
}
}
#if 0
X509_STORE_set_verify_cb_func(store, verify_cb);
#endif
if (untrustedchain!=NULL)
sk_X509_pop_free(untrustedchain, X509_free);
ret = check_cert(store, cert, untrustedchain, purpose);
lua_pushboolean(L, ret == X509_V_OK);
lua_pushinteger(L, ret);
return 2;
}
}
#if OPENSSL_VERSION_NUMBER > 0x10002000L
/***
check x509 for host (only for openssl 1.0.2 or greater)
@function check_host
@tparam string host hostname to check for match match with x509 subject
@treturn boolean result true if host is present and matches the certificate
*/
static LUA_FUNCTION(openssl_x509_check_host)
{
X509 * cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isstring(L, 2))
{
const char *hostname = lua_tostring(L, 2);
lua_pushboolean(L, X509_check_host(cert, hostname, strlen(hostname), 0, NULL));
}
else
{
lua_pushboolean(L, 0);
}
return 1;
}
/***
check x509 for email address (only for openssl 1.0.2 or greater)
@tparam string email to check for match match with x509 subject
@treturn boolean result true if host is present and matches the certificate
@function check_email
*/
static LUA_FUNCTION(openssl_x509_check_email)
{
X509 * cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isstring(L, 2))
{
const char *email = lua_tostring(L, 2);
lua_pushboolean(L, X509_check_email(cert, email, strlen(email), 0));
}
else
{
lua_pushboolean(L, 0);
}
return 1;
}
/***
check x509 for ip address (ipv4 or ipv6, only for openssl 1.0.2 or greater)
@function check_ip_asc
@tparam string ip to check for match match with x509 subject
@treturn boolean result true if host is present and matches the certificate
*/
static LUA_FUNCTION(openssl_x509_check_ip_asc)
{
X509 * cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isstring(L, 2))
{
const char *ip_asc = lua_tostring(L, 2);
lua_pushboolean(L, X509_check_ip_asc(cert, ip_asc, 0));
}
else
{
lua_pushboolean(L, 0);
}
return 1;
}
#endif
IMP_LUA_SK(X509, x509)
#if 0
static STACK_OF(X509) * load_all_certs_from_file(BIO *in)
{
STACK_OF(X509) *stack = sk_X509_new_null();
if (stack)
{
STACK_OF(X509_INFO) *sk = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL);
/* scan over it and pull out the certs */
while (sk_X509_INFO_num(sk))
{
X509_INFO *xi = sk_X509_INFO_shift(sk);
if (xi->x509 != NULL)
{
sk_X509_push(stack, xi->x509);
xi->x509 = NULL;
}
X509_INFO_free(xi);
}
sk_X509_INFO_free(sk);
};
if (sk_X509_num(stack) == 0)
{
sk_X509_free(stack);
stack = NULL;
}
return stack;
};
#endif
/***
get subject name of x509
@function subject
@treturn x509_name subject name
*/
/***
set subject name of x509
@function subject
@tparam x509_name subject
@treturn boolean result true for success
*/
static int openssl_x509_subject(lua_State* L)
{
X509* cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
X509_NAME* xn = X509_get_subject_name(cert);
return openssl_push_xname_asobject(L, xn);
}
else
{
X509_NAME *xn = CHECK_OBJECT(2, X509_NAME, "openssl.x509_name");
int ret = X509_set_subject_name(cert, xn);
return openssl_pushresult(L, ret);
}
}
/***
get issuer name of x509
@function issuer
@tparam[opt=false] boolean asobject, true for return as x509_name object, or as table
@treturn[1] x509_name issuer
@treturn[1] table issuer name as table
*/
/***
set issuer name of x509
@function issuer
@tparam x509_name name
@treturn boolean result true for success
*/
static int openssl_x509_issuer(lua_State* L)
{
X509* cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
X509_NAME* xn = X509_get_issuer_name(cert);
return openssl_push_xname_asobject(L, xn);
}
else
{
X509_NAME* xn = CHECK_OBJECT(2, X509_NAME, "openssl.x509_name");
int ret = X509_set_issuer_name(cert, xn);
return openssl_pushresult(L, ret);
}
}
/***
get digest of x509 object
@function digest
@tparam[opt='sha1'] evp_digest|string md_alg, default use 'sha1'
@treturn string digest result
*/
static int openssl_x509_digest(lua_State* L)
{
unsigned int bytes;
unsigned char buffer[EVP_MAX_MD_SIZE];
char hex_buffer[EVP_MAX_MD_SIZE * 2];
X509 *cert = CHECK_OBJECT(1, X509, "openssl.x509");
const EVP_MD *digest = get_digest(L, 2, "sha256");
int ret;
if (!digest)
{
lua_pushnil(L);
lua_pushfstring(L, "digest algorithm not supported (%s)", lua_tostring(L, 2));
return 2;
}
ret = X509_digest(cert, digest, buffer, &bytes);
if (ret)
{
to_hex((char*)buffer, bytes, hex_buffer);
lua_pushlstring(L, hex_buffer, bytes * 2);
return 1;
}
return openssl_pushresult(L, ret);
};
/***
get notbefore valid time of x509
@function notbefore
@treturn string notbefore time string
*/
/***
set notbefore valid time of x509
@function notbefore
@tparam string|number notbefore
*/
static int openssl_x509_notbefore(lua_State *L)
{
X509* cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
return PUSH_ASN1_TIME(L, X509_get0_notBefore(cert));
}
else
{
ASN1_TIME* at = NULL;
int ret = 1;
if (lua_isnumber(L, 2))
{
time_t time = lua_tointeger(L, 2);
at = ASN1_TIME_new();
ASN1_TIME_set(at, time);
}
else if (lua_isstring(L, 2))
{
const char* time = lua_tostring(L, 2);
at = ASN1_TIME_new();
if (ASN1_TIME_set_string(at, time) != 1)
{
ASN1_TIME_free(at);
at = NULL;
}
}
if (at)
{
ret = X509_set1_notBefore(cert, at);
ASN1_TIME_free(at);
}
else
ret = 0;
return openssl_pushresult(L, ret);
};
}
/***
get notafter valid time of x509
@function notafter
@treturn string notafter time string
*/
/***
set notafter valid time of x509
@function notafter
@tparam string|number notafter
*/
static int openssl_x509_notafter(lua_State *L)
{
X509* cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
return PUSH_ASN1_TIME(L, X509_get0_notAfter(cert));
}
else
{
ASN1_TIME* at = NULL;
int ret = 1;
if (lua_isnumber(L, 2))
{
time_t time = lua_tointeger(L, 2);
at = ASN1_TIME_new();
ASN1_TIME_set(at, time);
}
else if (lua_isstring(L, 2))
{
const char* time = lua_tostring(L, 2);
at = ASN1_TIME_new();
if (ASN1_TIME_set_string(at, time) != 1)
{
ASN1_TIME_free(at);
at = NULL;
}
}
if (at)
{
ret = X509_set1_notAfter(cert, at);
ASN1_TIME_free(at);
}
else
ret = 0;
return openssl_pushresult(L, ret);
}
}
/***
check x509 valid
@function validat
@tparam[opt] number time, default will use now time
@treturn boolean result true for valid, or for invalid
@treturn string notbefore
@treturn string notafter
*/
/***
set valid time, notbefore and notafter
@function validat
@tparam number notbefore
@tparam number notafter
@treturn boolean result, true for success
*/
static int openssl_x509_valid_at(lua_State* L)
{
X509* cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
time_t now = 0;;
time(&now);
lua_pushboolean(L, (X509_cmp_time(X509_get0_notAfter(cert), &now) >= 0
&& X509_cmp_time(X509_get0_notBefore(cert), &now) <= 0));
PUSH_ASN1_TIME(L, X509_get0_notBefore(cert));
PUSH_ASN1_TIME(L, X509_get0_notAfter(cert));
return 3;
}
else if (lua_gettop(L) == 2)
{
time_t time = luaL_checkinteger(L, 2);
lua_pushboolean(L, (X509_cmp_time(X509_get0_notAfter(cert), &time) >= 0
&& X509_cmp_time(X509_get0_notBefore(cert), &time) <= 0));
PUSH_ASN1_TIME(L, X509_get0_notBefore(cert));
PUSH_ASN1_TIME(L, X509_get0_notAfter(cert));
return 3;
}
else if (lua_gettop(L) == 3)
{
time_t before, after;
ASN1_TIME *ab, *aa;
int ret = 1;
before = lua_tointeger(L, 2);
after = lua_tointeger(L, 3);
ab = ASN1_TIME_new();
aa = ASN1_TIME_new();
ASN1_TIME_set(ab, before);
ASN1_TIME_set(aa, after);
ret = X509_set1_notBefore(cert, ab);
if (ret == 1)
ret = X509_set1_notAfter(cert, aa);
ASN1_TIME_free(ab);
ASN1_TIME_free(aa);
return openssl_pushresult(L, ret);
}
return 0;
}
/***
get serial number of x509
@function serial
@tparam[opt=true] boolean asobject
@treturn[1] bn object
@treturn[2] string result
*/
/***
set serial number of x509
@function serial
@tparam string|number|bn serail
@treturn boolean result true for success
*/
static int openssl_x509_serial(lua_State *L)
{
X509* cert = CHECK_OBJECT(1, X509, "openssl.x509");
ASN1_INTEGER *serial = X509_get_serialNumber(cert);
if (lua_isboolean(L, 2))
{
int asobj = lua_toboolean(L, 2);
if (asobj)
{
PUSH_ASN1_INTEGER(L, serial);
}
else
{
BIGNUM *bn = ASN1_INTEGER_to_BN(serial, NULL);
PUSH_OBJECT(bn, "openssl.bn");
}
}
else if (lua_isnone(L, 2))
{
BIGNUM *bn = ASN1_INTEGER_to_BN(serial, NULL);
char *tmp = BN_bn2hex(bn);
lua_pushstring(L, tmp);
OPENSSL_free(tmp);
BN_free(bn);
}
else
{
int ret;
if (auxiliar_getclassudata(L, "openssl.asn1_string", 2))
{
serial = CHECK_OBJECT(2, ASN1_STRING, "openssl.asn1_string");
}
else
{
BIGNUM *bn = BN_get(L, 2);
serial = BN_to_ASN1_INTEGER(bn, NULL);
BN_free(bn);
}
luaL_argcheck(L, serial != NULL, 2, "not accept");
ret = X509_set_serialNumber(cert, serial);
ASN1_INTEGER_free(serial);
return openssl_pushresult(L, ret);
}
return 1;
}
/***
get version number of x509
@function version
@treturn number version of x509
*/
/***
set version number of x509
@function version
@tparam number version
@treturn boolean result true for result
*/
static int openssl_x509_version(lua_State *L)
{
int version;
X509* cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
version = X509_get_version(cert);
lua_pushinteger(L, version);
return 1;
}
else
{
int ret;
version = luaL_checkint(L, 2);
ret = X509_set_version(cert, version);
return openssl_pushresult(L, ret);
}
}
/***
get extensions of x509 object
@function extensions
@tparam[opt=false] boolean asobject, true for return as stack_of_x509_extension or as table
@treturn[1] stack_of_x509_extension object when param set true
@treturn[2] table contain all x509_extension when param set false or nothing
*/
/***
set extension of x509 object
@function extensions
@tparam stack_of_x509_extension extensions
@treturn boolean result true for success
*/
static int openssl_x509_extensions(lua_State* L)
{
X509 *self = CHECK_OBJECT(1, X509, "openssl.x509");
STACK_OF(X509_EXTENSION) *exts = (STACK_OF(X509_EXTENSION) *)X509_get0_extensions(self);
if (lua_isnone(L, 2))
{
if (exts)
{
openssl_sk_x509_extension_totable(L, exts);
}
else
lua_pushnil(L);
return 1;
}
else
{
STACK_OF(X509_EXTENSION) *others = (STACK_OF(X509_EXTENSION) *)openssl_sk_x509_extension_fromtable(L, 2);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
sk_X509_EXTENSION_pop_free(self->cert_info->extensions, X509_EXTENSION_free);
self->cert_info->extensions = others;
#else
int i;
int n = sk_X509_EXTENSION_num(exts);
for (i = 0; i < n; i++)
sk_X509_EXTENSION_delete(exts, i);
n = sk_X509_EXTENSION_num(others);
for (i = 0; i < n; i++)
{
X509_EXTENSION* ext = sk_X509_EXTENSION_value(others, i);
if (exts!=NULL)
sk_X509_EXTENSION_push(exts, ext);
else
X509_add_ext(self, ext, -1);
}
sk_X509_EXTENSION_pop_free(others, X509_EXTENSION_free);
#endif
return openssl_pushresult(L, 1);
}
}
/***
sign x509
@function sign
@tparam evp_pkey pkey private key to sign x509
@tparam x509|x509_name cacert or cacert x509_name
@tparam[opt='sha1WithRSAEncryption'] string|md_digest md_alg
@treturn boolean result true for check pass
*/
static int openssl_x509_sign(lua_State*L)
{
X509* x = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
unsigned char *out = NULL;
int len = i2d_re_X509_tbs(x, &out);
if (len > 0)
{
lua_pushlstring(L, (const char *)out, len);
OPENSSL_free(out);
return 1;
}
return openssl_pushresult(L, len);
}
else if (auxiliar_getclassudata(L, "openssl.evp_pkey", 2))
{
EVP_PKEY* pkey = CHECK_OBJECT(2, EVP_PKEY, "openssl.evp_pkey");
const EVP_MD *md;
int ret = 1;
int i = 3;
if (auxiliar_getclassudata(L, "openssl.x509_name", 3))
{
X509_NAME* xn = CHECK_OBJECT(3, X509_NAME, "openssl.x509_name");
ret = X509_set_issuer_name(x, xn);
i++;
}
else
{
X509* ca = CHECK_OBJECT(3, X509, "openssl.x509");
X509_NAME* xn = X509_get_subject_name(ca);
ret = X509_check_private_key(ca, pkey);
if (ret == 1)
{
ret = X509_set_issuer_name(x, xn);
}
i++;
}
if (ret == 1)
{
md = get_digest(L, i, "sha256");
ret = X509_sign(x, pkey, md);
if (ret > 0)
ret = 1;
}
return openssl_pushresult(L, ret);
}
else
{
size_t sig_len;
const char* sig = luaL_checklstring(L, 2, &sig_len);
ASN1_OBJECT *obj = openssl_get_asn1object(L, 3, 0);
CONSTIFY_X509_get0 ASN1_BIT_STRING *psig = NULL;
CONSTIFY_X509_get0 X509_ALGOR *palg = NULL;
int ret;
X509_get0_signature(&psig, &palg, x);
ret = ASN1_BIT_STRING_set((ASN1_BIT_STRING*)psig, (unsigned char*)sig, (int)sig_len);
if (ret == 1)
{
ret = X509_ALGOR_set0((X509_ALGOR*)palg, obj, V_ASN1_UNDEF, NULL);
}
else
ASN1_OBJECT_free(obj);
return openssl_pushresult(L, ret);
}
}
static int openssl_x509_verify(lua_State*L)
{
X509* x = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
unsigned char *out = NULL;
int len = i2d_re_X509_tbs(x, &out);
if (len > 0)
{
CONSTIFY_X509_get0 ASN1_BIT_STRING *psig = NULL;
CONSTIFY_X509_get0 X509_ALGOR *palg = NULL;
lua_pushlstring(L, (const char *)out, len);
OPENSSL_free(out);
X509_get0_signature(&psig, &palg, x);
if (psig != NULL)
{
lua_pushlstring(L, (const char *)psig->data, psig->length);
}
else
lua_pushnil(L);
if (palg)
{
X509_ALGOR *alg = X509_ALGOR_dup((X509_ALGOR *)palg);
PUSH_OBJECT(alg, "openssl.x509_algor");
}
else
lua_pushnil(L);
return 3;
}
return openssl_pushresult(L, len);
}
else
{
EVP_PKEY *pkey = CHECK_OBJECT(2, EVP_PKEY, "openssl.evp_pkey");
int ret = X509_verify(x, pkey);
return openssl_pushresult(L, ret);
}
}
static luaL_Reg x509_funcs[] =
{
{"parse", openssl_x509_parse},
{"export", openssl_x509_export},
{"check", openssl_x509_check},
#if OPENSSL_VERSION_NUMBER > 0x10002000L
{"check_host", openssl_x509_check_host},
{"check_email", openssl_x509_check_email},
{"check_ip_asc", openssl_x509_check_ip_asc},
#endif
{"pubkey", openssl_x509_public_key},
{"version", openssl_x509_version},
{"__gc", openssl_x509_free},
{"__tostring", auxiliar_tostring},
/* compat with luasec */
{"digest", openssl_x509_digest},
{"extensions", openssl_x509_extensions},
{"issuer", openssl_x509_issuer},
{"notbefore", openssl_x509_notbefore},
{"notafter", openssl_x509_notafter},
{"serial", openssl_x509_serial},
{"subject", openssl_x509_subject},
{"validat", openssl_x509_valid_at},
{"sign", openssl_x509_sign},
{"verify", openssl_x509_verify},
{NULL, NULL},
};
int luaopen_x509(lua_State *L)
{
auxiliar_newclass(L, "openssl.x509", x509_funcs);
lua_newtable(L);
luaL_setfuncs(L, R, 0);
openssl_register_xname(L);
lua_setfield(L, -2, "name");
openssl_register_xattribute(L);
lua_setfield(L, -2, "attribute");
openssl_register_xextension(L);
lua_setfield(L, -2, "extension");
openssl_register_xstore(L);
lua_setfield(L, -2, "store");
openssl_register_xalgor(L);
lua_setfield(L, -2, "algor");
luaopen_x509_req(L);
lua_setfield(L, -2, "req");
luaopen_x509_crl(L);
lua_setfield(L, -2, "crl");
lua_pushliteral(L, "version"); /** version */
lua_pushliteral(L, MYVERSION);
lua_settable(L, -3);
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-295/c/bad_4693_0 |
crossvul-cpp_data_bad_1607_0 | /* libinfinity - a GObject-based infinote implementation
* Copyright (C) 2007-2014 Armin Burgmeier <armin@arbur.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
/* TODO: Rename to InfGtkCertificateChecker */
/* TODO: Put the non-GUI-relevant parts of this code into libinfinity */
/* TODO: Support CRLs/OCSP */
#include <libinfgtk/inf-gtk-certificate-manager.h>
#include <libinfgtk/inf-gtk-certificate-dialog.h>
#include <libinfinity/common/inf-xml-connection.h>
#include <libinfinity/common/inf-cert-util.h>
#include <libinfinity/common/inf-file-util.h>
#include <libinfinity/common/inf-error.h>
#include <libinfinity/inf-i18n.h>
#include <libinfinity/inf-signals.h>
#include <gnutls/x509.h>
#include <string.h>
#include <errno.h>
typedef struct _InfGtkCertificateManagerQuery InfGtkCertificateManagerQuery;
struct _InfGtkCertificateManagerQuery {
InfGtkCertificateManager* manager;
GHashTable* known_hosts;
InfXmppConnection* connection;
InfGtkCertificateDialog* dialog;
GtkWidget* checkbutton;
InfCertificateChain* certificate_chain;
};
typedef struct _InfGtkCertificateManagerPrivate
InfGtkCertificateManagerPrivate;
struct _InfGtkCertificateManagerPrivate {
GtkWindow* parent_window;
InfXmppManager* xmpp_manager;
gchar* known_hosts_file;
GSList* queries;
};
typedef enum _InfGtkCertificateManagerError {
INF_GTK_CERTIFICATE_MANAGER_ERROR_DUPLICATE_HOST_ENTRY
} InfGtkCertificateManagerError;
enum {
PROP_0,
PROP_PARENT_WINDOW,
PROP_XMPP_MANAGER,
PROP_KNOWN_HOSTS_FILE
};
#define INF_GTK_CERTIFICATE_MANAGER_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), INF_GTK_TYPE_CERTIFICATE_MANAGER, InfGtkCertificateManagerPrivate))
G_DEFINE_TYPE_WITH_CODE(InfGtkCertificateManager, inf_gtk_certificate_manager, G_TYPE_OBJECT,
G_ADD_PRIVATE(InfGtkCertificateManager))
/* When a host presents a certificate different from one that we have pinned,
* usually we warn the user that something fishy is going on. However, if the
* pinned certificate has expired or will expire soon, then we kind of expect
* the certificate to change, and issue a less "flashy" warning message. This
* value defines how long before the pinned certificate expires we show a
* less dramatic warning message. */
static const unsigned int
INF_GTK_CERTIFICATE_MANAGER_EXPIRATION_TOLERANCE = 3 * 24 * 3600; /* 3 days */
/* memrchr does not seem to be available everywhere, so we implement it
* ourselves. */
static void*
inf_gtk_certificate_manager_memrchr(void* buf,
char c,
size_t len)
{
char* pos;
char* end;
pos = buf + len;
end = buf;
while(pos >= end)
{
if(*(pos - 1) == c)
return pos - 1;
--pos;
}
return NULL;
}
static GQuark
inf_gtk_certificate_manager_verify_error_quark(void)
{
return g_quark_from_static_string(
"INF_GTK_CERTIFICATE_MANAGER_VERIFY_ERROR"
);
}
#if 0
static InfGtkCertificateManagerQuery*
inf_gtk_certificate_manager_find_query(InfGtkCertificateManager* manager,
InfXmppConnection* connection)
{
InfGtkCertificateManagerPrivate* priv;
GSList* item;
InfGtkCertificateManagerQuery* query;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);
for(item = priv->queries; item != NULL; item == item->next)
{
query = (InfGtkCertificateManagerQuery*)item->data;
if(query->connection == connection)
return query;
}
return NULL;
}
#endif
static void
inf_gtk_certificate_manager_notify_status_cb(GObject* object,
GParamSpec* pspec,
gpointer user_data);
static void
inf_gtk_certificate_manager_query_free(InfGtkCertificateManagerQuery* query)
{
inf_signal_handlers_disconnect_by_func(
G_OBJECT(query->connection),
G_CALLBACK(inf_gtk_certificate_manager_notify_status_cb),
query
);
g_object_unref(query->connection);
inf_certificate_chain_unref(query->certificate_chain);
gtk_widget_destroy(GTK_WIDGET(query->dialog));
g_hash_table_unref(query->known_hosts);
g_slice_free(InfGtkCertificateManagerQuery, query);
}
static gboolean
inf_gtk_certificate_manager_compare_fingerprint(gnutls_x509_crt_t cert1,
gnutls_x509_crt_t cert2,
GError** error)
{
static const unsigned int SHA256_DIGEST_SIZE = 32;
size_t size;
guchar cert1_fingerprint[SHA256_DIGEST_SIZE];
guchar cert2_fingerprint[SHA256_DIGEST_SIZE];
int ret;
int cmp;
size = SHA256_DIGEST_SIZE;
ret = gnutls_x509_crt_get_fingerprint(
cert1,
GNUTLS_DIG_SHA256,
cert1_fingerprint,
&size
);
if(ret == GNUTLS_E_SUCCESS)
{
g_assert(size == SHA256_DIGEST_SIZE);
ret = gnutls_x509_crt_get_fingerprint(
cert2,
GNUTLS_DIG_SHA256,
cert2_fingerprint,
&size
);
}
if(ret != GNUTLS_E_SUCCESS)
{
inf_gnutls_set_error(error, ret);
return FALSE;
}
cmp = memcmp(cert1_fingerprint, cert2_fingerprint, SHA256_DIGEST_SIZE);
if(cmp != 0) return FALSE;
return TRUE;
}
static void
inf_gtk_certificate_manager_set_known_hosts(InfGtkCertificateManager* manager,
const gchar* known_hosts_file)
{
InfGtkCertificateManagerPrivate* priv;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);
/* TODO: If there are running queries, the we need to load the new hosts
* file and then change it in all queries. */
g_assert(priv->queries == NULL);
g_free(priv->known_hosts_file);
priv->known_hosts_file = g_strdup(known_hosts_file);
}
static GHashTable*
inf_gtk_certificate_manager_load_known_hosts(InfGtkCertificateManager* mgr,
GError** error)
{
InfGtkCertificateManagerPrivate* priv;
GHashTable* table;
gchar* content;
gsize size;
GError* local_error;
gchar* out_buf;
gsize out_buf_len;
gchar* pos;
gchar* prev;
gchar* next;
gchar* sep;
gsize len;
gsize out_len;
gint base64_state;
guint base64_save;
gnutls_datum_t data;
gnutls_x509_crt_t cert;
int res;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(mgr);
table = g_hash_table_new_full(
g_str_hash,
g_str_equal,
g_free,
(GDestroyNotify)gnutls_x509_crt_deinit
);
local_error = NULL;
g_file_get_contents(priv->known_hosts_file, &content, &size, &local_error);
if(local_error != NULL)
{
if(local_error->domain == G_FILE_ERROR &&
local_error->code == G_FILE_ERROR_NOENT)
{
return table;
}
g_propagate_prefixed_error(
error,
local_error,
_("Failed to open known hosts file \"%s\": "),
priv->known_hosts_file
);
g_hash_table_destroy(table);
return NULL;
}
out_buf = NULL;
out_buf_len = 0;
prev = content;
for(prev = content; prev != NULL; prev = next)
{
pos = strchr(prev, '\n');
next = NULL;
if(pos == NULL)
pos = content + size;
else
next = pos + 1;
sep = inf_gtk_certificate_manager_memrchr(prev, ':', pos - prev);
if(sep == NULL) continue; /* ignore line */
*sep = '\0';
if(g_hash_table_lookup(table, prev) != NULL)
{
g_set_error(
error,
g_quark_from_static_string("INF_GTK_CERTIFICATE_MANAGER_ERROR"),
INF_GTK_CERTIFICATE_MANAGER_ERROR_DUPLICATE_HOST_ENTRY,
_("Certificate for host \"%s\" appears twice in "
"known hosts file \"%s\""),
prev,
priv->known_hosts_file
);
g_hash_table_destroy(table);
g_free(out_buf);
g_free(content);
return NULL;
}
/* decode base64, import DER certificate */
len = (pos - (sep + 1));
out_len = len * 3 / 4;
if(out_len > out_buf_len)
{
out_buf = g_realloc(out_buf, out_len);
out_buf_len = out_len;
}
base64_state = 0;
base64_save = 0;
out_len = g_base64_decode_step(
sep + 1,
len,
out_buf,
&base64_state,
&base64_save
);
cert = NULL;
res = gnutls_x509_crt_init(&cert);
if(res == GNUTLS_E_SUCCESS)
{
data.data = out_buf;
data.size = out_len;
res = gnutls_x509_crt_import(cert, &data, GNUTLS_X509_FMT_DER);
}
if(res != GNUTLS_E_SUCCESS)
{
inf_gnutls_set_error(&local_error, res);
g_propagate_prefixed_error(
error,
local_error,
_("Failed to read certificate for host \"%s\" from "
"known hosts file \"%s\": "),
prev,
priv->known_hosts_file
);
if(cert != NULL)
gnutls_x509_crt_deinit(cert);
g_hash_table_destroy(table);
g_free(out_buf);
g_free(content);
return NULL;
}
g_hash_table_insert(table, g_strdup(prev), cert);
}
g_free(out_buf);
g_free(content);
return table;
}
static GHashTable*
inf_gtk_certificate_manager_ref_known_hosts(InfGtkCertificateManager* mgr,
GError** error)
{
InfGtkCertificateManagerPrivate* priv;
InfGtkCertificateManagerQuery* query;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(mgr);
if(priv->queries != NULL)
{
query = (InfGtkCertificateManagerQuery*)priv->queries->data;
g_hash_table_ref(query->known_hosts);
return query->known_hosts;
}
else
{
return inf_gtk_certificate_manager_load_known_hosts(mgr, error);
}
}
static gboolean
inf_gtk_certificate_manager_write_known_hosts(InfGtkCertificateManager* mgr,
GHashTable* table,
GError** error)
{
InfGtkCertificateManagerPrivate* priv;
gchar* dirname;
GIOChannel* channel;
GIOStatus status;
GHashTableIter iter;
gpointer key;
gpointer value;
const gchar* hostname;
gnutls_x509_crt_t cert;
size_t size;
int res;
gchar* buffer;
gchar* encoded_cert;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(mgr);
/* Note that we pin the whole certificate and not only the public key of
* our known hosts. This allows us to differentiate two cases when a
* host presents a new certificate:
* a) The old certificate has expired or is very close to expiration. In
* this case we still show a message to the user asking whether they
* trust the new certificate.
* b) The old certificate was perfectly valid. In this case we show a
* message saying that the certificate change was unexpected, and
* unless it was expected the host should not be trusted.
*/
dirname = g_path_get_dirname(priv->known_hosts_file);
if(!inf_file_util_create_directory(dirname, 0755, error))
{
g_free(dirname);
return FALSE;
}
g_free(dirname);
channel = g_io_channel_new_file(priv->known_hosts_file, "w", error);
if(channel == NULL) return FALSE;
status = g_io_channel_set_encoding(channel, NULL, error);
if(status != G_IO_STATUS_NORMAL)
{
g_io_channel_unref(channel);
return FALSE;
}
g_hash_table_iter_init(&iter, table);
while(g_hash_table_iter_next(&iter, &key, &value))
{
hostname = (const gchar*)key;
cert = (gnutls_x509_crt_t)value;
size = 0;
res = gnutls_x509_crt_export(cert, GNUTLS_X509_FMT_DER, NULL, &size);
g_assert(res != GNUTLS_E_SUCCESS);
buffer = NULL;
if(res == GNUTLS_E_SHORT_MEMORY_BUFFER)
{
buffer = g_malloc(size);
res = gnutls_x509_crt_export(cert, GNUTLS_X509_FMT_DER, buffer, &size);
}
if(res != GNUTLS_E_SUCCESS)
{
g_free(buffer);
g_io_channel_unref(channel);
inf_gnutls_set_error(error, res);
return FALSE;
}
encoded_cert = g_base64_encode(buffer, size);
g_free(buffer);
status = g_io_channel_write_chars(channel, hostname, strlen(hostname), NULL, error);
if(status == G_IO_STATUS_NORMAL)
status = g_io_channel_write_chars(channel, ":", 1, NULL, error);
if(status == G_IO_STATUS_NORMAL)
status = g_io_channel_write_chars(channel, encoded_cert, strlen(encoded_cert), NULL, error);
if(status == G_IO_STATUS_NORMAL)
status = g_io_channel_write_chars(channel, "\n", 1, NULL, error);
g_free(encoded_cert);
if(status != G_IO_STATUS_NORMAL)
{
g_io_channel_unref(channel);
return FALSE;
}
}
g_io_channel_unref(channel);
return TRUE;
}
static void
inf_gtk_certificate_manager_write_known_hosts_with_warning(
InfGtkCertificateManager* mgr,
GHashTable* table)
{
InfGtkCertificateManagerPrivate* priv;
GError* error;
gboolean result;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(mgr);
error = NULL;
result = inf_gtk_certificate_manager_write_known_hosts(
mgr,
table,
&error
);
if(error != NULL)
{
g_warning(
_("Failed to write file with known hosts \"%s\": %s"),
priv->known_hosts_file,
error->message
);
g_error_free(error);
}
}
static void
inf_gtk_certificate_manager_response_cb(GtkDialog* dialog,
int response_id,
gpointer user_data)
{
InfGtkCertificateManagerQuery* query;
InfGtkCertificateManagerPrivate* priv;
InfXmppConnection* connection;
gchar* hostname;
gnutls_x509_crt_t cert;
gnutls_x509_crt_t known_cert;
GError* error;
gboolean cert_equal;
query = (InfGtkCertificateManagerQuery*)user_data;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(query->manager);
connection = query->connection;
g_object_ref(connection);
switch(response_id)
{
case GTK_RESPONSE_ACCEPT:
g_object_get(
G_OBJECT(query->connection),
"remote-hostname", &hostname,
NULL
);
/* Add the certificate to the known hosts file, but only if it is not
* already, to avoid unnecessary disk I/O. */
cert =
inf_certificate_chain_get_own_certificate(query->certificate_chain);
known_cert = g_hash_table_lookup(query->known_hosts, hostname);
error = NULL;
cert_equal = FALSE;
if(known_cert != NULL)
{
cert_equal = inf_gtk_certificate_manager_compare_fingerprint(
cert,
known_cert,
&error
);
}
if(error != NULL)
{
g_warning(
_("Failed to add certificate to list of known hosts: %s"),
error->message
);
}
else if(!cert_equal)
{
cert = inf_cert_util_copy_certificate(cert, &error);
g_hash_table_insert(query->known_hosts, hostname, cert);
inf_gtk_certificate_manager_write_known_hosts_with_warning(
query->manager,
query->known_hosts
);
}
else
{
g_free(hostname);
}
priv->queries = g_slist_remove(priv->queries, query);
inf_gtk_certificate_manager_query_free(query);
inf_xmpp_connection_certificate_verify_continue(connection);
break;
case GTK_RESPONSE_REJECT:
case GTK_RESPONSE_DELETE_EVENT:
priv->queries = g_slist_remove(priv->queries, query);
inf_gtk_certificate_manager_query_free(query);
inf_xmpp_connection_certificate_verify_cancel(connection, NULL);
break;
default:
g_assert_not_reached();
break;
}
g_object_unref(connection);
}
static void
inf_gtk_certificate_manager_notify_status_cb(GObject* object,
GParamSpec* pspec,
gpointer user_data)
{
InfGtkCertificateManagerQuery* query;
InfGtkCertificateManagerPrivate* priv;
InfXmppConnection* connection;
InfXmlConnectionStatus status;
query = (InfGtkCertificateManagerQuery*)user_data;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(query->manager);
connection = INF_XMPP_CONNECTION(object);
g_object_get(G_OBJECT(connection), "status", &status, NULL);
if(status == INF_XML_CONNECTION_CLOSING ||
status == INF_XML_CONNECTION_CLOSED)
{
priv->queries = g_slist_remove(priv->queries, query);
inf_gtk_certificate_manager_query_free(query);
}
}
static void
inf_gtk_certificate_manager_certificate_func(InfXmppConnection* connection,
gnutls_session_t session,
InfCertificateChain* chain,
gpointer user_data)
{
InfGtkCertificateManager* manager;
InfGtkCertificateManagerPrivate* priv;
InfGtkCertificateDialogFlags flags;
gnutls_x509_crt_t presented_cert;
gnutls_x509_crt_t known_cert;
gchar* hostname;
gboolean match_hostname;
gboolean issuer_known;
gnutls_x509_crt_t root_cert;
int ret;
unsigned int verify;
GHashTable* table;
gboolean cert_equal;
time_t expiration_time;
InfGtkCertificateManagerQuery* query;
gchar* text;
GtkWidget* vbox;
GtkWidget* label;
GError* error;
manager = INF_GTK_CERTIFICATE_MANAGER(user_data);
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);
g_object_get(G_OBJECT(connection), "remote-hostname", &hostname, NULL);
presented_cert = inf_certificate_chain_get_own_certificate(chain);
match_hostname = gnutls_x509_crt_check_hostname(presented_cert, hostname);
/* First, validate the certificate */
ret = gnutls_certificate_verify_peers2(session, &verify);
error = NULL;
if(ret != GNUTLS_E_SUCCESS)
inf_gnutls_set_error(&error, ret);
/* Remove the GNUTLS_CERT_ISSUER_NOT_KNOWN flag from the verification
* result, and if the certificate is still invalid, then set an error. */
if(error == NULL)
{
issuer_known = TRUE;
if(verify & GNUTLS_CERT_SIGNER_NOT_FOUND)
{
issuer_known = FALSE;
/* Re-validate the certificate for other failure reasons --
* unfortunately the gnutls_certificate_verify_peers2() call
* does not tell us whether the certificate is otherwise invalid
* if a signer is not found already. */
/* TODO: Here it would be good to use the verify flags from the
* certificate credentials, but GnuTLS does not have API to
* retrieve them. */
root_cert = inf_certificate_chain_get_root_certificate(chain);
ret = gnutls_x509_crt_list_verify(
inf_certificate_chain_get_raw(chain),
inf_certificate_chain_get_n_certificates(chain),
&root_cert,
1,
NULL,
0,
GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT,
&verify
);
if(ret != GNUTLS_E_SUCCESS)
inf_gnutls_set_error(&error, ret);
else if(verify & GNUTLS_CERT_INVALID)
inf_gnutls_certificate_verification_set_error(&error, verify);
}
}
/* Look up the host in our database of pinned certificates if we could not
* fully verify the certificate, i.e. if either the issuer is not known or
* the hostname of the connection does not match the certificate. */
table = NULL;
if(error == NULL)
{
known_cert = NULL;
if(!match_hostname || !issuer_known)
{
/* If we cannot load the known host file, then cancel the connection.
* Otherwise it might happen that someone shows us a certificate that we
* tell the user we don't know, if though actually for that host we expect
* a different certificate. */
table = inf_gtk_certificate_manager_ref_known_hosts(manager, &error);
if(table != NULL)
known_cert = g_hash_table_lookup(table, hostname);
}
}
/* Next, configure the flags for the dialog to be shown based on the
* verification result, and on whether the pinned certificate matches
* the one presented by the host or not. */
flags = 0;
if(error == NULL)
{
if(known_cert != NULL)
{
cert_equal = inf_gtk_certificate_manager_compare_fingerprint(
known_cert,
presented_cert,
&error
);
if(error == NULL && cert_equal == FALSE)
{
if(!match_hostname)
flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_HOSTNAME_MISMATCH;
if(!issuer_known)
flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_ISSUER_NOT_KNOWN;
flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_UNEXPECTED;
expiration_time = gnutls_x509_crt_get_expiration_time(known_cert);
if(expiration_time != (time_t)(-1))
{
expiration_time -= INF_GTK_CERTIFICATE_MANAGER_EXPIRATION_TOLERANCE;
if(time(NULL) > expiration_time)
{
flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_OLD_EXPIRED;
}
}
}
}
else
{
if(!match_hostname)
flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_HOSTNAME_MISMATCH;
if(!issuer_known)
flags |= INF_GTK_CERTIFICATE_DIALOG_CERT_ISSUER_NOT_KNOWN;
}
}
/* Now proceed either by accepting the connection, rejecting it, or
* bothering the user with an annoying dialog. */
if(error == NULL)
{
if(flags == 0)
{
if(match_hostname && issuer_known)
{
/* Remove the pinned entry if we now have a valid certificate for
* this host. */
if(table != NULL && g_hash_table_remove(table, hostname) == TRUE)
{
inf_gtk_certificate_manager_write_known_hosts_with_warning(
manager,
table
);
}
}
inf_xmpp_connection_certificate_verify_continue(connection);
}
else
{
query = g_slice_new(InfGtkCertificateManagerQuery);
query->manager = manager;
query->known_hosts = table;
query->connection = connection;
query->dialog = inf_gtk_certificate_dialog_new(
priv->parent_window,
0,
flags,
hostname,
chain
);
query->certificate_chain = chain;
table = NULL;
g_object_ref(query->connection);
inf_certificate_chain_ref(chain);
g_signal_connect(
G_OBJECT(connection),
"notify::status",
G_CALLBACK(inf_gtk_certificate_manager_notify_status_cb),
query
);
g_signal_connect(
G_OBJECT(query->dialog),
"response",
G_CALLBACK(inf_gtk_certificate_manager_response_cb),
query
);
gtk_dialog_add_button(
GTK_DIALOG(query->dialog),
_("_Cancel connection"),
GTK_RESPONSE_REJECT
);
gtk_dialog_add_button(
GTK_DIALOG(query->dialog),
_("C_ontinue connection"),
GTK_RESPONSE_ACCEPT
);
text = g_strdup_printf(
_("Do you want to continue the connection to host \"%s\"? If you "
"choose to continue, this certificate will be trusted in the "
"future when connecting to this host."),
hostname
);
label = gtk_label_new(text);
gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR);
gtk_label_set_max_width_chars(GTK_LABEL(label), 60);
gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.0);
gtk_widget_show(label);
g_free(text);
vbox = gtk_dialog_get_content_area(GTK_DIALOG(query->dialog));
gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
priv->queries = g_slist_prepend(priv->queries, query);
gtk_window_present(GTK_WINDOW(query->dialog));
}
}
else
{
inf_xmpp_connection_certificate_verify_cancel(connection, error);
g_error_free(error);
}
if(table != NULL) g_hash_table_unref(table);
g_free(hostname);
}
static void
inf_gtk_certificate_manager_connection_added_cb(InfXmppManager* manager,
InfXmppConnection* connection,
gpointer user_data)
{
InfXmppConnectionSite site;
g_object_get(G_OBJECT(connection), "site", &site, NULL);
if(site == INF_XMPP_CONNECTION_CLIENT)
{
inf_xmpp_connection_set_certificate_callback(
connection,
GNUTLS_CERT_REQUIRE, /* require a server certificate */
inf_gtk_certificate_manager_certificate_func,
user_data,
NULL
);
}
}
static void
inf_gtk_certificate_manager_init(InfGtkCertificateManager* manager)
{
InfGtkCertificateManagerPrivate* priv;
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);
priv->parent_window = NULL;
priv->xmpp_manager = NULL;
priv->known_hosts_file = NULL;
}
static void
inf_gtk_certificate_manager_dispose(GObject* object)
{
InfGtkCertificateManager* manager;
InfGtkCertificateManagerPrivate* priv;
GSList* item;
manager = INF_GTK_CERTIFICATE_MANAGER(object);
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);
if(priv->parent_window != NULL)
{
g_object_unref(priv->parent_window);
priv->parent_window = NULL;
}
if(priv->xmpp_manager != NULL)
{
g_object_unref(priv->xmpp_manager);
priv->xmpp_manager = NULL;
}
for(item = priv->queries; item != NULL; item = g_slist_next(item))
{
inf_gtk_certificate_manager_query_free(
(InfGtkCertificateManagerQuery*)item->data
);
}
g_slist_free(priv->queries);
priv->queries = NULL;
G_OBJECT_CLASS(inf_gtk_certificate_manager_parent_class)->dispose(object);
}
static void
inf_gtk_certificate_manager_finalize(GObject* object)
{
InfGtkCertificateManager* manager;
InfGtkCertificateManagerPrivate* priv;
manager = INF_GTK_CERTIFICATE_MANAGER(object);
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);
inf_gtk_certificate_manager_set_known_hosts(manager, NULL);
g_assert(priv->known_hosts_file == NULL);
G_OBJECT_CLASS(inf_gtk_certificate_manager_parent_class)->finalize(object);
}
static void
inf_gtk_certificate_manager_set_property(GObject* object,
guint prop_id,
const GValue* value,
GParamSpec* pspec)
{
InfGtkCertificateManager* manager;
InfGtkCertificateManagerPrivate* priv;
manager = INF_GTK_CERTIFICATE_MANAGER(object);
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);
switch(prop_id)
{
case PROP_PARENT_WINDOW:
g_assert(priv->parent_window == NULL); /* construct/only */
priv->parent_window = GTK_WINDOW(g_value_dup_object(value));
break;
case PROP_XMPP_MANAGER:
g_assert(priv->xmpp_manager == NULL); /* construct/only */
priv->xmpp_manager = INF_XMPP_MANAGER(g_value_dup_object(value));
g_signal_connect(
G_OBJECT(priv->xmpp_manager),
"connection-added",
G_CALLBACK(inf_gtk_certificate_manager_connection_added_cb),
manager
);
break;
case PROP_KNOWN_HOSTS_FILE:
inf_gtk_certificate_manager_set_known_hosts(
manager,
g_value_get_string(value)
);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
break;
}
}
static void
inf_gtk_certificate_manager_get_property(GObject* object,
guint prop_id,
GValue* value,
GParamSpec* pspec)
{
InfGtkCertificateManager* manager;
InfGtkCertificateManagerPrivate* priv;
manager = INF_GTK_CERTIFICATE_MANAGER(object);
priv = INF_GTK_CERTIFICATE_MANAGER_PRIVATE(manager);
switch(prop_id)
{
case PROP_PARENT_WINDOW:
g_value_set_object(value, G_OBJECT(priv->parent_window));
break;
case PROP_XMPP_MANAGER:
g_value_set_object(value, G_OBJECT(priv->xmpp_manager));
break;
case PROP_KNOWN_HOSTS_FILE:
g_value_set_string(value, priv->known_hosts_file);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
break;
}
}
/*
* GType registration
*/
static void
inf_gtk_certificate_manager_class_init(
InfGtkCertificateManagerClass* certificate_manager_class)
{
GObjectClass* object_class;
object_class = G_OBJECT_CLASS(certificate_manager_class);
object_class->dispose = inf_gtk_certificate_manager_dispose;
object_class->finalize = inf_gtk_certificate_manager_finalize;
object_class->set_property = inf_gtk_certificate_manager_set_property;
object_class->get_property = inf_gtk_certificate_manager_get_property;
g_object_class_install_property(
object_class,
PROP_PARENT_WINDOW,
g_param_spec_object(
"parent-window",
"Parent window",
"The parent window for certificate approval dialogs",
GTK_TYPE_WINDOW,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY
)
);
g_object_class_install_property(
object_class,
PROP_XMPP_MANAGER,
g_param_spec_object(
"xmpp-manager",
"XMPP manager",
"The XMPP manager of registered connections",
INF_TYPE_XMPP_MANAGER,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY
)
);
g_object_class_install_property(
object_class,
PROP_KNOWN_HOSTS_FILE,
g_param_spec_string(
"known-hosts-file",
"Known hosts file",
"File containing certificates of known hosts",
NULL,
G_PARAM_READWRITE
)
);
}
/*
* Public API.
*/
/**
* inf_gtk_certificate_manager_new: (constructor)
* @parent_window: The #GtkWindow to which to make certificate approval
* dialogs transient to.
* @xmpp_manager: The #InfXmppManager whose #InfXmppConnection<!-- -->s to
* manage the certificates for.
* @known_hosts_file: (type filename) (allow-none): Path pointing to a file
* that contains certificates of known hosts, or %NULL.
*
* Creates a new #InfGtkCertificateManager. For each new client-side
* #InfXmppConnection in @xmpp_manager, the certificate manager will verify
* the server's certificate.
*
* If the certificate is contained in @known_hosts_file, then
* the certificate is accepted automatically. Otherwise, the user is asked for
* approval. If the user approves the certificate, then it is inserted into
* the @known_hosts_file.
*
* Returns: (transfer full): A new #InfGtkCertificateManager.
**/
InfGtkCertificateManager*
inf_gtk_certificate_manager_new(GtkWindow* parent_window,
InfXmppManager* xmpp_manager,
const gchar* known_hosts_file)
{
GObject* object;
object = g_object_new(
INF_GTK_TYPE_CERTIFICATE_MANAGER,
"parent-window", parent_window,
"xmpp-manager", xmpp_manager,
"known-hosts-file", known_hosts_file,
NULL
);
return INF_GTK_CERTIFICATE_MANAGER(object);
}
/* vim:set et sw=2 ts=2: */
| ./CrossVul/dataset_final_sorted/CWE-295/c/bad_1607_0 |
crossvul-cpp_data_good_3203_1 | /*
* Copyright (c) 1997-2008 Kungliga Tekniska Högskolan
* (Royal Institute of Technology, Stockholm, Sweden).
* 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 Institute 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 INSTITUTE 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 INSTITUTE 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.
*/
#include "kdc_locl.h"
/*
* return the realm of a krbtgt-ticket or NULL
*/
static Realm
get_krbtgt_realm(const PrincipalName *p)
{
if(p->name_string.len == 2
&& strcmp(p->name_string.val[0], KRB5_TGS_NAME) == 0)
return p->name_string.val[1];
else
return NULL;
}
/*
* The KDC might add a signed path to the ticket authorization data
* field. This is to avoid server impersonating clients and the
* request constrained delegation.
*
* This is done by storing a KRB5_AUTHDATA_IF_RELEVANT with a single
* entry of type KRB5SignedPath.
*/
static krb5_error_code
find_KRB5SignedPath(krb5_context context,
const AuthorizationData *ad,
krb5_data *data)
{
AuthorizationData child;
krb5_error_code ret;
int pos;
if (ad == NULL || ad->len == 0)
return KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
pos = ad->len - 1;
if (ad->val[pos].ad_type != KRB5_AUTHDATA_IF_RELEVANT)
return KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
ret = decode_AuthorizationData(ad->val[pos].ad_data.data,
ad->val[pos].ad_data.length,
&child,
NULL);
if (ret) {
krb5_set_error_message(context, ret, "Failed to decode "
"IF_RELEVANT with %d", ret);
return ret;
}
if (child.len != 1) {
free_AuthorizationData(&child);
return KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
}
if (child.val[0].ad_type != KRB5_AUTHDATA_SIGNTICKET) {
free_AuthorizationData(&child);
return KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
}
if (data)
ret = der_copy_octet_string(&child.val[0].ad_data, data);
free_AuthorizationData(&child);
return ret;
}
krb5_error_code
_kdc_add_KRB5SignedPath(krb5_context context,
krb5_kdc_configuration *config,
hdb_entry_ex *krbtgt,
krb5_enctype enctype,
krb5_principal client,
krb5_const_principal server,
krb5_principals principals,
EncTicketPart *tkt)
{
krb5_error_code ret;
KRB5SignedPath sp;
krb5_data data;
krb5_crypto crypto = NULL;
size_t size = 0;
if (server && principals) {
ret = add_Principals(principals, server);
if (ret)
return ret;
}
{
KRB5SignedPathData spd;
spd.client = client;
spd.authtime = tkt->authtime;
spd.delegated = principals;
spd.method_data = NULL;
ASN1_MALLOC_ENCODE(KRB5SignedPathData, data.data, data.length,
&spd, &size, ret);
if (ret)
return ret;
if (data.length != size)
krb5_abortx(context, "internal asn.1 encoder error");
}
{
Key *key;
ret = hdb_enctype2key(context, &krbtgt->entry, NULL, enctype, &key);
if (ret == 0)
ret = krb5_crypto_init(context, &key->key, 0, &crypto);
if (ret) {
free(data.data);
return ret;
}
}
/*
* Fill in KRB5SignedPath
*/
sp.etype = enctype;
sp.delegated = principals;
sp.method_data = NULL;
ret = krb5_create_checksum(context, crypto, KRB5_KU_KRB5SIGNEDPATH, 0,
data.data, data.length, &sp.cksum);
krb5_crypto_destroy(context, crypto);
free(data.data);
if (ret)
return ret;
ASN1_MALLOC_ENCODE(KRB5SignedPath, data.data, data.length, &sp, &size, ret);
free_Checksum(&sp.cksum);
if (ret)
return ret;
if (data.length != size)
krb5_abortx(context, "internal asn.1 encoder error");
/*
* Add IF-RELEVANT(KRB5SignedPath) to the last slot in
* authorization data field.
*/
ret = _kdc_tkt_add_if_relevant_ad(context, tkt,
KRB5_AUTHDATA_SIGNTICKET, &data);
krb5_data_free(&data);
return ret;
}
static krb5_error_code
check_KRB5SignedPath(krb5_context context,
krb5_kdc_configuration *config,
hdb_entry_ex *krbtgt,
krb5_principal cp,
EncTicketPart *tkt,
krb5_principals *delegated,
int *signedpath)
{
krb5_error_code ret;
krb5_data data;
krb5_crypto crypto = NULL;
if (delegated)
*delegated = NULL;
ret = find_KRB5SignedPath(context, tkt->authorization_data, &data);
if (ret == 0) {
KRB5SignedPathData spd;
KRB5SignedPath sp;
size_t size = 0;
ret = decode_KRB5SignedPath(data.data, data.length, &sp, NULL);
krb5_data_free(&data);
if (ret)
return ret;
spd.client = cp;
spd.authtime = tkt->authtime;
spd.delegated = sp.delegated;
spd.method_data = sp.method_data;
ASN1_MALLOC_ENCODE(KRB5SignedPathData, data.data, data.length,
&spd, &size, ret);
if (ret) {
free_KRB5SignedPath(&sp);
return ret;
}
if (data.length != size)
krb5_abortx(context, "internal asn.1 encoder error");
{
Key *key;
ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use correct kvno! */
sp.etype, &key);
if (ret == 0)
ret = krb5_crypto_init(context, &key->key, 0, &crypto);
if (ret) {
free(data.data);
free_KRB5SignedPath(&sp);
return ret;
}
}
ret = krb5_verify_checksum(context, crypto, KRB5_KU_KRB5SIGNEDPATH,
data.data, data.length,
&sp.cksum);
krb5_crypto_destroy(context, crypto);
free(data.data);
if (ret) {
free_KRB5SignedPath(&sp);
kdc_log(context, config, 5,
"KRB5SignedPath not signed correctly, not marking as signed");
return 0;
}
if (delegated && sp.delegated) {
*delegated = malloc(sizeof(*sp.delegated));
if (*delegated == NULL) {
free_KRB5SignedPath(&sp);
return ENOMEM;
}
ret = copy_Principals(*delegated, sp.delegated);
if (ret) {
free_KRB5SignedPath(&sp);
free(*delegated);
*delegated = NULL;
return ret;
}
}
free_KRB5SignedPath(&sp);
*signedpath = 1;
}
return 0;
}
/*
*
*/
static krb5_error_code
check_PAC(krb5_context context,
krb5_kdc_configuration *config,
const krb5_principal client_principal,
const krb5_principal delegated_proxy_principal,
hdb_entry_ex *client,
hdb_entry_ex *server,
hdb_entry_ex *krbtgt,
const EncryptionKey *server_check_key,
const EncryptionKey *server_sign_key,
const EncryptionKey *krbtgt_sign_key,
EncTicketPart *tkt,
krb5_data *rspac,
int *signedpath)
{
AuthorizationData *ad = tkt->authorization_data;
unsigned i, j;
krb5_error_code ret;
if (ad == NULL || ad->len == 0)
return 0;
for (i = 0; i < ad->len; i++) {
AuthorizationData child;
if (ad->val[i].ad_type != KRB5_AUTHDATA_IF_RELEVANT)
continue;
ret = decode_AuthorizationData(ad->val[i].ad_data.data,
ad->val[i].ad_data.length,
&child,
NULL);
if (ret) {
krb5_set_error_message(context, ret, "Failed to decode "
"IF_RELEVANT with %d", ret);
return ret;
}
for (j = 0; j < child.len; j++) {
if (child.val[j].ad_type == KRB5_AUTHDATA_WIN2K_PAC) {
int signed_pac = 0;
krb5_pac pac;
/* Found PAC */
ret = krb5_pac_parse(context,
child.val[j].ad_data.data,
child.val[j].ad_data.length,
&pac);
free_AuthorizationData(&child);
if (ret)
return ret;
ret = krb5_pac_verify(context, pac, tkt->authtime,
client_principal,
server_check_key, NULL);
if (ret) {
krb5_pac_free(context, pac);
return ret;
}
ret = _kdc_pac_verify(context, client_principal,
delegated_proxy_principal,
client, server, krbtgt, &pac, &signed_pac);
if (ret) {
krb5_pac_free(context, pac);
return ret;
}
/*
* Only re-sign PAC if we could verify it with the PAC
* function. The no-verify case happens when we get in
* a PAC from cross realm from a Windows domain and
* that there is no PAC verification function.
*/
if (signed_pac) {
*signedpath = 1;
ret = _krb5_pac_sign(context, pac, tkt->authtime,
client_principal,
server_sign_key, krbtgt_sign_key, rspac);
}
krb5_pac_free(context, pac);
return ret;
}
}
free_AuthorizationData(&child);
}
return 0;
}
/*
*
*/
static krb5_error_code
check_tgs_flags(krb5_context context,
krb5_kdc_configuration *config,
KDC_REQ_BODY *b, const EncTicketPart *tgt, EncTicketPart *et)
{
KDCOptions f = b->kdc_options;
if(f.validate){
if(!tgt->flags.invalid || tgt->starttime == NULL){
kdc_log(context, config, 0,
"Bad request to validate ticket");
return KRB5KDC_ERR_BADOPTION;
}
if(*tgt->starttime > kdc_time){
kdc_log(context, config, 0,
"Early request to validate ticket");
return KRB5KRB_AP_ERR_TKT_NYV;
}
/* XXX tkt = tgt */
et->flags.invalid = 0;
}else if(tgt->flags.invalid){
kdc_log(context, config, 0,
"Ticket-granting ticket has INVALID flag set");
return KRB5KRB_AP_ERR_TKT_INVALID;
}
if(f.forwardable){
if(!tgt->flags.forwardable){
kdc_log(context, config, 0,
"Bad request for forwardable ticket");
return KRB5KDC_ERR_BADOPTION;
}
et->flags.forwardable = 1;
}
if(f.forwarded){
if(!tgt->flags.forwardable){
kdc_log(context, config, 0,
"Request to forward non-forwardable ticket");
return KRB5KDC_ERR_BADOPTION;
}
et->flags.forwarded = 1;
et->caddr = b->addresses;
}
if(tgt->flags.forwarded)
et->flags.forwarded = 1;
if(f.proxiable){
if(!tgt->flags.proxiable){
kdc_log(context, config, 0,
"Bad request for proxiable ticket");
return KRB5KDC_ERR_BADOPTION;
}
et->flags.proxiable = 1;
}
if(f.proxy){
if(!tgt->flags.proxiable){
kdc_log(context, config, 0,
"Request to proxy non-proxiable ticket");
return KRB5KDC_ERR_BADOPTION;
}
et->flags.proxy = 1;
et->caddr = b->addresses;
}
if(tgt->flags.proxy)
et->flags.proxy = 1;
if(f.allow_postdate){
if(!tgt->flags.may_postdate){
kdc_log(context, config, 0,
"Bad request for post-datable ticket");
return KRB5KDC_ERR_BADOPTION;
}
et->flags.may_postdate = 1;
}
if(f.postdated){
if(!tgt->flags.may_postdate){
kdc_log(context, config, 0,
"Bad request for postdated ticket");
return KRB5KDC_ERR_BADOPTION;
}
if(b->from)
*et->starttime = *b->from;
et->flags.postdated = 1;
et->flags.invalid = 1;
}else if(b->from && *b->from > kdc_time + context->max_skew){
kdc_log(context, config, 0, "Ticket cannot be postdated");
return KRB5KDC_ERR_CANNOT_POSTDATE;
}
if(f.renewable){
if(!tgt->flags.renewable || tgt->renew_till == NULL){
kdc_log(context, config, 0,
"Bad request for renewable ticket");
return KRB5KDC_ERR_BADOPTION;
}
et->flags.renewable = 1;
ALLOC(et->renew_till);
_kdc_fix_time(&b->rtime);
*et->renew_till = *b->rtime;
}
if(f.renew){
time_t old_life;
if(!tgt->flags.renewable || tgt->renew_till == NULL){
kdc_log(context, config, 0,
"Request to renew non-renewable ticket");
return KRB5KDC_ERR_BADOPTION;
}
old_life = tgt->endtime;
if(tgt->starttime)
old_life -= *tgt->starttime;
else
old_life -= tgt->authtime;
et->endtime = *et->starttime + old_life;
if (et->renew_till != NULL)
et->endtime = min(*et->renew_till, et->endtime);
}
#if 0
/* checks for excess flags */
if(f.request_anonymous && !config->allow_anonymous){
kdc_log(context, config, 0,
"Request for anonymous ticket");
return KRB5KDC_ERR_BADOPTION;
}
#endif
return 0;
}
/*
* Determine if constrained delegation is allowed from this client to this server
*/
static krb5_error_code
check_constrained_delegation(krb5_context context,
krb5_kdc_configuration *config,
HDB *clientdb,
hdb_entry_ex *client,
hdb_entry_ex *server,
krb5_const_principal target)
{
const HDB_Ext_Constrained_delegation_acl *acl;
krb5_error_code ret;
size_t i;
/*
* constrained_delegation (S4U2Proxy) only works within
* the same realm. We use the already canonicalized version
* of the principals here, while "target" is the principal
* provided by the client.
*/
if(!krb5_realm_compare(context, client->entry.principal, server->entry.principal)) {
ret = KRB5KDC_ERR_BADOPTION;
kdc_log(context, config, 0,
"Bad request for constrained delegation");
return ret;
}
if (clientdb->hdb_check_constrained_delegation) {
ret = clientdb->hdb_check_constrained_delegation(context, clientdb, client, target);
if (ret == 0)
return 0;
} else {
/* if client delegates to itself, that ok */
if (krb5_principal_compare(context, client->entry.principal, server->entry.principal) == TRUE)
return 0;
ret = hdb_entry_get_ConstrainedDelegACL(&client->entry, &acl);
if (ret) {
krb5_clear_error_message(context);
return ret;
}
if (acl) {
for (i = 0; i < acl->len; i++) {
if (krb5_principal_compare(context, target, &acl->val[i]) == TRUE)
return 0;
}
}
ret = KRB5KDC_ERR_BADOPTION;
}
kdc_log(context, config, 0,
"Bad request for constrained delegation");
return ret;
}
/*
* Determine if s4u2self is allowed from this client to this server
*
* For example, regardless of the principal being impersonated, if the
* 'client' and 'server' are the same, then it's safe.
*/
static krb5_error_code
check_s4u2self(krb5_context context,
krb5_kdc_configuration *config,
HDB *clientdb,
hdb_entry_ex *client,
krb5_const_principal server)
{
krb5_error_code ret;
/* if client does a s4u2self to itself, that ok */
if (krb5_principal_compare(context, client->entry.principal, server) == TRUE)
return 0;
if (clientdb->hdb_check_s4u2self) {
ret = clientdb->hdb_check_s4u2self(context, clientdb, client, server);
if (ret == 0)
return 0;
} else {
ret = KRB5KDC_ERR_BADOPTION;
}
return ret;
}
/*
*
*/
static krb5_error_code
verify_flags (krb5_context context,
krb5_kdc_configuration *config,
const EncTicketPart *et,
const char *pstr)
{
if(et->endtime < kdc_time){
kdc_log(context, config, 0, "Ticket expired (%s)", pstr);
return KRB5KRB_AP_ERR_TKT_EXPIRED;
}
if(et->flags.invalid){
kdc_log(context, config, 0, "Ticket not valid (%s)", pstr);
return KRB5KRB_AP_ERR_TKT_NYV;
}
return 0;
}
/*
*
*/
static krb5_error_code
fix_transited_encoding(krb5_context context,
krb5_kdc_configuration *config,
krb5_boolean check_policy,
const TransitedEncoding *tr,
EncTicketPart *et,
const char *client_realm,
const char *server_realm,
const char *tgt_realm)
{
krb5_error_code ret = 0;
char **realms, **tmp;
unsigned int num_realms;
size_t i;
switch (tr->tr_type) {
case DOMAIN_X500_COMPRESS:
break;
case 0:
/*
* Allow empty content of type 0 because that is was Microsoft
* generates in their TGT.
*/
if (tr->contents.length == 0)
break;
kdc_log(context, config, 0,
"Transited type 0 with non empty content");
return KRB5KDC_ERR_TRTYPE_NOSUPP;
default:
kdc_log(context, config, 0,
"Unknown transited type: %u", tr->tr_type);
return KRB5KDC_ERR_TRTYPE_NOSUPP;
}
ret = krb5_domain_x500_decode(context,
tr->contents,
&realms,
&num_realms,
client_realm,
server_realm);
if(ret){
krb5_warn(context, ret,
"Decoding transited encoding");
return ret;
}
/*
* If the realm of the presented tgt is neither the client nor the server
* realm, it is a transit realm and must be added to transited set.
*/
if(strcmp(client_realm, tgt_realm) && strcmp(server_realm, tgt_realm)) {
if (num_realms + 1 > UINT_MAX/sizeof(*realms)) {
ret = ERANGE;
goto free_realms;
}
tmp = realloc(realms, (num_realms + 1) * sizeof(*realms));
if(tmp == NULL){
ret = ENOMEM;
goto free_realms;
}
realms = tmp;
realms[num_realms] = strdup(tgt_realm);
if(realms[num_realms] == NULL){
ret = ENOMEM;
goto free_realms;
}
num_realms++;
}
if(num_realms == 0) {
if(strcmp(client_realm, server_realm))
kdc_log(context, config, 0,
"cross-realm %s -> %s", client_realm, server_realm);
} else {
size_t l = 0;
char *rs;
for(i = 0; i < num_realms; i++)
l += strlen(realms[i]) + 2;
rs = malloc(l);
if(rs != NULL) {
*rs = '\0';
for(i = 0; i < num_realms; i++) {
if(i > 0)
strlcat(rs, ", ", l);
strlcat(rs, realms[i], l);
}
kdc_log(context, config, 0,
"cross-realm %s -> %s via [%s]",
client_realm, server_realm, rs);
free(rs);
}
}
if(check_policy) {
ret = krb5_check_transited(context, client_realm,
server_realm,
realms, num_realms, NULL);
if(ret) {
krb5_warn(context, ret, "cross-realm %s -> %s",
client_realm, server_realm);
goto free_realms;
}
et->flags.transited_policy_checked = 1;
}
et->transited.tr_type = DOMAIN_X500_COMPRESS;
ret = krb5_domain_x500_encode(realms, num_realms, &et->transited.contents);
if(ret)
krb5_warn(context, ret, "Encoding transited encoding");
free_realms:
for(i = 0; i < num_realms; i++)
free(realms[i]);
free(realms);
return ret;
}
static krb5_error_code
tgs_make_reply(krb5_context context,
krb5_kdc_configuration *config,
KDC_REQ_BODY *b,
krb5_const_principal tgt_name,
const EncTicketPart *tgt,
const krb5_keyblock *replykey,
int rk_is_subkey,
const EncryptionKey *serverkey,
const krb5_keyblock *sessionkey,
krb5_kvno kvno,
AuthorizationData *auth_data,
hdb_entry_ex *server,
krb5_principal server_principal,
const char *server_name,
hdb_entry_ex *client,
krb5_principal client_principal,
const char *tgt_realm,
hdb_entry_ex *krbtgt,
krb5_enctype krbtgt_etype,
krb5_principals spp,
const krb5_data *rspac,
const METHOD_DATA *enc_pa_data,
const char **e_text,
krb5_data *reply)
{
KDC_REP rep;
EncKDCRepPart ek;
EncTicketPart et;
KDCOptions f = b->kdc_options;
krb5_error_code ret;
int is_weak = 0;
memset(&rep, 0, sizeof(rep));
memset(&et, 0, sizeof(et));
memset(&ek, 0, sizeof(ek));
rep.pvno = 5;
rep.msg_type = krb_tgs_rep;
et.authtime = tgt->authtime;
_kdc_fix_time(&b->till);
et.endtime = min(tgt->endtime, *b->till);
ALLOC(et.starttime);
*et.starttime = kdc_time;
ret = check_tgs_flags(context, config, b, tgt, &et);
if(ret)
goto out;
/* We should check the transited encoding if:
1) the request doesn't ask not to be checked
2) globally enforcing a check
3) principal requires checking
4) we allow non-check per-principal, but principal isn't marked as allowing this
5) we don't globally allow this
*/
#define GLOBAL_FORCE_TRANSITED_CHECK \
(config->trpolicy == TRPOLICY_ALWAYS_CHECK)
#define GLOBAL_ALLOW_PER_PRINCIPAL \
(config->trpolicy == TRPOLICY_ALLOW_PER_PRINCIPAL)
#define GLOBAL_ALLOW_DISABLE_TRANSITED_CHECK \
(config->trpolicy == TRPOLICY_ALWAYS_HONOUR_REQUEST)
/* these will consult the database in future release */
#define PRINCIPAL_FORCE_TRANSITED_CHECK(P) 0
#define PRINCIPAL_ALLOW_DISABLE_TRANSITED_CHECK(P) 0
ret = fix_transited_encoding(context, config,
!f.disable_transited_check ||
GLOBAL_FORCE_TRANSITED_CHECK ||
PRINCIPAL_FORCE_TRANSITED_CHECK(server) ||
!((GLOBAL_ALLOW_PER_PRINCIPAL &&
PRINCIPAL_ALLOW_DISABLE_TRANSITED_CHECK(server)) ||
GLOBAL_ALLOW_DISABLE_TRANSITED_CHECK),
&tgt->transited, &et,
krb5_principal_get_realm(context, client_principal),
krb5_principal_get_realm(context, server->entry.principal),
tgt_realm);
if(ret)
goto out;
copy_Realm(&server_principal->realm, &rep.ticket.realm);
_krb5_principal2principalname(&rep.ticket.sname, server_principal);
copy_Realm(&tgt_name->realm, &rep.crealm);
/*
if (f.request_anonymous)
_kdc_make_anonymous_principalname (&rep.cname);
else */
copy_PrincipalName(&tgt_name->name, &rep.cname);
rep.ticket.tkt_vno = 5;
ek.caddr = et.caddr;
{
time_t life;
life = et.endtime - *et.starttime;
if(client && client->entry.max_life)
life = min(life, *client->entry.max_life);
if(server->entry.max_life)
life = min(life, *server->entry.max_life);
et.endtime = *et.starttime + life;
}
if(f.renewable_ok && tgt->flags.renewable &&
et.renew_till == NULL && et.endtime < *b->till &&
tgt->renew_till != NULL)
{
et.flags.renewable = 1;
ALLOC(et.renew_till);
*et.renew_till = *b->till;
}
if(et.renew_till){
time_t renew;
renew = *et.renew_till - *et.starttime;
if(client && client->entry.max_renew)
renew = min(renew, *client->entry.max_renew);
if(server->entry.max_renew)
renew = min(renew, *server->entry.max_renew);
*et.renew_till = *et.starttime + renew;
}
if(et.renew_till){
*et.renew_till = min(*et.renew_till, *tgt->renew_till);
*et.starttime = min(*et.starttime, *et.renew_till);
et.endtime = min(et.endtime, *et.renew_till);
}
*et.starttime = min(*et.starttime, et.endtime);
if(*et.starttime == et.endtime){
ret = KRB5KDC_ERR_NEVER_VALID;
goto out;
}
if(et.renew_till && et.endtime == *et.renew_till){
free(et.renew_till);
et.renew_till = NULL;
et.flags.renewable = 0;
}
et.flags.pre_authent = tgt->flags.pre_authent;
et.flags.hw_authent = tgt->flags.hw_authent;
et.flags.anonymous = tgt->flags.anonymous;
et.flags.ok_as_delegate = server->entry.flags.ok_as_delegate;
if(rspac->length) {
/*
* No not need to filter out the any PAC from the
* auth_data since it's signed by the KDC.
*/
ret = _kdc_tkt_add_if_relevant_ad(context, &et,
KRB5_AUTHDATA_WIN2K_PAC, rspac);
if (ret)
goto out;
}
if (auth_data) {
unsigned int i = 0;
/* XXX check authdata */
if (et.authorization_data == NULL) {
et.authorization_data = calloc(1, sizeof(*et.authorization_data));
if (et.authorization_data == NULL) {
ret = ENOMEM;
krb5_set_error_message(context, ret, "malloc: out of memory");
goto out;
}
}
for(i = 0; i < auth_data->len ; i++) {
ret = add_AuthorizationData(et.authorization_data, &auth_data->val[i]);
if (ret) {
krb5_set_error_message(context, ret, "malloc: out of memory");
goto out;
}
}
/* Filter out type KRB5SignedPath */
ret = find_KRB5SignedPath(context, et.authorization_data, NULL);
if (ret == 0) {
if (et.authorization_data->len == 1) {
free_AuthorizationData(et.authorization_data);
free(et.authorization_data);
et.authorization_data = NULL;
} else {
AuthorizationData *ad = et.authorization_data;
free_AuthorizationDataElement(&ad->val[ad->len - 1]);
ad->len--;
}
}
}
ret = krb5_copy_keyblock_contents(context, sessionkey, &et.key);
if (ret)
goto out;
et.crealm = tgt_name->realm;
et.cname = tgt_name->name;
ek.key = et.key;
/* MIT must have at least one last_req */
ek.last_req.val = calloc(1, sizeof(*ek.last_req.val));
if (ek.last_req.val == NULL) {
ret = ENOMEM;
goto out;
}
ek.last_req.len = 1; /* set after alloc to avoid null deref on cleanup */
ek.nonce = b->nonce;
ek.flags = et.flags;
ek.authtime = et.authtime;
ek.starttime = et.starttime;
ek.endtime = et.endtime;
ek.renew_till = et.renew_till;
ek.srealm = rep.ticket.realm;
ek.sname = rep.ticket.sname;
_kdc_log_timestamp(context, config, "TGS-REQ", et.authtime, et.starttime,
et.endtime, et.renew_till);
/* Don't sign cross realm tickets, they can't be checked anyway */
{
char *r = get_krbtgt_realm(&ek.sname);
if (r == NULL || strcmp(r, ek.srealm) == 0) {
ret = _kdc_add_KRB5SignedPath(context,
config,
krbtgt,
krbtgt_etype,
client_principal,
NULL,
spp,
&et);
if (ret)
goto out;
}
}
if (enc_pa_data->len) {
rep.padata = calloc(1, sizeof(*rep.padata));
if (rep.padata == NULL) {
ret = ENOMEM;
goto out;
}
ret = copy_METHOD_DATA(enc_pa_data, rep.padata);
if (ret)
goto out;
}
if (krb5_enctype_valid(context, serverkey->keytype) != 0
&& _kdc_is_weak_exception(server->entry.principal, serverkey->keytype))
{
krb5_enctype_enable(context, serverkey->keytype);
is_weak = 1;
}
/* It is somewhat unclear where the etype in the following
encryption should come from. What we have is a session
key in the passed tgt, and a list of preferred etypes
*for the new ticket*. Should we pick the best possible
etype, given the keytype in the tgt, or should we look
at the etype list here as well? What if the tgt
session key is DES3 and we want a ticket with a (say)
CAST session key. Should the DES3 etype be added to the
etype list, even if we don't want a session key with
DES3? */
ret = _kdc_encode_reply(context, config, NULL, 0,
&rep, &et, &ek, serverkey->keytype,
kvno,
serverkey, 0, replykey, rk_is_subkey,
e_text, reply);
if (is_weak)
krb5_enctype_disable(context, serverkey->keytype);
out:
free_TGS_REP(&rep);
free_TransitedEncoding(&et.transited);
if(et.starttime)
free(et.starttime);
if(et.renew_till)
free(et.renew_till);
if(et.authorization_data) {
free_AuthorizationData(et.authorization_data);
free(et.authorization_data);
}
free_LastReq(&ek.last_req);
memset(et.key.keyvalue.data, 0, et.key.keyvalue.length);
free_EncryptionKey(&et.key);
return ret;
}
static krb5_error_code
tgs_check_authenticator(krb5_context context,
krb5_kdc_configuration *config,
krb5_auth_context ac,
KDC_REQ_BODY *b,
const char **e_text,
krb5_keyblock *key)
{
krb5_authenticator auth;
size_t len = 0;
unsigned char *buf;
size_t buf_size;
krb5_error_code ret;
krb5_crypto crypto;
krb5_auth_con_getauthenticator(context, ac, &auth);
if(auth->cksum == NULL){
kdc_log(context, config, 0, "No authenticator in request");
ret = KRB5KRB_AP_ERR_INAPP_CKSUM;
goto out;
}
/*
* according to RFC1510 it doesn't need to be keyed,
* but according to the latest draft it needs to.
*/
if (
#if 0
!krb5_checksum_is_keyed(context, auth->cksum->cksumtype)
||
#endif
!krb5_checksum_is_collision_proof(context, auth->cksum->cksumtype)) {
kdc_log(context, config, 0, "Bad checksum type in authenticator: %d",
auth->cksum->cksumtype);
ret = KRB5KRB_AP_ERR_INAPP_CKSUM;
goto out;
}
/* XXX should not re-encode this */
ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, buf_size, b, &len, ret);
if(ret){
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0, "Failed to encode KDC-REQ-BODY: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
if(buf_size != len) {
free(buf);
kdc_log(context, config, 0, "Internal error in ASN.1 encoder");
*e_text = "KDC internal error";
ret = KRB5KRB_ERR_GENERIC;
goto out;
}
ret = krb5_crypto_init(context, key, 0, &crypto);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
free(buf);
kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
ret = krb5_verify_checksum(context,
crypto,
KRB5_KU_TGS_REQ_AUTH_CKSUM,
buf,
len,
auth->cksum);
free(buf);
krb5_crypto_destroy(context, crypto);
if(ret){
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0,
"Failed to verify authenticator checksum: %s", msg);
krb5_free_error_message(context, msg);
}
out:
free_Authenticator(auth);
free(auth);
return ret;
}
static krb5_boolean
need_referral(krb5_context context, krb5_kdc_configuration *config,
const KDCOptions * const options, krb5_principal server,
krb5_realm **realms)
{
const char *name;
if(!options->canonicalize && server->name.name_type != KRB5_NT_SRV_INST)
return FALSE;
if (server->name.name_string.len == 1)
name = server->name.name_string.val[0];
else if (server->name.name_string.len == 3) {
/*
This is used to give referrals for the
E3514235-4B06-11D1-AB04-00C04FC2DCD2/NTDSGUID/DNSDOMAIN
SPN form, which is used for inter-domain communication in AD
*/
name = server->name.name_string.val[2];
kdc_log(context, config, 0, "Giving 3 part referral for %s", name);
*realms = malloc(sizeof(char *)*2);
if (*realms == NULL) {
krb5_set_error_message(context, ENOMEM, N_("malloc: out of memory", ""));
return FALSE;
}
(*realms)[0] = strdup(name);
(*realms)[1] = NULL;
return TRUE;
} else if (server->name.name_string.len > 1)
name = server->name.name_string.val[1];
else
return FALSE;
kdc_log(context, config, 0, "Searching referral for %s", name);
return _krb5_get_host_realm_int(context, name, FALSE, realms) == 0;
}
static krb5_error_code
tgs_parse_request(krb5_context context,
krb5_kdc_configuration *config,
KDC_REQ_BODY *b,
const PA_DATA *tgs_req,
hdb_entry_ex **krbtgt,
krb5_enctype *krbtgt_etype,
krb5_ticket **ticket,
const char **e_text,
const char *from,
const struct sockaddr *from_addr,
time_t **csec,
int **cusec,
AuthorizationData **auth_data,
krb5_keyblock **replykey,
int *rk_is_subkey)
{
static char failed[] = "<unparse_name failed>";
krb5_ap_req ap_req;
krb5_error_code ret;
krb5_principal princ;
krb5_auth_context ac = NULL;
krb5_flags ap_req_options;
krb5_flags verify_ap_req_flags;
krb5_crypto crypto;
krb5uint32 krbtgt_kvno; /* kvno used for the PA-TGS-REQ AP-REQ Ticket */
krb5uint32 krbtgt_kvno_try;
int kvno_search_tries = 4; /* number of kvnos to try when tkt_vno == 0 */
const Keys *krbtgt_keys;/* keyset for TGT tkt_vno */
Key *tkey;
krb5_keyblock *subkey = NULL;
unsigned usage;
*auth_data = NULL;
*csec = NULL;
*cusec = NULL;
*replykey = NULL;
memset(&ap_req, 0, sizeof(ap_req));
ret = krb5_decode_ap_req(context, &tgs_req->padata_value, &ap_req);
if(ret){
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0, "Failed to decode AP-REQ: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
if(!get_krbtgt_realm(&ap_req.ticket.sname)){
/* XXX check for ticket.sname == req.sname */
kdc_log(context, config, 0, "PA-DATA is not a ticket-granting ticket");
ret = KRB5KDC_ERR_POLICY; /* ? */
goto out;
}
_krb5_principalname2krb5_principal(context,
&princ,
ap_req.ticket.sname,
ap_req.ticket.realm);
krbtgt_kvno = ap_req.ticket.enc_part.kvno ? *ap_req.ticket.enc_part.kvno : 0;
ret = _kdc_db_fetch(context, config, princ, HDB_F_GET_KRBTGT,
&krbtgt_kvno, NULL, krbtgt);
if (ret == HDB_ERR_NOT_FOUND_HERE) {
/* XXX Factor out this unparsing of the same princ all over */
char *p;
ret = krb5_unparse_name(context, princ, &p);
if (ret != 0)
p = failed;
krb5_free_principal(context, princ);
kdc_log(context, config, 5,
"Ticket-granting ticket account %s does not have secrets at "
"this KDC, need to proxy", p);
if (ret == 0)
free(p);
ret = HDB_ERR_NOT_FOUND_HERE;
goto out;
} else if (ret == HDB_ERR_KVNO_NOT_FOUND) {
char *p;
ret = krb5_unparse_name(context, princ, &p);
if (ret != 0)
p = failed;
krb5_free_principal(context, princ);
kdc_log(context, config, 5,
"Ticket-granting ticket account %s does not have keys for "
"kvno %d at this KDC", p, krbtgt_kvno);
if (ret == 0)
free(p);
ret = HDB_ERR_KVNO_NOT_FOUND;
goto out;
} else if (ret == HDB_ERR_NO_MKEY) {
char *p;
ret = krb5_unparse_name(context, princ, &p);
if (ret != 0)
p = failed;
krb5_free_principal(context, princ);
kdc_log(context, config, 5,
"Missing master key for decrypting keys for ticket-granting "
"ticket account %s with kvno %d at this KDC", p, krbtgt_kvno);
if (ret == 0)
free(p);
ret = HDB_ERR_KVNO_NOT_FOUND;
goto out;
} else if (ret) {
const char *msg = krb5_get_error_message(context, ret);
char *p;
ret = krb5_unparse_name(context, princ, &p);
if (ret != 0)
p = failed;
krb5_free_principal(context, princ);
kdc_log(context, config, 0,
"Ticket-granting ticket not found in database: %s", msg);
krb5_free_error_message(context, msg);
if (ret == 0)
free(p);
ret = KRB5KRB_AP_ERR_NOT_US;
goto out;
}
krbtgt_kvno_try = krbtgt_kvno ? krbtgt_kvno : (*krbtgt)->entry.kvno;
*krbtgt_etype = ap_req.ticket.enc_part.etype;
next_kvno:
krbtgt_keys = hdb_kvno2keys(context, &(*krbtgt)->entry, krbtgt_kvno_try);
ret = hdb_enctype2key(context, &(*krbtgt)->entry, krbtgt_keys,
ap_req.ticket.enc_part.etype, &tkey);
if (ret && krbtgt_kvno == 0 && kvno_search_tries > 0) {
kvno_search_tries--;
krbtgt_kvno_try--;
goto next_kvno;
} else if (ret) {
char *str = NULL, *p = NULL;
krb5_enctype_to_string(context, ap_req.ticket.enc_part.etype, &str);
krb5_unparse_name(context, princ, &p);
kdc_log(context, config, 0,
"No server key with enctype %s found for %s",
str ? str : "<unknown enctype>",
p ? p : "<unparse_name failed>");
free(str);
free(p);
ret = KRB5KRB_AP_ERR_BADKEYVER;
goto out;
}
if (b->kdc_options.validate)
verify_ap_req_flags = KRB5_VERIFY_AP_REQ_IGNORE_INVALID;
else
verify_ap_req_flags = 0;
ret = krb5_verify_ap_req2(context,
&ac,
&ap_req,
princ,
&tkey->key,
verify_ap_req_flags,
&ap_req_options,
ticket,
KRB5_KU_TGS_REQ_AUTH);
if (ret == KRB5KRB_AP_ERR_BAD_INTEGRITY && kvno_search_tries > 0) {
kvno_search_tries--;
krbtgt_kvno_try--;
goto next_kvno;
}
krb5_free_principal(context, princ);
if(ret) {
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0, "Failed to verify AP-REQ: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
{
krb5_authenticator auth;
ret = krb5_auth_con_getauthenticator(context, ac, &auth);
if (ret == 0) {
*csec = malloc(sizeof(**csec));
if (*csec == NULL) {
krb5_free_authenticator(context, &auth);
kdc_log(context, config, 0, "malloc failed");
goto out;
}
**csec = auth->ctime;
*cusec = malloc(sizeof(**cusec));
if (*cusec == NULL) {
krb5_free_authenticator(context, &auth);
kdc_log(context, config, 0, "malloc failed");
goto out;
}
**cusec = auth->cusec;
krb5_free_authenticator(context, &auth);
}
}
ret = tgs_check_authenticator(context, config,
ac, b, e_text, &(*ticket)->ticket.key);
if (ret) {
krb5_auth_con_free(context, ac);
goto out;
}
usage = KRB5_KU_TGS_REQ_AUTH_DAT_SUBKEY;
*rk_is_subkey = 1;
ret = krb5_auth_con_getremotesubkey(context, ac, &subkey);
if(ret){
const char *msg = krb5_get_error_message(context, ret);
krb5_auth_con_free(context, ac);
kdc_log(context, config, 0, "Failed to get remote subkey: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
if(subkey == NULL){
usage = KRB5_KU_TGS_REQ_AUTH_DAT_SESSION;
*rk_is_subkey = 0;
ret = krb5_auth_con_getkey(context, ac, &subkey);
if(ret) {
const char *msg = krb5_get_error_message(context, ret);
krb5_auth_con_free(context, ac);
kdc_log(context, config, 0, "Failed to get session key: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
}
if(subkey == NULL){
krb5_auth_con_free(context, ac);
kdc_log(context, config, 0,
"Failed to get key for enc-authorization-data");
ret = KRB5KRB_AP_ERR_BAD_INTEGRITY; /* ? */
goto out;
}
*replykey = subkey;
if (b->enc_authorization_data) {
krb5_data ad;
ret = krb5_crypto_init(context, subkey, 0, &crypto);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
krb5_auth_con_free(context, ac);
kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
ret = krb5_decrypt_EncryptedData (context,
crypto,
usage,
b->enc_authorization_data,
&ad);
krb5_crypto_destroy(context, crypto);
if(ret){
krb5_auth_con_free(context, ac);
kdc_log(context, config, 0,
"Failed to decrypt enc-authorization-data");
ret = KRB5KRB_AP_ERR_BAD_INTEGRITY; /* ? */
goto out;
}
ALLOC(*auth_data);
if (*auth_data == NULL) {
krb5_auth_con_free(context, ac);
ret = KRB5KRB_AP_ERR_BAD_INTEGRITY; /* ? */
goto out;
}
ret = decode_AuthorizationData(ad.data, ad.length, *auth_data, NULL);
if(ret){
krb5_auth_con_free(context, ac);
free(*auth_data);
*auth_data = NULL;
kdc_log(context, config, 0, "Failed to decode authorization data");
ret = KRB5KRB_AP_ERR_BAD_INTEGRITY; /* ? */
goto out;
}
}
krb5_auth_con_free(context, ac);
out:
free_AP_REQ(&ap_req);
return ret;
}
static krb5_error_code
build_server_referral(krb5_context context,
krb5_kdc_configuration *config,
krb5_crypto session,
krb5_const_realm referred_realm,
const PrincipalName *true_principal_name,
const PrincipalName *requested_principal,
krb5_data *outdata)
{
PA_ServerReferralData ref;
krb5_error_code ret;
EncryptedData ed;
krb5_data data;
size_t size = 0;
memset(&ref, 0, sizeof(ref));
if (referred_realm) {
ALLOC(ref.referred_realm);
if (ref.referred_realm == NULL)
goto eout;
*ref.referred_realm = strdup(referred_realm);
if (*ref.referred_realm == NULL)
goto eout;
}
if (true_principal_name) {
ALLOC(ref.true_principal_name);
if (ref.true_principal_name == NULL)
goto eout;
ret = copy_PrincipalName(true_principal_name, ref.true_principal_name);
if (ret)
goto eout;
}
if (requested_principal) {
ALLOC(ref.requested_principal_name);
if (ref.requested_principal_name == NULL)
goto eout;
ret = copy_PrincipalName(requested_principal,
ref.requested_principal_name);
if (ret)
goto eout;
}
ASN1_MALLOC_ENCODE(PA_ServerReferralData,
data.data, data.length,
&ref, &size, ret);
free_PA_ServerReferralData(&ref);
if (ret)
return ret;
if (data.length != size)
krb5_abortx(context, "internal asn.1 encoder error");
ret = krb5_encrypt_EncryptedData(context, session,
KRB5_KU_PA_SERVER_REFERRAL,
data.data, data.length,
0 /* kvno */, &ed);
free(data.data);
if (ret)
return ret;
ASN1_MALLOC_ENCODE(EncryptedData,
outdata->data, outdata->length,
&ed, &size, ret);
free_EncryptedData(&ed);
if (ret)
return ret;
if (outdata->length != size)
krb5_abortx(context, "internal asn.1 encoder error");
return 0;
eout:
free_PA_ServerReferralData(&ref);
krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
return ENOMEM;
}
static krb5_error_code
tgs_build_reply(krb5_context context,
krb5_kdc_configuration *config,
KDC_REQ *req,
KDC_REQ_BODY *b,
hdb_entry_ex *krbtgt,
krb5_enctype krbtgt_etype,
const krb5_keyblock *replykey,
int rk_is_subkey,
krb5_ticket *ticket,
krb5_data *reply,
const char *from,
const char **e_text,
AuthorizationData **auth_data,
const struct sockaddr *from_addr)
{
krb5_error_code ret;
krb5_principal cp = NULL, sp = NULL, rsp = NULL, tp = NULL, dp = NULL;
krb5_principal krbtgt_out_principal = NULL;
char *spn = NULL, *cpn = NULL, *tpn = NULL, *dpn = NULL, *krbtgt_out_n = NULL;
hdb_entry_ex *server = NULL, *client = NULL, *s4u2self_impersonated_client = NULL;
HDB *clientdb, *s4u2self_impersonated_clientdb;
krb5_realm ref_realm = NULL;
EncTicketPart *tgt = &ticket->ticket;
krb5_principals spp = NULL;
const EncryptionKey *ekey;
krb5_keyblock sessionkey;
krb5_kvno kvno;
krb5_data rspac;
const char *tgt_realm = /* Realm of TGT issuer */
krb5_principal_get_realm(context, krbtgt->entry.principal);
const char *our_realm = /* Realm of this KDC */
krb5_principal_get_comp_string(context, krbtgt->entry.principal, 1);
char **capath = NULL;
size_t num_capath = 0;
hdb_entry_ex *krbtgt_out = NULL;
METHOD_DATA enc_pa_data;
PrincipalName *s;
Realm r;
EncTicketPart adtkt;
char opt_str[128];
int signedpath = 0;
Key *tkey_check;
Key *tkey_sign;
int flags = HDB_F_FOR_TGS_REQ;
memset(&sessionkey, 0, sizeof(sessionkey));
memset(&adtkt, 0, sizeof(adtkt));
krb5_data_zero(&rspac);
memset(&enc_pa_data, 0, sizeof(enc_pa_data));
s = b->sname;
r = b->realm;
/*
* Always to do CANON, see comment below about returned server principal (rsp).
*/
flags |= HDB_F_CANON;
if(b->kdc_options.enc_tkt_in_skey){
Ticket *t;
hdb_entry_ex *uu;
krb5_principal p;
Key *uukey;
krb5uint32 second_kvno = 0;
krb5uint32 *kvno_ptr = NULL;
if(b->additional_tickets == NULL ||
b->additional_tickets->len == 0){
ret = KRB5KDC_ERR_BADOPTION; /* ? */
kdc_log(context, config, 0,
"No second ticket present in request");
goto out;
}
t = &b->additional_tickets->val[0];
if(!get_krbtgt_realm(&t->sname)){
kdc_log(context, config, 0,
"Additional ticket is not a ticket-granting ticket");
ret = KRB5KDC_ERR_POLICY;
goto out;
}
_krb5_principalname2krb5_principal(context, &p, t->sname, t->realm);
if(t->enc_part.kvno){
second_kvno = *t->enc_part.kvno;
kvno_ptr = &second_kvno;
}
ret = _kdc_db_fetch(context, config, p,
HDB_F_GET_KRBTGT, kvno_ptr,
NULL, &uu);
krb5_free_principal(context, p);
if(ret){
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
goto out;
}
ret = hdb_enctype2key(context, &uu->entry, NULL,
t->enc_part.etype, &uukey);
if(ret){
_kdc_free_ent(context, uu);
ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */
goto out;
}
ret = krb5_decrypt_ticket(context, t, &uukey->key, &adtkt, 0);
_kdc_free_ent(context, uu);
if(ret)
goto out;
ret = verify_flags(context, config, &adtkt, spn);
if (ret)
goto out;
s = &adtkt.cname;
r = adtkt.crealm;
}
_krb5_principalname2krb5_principal(context, &sp, *s, r);
ret = krb5_unparse_name(context, sp, &spn);
if (ret)
goto out;
_krb5_principalname2krb5_principal(context, &cp, tgt->cname, tgt->crealm);
ret = krb5_unparse_name(context, cp, &cpn);
if (ret)
goto out;
unparse_flags (KDCOptions2int(b->kdc_options),
asn1_KDCOptions_units(),
opt_str, sizeof(opt_str));
if(*opt_str)
kdc_log(context, config, 0,
"TGS-REQ %s from %s for %s [%s]",
cpn, from, spn, opt_str);
else
kdc_log(context, config, 0,
"TGS-REQ %s from %s for %s", cpn, from, spn);
/*
* Fetch server
*/
server_lookup:
ret = _kdc_db_fetch(context, config, sp, HDB_F_GET_SERVER | flags,
NULL, NULL, &server);
if (ret == HDB_ERR_NOT_FOUND_HERE) {
kdc_log(context, config, 5, "target %s does not have secrets at this KDC, need to proxy", sp);
goto out;
} else if (ret == HDB_ERR_WRONG_REALM) {
free(ref_realm);
ref_realm = strdup(server->entry.principal->realm);
if (ref_realm == NULL) {
ret = krb5_enomem(context);
goto out;
}
kdc_log(context, config, 5,
"Returning a referral to realm %s for "
"server %s.",
ref_realm, spn);
krb5_free_principal(context, sp);
sp = NULL;
ret = krb5_make_principal(context, &sp, r, KRB5_TGS_NAME,
ref_realm, NULL);
if (ret)
goto out;
free(spn);
spn = NULL;
ret = krb5_unparse_name(context, sp, &spn);
if (ret)
goto out;
goto server_lookup;
} else if (ret) {
const char *new_rlm, *msg;
Realm req_rlm;
krb5_realm *realms;
if ((req_rlm = get_krbtgt_realm(&sp->name)) != NULL) {
if (capath == NULL) {
/* With referalls, hierarchical capaths are always enabled */
ret = _krb5_find_capath(context, tgt->crealm, our_realm,
req_rlm, TRUE, &capath, &num_capath);
if (ret)
goto out;
}
new_rlm = num_capath > 0 ? capath[--num_capath] : NULL;
if (new_rlm) {
kdc_log(context, config, 5, "krbtgt from %s via %s for "
"realm %s not found, trying %s", tgt->crealm,
our_realm, req_rlm, new_rlm);
free(ref_realm);
ref_realm = strdup(new_rlm);
if (ref_realm == NULL) {
ret = krb5_enomem(context);
goto out;
}
krb5_free_principal(context, sp);
sp = NULL;
krb5_make_principal(context, &sp, r,
KRB5_TGS_NAME, ref_realm, NULL);
free(spn);
spn = NULL;
ret = krb5_unparse_name(context, sp, &spn);
if (ret)
goto out;
goto server_lookup;
}
} else if (need_referral(context, config, &b->kdc_options, sp, &realms)) {
if (strcmp(realms[0], sp->realm) != 0) {
kdc_log(context, config, 5,
"Returning a referral to realm %s for "
"server %s that was not found",
realms[0], spn);
krb5_free_principal(context, sp);
sp = NULL;
krb5_make_principal(context, &sp, r, KRB5_TGS_NAME,
realms[0], NULL);
free(spn);
spn = NULL;
ret = krb5_unparse_name(context, sp, &spn);
if (ret) {
krb5_free_host_realm(context, realms);
goto out;
}
free(ref_realm);
ref_realm = strdup(realms[0]);
krb5_free_host_realm(context, realms);
goto server_lookup;
}
krb5_free_host_realm(context, realms);
}
msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0,
"Server not found in database: %s: %s", spn, msg);
krb5_free_error_message(context, msg);
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
goto out;
}
/* the name returned to the client depend on what was asked for,
* return canonical name if kdc_options.canonicalize was set, the
* client wants the true name of the principal, if not it just
* wants the name its asked for.
*/
if (b->kdc_options.canonicalize)
rsp = server->entry.principal;
else
rsp = sp;
/*
* Select enctype, return key and kvno.
*/
{
krb5_enctype etype;
if(b->kdc_options.enc_tkt_in_skey) {
size_t i;
ekey = &adtkt.key;
for(i = 0; i < b->etype.len; i++)
if (b->etype.val[i] == adtkt.key.keytype)
break;
if(i == b->etype.len) {
kdc_log(context, config, 0,
"Addition ticket have not matching etypes");
krb5_clear_error_message(context);
ret = KRB5KDC_ERR_ETYPE_NOSUPP;
goto out;
}
etype = b->etype.val[i];
kvno = 0;
} else {
Key *skey;
ret = _kdc_find_etype(context,
krb5_principal_is_krbtgt(context, sp) ?
config->tgt_use_strongest_session_key :
config->svc_use_strongest_session_key, FALSE,
server, b->etype.val, b->etype.len, &etype,
NULL);
if(ret) {
kdc_log(context, config, 0,
"Server (%s) has no support for etypes", spn);
goto out;
}
ret = _kdc_get_preferred_key(context, config, server, spn,
NULL, &skey);
if(ret) {
kdc_log(context, config, 0,
"Server (%s) has no supported etypes", spn);
goto out;
}
ekey = &skey->key;
kvno = server->entry.kvno;
}
ret = krb5_generate_random_keyblock(context, etype, &sessionkey);
if (ret)
goto out;
}
/*
* Check that service is in the same realm as the krbtgt. If it's
* not the same, it's someone that is using a uni-directional trust
* backward.
*/
/*
* Validate authoriation data
*/
ret = hdb_enctype2key(context, &krbtgt->entry, NULL, /* XXX use the right kvno! */
krbtgt_etype, &tkey_check);
if(ret) {
kdc_log(context, config, 0,
"Failed to find key for krbtgt PAC check");
goto out;
}
/*
* Now refetch the primary krbtgt, and get the current kvno (the
* sign check may have been on an old kvno, and the server may
* have been an incoming trust)
*/
ret = krb5_make_principal(context,
&krbtgt_out_principal,
our_realm,
KRB5_TGS_NAME,
our_realm,
NULL);
if (ret) {
kdc_log(context, config, 0,
"Failed to make krbtgt principal name object for "
"authz-data signatures");
goto out;
}
ret = krb5_unparse_name(context, krbtgt_out_principal, &krbtgt_out_n);
if (ret) {
kdc_log(context, config, 0,
"Failed to make krbtgt principal name object for "
"authz-data signatures");
goto out;
}
ret = _kdc_db_fetch(context, config, krbtgt_out_principal,
HDB_F_GET_KRBTGT, NULL, NULL, &krbtgt_out);
if (ret) {
char *ktpn = NULL;
ret = krb5_unparse_name(context, krbtgt->entry.principal, &ktpn);
kdc_log(context, config, 0,
"No such principal %s (needed for authz-data signature keys) "
"while processing TGS-REQ for service %s with krbtg %s",
krbtgt_out_n, spn, (ret == 0) ? ktpn : "<unknown>");
free(ktpn);
ret = KRB5KRB_AP_ERR_NOT_US;
goto out;
}
/*
* The first realm is the realm of the service, the second is
* krbtgt/<this>/@REALM component of the krbtgt DN the request was
* encrypted to. The redirection via the krbtgt_out entry allows
* the DB to possibly correct the case of the realm (Samba4 does
* this) before the strcmp()
*/
if (strcmp(krb5_principal_get_realm(context, server->entry.principal),
krb5_principal_get_realm(context, krbtgt_out->entry.principal)) != 0) {
char *ktpn;
ret = krb5_unparse_name(context, krbtgt_out->entry.principal, &ktpn);
kdc_log(context, config, 0,
"Request with wrong krbtgt: %s",
(ret == 0) ? ktpn : "<unknown>");
if(ret == 0)
free(ktpn);
ret = KRB5KRB_AP_ERR_NOT_US;
goto out;
}
ret = _kdc_get_preferred_key(context, config, krbtgt_out, krbtgt_out_n,
NULL, &tkey_sign);
if (ret) {
kdc_log(context, config, 0,
"Failed to find key for krbtgt PAC signature");
goto out;
}
ret = hdb_enctype2key(context, &krbtgt_out->entry, NULL,
tkey_sign->key.keytype, &tkey_sign);
if(ret) {
kdc_log(context, config, 0,
"Failed to find key for krbtgt PAC signature");
goto out;
}
ret = _kdc_db_fetch(context, config, cp, HDB_F_GET_CLIENT | flags,
NULL, &clientdb, &client);
if(ret == HDB_ERR_NOT_FOUND_HERE) {
/* This is OK, we are just trying to find out if they have
* been disabled or deleted in the meantime, missing secrets
* is OK */
} else if(ret){
const char *krbtgt_realm, *msg;
/*
* If the client belongs to the same realm as our krbtgt, it
* should exist in the local database.
*
*/
krbtgt_realm = krb5_principal_get_realm(context, krbtgt_out->entry.principal);
if(strcmp(krb5_principal_get_realm(context, cp), krbtgt_realm) == 0) {
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
kdc_log(context, config, 1, "Client no longer in database: %s",
cpn);
goto out;
}
msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 1, "Client not found in database: %s", msg);
krb5_free_error_message(context, msg);
}
ret = check_PAC(context, config, cp, NULL,
client, server, krbtgt,
&tkey_check->key,
ekey, &tkey_sign->key,
tgt, &rspac, &signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0,
"Verify PAC failed for %s (%s) from %s with %s",
spn, cpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
/* also check the krbtgt for signature */
ret = check_KRB5SignedPath(context,
config,
krbtgt,
cp,
tgt,
&spp,
&signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0,
"KRB5SignedPath check failed for %s (%s) from %s with %s",
spn, cpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
/*
* Process request
*/
/* by default the tgt principal matches the client principal */
tp = cp;
tpn = cpn;
if (client) {
const PA_DATA *sdata;
int i = 0;
sdata = _kdc_find_padata(req, &i, KRB5_PADATA_FOR_USER);
if (sdata) {
krb5_crypto crypto;
krb5_data datack;
PA_S4U2Self self;
const char *str;
ret = decode_PA_S4U2Self(sdata->padata_value.data,
sdata->padata_value.length,
&self, NULL);
if (ret) {
kdc_log(context, config, 0, "Failed to decode PA-S4U2Self");
goto out;
}
ret = _krb5_s4u2self_to_checksumdata(context, &self, &datack);
if (ret)
goto out;
ret = krb5_crypto_init(context, &tgt->key, 0, &crypto);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
free_PA_S4U2Self(&self);
krb5_data_free(&datack);
kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
ret = krb5_verify_checksum(context,
crypto,
KRB5_KU_OTHER_CKSUM,
datack.data,
datack.length,
&self.cksum);
krb5_data_free(&datack);
krb5_crypto_destroy(context, crypto);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
free_PA_S4U2Self(&self);
kdc_log(context, config, 0,
"krb5_verify_checksum failed for S4U2Self: %s", msg);
krb5_free_error_message(context, msg);
goto out;
}
ret = _krb5_principalname2krb5_principal(context,
&tp,
self.name,
self.realm);
free_PA_S4U2Self(&self);
if (ret)
goto out;
ret = krb5_unparse_name(context, tp, &tpn);
if (ret)
goto out;
/* If we were about to put a PAC into the ticket, we better fix it to be the right PAC */
if(rspac.data) {
krb5_pac p = NULL;
krb5_data_free(&rspac);
ret = _kdc_db_fetch(context, config, tp, HDB_F_GET_CLIENT | flags,
NULL, &s4u2self_impersonated_clientdb, &s4u2self_impersonated_client);
if (ret) {
const char *msg;
/*
* If the client belongs to the same realm as our krbtgt, it
* should exist in the local database.
*
*/
if (ret == HDB_ERR_NOENTRY)
ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 1,
"S2U4Self principal to impersonate %s not found in database: %s",
tpn, msg);
krb5_free_error_message(context, msg);
goto out;
}
ret = _kdc_pac_generate(context, s4u2self_impersonated_client, &p);
if (ret) {
kdc_log(context, config, 0, "PAC generation failed for -- %s",
tpn);
goto out;
}
if (p != NULL) {
ret = _krb5_pac_sign(context, p, ticket->ticket.authtime,
s4u2self_impersonated_client->entry.principal,
ekey, &tkey_sign->key,
&rspac);
krb5_pac_free(context, p);
if (ret) {
kdc_log(context, config, 0, "PAC signing failed for -- %s",
tpn);
goto out;
}
}
}
/*
* Check that service doing the impersonating is
* requesting a ticket to it-self.
*/
ret = check_s4u2self(context, config, clientdb, client, sp);
if (ret) {
kdc_log(context, config, 0, "S4U2Self: %s is not allowed "
"to impersonate to service "
"(tried for user %s to service %s)",
cpn, tpn, spn);
goto out;
}
/*
* If the service isn't trusted for authentication to
* delegation, remove the forward flag.
*/
if (client->entry.flags.trusted_for_delegation) {
str = "[forwardable]";
} else {
b->kdc_options.forwardable = 0;
str = "";
}
kdc_log(context, config, 0, "s4u2self %s impersonating %s to "
"service %s %s", cpn, tpn, spn, str);
}
}
/*
* Constrained delegation
*/
if (client != NULL
&& b->additional_tickets != NULL
&& b->additional_tickets->len != 0
&& b->kdc_options.enc_tkt_in_skey == 0)
{
int ad_signedpath = 0;
Key *clientkey;
Ticket *t;
/*
* Require that the KDC have issued the service's krbtgt (not
* self-issued ticket with kimpersonate(1).
*/
if (!signedpath) {
ret = KRB5KDC_ERR_BADOPTION;
kdc_log(context, config, 0,
"Constrained delegation done on service ticket %s/%s",
cpn, spn);
goto out;
}
t = &b->additional_tickets->val[0];
ret = hdb_enctype2key(context, &client->entry,
hdb_kvno2keys(context, &client->entry,
t->enc_part.kvno ? * t->enc_part.kvno : 0),
t->enc_part.etype, &clientkey);
if(ret){
ret = KRB5KDC_ERR_ETYPE_NOSUPP; /* XXX */
goto out;
}
ret = krb5_decrypt_ticket(context, t, &clientkey->key, &adtkt, 0);
if (ret) {
kdc_log(context, config, 0,
"failed to decrypt ticket for "
"constrained delegation from %s to %s ", cpn, spn);
goto out;
}
ret = _krb5_principalname2krb5_principal(context,
&tp,
adtkt.cname,
adtkt.crealm);
if (ret)
goto out;
ret = krb5_unparse_name(context, tp, &tpn);
if (ret)
goto out;
ret = _krb5_principalname2krb5_principal(context,
&dp,
t->sname,
t->realm);
if (ret)
goto out;
ret = krb5_unparse_name(context, dp, &dpn);
if (ret)
goto out;
/* check that ticket is valid */
if (adtkt.flags.forwardable == 0) {
kdc_log(context, config, 0,
"Missing forwardable flag on ticket for "
"constrained delegation from %s (%s) as %s to %s ",
cpn, dpn, tpn, spn);
ret = KRB5KDC_ERR_BADOPTION;
goto out;
}
ret = check_constrained_delegation(context, config, clientdb,
client, server, sp);
if (ret) {
kdc_log(context, config, 0,
"constrained delegation from %s (%s) as %s to %s not allowed",
cpn, dpn, tpn, spn);
goto out;
}
ret = verify_flags(context, config, &adtkt, tpn);
if (ret) {
goto out;
}
krb5_data_free(&rspac);
/*
* generate the PAC for the user.
*
* TODO: pass in t->sname and t->realm and build
* a S4U_DELEGATION_INFO blob to the PAC.
*/
ret = check_PAC(context, config, tp, dp,
client, server, krbtgt,
&clientkey->key,
ekey, &tkey_sign->key,
&adtkt, &rspac, &ad_signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0,
"Verify delegated PAC failed to %s for client"
"%s (%s) as %s from %s with %s",
spn, cpn, dpn, tpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
/*
* Check that the KDC issued the user's ticket.
*/
ret = check_KRB5SignedPath(context,
config,
krbtgt,
cp,
&adtkt,
NULL,
&ad_signedpath);
if (ret) {
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0,
"KRB5SignedPath check from service %s failed "
"for delegation to %s for client %s (%s)"
"from %s failed with %s",
spn, tpn, dpn, cpn, from, msg);
krb5_free_error_message(context, msg);
goto out;
}
if (!ad_signedpath) {
ret = KRB5KDC_ERR_BADOPTION;
kdc_log(context, config, 0,
"Ticket not signed with PAC nor SignedPath service %s failed "
"for delegation to %s for client %s (%s)"
"from %s",
spn, tpn, dpn, cpn, from);
goto out;
}
kdc_log(context, config, 0, "constrained delegation for %s "
"from %s (%s) to %s", tpn, cpn, dpn, spn);
}
/*
* Check flags
*/
ret = kdc_check_flags(context, config,
client, cpn,
server, spn,
FALSE);
if(ret)
goto out;
if((b->kdc_options.validate || b->kdc_options.renew) &&
!krb5_principal_compare(context,
krbtgt->entry.principal,
server->entry.principal)){
kdc_log(context, config, 0, "Inconsistent request.");
ret = KRB5KDC_ERR_SERVER_NOMATCH;
goto out;
}
/* check for valid set of addresses */
if(!_kdc_check_addresses(context, config, tgt->caddr, from_addr)) {
ret = KRB5KRB_AP_ERR_BADADDR;
kdc_log(context, config, 0, "Request from wrong address");
goto out;
}
/*
* If this is an referral, add server referral data to the
* auth_data reply .
*/
if (ref_realm) {
PA_DATA pa;
krb5_crypto crypto;
kdc_log(context, config, 0,
"Adding server referral to %s", ref_realm);
ret = krb5_crypto_init(context, &sessionkey, 0, &crypto);
if (ret)
goto out;
ret = build_server_referral(context, config, crypto, ref_realm,
NULL, s, &pa.padata_value);
krb5_crypto_destroy(context, crypto);
if (ret) {
kdc_log(context, config, 0,
"Failed building server referral");
goto out;
}
pa.padata_type = KRB5_PADATA_SERVER_REFERRAL;
ret = add_METHOD_DATA(&enc_pa_data, &pa);
krb5_data_free(&pa.padata_value);
if (ret) {
kdc_log(context, config, 0,
"Add server referral METHOD-DATA failed");
goto out;
}
}
/*
*
*/
ret = tgs_make_reply(context,
config,
b,
tp,
tgt,
replykey,
rk_is_subkey,
ekey,
&sessionkey,
kvno,
*auth_data,
server,
rsp,
spn,
client,
cp,
tgt_realm,
krbtgt_out,
tkey_sign->key.keytype,
spp,
&rspac,
&enc_pa_data,
e_text,
reply);
out:
if (tpn != cpn)
free(tpn);
free(spn);
free(cpn);
free(dpn);
free(krbtgt_out_n);
_krb5_free_capath(context, capath);
krb5_data_free(&rspac);
krb5_free_keyblock_contents(context, &sessionkey);
if(krbtgt_out)
_kdc_free_ent(context, krbtgt_out);
if(server)
_kdc_free_ent(context, server);
if(client)
_kdc_free_ent(context, client);
if(s4u2self_impersonated_client)
_kdc_free_ent(context, s4u2self_impersonated_client);
if (tp && tp != cp)
krb5_free_principal(context, tp);
krb5_free_principal(context, cp);
krb5_free_principal(context, dp);
krb5_free_principal(context, sp);
krb5_free_principal(context, krbtgt_out_principal);
free(ref_realm);
free_METHOD_DATA(&enc_pa_data);
free_EncTicketPart(&adtkt);
return ret;
}
/*
*
*/
krb5_error_code
_kdc_tgs_rep(krb5_context context,
krb5_kdc_configuration *config,
KDC_REQ *req,
krb5_data *data,
const char *from,
struct sockaddr *from_addr,
int datagram_reply)
{
AuthorizationData *auth_data = NULL;
krb5_error_code ret;
int i = 0;
const PA_DATA *tgs_req;
hdb_entry_ex *krbtgt = NULL;
krb5_ticket *ticket = NULL;
const char *e_text = NULL;
krb5_enctype krbtgt_etype = ETYPE_NULL;
krb5_keyblock *replykey = NULL;
int rk_is_subkey = 0;
time_t *csec = NULL;
int *cusec = NULL;
if(req->padata == NULL){
ret = KRB5KDC_ERR_PREAUTH_REQUIRED; /* XXX ??? */
kdc_log(context, config, 0,
"TGS-REQ from %s without PA-DATA", from);
goto out;
}
tgs_req = _kdc_find_padata(req, &i, KRB5_PADATA_TGS_REQ);
if(tgs_req == NULL){
ret = KRB5KDC_ERR_PADATA_TYPE_NOSUPP;
kdc_log(context, config, 0,
"TGS-REQ from %s without PA-TGS-REQ", from);
goto out;
}
ret = tgs_parse_request(context, config,
&req->req_body, tgs_req,
&krbtgt,
&krbtgt_etype,
&ticket,
&e_text,
from, from_addr,
&csec, &cusec,
&auth_data,
&replykey,
&rk_is_subkey);
if (ret == HDB_ERR_NOT_FOUND_HERE) {
/* kdc_log() is called in tgs_parse_request() */
goto out;
}
if (ret) {
kdc_log(context, config, 0,
"Failed parsing TGS-REQ from %s", from);
goto out;
}
{
const PA_DATA *pa = _kdc_find_padata(req, &i, KRB5_PADATA_FX_FAST);
if (pa)
kdc_log(context, config, 10, "Got TGS FAST request");
}
ret = tgs_build_reply(context,
config,
req,
&req->req_body,
krbtgt,
krbtgt_etype,
replykey,
rk_is_subkey,
ticket,
data,
from,
&e_text,
&auth_data,
from_addr);
if (ret) {
kdc_log(context, config, 0,
"Failed building TGS-REP to %s", from);
goto out;
}
/* */
if (datagram_reply && data->length > config->max_datagram_reply_length) {
krb5_data_free(data);
ret = KRB5KRB_ERR_RESPONSE_TOO_BIG;
e_text = "Reply packet too large";
}
out:
if (replykey)
krb5_free_keyblock(context, replykey);
if(ret && ret != HDB_ERR_NOT_FOUND_HERE && data->data == NULL){
/* XXX add fast wrapping on the error */
METHOD_DATA error_method = { 0, NULL };
kdc_log(context, config, 10, "tgs-req: sending error: %d to client", ret);
ret = _kdc_fast_mk_error(context, NULL,
&error_method,
NULL,
NULL,
ret, NULL,
NULL,
NULL, NULL,
csec, cusec,
data);
free_METHOD_DATA(&error_method);
}
free(csec);
free(cusec);
if (ticket)
krb5_free_ticket(context, ticket);
if(krbtgt)
_kdc_free_ent(context, krbtgt);
if (auth_data) {
free_AuthorizationData(auth_data);
free(auth_data);
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-295/c/good_3203_1 |
crossvul-cpp_data_good_4693_0 | /***
x509 modules for lua-openssl binding
create and manage x509 certificate
@module x509
@usage
x509 = require'openssl'.x509
*/
#include "openssl.h"
#include "private.h"
#define CRYPTO_LOCK_REF
#include "sk.h"
#define MYNAME "x509"
#define MYVERSION MYNAME " library for " LUA_VERSION " / Nov 2014 / "\
"based on OpenSSL " SHLIB_VERSION_NUMBER
#if OPENSSL_VERSION_NUMBER < 0x1010000fL || \
(defined(LIBRESSL_VERSION_NUMBER) && (LIBRESSL_VERSION_NUMBER < 0x20700000L))
#define X509_get0_notBefore X509_get_notBefore
#define X509_get0_notAfter X509_get_notAfter
#define X509_set1_notBefore X509_set_notBefore
#define X509_set1_notAfter X509_set_notAfter
#endif
static int openssl_push_purpose(lua_State*L, X509_PURPOSE* purpose)
{
lua_newtable(L);
AUXILIAR_SET(L, -1, "purpose", purpose->purpose, integer);
AUXILIAR_SET(L, -1, "trust", purpose->trust, integer);
AUXILIAR_SET(L, -1, "flags", purpose->flags, integer);
AUXILIAR_SET(L, -1, "name", purpose->name, string);
AUXILIAR_SET(L, -1, "sname", purpose->sname, string);
return 1;
};
/***
return all supported purpose as table
@function purpose
@treturn table
*/
/*
get special purpose info as table
@function purpose
@tparam number|string purpose id or short name
@treturn table
*/
static int openssl_x509_purpose(lua_State*L)
{
if (lua_isnone(L, 1))
{
int count = X509_PURPOSE_get_count();
int i;
lua_newtable(L);
for (i = 0; i < count; i++)
{
X509_PURPOSE* purpose = X509_PURPOSE_get0(i);
openssl_push_purpose(L, purpose);
lua_rawseti(L, -2, i + 1);
}
return 1;
}
else if (lua_isnumber(L, 1))
{
int idx = X509_PURPOSE_get_by_id(lua_tointeger(L, 1));
if (idx >= 0)
{
X509_PURPOSE* purpose = X509_PURPOSE_get0(idx);
openssl_push_purpose(L, purpose);
}
else
lua_pushnil(L);
return 1;
}
else if (lua_isstring(L, 1))
{
char* name = (char*)lua_tostring(L, 1);
int idx = X509_PURPOSE_get_by_sname(name);
if (idx >= 0)
{
X509_PURPOSE* purpose = X509_PURPOSE_get0(idx);
openssl_push_purpose(L, purpose);
}
else
lua_pushnil(L);
return 1;
}
else
luaL_argerror(L, 1, "only accpet none, string or number as nid or short name");
return 0;
};
static const char* usage_mode[] =
{
"standard",
"netscape",
"extend",
NULL
};
/***
get support certtypes
@function certtypes
@tparam[opt='standard'] string type support 'standard','netscape','extend'
@treturn table if type is 'standard' or 'netscape', contains node with {lname=...,sname=...,bitname=...},
if type is 'extend', contains node with {lname=...,sname=...,nid=...}
*/
static int openssl_x509_certtypes(lua_State*L)
{
int mode = luaL_checkoption(L, 1, "standard", usage_mode);
int i;
const BIT_STRING_BITNAME* bitname;
switch (mode)
{
case 0:
{
const static BIT_STRING_BITNAME key_usage_type_table[] =
{
{0, "Digital Signature", "digitalSignature"},
{1, "Non Repudiation", "nonRepudiation"},
{2, "Key Encipherment", "keyEncipherment"},
{3, "Data Encipherment", "dataEncipherment"},
{4, "Key Agreement", "keyAgreement"},
{5, "Certificate Sign", "keyCertSign"},
{6, "CRL Sign", "cRLSign"},
{7, "Encipher Only", "encipherOnly"},
{8, "Decipher Only", "decipherOnly"},
{ -1, NULL, NULL}
};
lua_newtable(L);
for (i = 0, bitname = &key_usage_type_table[i]; bitname->bitnum != -1; i++, bitname = &key_usage_type_table[i])
{
openssl_push_bit_string_bitname(L, bitname);
lua_rawseti(L, -2, i + 1);
}
return 1;
}
case 1:
{
const static BIT_STRING_BITNAME ns_cert_type_table[] =
{
{0, "SSL Client", "client"},
{1, "SSL Server", "server"},
{2, "S/MIME", "email"},
{3, "Object Signing", "objsign"},
{4, "Unused", "reserved"},
{5, "SSL CA", "sslCA"},
{6, "S/MIME CA", "emailCA"},
{7, "Object Signing CA", "objCA"},
{ -1, NULL, NULL}
};
lua_newtable(L);
for (i = 0, bitname = &ns_cert_type_table[i]; bitname->bitnum != -1; i++, bitname = &ns_cert_type_table[i])
{
openssl_push_bit_string_bitname(L, bitname);
lua_rawseti(L, -2, i + 1);
}
return 1;
}
case 2:
{
static const int ext_nids[] =
{
NID_server_auth,
NID_client_auth,
NID_email_protect,
NID_code_sign,
NID_ms_sgc,
NID_ns_sgc,
NID_OCSP_sign,
NID_time_stamp,
NID_dvcs,
NID_anyExtendedKeyUsage
};
int count = sizeof(ext_nids) / sizeof(int);
int nid;
lua_newtable(L);
for (i = 0; i < count; i++)
{
nid = ext_nids[i];
lua_newtable(L);
lua_pushstring(L, OBJ_nid2ln(nid));
lua_setfield(L, -2, "lname");
lua_pushstring(L, OBJ_nid2sn(nid));
lua_setfield(L, -2, "sname");
lua_pushinteger(L, nid);
lua_setfield(L, -2, "nid");
lua_rawseti(L, -2, i + 1);
};
return 1;
}
}
return 0;
}
/***
get certificate verify result string message
@function verify_cert_error_string
@tparam number verify_result
@treturn string result message
*/
static int openssl_verify_cert_error_string(lua_State*L)
{
int v = luaL_checkint(L, 1);
const char*s = X509_verify_cert_error_string(v);
lua_pushstring(L, s);
return 1;
}
/***
read x509 from string or bio input
@function read
@tparam bio|string input input data
@tparam[opt='auto'] string format support 'auto','pem','der'
@treturn x509 certificate object
*/
static LUA_FUNCTION(openssl_x509_read)
{
X509 *cert = NULL;
BIO *in = load_bio_object(L, 1);
int fmt = luaL_checkoption(L, 2, "auto", format);
if (fmt == FORMAT_AUTO)
{
fmt = bio_is_der(in) ? FORMAT_DER : FORMAT_PEM;
}
if (fmt == FORMAT_DER)
{
cert = d2i_X509_bio(in, NULL);
}
else if (fmt == FORMAT_PEM)
{
cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
}
BIO_free(in);
if (cert)
{
PUSH_OBJECT(cert, "openssl.x509");
return 1;
}
return openssl_pushresult(L, 0);
}
/***
create or generate a new x509 object.
@function new
@tparam[opt] openssl.bn serial serial number
@tparam[opt] x509_req csr,copy x509_name, pubkey and extension to new object
@tparam[opt] x509_name subject subject name set to x509_req
@tparam[opt] stack_of_x509_extension extensions add to x509
@tparam[opt] stack_of_x509_attribute attributes add to x509
@treturn x509 certificate object
*/
static int openssl_x509_new(lua_State* L)
{
int i = 1;
int ret = 1;
int n = lua_gettop(L);
X509 *x = X509_new();
ret = X509_set_version(x, 2);
if (ret == 1 && (
auxiliar_getclassudata(L, "openssl.bn", i) ||
lua_isstring(L, i) || lua_isnumber(L, i)
))
{
BIGNUM *bn = BN_get(L, i);
ASN1_INTEGER* ai = BN_to_ASN1_INTEGER(bn, NULL);
BN_free(bn);
ret = X509_set_serialNumber(x, ai);
ASN1_INTEGER_free(ai);
i++;
}
for (; i <= n; i++)
{
if (ret == 1 && auxiliar_getclassudata(L, "openssl.x509_req", i))
{
X509_REQ* csr = CHECK_OBJECT(i, X509_REQ, "openssl.x509_req");
X509_NAME* xn = X509_REQ_get_subject_name(csr);
ret = X509_set_subject_name(x, xn);
if (ret == 1)
{
STACK_OF(X509_EXTENSION) *exts = X509_REQ_get_extensions(csr);
int j, n1;
n1 = sk_X509_EXTENSION_num(exts);
for (j = 0; ret == 1 && j < n1; j++)
{
ret = X509_add_ext(x, sk_X509_EXTENSION_value(exts, j), j);
}
sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
}
if (ret == 1)
{
EVP_PKEY* pkey = X509_REQ_get_pubkey(csr);
ret = X509_set_pubkey(x, pkey);
EVP_PKEY_free(pkey);
}
i++;
};
if (ret == 1 && auxiliar_getclassudata(L, "openssl.x509_name", i))
{
X509_NAME *xn = CHECK_OBJECT(i, X509_NAME, "openssl.x509_name");
ret = X509_set_subject_name(x, xn);
i++;
}
}
if (ret == 1)
{
PUSH_OBJECT(x, "openssl.x509");
return 1;
}
else
{
X509_free(x);
return openssl_pushresult(L, ret);
}
};
static luaL_Reg R[] =
{
{"new", openssl_x509_new },
{"read", openssl_x509_read },
{"purpose", openssl_x509_purpose },
{"certtypes", openssl_x509_certtypes },
{"verify_cert_error_string", openssl_verify_cert_error_string },
{NULL, NULL}
};
int openssl_push_general_name(lua_State*L, const GENERAL_NAME* general_name)
{
if (general_name == NULL)
{
lua_pushnil(L);
return 1;
}
lua_newtable(L);
switch (general_name->type)
{
case GEN_OTHERNAME:
{
OTHERNAME *otherName = general_name->d.otherName;
lua_newtable(L);
openssl_push_asn1object(L, otherName->type_id);
PUSH_ASN1_STRING(L, otherName->value->value.asn1_string);
lua_settable(L, -3);
lua_setfield(L, -2, "otherName");
lua_pushstring(L, "otherName");
lua_setfield(L, -2, "type");
break;
}
case GEN_EMAIL:
PUSH_ASN1_STRING(L, general_name->d.rfc822Name);
lua_setfield(L, -2, "rfc822Name");
lua_pushstring(L, "rfc822Name");
lua_setfield(L, -2, "type");
break;
case GEN_DNS:
PUSH_ASN1_STRING(L, general_name->d.dNSName);
lua_setfield(L, -2, "dNSName");
lua_pushstring(L, "dNSName");
lua_setfield(L, -2, "type");
break;
case GEN_X400:
openssl_push_asn1type(L, general_name->d.x400Address);
lua_setfield(L, -2, "x400Address");
lua_pushstring(L, "x400Address");
lua_setfield(L, -2, "type");
break;
case GEN_DIRNAME:
{
X509_NAME* xn = general_name->d.directoryName;
openssl_push_xname_asobject(L, xn);
lua_setfield(L, -2, "directoryName");
lua_pushstring(L, "directoryName");
lua_setfield(L, -2, "type");
}
break;
case GEN_URI:
PUSH_ASN1_STRING(L, general_name->d.uniformResourceIdentifier);
lua_setfield(L, -2, "uniformResourceIdentifier");
lua_pushstring(L, "uniformResourceIdentifier");
lua_setfield(L, -2, "type");
break;
case GEN_IPADD:
lua_newtable(L);
PUSH_ASN1_OCTET_STRING(L, general_name->d.iPAddress);
lua_setfield(L, -2, "iPAddress");
lua_pushstring(L, "iPAddress");
lua_setfield(L, -2, "type");
break;
case GEN_EDIPARTY:
lua_newtable(L);
PUSH_ASN1_STRING(L, general_name->d.ediPartyName->nameAssigner);
lua_setfield(L, -2, "nameAssigner");
PUSH_ASN1_STRING(L, general_name->d.ediPartyName->partyName);
lua_setfield(L, -2, "partyName");
lua_setfield(L, -2, "ediPartyName");
lua_pushstring(L, "ediPartyName");
lua_setfield(L, -2, "type");
break;
case GEN_RID:
lua_newtable(L);
openssl_push_asn1object(L, general_name->d.registeredID);
lua_setfield(L, -2, "registeredID");
lua_pushstring(L, "registeredID");
lua_setfield(L, -2, "type");
break;
default:
lua_pushstring(L, "unsupport");
lua_setfield(L, -2, "type");
}
return 1;
};
static int check_cert(X509_STORE *ca, X509 *x, STACK_OF(X509) *untrustedchain, int purpose)
{
int ret = 0;
X509_STORE_CTX *csc = X509_STORE_CTX_new();
if (csc)
{
X509_STORE_set_flags(ca, X509_V_FLAG_CHECK_SS_SIGNATURE);
if (X509_STORE_CTX_init(csc, ca, x, untrustedchain) == 1)
{
if (purpose > 0)
{
X509_STORE_CTX_set_purpose(csc, purpose);
}
ret = X509_verify_cert(csc);
if (ret == 1)
ret = X509_V_OK;
else
ret = X509_STORE_CTX_get_error(csc);
}
X509_STORE_CTX_free(csc);
return ret;
}
return X509_V_ERR_OUT_OF_MEM;
}
/***
openssl.x509 object
@type x509
*/
/***
export x509_req to string
@function export
@tparam[opt='pem'] string format, 'der' or 'pem' default
@tparam[opt='true'] boolean noext not export extension
@treturn string
*/
static LUA_FUNCTION(openssl_x509_export)
{
X509 *cert = CHECK_OBJECT(1, X509, "openssl.x509");
int fmt = luaL_checkoption(L, 2, "pem", format);
int notext = lua_isnone(L, 3) ? 1 : lua_toboolean(L, 3);
BIO* out = NULL;
if (fmt != FORMAT_DER && fmt != FORMAT_PEM)
{
luaL_argerror(L, 2, "format only accept pem or der");
}
out = BIO_new(BIO_s_mem());
if (fmt == FORMAT_PEM)
{
if (!notext)
{
X509_print(out, cert);
}
if (PEM_write_bio_X509(out, cert))
{
BUF_MEM *bio_buf;
BIO_get_mem_ptr(out, &bio_buf);
lua_pushlstring(L, bio_buf->data, bio_buf->length);
}
else
lua_pushnil(L);
}
else
{
if (i2d_X509_bio(out, cert))
{
BUF_MEM *bio_buf;
BIO_get_mem_ptr(out, &bio_buf);
lua_pushlstring(L, bio_buf->data, bio_buf->length);
}
else
lua_pushnil(L);
}
BIO_free(out);
return 1;
};
/***
parse x509 object as table
@function parse
@tparam[opt=true] shortname default will use short object name
@treturn table result which all x509 information
*/
static LUA_FUNCTION(openssl_x509_parse)
{
int i;
X509 * cert = CHECK_OBJECT(1, X509, "openssl.x509");
X509_ALGOR* alg = 0;
lua_newtable(L);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
if (cert->name)
{
AUXILIAR_SET(L, -1, "name", cert->name, string);
}
AUXILIAR_SET(L, -1, "valid", cert->valid, boolean);
#endif
AUXILIAR_SET(L, -1, "version", X509_get_version(cert), integer);
openssl_push_xname_asobject(L, X509_get_subject_name(cert));
lua_setfield(L, -2, "subject");
openssl_push_xname_asobject(L, X509_get_issuer_name(cert));
lua_setfield(L, -2, "issuer");
{
char buf[32];
snprintf(buf, sizeof(buf), "%08lx", X509_subject_name_hash(cert));
AUXILIAR_SET(L, -1, "hash", buf, string);
}
PUSH_ASN1_INTEGER(L, X509_get0_serialNumber(cert));
lua_setfield(L, -2, "serialNumber");
PUSH_ASN1_TIME(L, X509_get0_notBefore(cert));
lua_setfield(L, -2, "notBefore");
PUSH_ASN1_TIME(L, X509_get0_notAfter(cert));
lua_setfield(L, -2, "notAfter");
{
CONSTIFY_X509_get0 X509_ALGOR *palg = NULL;
CONSTIFY_X509_get0 ASN1_BIT_STRING *psig = NULL;
X509_get0_signature(&psig, &palg, cert);
if (palg != NULL)
{
alg = X509_ALGOR_dup((X509_ALGOR*)palg);
PUSH_OBJECT(alg, "openssl.x509_algor");
lua_setfield(L, -2, "sig_alg");
}
if (psig != NULL)
{
lua_pushlstring(L, (const char *)psig->data, psig->length);
lua_setfield(L, -2, "sig");
}
}
{
int l = 0;
char* tmpstr = (char *)X509_alias_get0(cert, &l);
if (tmpstr)
{
AUXILIAR_SETLSTR(L, -1, "alias", tmpstr, l);
}
}
AUXILIAR_SET(L, -1, "ca", X509_check_ca(cert), boolean);
lua_newtable(L);
for (i = 0; i < X509_PURPOSE_get_count(); i++)
{
int set;
X509_PURPOSE *purp = X509_PURPOSE_get0(i);
int id = X509_PURPOSE_get_id(purp);
const char * pname = X509_PURPOSE_get0_sname(purp);
set = X509_check_purpose(cert, id, 0);
if (set)
{
AUXILIAR_SET(L, -1, pname, 1, boolean);
}
set = X509_check_purpose(cert, id, 1);
if (set)
{
lua_pushfstring(L, "%s CA", pname);
pname = lua_tostring(L, -1);
AUXILIAR_SET(L, -2, pname, 1, boolean);
lua_pop(L, 1);
}
}
lua_setfield(L, -2, "purposes");
{
int n = X509_get_ext_count(cert);
if (n > 0)
{
lua_pushstring(L, "extensions");
lua_newtable(L);
for (i = 0; i < n; i++)
{
X509_EXTENSION *ext = X509_get_ext(cert, i);
ext = X509_EXTENSION_dup(ext);
lua_pushinteger(L, i + 1);
PUSH_OBJECT(ext, "openssl.x509_extension");
lua_rawset(L, -3);
}
lua_rawset(L, -3);
}
}
return 1;
}
static LUA_FUNCTION(openssl_x509_free)
{
X509 *cert = CHECK_OBJECT(1, X509, "openssl.x509");
X509_free(cert);
return 0;
}
/***
get public key of x509
@function pubkey
@treturn evp_pkey public key
*/
/***
set public key of x509
@function pubkey
@tparam evp_pkey pubkey public key set to x509
@treturn boolean result, true for success
*/
static LUA_FUNCTION(openssl_x509_public_key)
{
X509 *cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
EVP_PKEY *pkey = X509_get_pubkey(cert);
PUSH_OBJECT(pkey, "openssl.evp_pkey");
return 1;
}
else
{
EVP_PKEY* pkey = CHECK_OBJECT(2, EVP_PKEY, "openssl.evp_pkey");
int ret = X509_set_pubkey(cert, pkey);
return openssl_pushresult(L, ret);
}
}
#if 0
static int verify_cb(int ok, X509_STORE_CTX *ctx)
{
int err;
X509 *err_cert;
/*
* it is ok to use a self signed certificate This case will catch both
* the initial ok == 0 and the final ok == 1 calls to this function
*/
err = X509_STORE_CTX_get_error(ctx);
if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
return 1;
/*
* BAD we should have gotten an error. Normally if everything worked
* X509_STORE_CTX_get_error(ctx) will still be set to
* DEPTH_ZERO_SELF_....
*/
if (ok)
{
//BIO_printf(bio_err, "error with certificate to be certified - should be self signed\n");
return 0;
}
else
{
err_cert = X509_STORE_CTX_get_current_cert(ctx);
//print_name(bio_err, NULL, X509_get_subject_name(err_cert), 0);
//BIO_printf(bio_err, "error with certificate - error %d at depth %d\n%s\n", err, X509_STORE_CTX_get_error_depth(ctx), X509_verify_cert_error_string(err));
return 1;
}
}
#endif
/***
check x509 with ca certchian and option purpose
purpose can be one of: ssl_client, ssl_server, ns_ssl_server, smime_sign, smime_encrypt, crl_sign, any, ocsp_helper, timestamp_sign
@function check
@tparam x509_store cacerts
@tparam x509_store untrusted certs containing a bunch of certs that are not trusted but may be useful in validating the certificate.
@tparam[opt] string purpose to check supported
@treturn boolean result true for check pass
@treturn integer verify result
@see verify_cert_error_string
*/
/***
check x509 with evp_pkey
@function check
@tparam evp_pkey pkey private key witch match with x509 pubkey
@treturn boolean result true for check pass
*/
static LUA_FUNCTION(openssl_x509_check)
{
X509 * cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (auxiliar_getclassudata(L, "openssl.evp_pkey", 2))
{
EVP_PKEY * key = CHECK_OBJECT(2, EVP_PKEY, "openssl.evp_pkey");
lua_pushboolean(L, X509_check_private_key(cert, key));
return 1;
}
else
{
X509_STORE* store = CHECK_OBJECT(2, X509_STORE, "openssl.x509_store");
STACK_OF(X509)* untrustedchain = lua_isnoneornil(L, 3) ? NULL : openssl_sk_x509_fromtable(L, 3);
int purpose = 0;
int ret = 0;
if (!lua_isnone(L, 4))
{
int purpose_id = X509_PURPOSE_get_by_sname((char*)luaL_optstring(L, 4, "any"));
if (purpose_id >= 0)
{
X509_PURPOSE* ppurpose = X509_PURPOSE_get0(purpose_id);
if (ppurpose)
{
purpose = ppurpose->purpose;
}
}
}
#if 0
X509_STORE_set_verify_cb_func(store, verify_cb);
#endif
if (untrustedchain!=NULL)
sk_X509_pop_free(untrustedchain, X509_free);
ret = check_cert(store, cert, untrustedchain, purpose);
lua_pushboolean(L, ret == X509_V_OK);
lua_pushinteger(L, ret);
return 2;
}
}
/***
The functions return 1 for a successful match, 0 for a failed match and -1 for
an internal error: typically a memory allocation failure or an ASN.1 decoding
error.
All functions can also return -2 if the input is malformed. For example,
X509_check_host() returns -2 if the provided name contains embedded NULs.
*/
static int openssl_push_check_result(lua_State *L, int ret, const char* name)
{
switch (ret)
{
case 1:
lua_pushboolean(L, 1);
if (name)
{
lua_pushstring(L, name);
ret = 2;
}
break;
case 0:
lua_pushboolean(L, 0);
ret = 1;
break;
case -1:
lua_pushnil(L);
lua_pushliteral(L, "internal");
ret = 2;
case -2:
lua_pushnil(L);
lua_pushliteral(L, "malformed");
ret = 2;
default:
lua_pushnil(L);
lua_pushinteger(L, ret);
ret = 2;
}
return ret;
}
#if OPENSSL_VERSION_NUMBER > 0x10002000L
/***
check x509 for host (only for openssl 1.0.2 or greater)
@function check_host
@tparam string host hostname to check for match match with x509 subject
@treturn boolean result true if host is present and matches the certificate
*/
static LUA_FUNCTION(openssl_x509_check_host)
{
X509 * cert = CHECK_OBJECT(1, X509, "openssl.x509");
size_t sz;
const char* hostname = luaL_checklstring(L, 2, &sz);
int flags = luaL_optint(L, 3, 0);
char *peer = NULL;
int ret = X509_check_host(cert, hostname, sz, flags, &peer);
ret = openssl_push_check_result(L, ret, peer);
OPENSSL_free(peer);
return ret;
}
/***
check x509 for email address (only for openssl 1.0.2 or greater)
@tparam string email to check for match match with x509 subject
@treturn boolean result true if host is present and matches the certificate
@function check_email
*/
static LUA_FUNCTION(openssl_x509_check_email)
{
X509 * cert = CHECK_OBJECT(1, X509, "openssl.x509");
size_t sz;
const char *email = luaL_checklstring(L, 2, &sz);
int flags = luaL_optint(L, 3, 0);
int ret = X509_check_email(cert, email, sz, flags);
return openssl_push_check_result(L, ret, NULL);
}
/***
check x509 for ip address (ipv4 or ipv6, only for openssl 1.0.2 or greater)
@function check_ip_asc
@tparam string ip to check for match match with x509 subject
@treturn boolean result true if host is present and matches the certificate
*/
static LUA_FUNCTION(openssl_x509_check_ip)
{
X509 * cert = CHECK_OBJECT(1, X509, "openssl.x509");
size_t sz;
const char *ip = luaL_checklstring(L, 2, &sz);
int flags = luaL_optint(L, 3, 0);
int ret = X509_check_ip(cert, (const unsigned char*)ip, sz, flags);
return openssl_push_check_result(L, ret, NULL);
}
#endif
IMP_LUA_SK(X509, x509)
#if 0
static STACK_OF(X509) * load_all_certs_from_file(BIO *in)
{
STACK_OF(X509) *stack = sk_X509_new_null();
if (stack)
{
STACK_OF(X509_INFO) *sk = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL);
/* scan over it and pull out the certs */
while (sk_X509_INFO_num(sk))
{
X509_INFO *xi = sk_X509_INFO_shift(sk);
if (xi->x509 != NULL)
{
sk_X509_push(stack, xi->x509);
xi->x509 = NULL;
}
X509_INFO_free(xi);
}
sk_X509_INFO_free(sk);
};
if (sk_X509_num(stack) == 0)
{
sk_X509_free(stack);
stack = NULL;
}
return stack;
};
#endif
/***
get subject name of x509
@function subject
@treturn x509_name subject name
*/
/***
set subject name of x509
@function subject
@tparam x509_name subject
@treturn boolean result true for success
*/
static int openssl_x509_subject(lua_State* L)
{
X509* cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
X509_NAME* xn = X509_get_subject_name(cert);
return openssl_push_xname_asobject(L, xn);
}
else
{
X509_NAME *xn = CHECK_OBJECT(2, X509_NAME, "openssl.x509_name");
int ret = X509_set_subject_name(cert, xn);
return openssl_pushresult(L, ret);
}
}
/***
get issuer name of x509
@function issuer
@tparam[opt=false] boolean asobject, true for return as x509_name object, or as table
@treturn[1] x509_name issuer
@treturn[1] table issuer name as table
*/
/***
set issuer name of x509
@function issuer
@tparam x509_name name
@treturn boolean result true for success
*/
static int openssl_x509_issuer(lua_State* L)
{
X509* cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
X509_NAME* xn = X509_get_issuer_name(cert);
return openssl_push_xname_asobject(L, xn);
}
else
{
X509_NAME* xn = CHECK_OBJECT(2, X509_NAME, "openssl.x509_name");
int ret = X509_set_issuer_name(cert, xn);
return openssl_pushresult(L, ret);
}
}
/***
get digest of x509 object
@function digest
@tparam[opt='sha1'] evp_digest|string md_alg, default use 'sha1'
@treturn string digest result
*/
static int openssl_x509_digest(lua_State* L)
{
unsigned int bytes;
unsigned char buffer[EVP_MAX_MD_SIZE];
char hex_buffer[EVP_MAX_MD_SIZE * 2];
X509 *cert = CHECK_OBJECT(1, X509, "openssl.x509");
const EVP_MD *digest = get_digest(L, 2, "sha256");
int ret;
if (!digest)
{
lua_pushnil(L);
lua_pushfstring(L, "digest algorithm not supported (%s)", lua_tostring(L, 2));
return 2;
}
ret = X509_digest(cert, digest, buffer, &bytes);
if (ret)
{
to_hex((char*)buffer, bytes, hex_buffer);
lua_pushlstring(L, hex_buffer, bytes * 2);
return 1;
}
return openssl_pushresult(L, ret);
};
/***
get notbefore valid time of x509
@function notbefore
@treturn string notbefore time string
*/
/***
set notbefore valid time of x509
@function notbefore
@tparam string|number notbefore
*/
static int openssl_x509_notbefore(lua_State *L)
{
X509* cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
return PUSH_ASN1_TIME(L, X509_get0_notBefore(cert));
}
else
{
ASN1_TIME* at = NULL;
int ret = 1;
if (lua_isnumber(L, 2))
{
time_t time = lua_tointeger(L, 2);
at = ASN1_TIME_new();
ASN1_TIME_set(at, time);
}
else if (lua_isstring(L, 2))
{
const char* time = lua_tostring(L, 2);
at = ASN1_TIME_new();
if (ASN1_TIME_set_string(at, time) != 1)
{
ASN1_TIME_free(at);
at = NULL;
}
}
if (at)
{
ret = X509_set1_notBefore(cert, at);
ASN1_TIME_free(at);
}
else
ret = 0;
return openssl_pushresult(L, ret);
};
}
/***
get notafter valid time of x509
@function notafter
@treturn string notafter time string
*/
/***
set notafter valid time of x509
@function notafter
@tparam string|number notafter
*/
static int openssl_x509_notafter(lua_State *L)
{
X509* cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
return PUSH_ASN1_TIME(L, X509_get0_notAfter(cert));
}
else
{
ASN1_TIME* at = NULL;
int ret = 1;
if (lua_isnumber(L, 2))
{
time_t time = lua_tointeger(L, 2);
at = ASN1_TIME_new();
ASN1_TIME_set(at, time);
}
else if (lua_isstring(L, 2))
{
const char* time = lua_tostring(L, 2);
at = ASN1_TIME_new();
if (ASN1_TIME_set_string(at, time) != 1)
{
ASN1_TIME_free(at);
at = NULL;
}
}
if (at)
{
ret = X509_set1_notAfter(cert, at);
ASN1_TIME_free(at);
}
else
ret = 0;
return openssl_pushresult(L, ret);
}
}
/***
check x509 valid
@function validat
@tparam[opt] number time, default will use now time
@treturn boolean result true for valid, or for invalid
@treturn string notbefore
@treturn string notafter
*/
/***
set valid time, notbefore and notafter
@function validat
@tparam number notbefore
@tparam number notafter
@treturn boolean result, true for success
*/
static int openssl_x509_valid_at(lua_State* L)
{
X509* cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
time_t now = 0;;
time(&now);
lua_pushboolean(L, (X509_cmp_time(X509_get0_notAfter(cert), &now) >= 0
&& X509_cmp_time(X509_get0_notBefore(cert), &now) <= 0));
PUSH_ASN1_TIME(L, X509_get0_notBefore(cert));
PUSH_ASN1_TIME(L, X509_get0_notAfter(cert));
return 3;
}
else if (lua_gettop(L) == 2)
{
time_t time = luaL_checkinteger(L, 2);
lua_pushboolean(L, (X509_cmp_time(X509_get0_notAfter(cert), &time) >= 0
&& X509_cmp_time(X509_get0_notBefore(cert), &time) <= 0));
PUSH_ASN1_TIME(L, X509_get0_notBefore(cert));
PUSH_ASN1_TIME(L, X509_get0_notAfter(cert));
return 3;
}
else if (lua_gettop(L) == 3)
{
time_t before, after;
ASN1_TIME *ab, *aa;
int ret = 1;
before = lua_tointeger(L, 2);
after = lua_tointeger(L, 3);
ab = ASN1_TIME_new();
aa = ASN1_TIME_new();
ASN1_TIME_set(ab, before);
ASN1_TIME_set(aa, after);
ret = X509_set1_notBefore(cert, ab);
if (ret == 1)
ret = X509_set1_notAfter(cert, aa);
ASN1_TIME_free(ab);
ASN1_TIME_free(aa);
return openssl_pushresult(L, ret);
}
return 0;
}
/***
get serial number of x509
@function serial
@tparam[opt=true] boolean asobject
@treturn[1] bn object
@treturn[2] string result
*/
/***
set serial number of x509
@function serial
@tparam string|number|bn serail
@treturn boolean result true for success
*/
static int openssl_x509_serial(lua_State *L)
{
X509* cert = CHECK_OBJECT(1, X509, "openssl.x509");
ASN1_INTEGER *serial = X509_get_serialNumber(cert);
if (lua_isboolean(L, 2))
{
int asobj = lua_toboolean(L, 2);
if (asobj)
{
PUSH_ASN1_INTEGER(L, serial);
}
else
{
BIGNUM *bn = ASN1_INTEGER_to_BN(serial, NULL);
PUSH_OBJECT(bn, "openssl.bn");
}
}
else if (lua_isnone(L, 2))
{
BIGNUM *bn = ASN1_INTEGER_to_BN(serial, NULL);
char *tmp = BN_bn2hex(bn);
lua_pushstring(L, tmp);
OPENSSL_free(tmp);
BN_free(bn);
}
else
{
int ret;
if (auxiliar_getclassudata(L, "openssl.asn1_string", 2))
{
serial = CHECK_OBJECT(2, ASN1_STRING, "openssl.asn1_string");
}
else
{
BIGNUM *bn = BN_get(L, 2);
serial = BN_to_ASN1_INTEGER(bn, NULL);
BN_free(bn);
}
luaL_argcheck(L, serial != NULL, 2, "not accept");
ret = X509_set_serialNumber(cert, serial);
ASN1_INTEGER_free(serial);
return openssl_pushresult(L, ret);
}
return 1;
}
/***
get version number of x509
@function version
@treturn number version of x509
*/
/***
set version number of x509
@function version
@tparam number version
@treturn boolean result true for result
*/
static int openssl_x509_version(lua_State *L)
{
int version;
X509* cert = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
version = X509_get_version(cert);
lua_pushinteger(L, version);
return 1;
}
else
{
int ret;
version = luaL_checkint(L, 2);
ret = X509_set_version(cert, version);
return openssl_pushresult(L, ret);
}
}
/***
get extensions of x509 object
@function extensions
@tparam[opt=false] boolean asobject, true for return as stack_of_x509_extension or as table
@treturn[1] stack_of_x509_extension object when param set true
@treturn[2] table contain all x509_extension when param set false or nothing
*/
/***
set extension of x509 object
@function extensions
@tparam stack_of_x509_extension extensions
@treturn boolean result true for success
*/
static int openssl_x509_extensions(lua_State* L)
{
X509 *self = CHECK_OBJECT(1, X509, "openssl.x509");
STACK_OF(X509_EXTENSION) *exts = (STACK_OF(X509_EXTENSION) *)X509_get0_extensions(self);
if (lua_isnone(L, 2))
{
if (exts)
{
openssl_sk_x509_extension_totable(L, exts);
}
else
lua_pushnil(L);
return 1;
}
else
{
STACK_OF(X509_EXTENSION) *others = (STACK_OF(X509_EXTENSION) *)openssl_sk_x509_extension_fromtable(L, 2);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
sk_X509_EXTENSION_pop_free(self->cert_info->extensions, X509_EXTENSION_free);
self->cert_info->extensions = others;
#else
int i;
int n = sk_X509_EXTENSION_num(exts);
for (i = 0; i < n; i++)
sk_X509_EXTENSION_delete(exts, i);
n = sk_X509_EXTENSION_num(others);
for (i = 0; i < n; i++)
{
X509_EXTENSION* ext = sk_X509_EXTENSION_value(others, i);
if (exts!=NULL)
sk_X509_EXTENSION_push(exts, ext);
else
X509_add_ext(self, ext, -1);
}
sk_X509_EXTENSION_pop_free(others, X509_EXTENSION_free);
#endif
return openssl_pushresult(L, 1);
}
}
/***
sign x509
@function sign
@tparam evp_pkey pkey private key to sign x509
@tparam x509|x509_name cacert or cacert x509_name
@tparam[opt='sha1WithRSAEncryption'] string|md_digest md_alg
@treturn boolean result true for check pass
*/
static int openssl_x509_sign(lua_State*L)
{
X509* x = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
unsigned char *out = NULL;
int len = i2d_re_X509_tbs(x, &out);
if (len > 0)
{
lua_pushlstring(L, (const char *)out, len);
OPENSSL_free(out);
return 1;
}
return openssl_pushresult(L, len);
}
else if (auxiliar_getclassudata(L, "openssl.evp_pkey", 2))
{
EVP_PKEY* pkey = CHECK_OBJECT(2, EVP_PKEY, "openssl.evp_pkey");
const EVP_MD *md;
int ret = 1;
int i = 3;
if (auxiliar_getclassudata(L, "openssl.x509_name", 3))
{
X509_NAME* xn = CHECK_OBJECT(3, X509_NAME, "openssl.x509_name");
ret = X509_set_issuer_name(x, xn);
i++;
}
else
{
X509* ca = CHECK_OBJECT(3, X509, "openssl.x509");
X509_NAME* xn = X509_get_subject_name(ca);
ret = X509_check_private_key(ca, pkey);
if (ret == 1)
{
ret = X509_set_issuer_name(x, xn);
}
i++;
}
if (ret == 1)
{
md = get_digest(L, i, "sha256");
ret = X509_sign(x, pkey, md);
if (ret > 0)
ret = 1;
}
return openssl_pushresult(L, ret);
}
else
{
size_t sig_len;
const char* sig = luaL_checklstring(L, 2, &sig_len);
ASN1_OBJECT *obj = openssl_get_asn1object(L, 3, 0);
CONSTIFY_X509_get0 ASN1_BIT_STRING *psig = NULL;
CONSTIFY_X509_get0 X509_ALGOR *palg = NULL;
int ret;
X509_get0_signature(&psig, &palg, x);
ret = ASN1_BIT_STRING_set((ASN1_BIT_STRING*)psig, (unsigned char*)sig, (int)sig_len);
if (ret == 1)
{
ret = X509_ALGOR_set0((X509_ALGOR*)palg, obj, V_ASN1_UNDEF, NULL);
}
else
ASN1_OBJECT_free(obj);
return openssl_pushresult(L, ret);
}
}
static int openssl_x509_verify(lua_State*L)
{
X509* x = CHECK_OBJECT(1, X509, "openssl.x509");
if (lua_isnone(L, 2))
{
unsigned char *out = NULL;
int len = i2d_re_X509_tbs(x, &out);
if (len > 0)
{
CONSTIFY_X509_get0 ASN1_BIT_STRING *psig = NULL;
CONSTIFY_X509_get0 X509_ALGOR *palg = NULL;
lua_pushlstring(L, (const char *)out, len);
OPENSSL_free(out);
X509_get0_signature(&psig, &palg, x);
if (psig != NULL)
{
lua_pushlstring(L, (const char *)psig->data, psig->length);
}
else
lua_pushnil(L);
if (palg)
{
X509_ALGOR *alg = X509_ALGOR_dup((X509_ALGOR *)palg);
PUSH_OBJECT(alg, "openssl.x509_algor");
}
else
lua_pushnil(L);
return 3;
}
return openssl_pushresult(L, len);
}
else
{
EVP_PKEY *pkey = CHECK_OBJECT(2, EVP_PKEY, "openssl.evp_pkey");
int ret = X509_verify(x, pkey);
return openssl_pushresult(L, ret);
}
}
static luaL_Reg x509_funcs[] =
{
{"parse", openssl_x509_parse},
{"export", openssl_x509_export},
{"check", openssl_x509_check},
#if OPENSSL_VERSION_NUMBER > 0x10002000L
{"check_host", openssl_x509_check_host},
{"check_email", openssl_x509_check_email},
{"check_ip_asc", openssl_x509_check_ip},
#endif
{"pubkey", openssl_x509_public_key},
{"version", openssl_x509_version},
{"__gc", openssl_x509_free},
{"__tostring", auxiliar_tostring},
/* compat with luasec */
{"digest", openssl_x509_digest},
{"extensions", openssl_x509_extensions},
{"issuer", openssl_x509_issuer},
{"notbefore", openssl_x509_notbefore},
{"notafter", openssl_x509_notafter},
{"serial", openssl_x509_serial},
{"subject", openssl_x509_subject},
{"validat", openssl_x509_valid_at},
{"sign", openssl_x509_sign},
{"verify", openssl_x509_verify},
{NULL, NULL},
};
#if OPENSSL_VERSION_NUMBER > 0x10002000L
static LuaL_Enumeration check_flags_const[] =
{
#define DEFINE_ENUM(x) \
{#x, X509_CHECK_FLAG_##x}
DEFINE_ENUM(ALWAYS_CHECK_SUBJECT),
#if OPENSSL_VERSION_NUMBER > 0x10100000L
DEFINE_ENUM(NEVER_CHECK_SUBJECT),
#endif
DEFINE_ENUM(NO_WILDCARDS),
DEFINE_ENUM(NO_PARTIAL_WILDCARDS),
DEFINE_ENUM(MULTI_LABEL_WILDCARDS),
DEFINE_ENUM(SINGLE_LABEL_SUBDOMAINS),
#undef DEFINE_ENUM
{NULL, 0}
};
#endif
int luaopen_x509(lua_State *L)
{
auxiliar_newclass(L, "openssl.x509", x509_funcs);
lua_newtable(L);
luaL_setfuncs(L, R, 0);
openssl_register_xname(L);
lua_setfield(L, -2, "name");
openssl_register_xattribute(L);
lua_setfield(L, -2, "attribute");
openssl_register_xextension(L);
lua_setfield(L, -2, "extension");
openssl_register_xstore(L);
lua_setfield(L, -2, "store");
openssl_register_xalgor(L);
lua_setfield(L, -2, "algor");
luaopen_x509_req(L);
lua_setfield(L, -2, "req");
luaopen_x509_crl(L);
lua_setfield(L, -2, "crl");
lua_pushliteral(L, "version"); /** version */
lua_pushliteral(L, MYVERSION);
lua_settable(L, -3);
#if OPENSSL_VERSION_NUMBER > 0x10002000L
lua_pushliteral(L, "check_flag");
lua_newtable(L);
auxiliar_enumerate(L, -1, check_flags_const);
lua_settable(L, -3);
#endif
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-295/c/good_4693_0 |
crossvul-cpp_data_bad_4600_3 | /*
* Copyright (C) 2015 Adrien Vergé
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* In addition, as a special exception, the copyright holders give permission
* to link the code of portions of this program with the OpenSSL library under
* certain conditions as described in each individual source file, and
* distribute linked combinations including the two.
* You must obey the GNU General Public License in all respects for all of the
* code used other than OpenSSL. If you modify file(s) with this exception,
* you may extend this exception to your version of the file(s), but you are
* not obligated to do so. If you do not wish to do so, delete this exception
* statement from your version. If you delete this exception statement from
* all source files in the program, then also delete it here.
*/
#include "tunnel.h"
#include "http.h"
#include "log.h"
#include <unistd.h>
#include <fcntl.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <errno.h>
#include <string.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <openssl/err.h>
#include <openssl/x509v3.h>
#include <openssl/engine.h>
#if HAVE_PTY_H
#include <pty.h>
#elif HAVE_UTIL_H
#include <util.h>
#endif
#include <termios.h>
#include <signal.h>
#include <sys/wait.h>
#if HAVE_SYSTEMD
#include <systemd/sd-daemon.h>
#endif
// we use this constant in the source, so define a fallback if not defined
#ifndef OPENSSL_API_COMPAT
#define OPENSSL_API_COMPAT 0x0908000L
#endif
struct ofv_varr {
unsigned int cap; // current capacity
unsigned int off; // next slot to write, always < max(cap - 1, 1)
const char **data; // NULL terminated
};
static int ofv_append_varr(struct ofv_varr *p, const char *x)
{
if (p->off + 1 >= p->cap) {
const char **ndata;
unsigned int ncap = (p->off + 1) * 2;
if (p->off + 1 >= ncap) {
log_error("%s: ncap exceeded\n", __func__);
return 1;
};
ndata = realloc(p->data, ncap * sizeof(const char *));
if (ndata) {
p->data = ndata;
p->cap = ncap;
} else {
log_error("realloc: %s\n", strerror(errno));
return 1;
}
}
if (p->data == NULL) {
log_error("%s: NULL data\n", __func__);
return 1;
}
if (p->off + 1 >= p->cap) {
log_error("%s: cap exceeded in p\n", __func__);
return 1;
}
p->data[p->off] = x;
p->data[++p->off] = NULL;
return 0;
}
static int on_ppp_if_up(struct tunnel *tunnel)
{
log_info("Interface %s is UP.\n", tunnel->ppp_iface);
if (tunnel->config->set_routes) {
int ret;
log_info("Setting new routes...\n");
ret = ipv4_set_tunnel_routes(tunnel);
if (ret != 0)
log_warn("Adding route table is incomplete. Please check route table.\n");
}
if (tunnel->config->set_dns) {
log_info("Adding VPN nameservers...\n");
ipv4_add_nameservers_to_resolv_conf(tunnel);
}
log_info("Tunnel is up and running.\n");
#if HAVE_SYSTEMD
sd_notify(0, "READY=1");
#endif
return 0;
}
static int on_ppp_if_down(struct tunnel *tunnel)
{
log_info("Setting ppp interface down.\n");
if (tunnel->config->set_routes) {
log_info("Restoring routes...\n");
ipv4_restore_routes(tunnel);
}
if (tunnel->config->set_dns) {
log_info("Removing VPN nameservers...\n");
ipv4_del_nameservers_from_resolv_conf(tunnel);
}
return 0;
}
static int pppd_run(struct tunnel *tunnel)
{
pid_t pid;
int amaster;
int slave_stderr;
#ifdef HAVE_STRUCT_TERMIOS
struct termios termp = {
.c_cflag = B9600,
.c_cc[VTIME] = 0,
.c_cc[VMIN] = 1
};
#endif
static const char ppp_path[] = PPP_PATH;
if (access(ppp_path, F_OK) != 0) {
log_error("%s: %s.\n", ppp_path, strerror(errno));
return 1;
}
log_debug("ppp_path: %s\n", ppp_path);
slave_stderr = dup(STDERR_FILENO);
if (slave_stderr < 0) {
log_error("slave stderr %s\n", strerror(errno));
return 1;
}
#ifdef HAVE_STRUCT_TERMIOS
pid = forkpty(&amaster, NULL, &termp, NULL);
#else
pid = forkpty(&amaster, NULL, NULL, NULL);
#endif
if (pid == 0) { // child process
struct ofv_varr pppd_args = { 0, 0, NULL };
dup2(slave_stderr, STDERR_FILENO);
close(slave_stderr);
#if HAVE_USR_SBIN_PPP
/*
* assume there is a default configuration to start.
* Support for taking options from the command line
* e.g. the name of the configuration or options
* to send interactively to ppp will be added later
*/
static const char *const v[] = {
ppp_path,
"-direct"
};
for (unsigned int i = 0; i < ARRAY_SIZE(v); i++)
if (ofv_append_varr(&pppd_args, v[i]))
return 1;
#endif
#if HAVE_USR_SBIN_PPPD
if (tunnel->config->pppd_call) {
if (ofv_append_varr(&pppd_args, ppp_path))
return 1;
if (ofv_append_varr(&pppd_args, "call"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_call))
return 1;
} else {
static const char *const v[] = {
ppp_path,
"115200", // speed
":192.0.2.1", // <local_IP_address>:<remote_IP_address>
"noipdefault",
"noaccomp",
"noauth",
"default-asyncmap",
"nopcomp",
"receive-all",
"nodefaultroute",
"nodetach",
"lcp-max-configure", "40",
"mru", "1354"
};
for (unsigned int i = 0; i < ARRAY_SIZE(v); i++)
if (ofv_append_varr(&pppd_args, v[i]))
return 1;
}
if (tunnel->config->pppd_use_peerdns)
if (ofv_append_varr(&pppd_args, "usepeerdns"))
return 1;
if (tunnel->config->pppd_log) {
if (ofv_append_varr(&pppd_args, "debug"))
return 1;
if (ofv_append_varr(&pppd_args, "logfile"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_log))
return 1;
} else {
/*
* pppd defaults to logging to fd=1, clobbering the
* actual PPP data
*/
if (ofv_append_varr(&pppd_args, "logfd"))
return 1;
if (ofv_append_varr(&pppd_args, "2"))
return 1;
}
if (tunnel->config->pppd_plugin) {
if (ofv_append_varr(&pppd_args, "plugin"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_plugin))
return 1;
}
if (tunnel->config->pppd_ipparam) {
if (ofv_append_varr(&pppd_args, "ipparam"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_ipparam))
return 1;
}
if (tunnel->config->pppd_ifname) {
if (ofv_append_varr(&pppd_args, "ifname"))
return 1;
if (ofv_append_varr(&pppd_args, tunnel->config->pppd_ifname))
return 1;
}
#endif
#if HAVE_USR_SBIN_PPP
if (tunnel->config->ppp_system) {
if (ofv_append_varr(&pppd_args, tunnel->config->ppp_system))
return 1;
}
#endif
close(tunnel->ssl_socket);
execv(pppd_args.data[0], (char *const *)pppd_args.data);
free(pppd_args.data);
fprintf(stderr, "execvp: %s\n", strerror(errno));
_exit(EXIT_FAILURE);
} else {
close(slave_stderr);
if (pid == -1) {
log_error("forkpty: %s\n", strerror(errno));
return 1;
}
}
// Set non-blocking
int flags = fcntl(amaster, F_GETFL, 0);
if (flags == -1)
flags = 0;
if (fcntl(amaster, F_SETFL, flags | O_NONBLOCK) == -1) {
log_error("fcntl: %s\n", strerror(errno));
return 1;
}
tunnel->pppd_pid = pid;
tunnel->pppd_pty = amaster;
return 0;
}
static const char * const pppd_message[] = {
"Has detached, or otherwise the connection was successfully established and terminated at the peer's request.",
"An immediately fatal error of some kind occurred, such as an essential system call failing, or running out of virtual memory.",
"An error was detected in processing the options given, such as two mutually exclusive options being used.",
"Is not setuid-root and the invoking user is not root.",
"The kernel does not support PPP, for example, the PPP kernel driver is not included or cannot be loaded.",
"Terminated because it was sent a SIGINT, SIGTERM or SIGHUP signal.",
"The serial port could not be locked.",
"The serial port could not be opened.",
"The connect script failed (returned a non-zero exit status).",
"The command specified as the argument to the pty option could not be run.",
"The PPP negotiation failed, that is, it didn't reach the point where at least one network protocol (e.g. IP) was running.",
"The peer system failed (or refused) to authenticate itself.",
"The link was established successfully and terminated because it was idle.",
"The link was established successfully and terminated because the connect time limit was reached.",
"Callback was negotiated and an incoming call should arrive shortly.",
"The link was terminated because the peer is not responding to echo requests.",
"The link was terminated by the modem hanging up.",
"The PPP negotiation failed because serial loopback was detected.",
"The init script failed (returned a non-zero exit status).",
"We failed to authenticate ourselves to the peer."
};
static int pppd_terminate(struct tunnel *tunnel)
{
close(tunnel->pppd_pty);
log_debug("Waiting for %s to exit...\n", PPP_DAEMON);
int status;
if (waitpid(tunnel->pppd_pid, &status, 0) == -1) {
log_error("waitpid: %s\n", strerror(errno));
return 1;
}
if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
log_debug("waitpid: %s exit status code %d\n",
PPP_DAEMON, exit_status);
#if HAVE_USR_SBIN_PPPD
if (exit_status >= ARRAY_SIZE(pppd_message) || exit_status < 0) {
log_error("%s: Returned an unknown exit status: %d\n",
PPP_DAEMON, exit_status);
} else {
switch (exit_status) {
case 0: // success
log_debug("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
case 16: // emitted when exiting normally
log_info("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
default:
log_error("%s: %s\n",
PPP_DAEMON, pppd_message[exit_status]);
break;
}
}
#else
// ppp exit codes in the FreeBSD case
switch (exit_status) {
case 0: // success and EX_NORMAL as defined in ppp source directly
log_debug("%s: %s\n", PPP_DAEMON, pppd_message[exit_status]);
break;
case 1:
case 127:
case 255: // abnormal exit with hard-coded error codes in ppp
log_error("%s: exited with return value of %d\n",
PPP_DAEMON, exit_status);
break;
default:
log_error("%s: %s (%d)\n", PPP_DAEMON, strerror(exit_status),
exit_status);
break;
}
#endif
} else if (WIFSIGNALED(status)) {
int signal_number = WTERMSIG(status);
log_debug("waitpid: %s terminated by signal %d\n",
PPP_DAEMON, signal_number);
log_error("%s: terminated by signal: %s\n",
PPP_DAEMON, strsignal(signal_number));
}
return 0;
}
int ppp_interface_is_up(struct tunnel *tunnel)
{
struct ifaddrs *ifap, *ifa;
log_debug("Got Address: %s\n", inet_ntoa(tunnel->ipv4.ip_addr));
if (getifaddrs(&ifap)) {
log_error("getifaddrs: %s\n", strerror(errno));
return 0;
}
for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
if ((
#if HAVE_USR_SBIN_PPPD
(tunnel->config->pppd_ifname
&& strstr(ifa->ifa_name, tunnel->config->pppd_ifname)
!= NULL)
|| strstr(ifa->ifa_name, "ppp") != NULL
#endif
#if HAVE_USR_SBIN_PPP
strstr(ifa->ifa_name, "tun") != NULL
#endif
) && ifa->ifa_flags & IFF_UP) {
if (&(ifa->ifa_addr->sa_family) != NULL
&& ifa->ifa_addr->sa_family == AF_INET) {
struct in_addr if_ip_addr =
cast_addr(ifa->ifa_addr)->sin_addr;
log_debug("Interface Name: %s\n", ifa->ifa_name);
log_debug("Interface Addr: %s\n", inet_ntoa(if_ip_addr));
if (tunnel->ipv4.ip_addr.s_addr == if_ip_addr.s_addr) {
strncpy(tunnel->ppp_iface, ifa->ifa_name,
ROUTE_IFACE_LEN - 1);
freeifaddrs(ifap);
return 1;
}
}
}
}
freeifaddrs(ifap);
return 0;
}
static int get_gateway_host_ip(struct tunnel *tunnel)
{
const struct addrinfo hints = { .ai_family = AF_INET };
struct addrinfo *result = NULL;
int ret = getaddrinfo(tunnel->config->gateway_host, NULL, &hints, &result);
if (ret) {
if (ret == EAI_SYSTEM)
log_error("getaddrinfo: %s\n", strerror(errno));
else
log_error("getaddrinfo: %s\n", gai_strerror(ret));
return 1;
}
tunnel->config->gateway_ip = ((struct sockaddr_in *)
result->ai_addr)->sin_addr;
freeaddrinfo(result);
setenv("VPN_GATEWAY", inet_ntoa(tunnel->config->gateway_ip), 0);
return 0;
}
/*
* Establish a regular TCP connection.
*/
static int tcp_connect(struct tunnel *tunnel)
{
int ret, handle;
struct sockaddr_in server;
char *env_proxy;
handle = socket(AF_INET, SOCK_STREAM, 0);
if (handle == -1) {
log_error("socket: %s\n", strerror(errno));
goto err_socket;
}
env_proxy = getenv("https_proxy");
if (env_proxy == NULL)
env_proxy = getenv("HTTPS_PROXY");
if (env_proxy == NULL)
env_proxy = getenv("all_proxy");
if (env_proxy == NULL)
env_proxy = getenv("ALL_PROXY");
if (env_proxy != NULL) {
char *proxy_host, *proxy_port;
// protect the original environment from modifications
env_proxy = strdup(env_proxy);
if (env_proxy == NULL) {
log_error("strdup: %s\n", strerror(errno));
goto err_strdup;
}
// get rid of a trailing slash
if (*env_proxy && env_proxy[strlen(env_proxy) - 1] == '/')
env_proxy[strlen(env_proxy) - 1] = '\0';
// get rid of a http(s):// prefix in env_proxy
proxy_host = strstr(env_proxy, "://");
if (proxy_host == NULL)
proxy_host = env_proxy;
else
proxy_host += 3;
// split host and port
proxy_port = index(proxy_host, ':');
if (proxy_port != NULL) {
proxy_port[0] = '\0';
proxy_port++;
server.sin_port = htons(strtoul(proxy_port, NULL, 10));
} else {
server.sin_port = htons(tunnel->config->gateway_port);
}
// get rid of a trailing slash
if (*proxy_host && proxy_host[strlen(proxy_host) - 1] == '/')
proxy_host[strlen(proxy_host) - 1] = '\0';
log_debug("proxy_host: %s\n", proxy_host);
log_debug("proxy_port: %s\n", proxy_port);
server.sin_addr.s_addr = inet_addr(proxy_host);
// if host is given as a FQDN we have to do a DNS lookup
if (server.sin_addr.s_addr == INADDR_NONE) {
const struct addrinfo hints = { .ai_family = AF_INET };
struct addrinfo *result = NULL;
ret = getaddrinfo(proxy_host, NULL, &hints, &result);
if (ret) {
if (ret == EAI_SYSTEM)
log_error("getaddrinfo: %s\n", strerror(errno));
else
log_error("getaddrinfo: %s\n", gai_strerror(ret));
goto err_connect;
}
server.sin_addr = ((struct sockaddr_in *)
result->ai_addr)->sin_addr;
freeaddrinfo(result);
}
} else {
server.sin_port = htons(tunnel->config->gateway_port);
server.sin_addr = tunnel->config->gateway_ip;
}
log_debug("server_addr: %s\n", inet_ntoa(server.sin_addr));
log_debug("server_port: %u\n", ntohs(server.sin_port));
server.sin_family = AF_INET;
memset(&(server.sin_zero), '\0', 8);
log_debug("gateway_addr: %s\n", inet_ntoa(tunnel->config->gateway_ip));
log_debug("gateway_port: %u\n", tunnel->config->gateway_port);
ret = connect(handle, (struct sockaddr *) &server, sizeof(server));
if (ret) {
log_error("connect: %s\n", strerror(errno));
goto err_connect;
}
if (env_proxy != NULL) {
char request[128];
// https://tools.ietf.org/html/rfc7231#section-4.3.6
sprintf(request, "CONNECT %s:%u HTTP/1.1\r\nHost: %s:%u\r\n\r\n",
inet_ntoa(tunnel->config->gateway_ip),
tunnel->config->gateway_port,
inet_ntoa(tunnel->config->gateway_ip),
tunnel->config->gateway_port);
ssize_t bytes_written = write(handle, request, strlen(request));
if (bytes_written != strlen(request)) {
log_error("write error while talking to proxy: %s\n",
strerror(errno));
goto err_connect;
}
// wait for a "200 OK" reply from the proxy,
// be careful not to fetch too many bytes at once
const char *response = NULL;
memset(&(request), '\0', sizeof(request));
for (int j = 0; response == NULL; j++) {
/*
* Coverity detected a defect:
* CID 200508: String not null terminated (STRING_NULL)
*
* It is actually a false positive:
* • Function memset() initializes 'request' with '\0'
* • Function read() gets a single char into: request[j]
* • The final '\0' cannot be overwritten because:
* j < ARRAY_SIZE(request) - 1
*/
ssize_t bytes_read = read(handle, &(request[j]), 1);
if (bytes_read < 1) {
log_error("Proxy response is unexpectedly large and cannot fit in the %lu-bytes buffer.\n",
ARRAY_SIZE(request));
goto err_proxy_response;
}
// detect "200"
static const char HTTP_STATUS_200[] = "200";
response = strstr(request, HTTP_STATUS_200);
// detect end-of-line after "200"
if (response != NULL) {
/*
* RFC2616 states in section 2.2 Basic Rules:
* CR = <US-ASCII CR, carriage return (13)>
* LF = <US-ASCII LF, linefeed (10)>
* HTTP/1.1 defines the sequence CR LF as the
* end-of-line marker for all protocol elements
* except the entity-body (see appendix 19.3
* for tolerant applications).
* CRLF = CR LF
*
* RFC2616 states in section 19.3 Tolerant Applications:
* The line terminator for message-header fields
* is the sequence CRLF. However, we recommend
* that applications, when parsing such headers,
* recognize a single LF as a line terminator
* and ignore the leading CR.
*/
static const char *const HTTP_EOL[] = {
"\r\n\r\n",
"\n\n"
};
const char *eol = NULL;
for (int i = 0; (i < ARRAY_SIZE(HTTP_EOL)) &&
(eol == NULL); i++)
eol = strstr(response, HTTP_EOL[i]);
response = eol;
}
if (j > ARRAY_SIZE(request) - 2) {
log_error("Proxy response does not contain \"%s\" as expected.\n",
HTTP_STATUS_200);
goto err_proxy_response;
}
}
free(env_proxy); // release memory allocated by strdup()
}
return handle;
err_proxy_response:
err_connect:
free(env_proxy); // release memory allocated by strdup()
err_strdup:
close(handle);
err_socket:
return -1;
}
static int ssl_verify_cert(struct tunnel *tunnel)
{
int ret = -1;
int cert_valid = 0;
unsigned char digest[SHA256LEN];
unsigned int len;
struct x509_digest *elem;
char digest_str[SHA256STRLEN], *subject, *issuer;
char *line;
int i;
X509_NAME *subj;
SSL_set_verify(tunnel->ssl_handle, SSL_VERIFY_PEER, NULL);
X509 *cert = SSL_get_peer_certificate(tunnel->ssl_handle);
if (cert == NULL) {
log_error("Unable to get gateway certificate.\n");
return 1;
}
subj = X509_get_subject_name(cert);
#ifdef HAVE_X509_CHECK_HOST
// Use OpenSSL native host validation if v >= 1.0.2.
// compare against gateway_host and correctly check return value
// to fix piror Incorrect use of X509_check_host
if (X509_check_host(cert, tunnel->config->gateway_host,
0, 0, NULL) == 1)
cert_valid = 1;
#else
char common_name[FIELD_SIZE + 1];
// Use explicit Common Name check if native validation not available.
// Note: this will ignore Subject Alternative Name fields.
if (subj
&& X509_NAME_get_text_by_NID(subj, NID_commonName, common_name,
FIELD_SIZE) > 0
&& strncasecmp(common_name, tunnel->config->gateway_host,
FIELD_SIZE) == 0)
cert_valid = 1;
#endif
// Try to validate certificate using local PKI
if (cert_valid
&& SSL_get_verify_result(tunnel->ssl_handle) == X509_V_OK) {
log_debug("Gateway certificate validation succeeded.\n");
ret = 0;
goto free_cert;
}
log_debug("Gateway certificate validation failed.\n");
// If validation failed, check if cert is in the white list
if (X509_digest(cert, EVP_sha256(), digest, &len) <= 0
|| len != SHA256LEN) {
log_error("Could not compute certificate sha256 digest.\n");
goto free_cert;
}
// Encode digest in base16
for (i = 0; i < SHA256LEN; i++)
sprintf(&digest_str[2 * i], "%02x", digest[i]);
digest_str[SHA256STRLEN - 1] = '\0';
// Is it in whitelist?
for (elem = tunnel->config->cert_whitelist; elem != NULL;
elem = elem->next)
if (memcmp(digest_str, elem->data, SHA256STRLEN - 1) == 0)
break;
if (elem != NULL) { // break before end of loop
log_debug("Gateway certificate digest found in white list.\n");
ret = 0;
goto free_cert;
}
subject = X509_NAME_oneline(subj, NULL, 0);
issuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
log_error("Gateway certificate validation failed, and the certificate digest in not in the local whitelist. If you trust it, rerun with:\n");
log_error(" --trusted-cert %s\n", digest_str);
log_error("or add this line to your config file:\n");
log_error(" trusted-cert = %s\n", digest_str);
log_error("Gateway certificate:\n");
log_error(" subject:\n");
for (line = strtok(subject, "/"); line != NULL;
line = strtok(NULL, "/"))
log_error(" %s\n", line);
log_error(" issuer:\n");
for (line = strtok(issuer, "/"); line != NULL;
line = strtok(NULL, "/"))
log_error(" %s\n", line);
log_error(" sha256 digest:\n");
log_error(" %s\n", digest_str);
free_cert:
X509_free(cert);
return ret;
}
/*
* Destroy and free the SSL connection to the gateway.
*/
static void ssl_disconnect(struct tunnel *tunnel)
{
if (!tunnel->ssl_handle)
return;
SSL_shutdown(tunnel->ssl_handle);
SSL_free(tunnel->ssl_handle);
SSL_CTX_free(tunnel->ssl_context);
close(tunnel->ssl_socket);
tunnel->ssl_handle = NULL;
tunnel->ssl_context = NULL;
}
/*
* Connects to the gateway and initiate an SSL session.
*/
int ssl_connect(struct tunnel *tunnel)
{
ssl_disconnect(tunnel);
tunnel->ssl_socket = tcp_connect(tunnel);
if (tunnel->ssl_socket == -1)
return 1;
// registration is deprecated from OpenSSL 1.1.0 onward
#if OPENSSL_API_COMPAT < 0x10100000L
// Register the error strings for libcrypto & libssl
SSL_load_error_strings();
// Register the available ciphers and digests
SSL_library_init();
#endif
tunnel->ssl_context = SSL_CTX_new(SSLv23_client_method());
if (tunnel->ssl_context == NULL) {
log_error("SSL_CTX_new: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
// Load the OS default CA files
if (!SSL_CTX_set_default_verify_paths(tunnel->ssl_context))
log_error("Could not load OS OpenSSL files.\n");
if (tunnel->config->ca_file) {
if (!SSL_CTX_load_verify_locations(
tunnel->ssl_context,
tunnel->config->ca_file, NULL)) {
log_error("SSL_CTX_load_verify_locations: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
/* Use engine for PIV if user-cert config starts with pkcs11 URI: */
if (tunnel->config->use_engine > 0) {
ENGINE *e;
ENGINE_load_builtin_engines();
e = ENGINE_by_id("pkcs11");
if (!e) {
log_error("Could not load pkcs11 Engine: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!ENGINE_init(e)) {
log_error("Could not init pkcs11 Engine: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
ENGINE_free(e);
return 1;
}
if (!ENGINE_set_default_RSA(e))
abort();
ENGINE_finish(e);
ENGINE_free(e);
struct token parms;
parms.uri = tunnel->config->user_cert;
parms.cert = NULL;
if (!ENGINE_ctrl_cmd(e, "LOAD_CERT_CTRL", 0, &parms, NULL, 1)) {
log_error("PKCS11 ENGINE_ctrl_cmd: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_use_certificate(tunnel->ssl_context, parms.cert)) {
log_error("PKCS11 SSL_CTX_use_certificate: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
EVP_PKEY * privkey = ENGINE_load_private_key(
e, parms.uri, UI_OpenSSL(), NULL);
if (!privkey) {
log_error("PKCS11 ENGINE_load_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_use_PrivateKey(tunnel->ssl_context, privkey)) {
log_error("PKCS11 SSL_CTX_use_PrivateKey_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!SSL_CTX_check_private_key(tunnel->ssl_context)) {
log_error("PKCS11 SSL_CTX_check_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
} else { /* end PKCS11-engine */
if (tunnel->config->user_cert) {
if (!SSL_CTX_use_certificate_file(
tunnel->ssl_context, tunnel->config->user_cert,
SSL_FILETYPE_PEM)) {
log_error("SSL_CTX_use_certificate_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
if (tunnel->config->user_key) {
if (!SSL_CTX_use_PrivateKey_file(
tunnel->ssl_context, tunnel->config->user_key,
SSL_FILETYPE_PEM)) {
log_error("SSL_CTX_use_PrivateKey_file: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
if (tunnel->config->user_cert && tunnel->config->user_key) {
if (!SSL_CTX_check_private_key(tunnel->ssl_context)) {
log_error("SSL_CTX_check_private_key: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
}
if (!tunnel->config->insecure_ssl) {
long sslctxopt = SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
long checkopt;
checkopt = SSL_CTX_set_options(tunnel->ssl_context, sslctxopt);
if ((checkopt & sslctxopt) != sslctxopt) {
log_error("SSL_CTX_set_options didn't set opt: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
tunnel->ssl_handle = SSL_new(tunnel->ssl_context);
if (tunnel->ssl_handle == NULL) {
log_error("SSL_new: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
if (!tunnel->config->insecure_ssl) {
if (!tunnel->config->cipher_list) {
const char *cipher_list;
if (tunnel->config->seclevel_1)
cipher_list = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4@SECLEVEL=1";
else
cipher_list = "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4";
tunnel->config->cipher_list = strdup(cipher_list);
}
} else {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (tunnel->config->min_tls <= 0)
tunnel->config->min_tls = TLS1_VERSION;
#endif
if (!tunnel->config->cipher_list && tunnel->config->seclevel_1) {
const char *cipher_list = "DEFAULT@SECLEVEL=1";
tunnel->config->cipher_list = strdup(cipher_list);
}
}
if (tunnel->config->cipher_list) {
log_debug("Setting cipher list to: %s\n", tunnel->config->cipher_list);
if (!SSL_set_cipher_list(tunnel->ssl_handle,
tunnel->config->cipher_list)) {
log_error("SSL_set_cipher_list failed: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
if (tunnel->config->min_tls > 0) {
log_debug("Setting min proto version to: 0x%x\n",
tunnel->config->min_tls);
if (!SSL_set_min_proto_version(tunnel->ssl_handle,
tunnel->config->min_tls)) {
log_error("SSL_set_min_proto_version failed: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
}
#endif
if (!SSL_set_fd(tunnel->ssl_handle, tunnel->ssl_socket)) {
log_error("SSL_set_fd: %s\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
SSL_set_mode(tunnel->ssl_handle, SSL_MODE_AUTO_RETRY);
// Initiate SSL handshake
if (SSL_connect(tunnel->ssl_handle) != 1) {
log_error("SSL_connect: %s\n"
"You might want to try --insecure-ssl or specify a different --cipher-list\n",
ERR_error_string(ERR_peek_last_error(), NULL));
return 1;
}
SSL_set_mode(tunnel->ssl_handle, SSL_MODE_AUTO_RETRY);
if (ssl_verify_cert(tunnel))
return 1;
// Disable SIGPIPE (occurs when trying to write to an already-closed
// socket).
signal(SIGPIPE, SIG_IGN);
return 0;
}
int run_tunnel(struct vpn_config *config)
{
int ret;
struct tunnel tunnel = {
.config = config,
.state = STATE_DOWN,
.ssl_context = NULL,
.ssl_handle = NULL,
.ipv4.ns1_addr.s_addr = 0,
.ipv4.ns2_addr.s_addr = 0,
.ipv4.dns_suffix = NULL,
.on_ppp_if_up = on_ppp_if_up,
.on_ppp_if_down = on_ppp_if_down
};
// Step 0: get gateway host IP
log_debug("Resolving gateway host ip\n");
ret = get_gateway_host_ip(&tunnel);
if (ret)
goto err_tunnel;
// Step 1: open a SSL connection to the gateway
log_debug("Establishing ssl connection\n");
ret = ssl_connect(&tunnel);
if (ret)
goto err_tunnel;
log_info("Connected to gateway.\n");
// Step 2: connect to the HTTP interface and authenticate to get a
// cookie
ret = auth_log_in(&tunnel);
if (ret != 1) {
log_error("Could not authenticate to gateway. Please check the password, client certificate, etc.\n");
log_debug("%s %d\n", err_http_str(ret), ret);
ret = 1;
goto err_tunnel;
}
log_info("Authenticated.\n");
log_debug("Cookie: %s\n", tunnel.cookie);
ret = auth_request_vpn_allocation(&tunnel);
if (ret != 1) {
log_error("VPN allocation request failed (%s).\n",
err_http_str(ret));
ret = 1;
goto err_tunnel;
}
log_info("Remote gateway has allocated a VPN.\n");
ret = ssl_connect(&tunnel);
if (ret)
goto err_tunnel;
// Step 3: get configuration
log_debug("Retrieving configuration\n");
ret = auth_get_config(&tunnel);
if (ret != 1) {
log_error("Could not get VPN configuration (%s).\n",
err_http_str(ret));
ret = 1;
goto err_tunnel;
}
// Step 4: run a pppd process
log_debug("Establishing the tunnel\n");
ret = pppd_run(&tunnel);
if (ret)
goto err_tunnel;
// Step 5: ask gateway to start tunneling
log_debug("Switch to tunneling mode\n");
ret = http_send(&tunnel,
"GET /remote/sslvpn-tunnel HTTP/1.1\r\n"
"Host: sslvpn\r\n"
"Cookie: %s\r\n\r\n",
tunnel.cookie);
if (ret != 1) {
log_error("Could not start tunnel (%s).\n", err_http_str(ret));
ret = 1;
goto err_start_tunnel;
}
tunnel.state = STATE_CONNECTING;
ret = 0;
// Step 6: perform io between pppd and the gateway, while tunnel is up
log_debug("Starting IO through the tunnel\n");
io_loop(&tunnel);
log_debug("disconnecting\n");
if (tunnel.state == STATE_UP)
if (tunnel.on_ppp_if_down != NULL)
tunnel.on_ppp_if_down(&tunnel);
tunnel.state = STATE_DISCONNECTING;
err_start_tunnel:
pppd_terminate(&tunnel);
log_info("Terminated %s.\n", PPP_DAEMON);
err_tunnel:
log_info("Closed connection to gateway.\n");
tunnel.state = STATE_DOWN;
if (ssl_connect(&tunnel)) {
log_info("Could not log out.\n");
} else {
auth_log_out(&tunnel);
log_info("Logged out.\n");
}
// explicitly free the buffer allocated for split routes of the ipv4 config
if (tunnel.ipv4.split_rt != NULL) {
free(tunnel.ipv4.split_rt);
tunnel.ipv4.split_rt = NULL;
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-295/c/bad_4600_3 |
crossvul-cpp_data_bad_682_0 | /* $OpenBSD: x509_vpm.c,v 1.16 2017/12/09 07:09:25 deraadt Exp $ */
/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
* project 2004.
*/
/* ====================================================================
* Copyright (c) 2004 The OpenSSL Project. 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 acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS 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.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include <string.h>
#include <openssl/buffer.h>
#include <openssl/crypto.h>
#include <openssl/lhash.h>
#include <openssl/stack.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "vpm_int.h"
/* X509_VERIFY_PARAM functions */
int X509_VERIFY_PARAM_set1_email(X509_VERIFY_PARAM *param, const char *email,
size_t emaillen);
int X509_VERIFY_PARAM_set1_ip(X509_VERIFY_PARAM *param, const unsigned char *ip,
size_t iplen);
#define SET_HOST 0
#define ADD_HOST 1
static void
str_free(char *s)
{
free(s);
}
#define string_stack_free(sk) sk_OPENSSL_STRING_pop_free(sk, str_free)
/*
* Post 1.0.1 sk function "deep_copy". For the moment we simply make
* these take void * and use them directly without a glorious blob of
* obfuscating macros of dubious value in front of them. All this in
* preparation for a rototilling of safestack.h (likely inspired by
* this).
*/
static void *
sk_deep_copy(void *sk_void, void *copy_func_void, void *free_func_void)
{
_STACK *sk = sk_void;
void *(*copy_func)(void *) = copy_func_void;
void (*free_func)(void *) = free_func_void;
_STACK *ret = sk_dup(sk);
size_t i;
if (ret == NULL)
return NULL;
for (i = 0; i < ret->num; i++) {
if (ret->data[i] == NULL)
continue;
ret->data[i] = copy_func(ret->data[i]);
if (ret->data[i] == NULL) {
size_t j;
for (j = 0; j < i; j++) {
if (ret->data[j] != NULL)
free_func(ret->data[j]);
}
sk_free(ret);
return NULL;
}
}
return ret;
}
static int
int_x509_param_set_hosts(X509_VERIFY_PARAM_ID *id, int mode,
const char *name, size_t namelen)
{
char *copy;
/*
* Refuse names with embedded NUL bytes.
* XXX: Do we need to push an error onto the error stack?
*/
if (name && memchr(name, '\0', namelen))
return 0;
if (mode == SET_HOST && id->hosts) {
string_stack_free(id->hosts);
id->hosts = NULL;
}
if (name == NULL || namelen == 0)
return 1;
copy = strndup(name, namelen);
if (copy == NULL)
return 0;
if (id->hosts == NULL &&
(id->hosts = sk_OPENSSL_STRING_new_null()) == NULL) {
free(copy);
return 0;
}
if (!sk_OPENSSL_STRING_push(id->hosts, copy)) {
free(copy);
if (sk_OPENSSL_STRING_num(id->hosts) == 0) {
sk_OPENSSL_STRING_free(id->hosts);
id->hosts = NULL;
}
return 0;
}
return 1;
}
static void
x509_verify_param_zero(X509_VERIFY_PARAM *param)
{
X509_VERIFY_PARAM_ID *paramid;
if (!param)
return;
param->name = NULL;
param->purpose = 0;
param->trust = 0;
/*param->inh_flags = X509_VP_FLAG_DEFAULT;*/
param->inh_flags = 0;
param->flags = 0;
param->depth = -1;
if (param->policies) {
sk_ASN1_OBJECT_pop_free(param->policies, ASN1_OBJECT_free);
param->policies = NULL;
}
paramid = param->id;
if (paramid->hosts) {
string_stack_free(paramid->hosts);
paramid->hosts = NULL;
}
free(paramid->peername);
paramid->peername = NULL;
free(paramid->email);
paramid->email = NULL;
paramid->emaillen = 0;
free(paramid->ip);
paramid->ip = NULL;
paramid->iplen = 0;
}
X509_VERIFY_PARAM *
X509_VERIFY_PARAM_new(void)
{
X509_VERIFY_PARAM *param;
X509_VERIFY_PARAM_ID *paramid;
param = calloc(1, sizeof(X509_VERIFY_PARAM));
if (param == NULL)
return NULL;
paramid = calloc (1, sizeof(X509_VERIFY_PARAM_ID));
if (paramid == NULL) {
free(param);
return NULL;
}
param->id = paramid;
x509_verify_param_zero(param);
return param;
}
void
X509_VERIFY_PARAM_free(X509_VERIFY_PARAM *param)
{
if (param == NULL)
return;
x509_verify_param_zero(param);
free(param->id);
free(param);
}
/* This function determines how parameters are "inherited" from one structure
* to another. There are several different ways this can happen.
*
* 1. If a child structure needs to have its values initialized from a parent
* they are simply copied across. For example SSL_CTX copied to SSL.
* 2. If the structure should take on values only if they are currently unset.
* For example the values in an SSL structure will take appropriate value
* for SSL servers or clients but only if the application has not set new
* ones.
*
* The "inh_flags" field determines how this function behaves.
*
* Normally any values which are set in the default are not copied from the
* destination and verify flags are ORed together.
*
* If X509_VP_FLAG_DEFAULT is set then anything set in the source is copied
* to the destination. Effectively the values in "to" become default values
* which will be used only if nothing new is set in "from".
*
* If X509_VP_FLAG_OVERWRITE is set then all value are copied across whether
* they are set or not. Flags is still Ored though.
*
* If X509_VP_FLAG_RESET_FLAGS is set then the flags value is copied instead
* of ORed.
*
* If X509_VP_FLAG_LOCKED is set then no values are copied.
*
* If X509_VP_FLAG_ONCE is set then the current inh_flags setting is zeroed
* after the next call.
*/
/* Macro to test if a field should be copied from src to dest */
#define test_x509_verify_param_copy(field, def) \
(to_overwrite || \
((src->field != def) && (to_default || (dest->field == def))))
/* As above but for ID fields */
#define test_x509_verify_param_copy_id(idf, def) \
test_x509_verify_param_copy(id->idf, def)
/* Macro to test and copy a field if necessary */
#define x509_verify_param_copy(field, def) \
if (test_x509_verify_param_copy(field, def)) \
dest->field = src->field
int
X509_VERIFY_PARAM_inherit(X509_VERIFY_PARAM *dest, const X509_VERIFY_PARAM *src)
{
unsigned long inh_flags;
int to_default, to_overwrite;
X509_VERIFY_PARAM_ID *id;
if (!src)
return 1;
id = src->id;
inh_flags = dest->inh_flags | src->inh_flags;
if (inh_flags & X509_VP_FLAG_ONCE)
dest->inh_flags = 0;
if (inh_flags & X509_VP_FLAG_LOCKED)
return 1;
if (inh_flags & X509_VP_FLAG_DEFAULT)
to_default = 1;
else
to_default = 0;
if (inh_flags & X509_VP_FLAG_OVERWRITE)
to_overwrite = 1;
else
to_overwrite = 0;
x509_verify_param_copy(purpose, 0);
x509_verify_param_copy(trust, 0);
x509_verify_param_copy(depth, -1);
/* If overwrite or check time not set, copy across */
if (to_overwrite || !(dest->flags & X509_V_FLAG_USE_CHECK_TIME)) {
dest->check_time = src->check_time;
dest->flags &= ~X509_V_FLAG_USE_CHECK_TIME;
/* Don't need to copy flag: that is done below */
}
if (inh_flags & X509_VP_FLAG_RESET_FLAGS)
dest->flags = 0;
dest->flags |= src->flags;
if (test_x509_verify_param_copy(policies, NULL)) {
if (!X509_VERIFY_PARAM_set1_policies(dest, src->policies))
return 0;
}
/* Copy the host flags if and only if we're copying the host list */
if (test_x509_verify_param_copy_id(hosts, NULL)) {
if (dest->id->hosts) {
string_stack_free(dest->id->hosts);
dest->id->hosts = NULL;
}
if (id->hosts) {
dest->id->hosts =
sk_deep_copy(id->hosts, strdup, str_free);
if (dest->id->hosts == NULL)
return 0;
dest->id->hostflags = id->hostflags;
}
}
if (test_x509_verify_param_copy_id(email, NULL)) {
if (!X509_VERIFY_PARAM_set1_email(dest, id->email,
id->emaillen))
return 0;
}
if (test_x509_verify_param_copy_id(ip, NULL)) {
if (!X509_VERIFY_PARAM_set1_ip(dest, id->ip, id->iplen))
return 0;
}
return 1;
}
int
X509_VERIFY_PARAM_set1(X509_VERIFY_PARAM *to, const X509_VERIFY_PARAM *from)
{
unsigned long save_flags = to->inh_flags;
int ret;
to->inh_flags |= X509_VP_FLAG_DEFAULT;
ret = X509_VERIFY_PARAM_inherit(to, from);
to->inh_flags = save_flags;
return ret;
}
static int
int_x509_param_set1(char **pdest, size_t *pdestlen, const char *src,
size_t srclen)
{
char *tmp;
if (src) {
if (srclen == 0) {
if ((tmp = strdup(src)) == NULL)
return 0;
srclen = strlen(src);
} else {
if ((tmp = malloc(srclen)) == NULL)
return 0;
memcpy(tmp, src, srclen);
}
} else {
tmp = NULL;
srclen = 0;
}
if (*pdest)
free(*pdest);
*pdest = tmp;
if (pdestlen)
*pdestlen = srclen;
return 1;
}
int
X509_VERIFY_PARAM_set1_name(X509_VERIFY_PARAM *param, const char *name)
{
free(param->name);
param->name = NULL;
if (name == NULL)
return 1;
param->name = strdup(name);
if (param->name)
return 1;
return 0;
}
int
X509_VERIFY_PARAM_set_flags(X509_VERIFY_PARAM *param, unsigned long flags)
{
param->flags |= flags;
if (flags & X509_V_FLAG_POLICY_MASK)
param->flags |= X509_V_FLAG_POLICY_CHECK;
return 1;
}
int
X509_VERIFY_PARAM_clear_flags(X509_VERIFY_PARAM *param, unsigned long flags)
{
param->flags &= ~flags;
return 1;
}
unsigned long
X509_VERIFY_PARAM_get_flags(X509_VERIFY_PARAM *param)
{
return param->flags;
}
int
X509_VERIFY_PARAM_set_purpose(X509_VERIFY_PARAM *param, int purpose)
{
return X509_PURPOSE_set(¶m->purpose, purpose);
}
int
X509_VERIFY_PARAM_set_trust(X509_VERIFY_PARAM *param, int trust)
{
return X509_TRUST_set(¶m->trust, trust);
}
void
X509_VERIFY_PARAM_set_depth(X509_VERIFY_PARAM *param, int depth)
{
param->depth = depth;
}
void
X509_VERIFY_PARAM_set_time(X509_VERIFY_PARAM *param, time_t t)
{
param->check_time = t;
param->flags |= X509_V_FLAG_USE_CHECK_TIME;
}
int
X509_VERIFY_PARAM_add0_policy(X509_VERIFY_PARAM *param, ASN1_OBJECT *policy)
{
if (!param->policies) {
param->policies = sk_ASN1_OBJECT_new_null();
if (!param->policies)
return 0;
}
if (!sk_ASN1_OBJECT_push(param->policies, policy))
return 0;
return 1;
}
int
X509_VERIFY_PARAM_set1_policies(X509_VERIFY_PARAM *param,
STACK_OF(ASN1_OBJECT) *policies)
{
int i;
ASN1_OBJECT *oid, *doid;
if (!param)
return 0;
if (param->policies)
sk_ASN1_OBJECT_pop_free(param->policies, ASN1_OBJECT_free);
if (!policies) {
param->policies = NULL;
return 1;
}
param->policies = sk_ASN1_OBJECT_new_null();
if (!param->policies)
return 0;
for (i = 0; i < sk_ASN1_OBJECT_num(policies); i++) {
oid = sk_ASN1_OBJECT_value(policies, i);
doid = OBJ_dup(oid);
if (!doid)
return 0;
if (!sk_ASN1_OBJECT_push(param->policies, doid)) {
ASN1_OBJECT_free(doid);
return 0;
}
}
param->flags |= X509_V_FLAG_POLICY_CHECK;
return 1;
}
int
X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param,
const char *name, size_t namelen)
{
return int_x509_param_set_hosts(param->id, SET_HOST, name, namelen);
}
int
X509_VERIFY_PARAM_add1_host(X509_VERIFY_PARAM *param,
const char *name, size_t namelen)
{
return int_x509_param_set_hosts(param->id, ADD_HOST, name, namelen);
}
void
X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param, unsigned int flags)
{
param->id->hostflags = flags;
}
char *
X509_VERIFY_PARAM_get0_peername(X509_VERIFY_PARAM *param)
{
return param->id->peername;
}
int
X509_VERIFY_PARAM_set1_email(X509_VERIFY_PARAM *param, const char *email,
size_t emaillen)
{
return int_x509_param_set1(¶m->id->email, ¶m->id->emaillen,
email, emaillen);
}
int
X509_VERIFY_PARAM_set1_ip(X509_VERIFY_PARAM *param, const unsigned char *ip,
size_t iplen)
{
if (iplen != 0 && iplen != 4 && iplen != 16)
return 0;
return int_x509_param_set1((char **)¶m->id->ip, ¶m->id->iplen,
(char *)ip, iplen);
}
int
X509_VERIFY_PARAM_set1_ip_asc(X509_VERIFY_PARAM *param, const char *ipasc)
{
unsigned char ipout[16];
size_t iplen;
iplen = (size_t)a2i_ipadd(ipout, ipasc);
if (iplen == 0)
return 0;
return X509_VERIFY_PARAM_set1_ip(param, ipout, iplen);
}
int
X509_VERIFY_PARAM_get_depth(const X509_VERIFY_PARAM *param)
{
return param->depth;
}
const char *
X509_VERIFY_PARAM_get0_name(const X509_VERIFY_PARAM *param)
{
return param->name;
}
static const X509_VERIFY_PARAM_ID _empty_id = { NULL };
#define vpm_empty_id (X509_VERIFY_PARAM_ID *)&_empty_id
/*
* Default verify parameters: these are used for various applications and can
* be overridden by the user specified table.
*/
static const X509_VERIFY_PARAM default_table[] = {
{
.name = "default",
.depth = 100,
.trust = 0, /* XXX This is not the default trust value */
.id = vpm_empty_id
},
{
.name = "pkcs7",
.purpose = X509_PURPOSE_SMIME_SIGN,
.trust = X509_TRUST_EMAIL,
.depth = -1,
.id = vpm_empty_id
},
{
.name = "smime_sign",
.purpose = X509_PURPOSE_SMIME_SIGN,
.trust = X509_TRUST_EMAIL,
.depth = -1,
.id = vpm_empty_id
},
{
.name = "ssl_client",
.purpose = X509_PURPOSE_SSL_CLIENT,
.trust = X509_TRUST_SSL_CLIENT,
.depth = -1,
.id = vpm_empty_id
},
{
.name = "ssl_server",
.purpose = X509_PURPOSE_SSL_SERVER,
.trust = X509_TRUST_SSL_SERVER,
.depth = -1,
.id = vpm_empty_id
}
};
static STACK_OF(X509_VERIFY_PARAM) *param_table = NULL;
static int
param_cmp(const X509_VERIFY_PARAM * const *a,
const X509_VERIFY_PARAM * const *b)
{
return strcmp((*a)->name, (*b)->name);
}
int
X509_VERIFY_PARAM_add0_table(X509_VERIFY_PARAM *param)
{
X509_VERIFY_PARAM *ptmp;
if (!param_table) {
param_table = sk_X509_VERIFY_PARAM_new(param_cmp);
if (!param_table)
return 0;
} else {
size_t idx;
if ((idx = sk_X509_VERIFY_PARAM_find(param_table, param))
!= -1) {
ptmp = sk_X509_VERIFY_PARAM_value(param_table,
idx);
X509_VERIFY_PARAM_free(ptmp);
(void)sk_X509_VERIFY_PARAM_delete(param_table,
idx);
}
}
if (!sk_X509_VERIFY_PARAM_push(param_table, param))
return 0;
return 1;
}
int
X509_VERIFY_PARAM_get_count(void)
{
int num = sizeof(default_table) / sizeof(X509_VERIFY_PARAM);
if (param_table)
num += sk_X509_VERIFY_PARAM_num(param_table);
return num;
}
const
X509_VERIFY_PARAM *X509_VERIFY_PARAM_get0(int id)
{
int num = sizeof(default_table) / sizeof(X509_VERIFY_PARAM);
if (id < num)
return default_table + id;
return sk_X509_VERIFY_PARAM_value(param_table, id - num);
}
const
X509_VERIFY_PARAM *X509_VERIFY_PARAM_lookup(const char *name)
{
X509_VERIFY_PARAM pm;
unsigned int i, limit;
pm.name = (char *)name;
if (param_table) {
size_t idx;
if ((idx = sk_X509_VERIFY_PARAM_find(param_table, &pm)) != -1)
return sk_X509_VERIFY_PARAM_value(param_table, idx);
}
limit = sizeof(default_table) / sizeof(X509_VERIFY_PARAM);
for (i = 0; i < limit; i++) {
if (strcmp(default_table[i].name, name) == 0) {
return &default_table[i];
}
}
return NULL;
}
void
X509_VERIFY_PARAM_table_cleanup(void)
{
if (param_table)
sk_X509_VERIFY_PARAM_pop_free(param_table,
X509_VERIFY_PARAM_free);
param_table = NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-295/c/bad_682_0 |
crossvul-cpp_data_good_608_0 | /*
* Copyright © 2015 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Alexander Larsson <alexl@redhat.com>
*/
#include "config.h"
#include <unistd.h>
#include <string.h>
#include "flatpak-proxy.h"
#include <gio/gunixsocketaddress.h>
#include <gio/gunixconnection.h>
#include <gio/gunixfdmessage.h>
/**
* The proxy listens to a unix domain socket, and for each new
* connection it opens up a new connection to a specified dbus bus
* address (typically the session bus) and forwards data between the
* two. During the authentication phase all data is forwarded as
* received, and additionally for the first 1 byte zero we also send
* the proxy credentials to the bus.
*
* Once the connection is authenticated there are two modes, filtered
* and unfiltered. In the unfiltered mode we just send all messages on
* as we receive, but in the in the filtering mode we apply a policy,
* which is similar to the policy supported by kdbus.
*
* The policy for the filtering consists of a mapping from well-known
* names to a policy that is either SEE, TALK or OWN. The default
* initial policy is that the the user is only allowed to TALK to the
* bus itself (org.freedesktop.DBus, or no destination specified), and
* TALK to its own unique id. All other clients are invisible. The
* well-known names can be specified exactly, or as a simple one-level
* wildcard like "org.foo.*" which matches "org.foo.bar", but not
* "org.foobar" or "org.foo.bar.gazonk".
*
* Polices are specified for well-known names, but they also affect
* the owner of that name, so that the policy for a unique id is the
* superset of the polices for all the names it owns. Due to technical
* reasons the policy for a unique name is "sticky", in that we keep
* the highest policy granted by a once-owned name even when the client
* releases that name. This is impossible to avoid in a race-free way
* in a proxy. But this is rarely a problem in practice, as clients
* rarely release names and stay on the bus.
*
* Here is a description of the policy levels:
* (all policy levels also imply the ones before it)
*
* SEE:
* The name/id is visible in the ListNames reply
* The name/id is visible in the ListActivatableNames reply
* You can call GetNameOwner on the name
* You can call NameHasOwner on the name
* You see NameOwnerChanged signals on the name
* You see NameOwnerChanged signals on the id when the client disconnects
* You can call the GetXXX methods on the name/id to get e.g. the peer pid
* You get AccessDenied rather than NameHasNoOwner when sending messages to the name/id
*
* FILTERED:
* You can send *some* method calls to the name (not id)
*
* TALK:
* You can send any method calls and signals to the name/id
* You will receive broadcast signals from the name/id (if you have a match rule for them)
* You can call StartServiceByName on the name
*
* OWN:
* You are allowed to call RequestName/ReleaseName/ListQueuedOwners on the name.
*
* The policy applies only to signals and method calls. All replies
* (errors or method returns) are allowed once for an outstanding
* method call, and never otherwise.
*
* Every peer on the bus is considered priviledged, and we thus trust
* it. So we rely on similar proxies to be running for all untrusted
* clients. Any such priviledged peer is allowed to send method call
* or unicast signal messages to the proxied client. Once another peer
* sends you a message the unique id of that peer is now made visible
* (policy SEE) to the proxied client, allowing the client to track
* caller lifetimes via NameOwnerChanged signals.
*
* Differences to kdbus custom endpoint policies:
*
* * The proxy will return the credentials (like pid) of the proxy,
* not the real client.
*
* * Policy is not dropped when a peer releases a name.
*
* * Peers that call you become visible (SEE) (and get signals for
* NameOwnerChange disconnect) In kdbus currently custom endpoints
* never get NameOwnerChange signals for unique ids, but this is
* problematic as it disallows a services to track lifetimes of its
* clients.
*
* Mode of operation
*
* Once authenticated we receive incoming messages one at a time,
* and then we demarshal the message headers to make routing decisions.
* This means we trust the bus to do message format validation, etc.
* (because we don't parse the body). Also we assume that the bus verifies
* reply_serials, i.e. that a reply can only be sent once and by the real
* recipient of an previously sent method call.
*
* We don't however trust the serials from the client. We verify that
* they are strictly increasing to make sure the code is not confused
* by serials being reused.
*
* In order to track the ownership of the allowed names we hijack the
* connection after the initial Hello message, sending AddMatch,
* ListNames and GetNameOwner messages to get a proper view of who
* owns the names atm. Then we listen to NameOwnerChanged events for
* further updates. This causes a slight offset between serials in the
* client and serials as seen by the bus.
*
* After that the filter is strictly passive, in that we never
* construct our own requests. For each message received from the
* client we look up the type and the destination policy and make a
* decision to either pass it on as is, rewrite it before passing on
* (for instance ListName replies), drop it completely, or return a
* made-up reply/error to the sender.
*
* When returning a made-up reply we replace the actual message with a
* Ping request to the bus with the same serial and replace the resulting
* reply with the made up reply (with the serial from the Ping reply).
* This means we keep the strict message ordering and serial numbers of
* the bus.
*
* Policy is applied to unique ids in the following cases:
* * During startup we call AddWatch for signals on all policy names
* and wildcards (using arg0namespace) so that we get NameOwnerChanged
* events which we use to update the unique id policies.
* * During startup we create synthetic GetNameOwner requests for all
* normal policy names, and if there are wildcarded names we create a
* synthetic ListNames request and use the results of that to do further
* GetNameOwner for the existing names matching the wildcards. When we get
* replies for the GetNameOwner requests the unique id policy is updated.
* * When we get a method call from a unique id, it gets SEE
* * When we get a reply to the initial Hello request we give
* our own assigned unique id policy TALK.
*
* All messages sent to the bus itself are fully demarshalled
* and handled on a per-method basis:
*
* Hello, AddMatch, RemoveMatch, GetId: Always allowed
* ListNames, ListActivatableNames: Always allowed, but response filtered
* UpdateActivationEnvironment, BecomeMonitor: Always denied
* RequestName, ReleaseName, ListQueuedOwners: Only allowed if arg0 is a name with policy OWN
* NameHasOwner, GetNameOwner: Only pass on if arg0 is a name with policy SEE, otherwise return synthetic reply
* StartServiceByName: Only allowed if policy TALK on arg0
* GetConnectionUnixProcessID, GetConnectionCredentials,
* GetAdtAuditSessionData, GetConnectionSELinuxSecurityContext,
* GetConnectionUnixUser: Allowed if policy SEE on arg0
*
* For unknown methods, we return a synthetic error.
*/
typedef struct FlatpakProxyClient FlatpakProxyClient;
#define FIND_AUTH_END_CONTINUE -1
#define FIND_AUTH_END_ABORT -2
#define AUTH_LINE_SENTINEL "\r\n"
#define AUTH_BEGIN "BEGIN"
typedef enum {
EXPECTED_REPLY_NONE,
EXPECTED_REPLY_NORMAL,
EXPECTED_REPLY_HELLO,
EXPECTED_REPLY_FILTER,
EXPECTED_REPLY_FAKE_GET_NAME_OWNER,
EXPECTED_REPLY_FAKE_LIST_NAMES,
EXPECTED_REPLY_LIST_NAMES,
EXPECTED_REPLY_REWRITE,
} ExpectedReplyType;
typedef struct
{
gsize size;
gsize pos;
int refcount;
gboolean send_credentials;
GList *control_messages;
guchar data[16];
/* data continues here */
} Buffer;
typedef struct
{
Buffer *buffer;
gboolean big_endian;
guchar type;
guchar flags;
guint32 length;
guint32 serial;
const char *path;
const char *interface;
const char *member;
const char *error_name;
const char *destination;
const char *sender;
const char *signature;
gboolean has_reply_serial;
guint32 reply_serial;
guint32 unix_fds;
} Header;
typedef struct
{
char *path;
char *interface;
char *member;
} Filter;
static void header_free (Header *header);
G_DEFINE_AUTOPTR_CLEANUP_FUNC (Header, header_free)
typedef struct
{
gboolean got_first_byte; /* always true on bus side */
gboolean closed; /* always true on bus side */
FlatpakProxyClient *client;
GSocketConnection *connection;
GSource *in_source;
GSource *out_source;
GBytes *extra_input_data;
Buffer *current_read_buffer;
Buffer header_buffer;
GList *buffers; /* to be sent */
GList *control_messages;
GHashTable *expected_replies;
} ProxySide;
struct FlatpakProxyClient
{
GObject parent;
FlatpakProxy *proxy;
gboolean authenticated;
GByteArray *auth_buffer;
ProxySide client_side;
ProxySide bus_side;
/* Filtering data: */
guint32 serial_offset;
guint32 hello_serial;
guint32 last_serial;
GHashTable *rewrite_reply;
GHashTable *get_owner_reply;
GHashTable *unique_id_policy;
};
typedef struct
{
GObjectClass parent_class;
} FlatpakProxyClientClass;
struct FlatpakProxy
{
GSocketService parent;
gboolean log_messages;
GList *clients;
char *socket_path;
char *dbus_address;
gboolean filter;
gboolean sloppy_names;
GHashTable *wildcard_policy;
GHashTable *policy;
GHashTable *filters;
};
typedef struct
{
GSocketServiceClass parent_class;
} FlatpakProxyClass;
enum {
PROP_0,
PROP_DBUS_ADDRESS,
PROP_SOCKET_PATH
};
#define FLATPAK_TYPE_PROXY flatpak_proxy_get_type ()
#define FLATPAK_PROXY(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), FLATPAK_TYPE_PROXY, FlatpakProxy))
#define FLATPAK_IS_PROXY(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), FLATPAK_TYPE_PROXY))
#define FLATPAK_TYPE_PROXY_CLIENT flatpak_proxy_client_get_type ()
#define FLATPAK_PROXY_CLIENT(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), FLATPAK_TYPE_PROXY_CLIENT, FlatpakProxyClient))
#define FLATPAK_IS_PROXY_CLIENT(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), FLATPAK_TYPE_PROXY_CLIENT))
GType flatpak_proxy_client_get_type (void);
G_DEFINE_TYPE (FlatpakProxy, flatpak_proxy, G_TYPE_SOCKET_SERVICE)
G_DEFINE_TYPE (FlatpakProxyClient, flatpak_proxy_client, G_TYPE_OBJECT)
static void start_reading (ProxySide *side);
static void stop_reading (ProxySide *side);
static void
buffer_unref (Buffer *buffer)
{
g_assert (buffer->refcount > 0);
buffer->refcount--;
if (buffer->refcount == 0)
{
g_list_free_full (buffer->control_messages, g_object_unref);
g_free (buffer);
}
}
static Buffer *
buffer_ref (Buffer *buffer)
{
g_assert (buffer->refcount > 0);
buffer->refcount++;
return buffer;
}
static void
free_side (ProxySide *side)
{
g_clear_object (&side->connection);
g_clear_pointer (&side->extra_input_data, g_bytes_unref);
g_list_free_full (side->buffers, (GDestroyNotify) buffer_unref);
g_list_free_full (side->control_messages, (GDestroyNotify) g_object_unref);
if (side->in_source)
g_source_destroy (side->in_source);
if (side->out_source)
g_source_destroy (side->out_source);
g_hash_table_destroy (side->expected_replies);
}
static void
flatpak_proxy_client_finalize (GObject *object)
{
FlatpakProxyClient *client = FLATPAK_PROXY_CLIENT (object);
client->proxy->clients = g_list_remove (client->proxy->clients, client);
g_clear_object (&client->proxy);
g_byte_array_free (client->auth_buffer, TRUE);
g_hash_table_destroy (client->rewrite_reply);
g_hash_table_destroy (client->get_owner_reply);
g_hash_table_destroy (client->unique_id_policy);
free_side (&client->client_side);
free_side (&client->bus_side);
G_OBJECT_CLASS (flatpak_proxy_client_parent_class)->finalize (object);
}
static void
flatpak_proxy_client_class_init (FlatpakProxyClientClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->finalize = flatpak_proxy_client_finalize;
}
static void
init_side (FlatpakProxyClient *client, ProxySide *side)
{
side->got_first_byte = (side == &client->bus_side);
side->client = client;
side->header_buffer.size = 16;
side->header_buffer.pos = 0;
side->current_read_buffer = &side->header_buffer;
side->expected_replies = g_hash_table_new (g_direct_hash, g_direct_equal);
}
static void
flatpak_proxy_client_init (FlatpakProxyClient *client)
{
init_side (client, &client->client_side);
init_side (client, &client->bus_side);
client->auth_buffer = g_byte_array_new ();
client->rewrite_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref);
client->get_owner_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_free);
client->unique_id_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
}
static FlatpakProxyClient *
flatpak_proxy_client_new (FlatpakProxy *proxy, GSocketConnection *connection)
{
FlatpakProxyClient *client;
g_socket_set_blocking (g_socket_connection_get_socket (connection), FALSE);
client = g_object_new (FLATPAK_TYPE_PROXY_CLIENT, NULL);
client->proxy = g_object_ref (proxy);
client->client_side.connection = g_object_ref (connection);
proxy->clients = g_list_prepend (proxy->clients, client);
return client;
}
static FlatpakPolicy
flatpak_proxy_get_wildcard_policy (FlatpakProxy *proxy,
const char *_name)
{
guint policy, wildcard_policy = 0;
char *dot;
g_autofree char *name = g_strdup (_name);
dot = name + strlen (name);
while (dot)
{
*dot = 0;
policy = GPOINTER_TO_INT (g_hash_table_lookup (proxy->wildcard_policy, name));
wildcard_policy = MAX (wildcard_policy, policy);
dot = strrchr (name, '.');
}
return wildcard_policy;
}
static FlatpakPolicy
flatpak_proxy_get_policy (FlatpakProxy *proxy,
const char *name)
{
guint policy, wildcard_policy;
policy = GPOINTER_TO_INT (g_hash_table_lookup (proxy->policy, name));
wildcard_policy = flatpak_proxy_get_wildcard_policy (proxy, name);
return MAX (policy, wildcard_policy);
}
void
flatpak_proxy_set_filter (FlatpakProxy *proxy,
gboolean filter)
{
proxy->filter = filter;
}
void
flatpak_proxy_set_sloppy_names (FlatpakProxy *proxy,
gboolean sloppy_names)
{
proxy->sloppy_names = sloppy_names;
}
void
flatpak_proxy_set_log_messages (FlatpakProxy *proxy,
gboolean log)
{
proxy->log_messages = log;
}
void
flatpak_proxy_add_policy (FlatpakProxy *proxy,
const char *name,
FlatpakPolicy policy)
{
guint current_policy = GPOINTER_TO_INT (g_hash_table_lookup (proxy->policy, name));
current_policy = MAX (policy, current_policy);
g_hash_table_replace (proxy->policy, g_strdup (name), GINT_TO_POINTER (current_policy));
}
void
flatpak_proxy_add_wildcarded_policy (FlatpakProxy *proxy,
const char *name,
FlatpakPolicy policy)
{
g_hash_table_replace (proxy->wildcard_policy, g_strdup (name), GINT_TO_POINTER (policy));
}
static void
filter_free (Filter *filter)
{
g_free (filter->path);
g_free (filter->interface);
g_free (filter->member);
g_free (filter);
}
static void
filter_list_free (GList *filters)
{
g_list_free_full (filters, (GDestroyNotify)filter_free);
}
/* rules are of the form [org.the.interface.[method|*]][@/obj/path] */
static Filter *
filter_new (const char *rule)
{
Filter *filter = g_new0 (Filter, 1);
const char *obj_path_start = NULL;
const char *method_end = NULL;
obj_path_start = strchr (rule, '@');
if (obj_path_start && obj_path_start[1] != 0)
filter->path = g_strdup (obj_path_start + 1);
if (obj_path_start != NULL)
method_end = obj_path_start;
else
method_end = rule + strlen(rule);
if (rule[0] != '@')
{
filter->interface = g_strndup (rule, method_end - rule);
char *dot = strrchr (filter->interface, '.');
if (dot != NULL)
{
*dot = 0;
if (strcmp (dot+1, "*") != 0)
filter->member = g_strdup (dot + 1);
}
}
return filter;
}
void
flatpak_proxy_add_filter (FlatpakProxy *proxy,
const char *name,
const char *rule)
{
Filter *filter;
GList *filters, *new_filters;
filter = filter_new (rule);
if (g_hash_table_lookup_extended (proxy->filters,
name,
NULL, (void **)&filters))
{
new_filters = g_list_append (filters, filter);
g_assert (new_filters == filters);
}
else
{
filters = g_list_append (NULL, filter);
g_hash_table_insert (proxy->filters, g_strdup (name), filters);
}
}
static void
flatpak_proxy_finalize (GObject *object)
{
FlatpakProxy *proxy = FLATPAK_PROXY (object);
if (g_socket_service_is_active (G_SOCKET_SERVICE (proxy)))
unlink (proxy->socket_path);
g_assert (proxy->clients == NULL);
g_hash_table_destroy (proxy->policy);
g_hash_table_destroy (proxy->wildcard_policy);
g_hash_table_destroy (proxy->filters);
g_free (proxy->socket_path);
g_free (proxy->dbus_address);
G_OBJECT_CLASS (flatpak_proxy_parent_class)->finalize (object);
}
static void
flatpak_proxy_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
FlatpakProxy *proxy = FLATPAK_PROXY (object);
switch (prop_id)
{
case PROP_DBUS_ADDRESS:
proxy->dbus_address = g_value_dup_string (value);
break;
case PROP_SOCKET_PATH:
proxy->socket_path = g_value_dup_string (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
flatpak_proxy_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
FlatpakProxy *proxy = FLATPAK_PROXY (object);
switch (prop_id)
{
case PROP_DBUS_ADDRESS:
g_value_set_string (value, proxy->dbus_address);
break;
case PROP_SOCKET_PATH:
g_value_set_string (value, proxy->socket_path);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static Buffer *
buffer_new (gsize size, Buffer *old)
{
Buffer *buffer = g_malloc0 (sizeof (Buffer) + size - 16);
buffer->control_messages = NULL;
buffer->size = size;
buffer->refcount = 1;
if (old)
{
buffer->pos = old->pos;
/* Takes ownership of any old control messages */
buffer->control_messages = old->control_messages;
old->control_messages = NULL;
g_assert (size >= old->size);
memcpy (buffer->data, old->data, old->size);
}
return buffer;
}
static ProxySide *
get_other_side (ProxySide *side)
{
FlatpakProxyClient *client = side->client;
if (side == &client->client_side)
return &client->bus_side;
return &client->client_side;
}
static void
side_closed (ProxySide *side)
{
GSocket *socket, *other_socket;
ProxySide *other_side = get_other_side (side);
if (side->closed)
return;
socket = g_socket_connection_get_socket (side->connection);
g_socket_close (socket, NULL);
side->closed = TRUE;
other_socket = g_socket_connection_get_socket (other_side->connection);
if (!other_side->closed && other_side->buffers == NULL)
{
g_socket_close (other_socket, NULL);
other_side->closed = TRUE;
}
if (other_side->closed)
{
g_object_unref (side->client);
}
else
{
GError *error = NULL;
if (!g_socket_shutdown (other_socket, TRUE, FALSE, &error))
{
g_warning ("Unable to shutdown read side: %s", error->message);
g_error_free (error);
}
}
}
static gboolean
buffer_read (ProxySide *side,
Buffer *buffer,
GSocket *socket)
{
gssize res;
GInputVector v;
GError *error = NULL;
GSocketControlMessage **messages;
int num_messages, i;
if (side->extra_input_data)
{
gsize extra_size;
const guchar *extra_bytes = g_bytes_get_data (side->extra_input_data, &extra_size);
res = MIN (extra_size, buffer->size - buffer->pos);
memcpy (&buffer->data[buffer->pos], extra_bytes, res);
if (res < extra_size)
{
side->extra_input_data =
g_bytes_new_with_free_func (extra_bytes + res,
extra_size - res,
(GDestroyNotify) g_bytes_unref,
side->extra_input_data);
}
else
{
g_clear_pointer (&side->extra_input_data, g_bytes_unref);
}
}
else
{
int flags = 0;
v.buffer = &buffer->data[buffer->pos];
v.size = buffer->size - buffer->pos;
res = g_socket_receive_message (socket, NULL, &v, 1,
&messages,
&num_messages,
&flags, NULL, &error);
if (res < 0 && g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
{
g_error_free (error);
return FALSE;
}
if (res <= 0)
{
if (res != 0)
{
g_debug ("Error reading from socket: %s", error->message);
g_error_free (error);
}
side_closed (side);
return FALSE;
}
for (i = 0; i < num_messages; i++)
buffer->control_messages = g_list_append (buffer->control_messages, messages[i]);
g_free (messages);
}
buffer->pos += res;
return TRUE;
}
static gboolean
buffer_write (ProxySide *side,
Buffer *buffer,
GSocket *socket)
{
gssize res;
GOutputVector v;
GError *error = NULL;
GSocketControlMessage **messages = NULL;
int i, n_messages;
GList *l;
if (buffer->send_credentials &&
G_IS_UNIX_CONNECTION (side->connection))
{
g_assert (buffer->size == 1);
if (!g_unix_connection_send_credentials (G_UNIX_CONNECTION (side->connection),
NULL,
&error))
{
if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
{
g_error_free (error);
return FALSE;
}
g_warning ("Error writing credentials to socket: %s", error->message);
g_error_free (error);
side_closed (side);
return FALSE;
}
buffer->pos = 1;
return TRUE;
}
n_messages = g_list_length (buffer->control_messages);
messages = g_new (GSocketControlMessage *, n_messages);
for (l = buffer->control_messages, i = 0; l != NULL; l = l->next, i++)
messages[i] = l->data;
v.buffer = &buffer->data[buffer->pos];
v.size = buffer->size - buffer->pos;
res = g_socket_send_message (socket, NULL, &v, 1,
messages, n_messages,
G_SOCKET_MSG_NONE, NULL, &error);
g_free (messages);
if (res < 0 && g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
{
g_error_free (error);
return FALSE;
}
if (res <= 0)
{
if (res < 0)
{
g_warning ("Error writing credentials to socket: %s", error->message);
g_error_free (error);
}
side_closed (side);
return FALSE;
}
g_list_free_full (buffer->control_messages, g_object_unref);
buffer->control_messages = NULL;
buffer->pos += res;
return TRUE;
}
static gboolean
side_out_cb (GSocket *socket, GIOCondition condition, gpointer user_data)
{
ProxySide *side = user_data;
FlatpakProxyClient *client = side->client;
gboolean retval = G_SOURCE_CONTINUE;
g_object_ref (client);
while (side->buffers)
{
Buffer *buffer = side->buffers->data;
if (buffer_write (side, buffer, socket))
{
if (buffer->pos == buffer->size)
{
side->buffers = g_list_delete_link (side->buffers, side->buffers);
buffer_unref (buffer);
}
}
else
{
break;
}
}
if (side->buffers == NULL)
{
ProxySide *other_side = get_other_side (side);
side->out_source = NULL;
retval = G_SOURCE_REMOVE;
if (other_side->closed)
side_closed (side);
}
g_object_unref (client);
return retval;
}
static void
queue_expected_reply (ProxySide *side, guint32 serial, ExpectedReplyType type)
{
g_hash_table_replace (side->expected_replies,
GUINT_TO_POINTER (serial),
GUINT_TO_POINTER (type));
}
static ExpectedReplyType
steal_expected_reply (ProxySide *side, guint32 serial)
{
ExpectedReplyType type;
type = GPOINTER_TO_UINT (g_hash_table_lookup (side->expected_replies,
GUINT_TO_POINTER (serial)));
if (type)
g_hash_table_remove (side->expected_replies,
GUINT_TO_POINTER (serial));
return type;
}
static void
queue_outgoing_buffer (ProxySide *side, Buffer *buffer)
{
if (side->out_source == NULL)
{
GSocket *socket;
socket = g_socket_connection_get_socket (side->connection);
side->out_source = g_socket_create_source (socket, G_IO_OUT, NULL);
g_source_set_callback (side->out_source, (GSourceFunc) side_out_cb, side, NULL);
g_source_attach (side->out_source, NULL);
g_source_unref (side->out_source);
}
buffer->pos = 0;
side->buffers = g_list_append (side->buffers, buffer);
}
static guint32
read_uint32 (Header *header, guint8 *ptr)
{
if (header->big_endian)
return GUINT32_FROM_BE (*(guint32 *) ptr);
else
return GUINT32_FROM_LE (*(guint32 *) ptr);
}
static void
write_uint32 (Header *header, guint8 *ptr, guint32 val)
{
if (header->big_endian)
*(guint32 *) ptr = GUINT32_TO_BE (val);
else
*(guint32 *) ptr = GUINT32_TO_LE (val);
}
static inline guint32
align_by_8 (guint32 offset)
{
return (offset + 8 - 1) & ~(8 - 1);
}
static inline guint32
align_by_4 (guint32 offset)
{
return (offset + 4 - 1) & ~(4 - 1);
}
static const char *
get_signature (Buffer *buffer, guint32 *offset, guint32 end_offset)
{
guint8 len;
char *str;
if (*offset >= end_offset)
return FALSE;
len = buffer->data[*offset];
(*offset)++;
if ((*offset) + len + 1 > end_offset)
return FALSE;
if (buffer->data[(*offset) + len] != 0)
return FALSE;
str = (char *) &buffer->data[(*offset)];
*offset += len + 1;
return str;
}
static const char *
get_string (Buffer *buffer, Header *header, guint32 *offset, guint32 end_offset)
{
guint8 len;
char *str;
*offset = align_by_4 (*offset);
if (*offset + 4 >= end_offset)
return FALSE;
len = read_uint32 (header, &buffer->data[*offset]);
*offset += 4;
if ((*offset) + len + 1 > end_offset)
return FALSE;
if (buffer->data[(*offset) + len] != 0)
return FALSE;
str = (char *) &buffer->data[(*offset)];
*offset += len + 1;
return str;
}
static void
header_free (Header *header)
{
if (header->buffer)
buffer_unref (header->buffer);
g_free (header);
}
static Header *
parse_header (Buffer *buffer, guint32 serial_offset, guint32 reply_serial_offset, guint32 hello_serial)
{
guint32 array_len, header_len;
guint32 offset, end_offset;
guint8 header_type;
guint32 reply_serial_pos = 0;
const char *signature;
g_autoptr(Header) header = g_new0 (Header, 1);
header->buffer = buffer_ref (buffer);
if (buffer->size < 16)
return NULL;
if (buffer->data[3] != 1) /* Protocol version */
return NULL;
if (buffer->data[0] == 'B')
header->big_endian = TRUE;
else if (buffer->data[0] == 'l')
header->big_endian = FALSE;
else
return NULL;
header->type = buffer->data[1];
header->flags = buffer->data[2];
header->length = read_uint32 (header, &buffer->data[4]);
header->serial = read_uint32 (header, &buffer->data[8]);
if (header->serial == 0)
return NULL;
array_len = read_uint32 (header, &buffer->data[12]);
header_len = align_by_8 (12 + 4 + array_len);
g_assert (buffer->size >= header_len); /* We should have verified this when reading in the message */
if (header_len > buffer->size)
return NULL;
offset = 12 + 4;
end_offset = offset + array_len;
while (offset < end_offset)
{
offset = align_by_8 (offset); /* Structs must be 8 byte aligned */
if (offset >= end_offset)
return NULL;
header_type = buffer->data[offset++];
if (offset >= end_offset)
return NULL;
signature = get_signature (buffer, &offset, end_offset);
if (signature == NULL)
return NULL;
switch (header_type)
{
case G_DBUS_MESSAGE_HEADER_FIELD_INVALID:
return NULL;
case G_DBUS_MESSAGE_HEADER_FIELD_PATH:
if (strcmp (signature, "o") != 0)
return NULL;
header->path = get_string (buffer, header, &offset, end_offset);
if (header->path == NULL)
return NULL;
break;
case G_DBUS_MESSAGE_HEADER_FIELD_INTERFACE:
if (strcmp (signature, "s") != 0)
return NULL;
header->interface = get_string (buffer, header, &offset, end_offset);
if (header->interface == NULL)
return NULL;
break;
case G_DBUS_MESSAGE_HEADER_FIELD_MEMBER:
if (strcmp (signature, "s") != 0)
return NULL;
header->member = get_string (buffer, header, &offset, end_offset);
if (header->member == NULL)
return NULL;
break;
case G_DBUS_MESSAGE_HEADER_FIELD_ERROR_NAME:
if (strcmp (signature, "s") != 0)
return NULL;
header->error_name = get_string (buffer, header, &offset, end_offset);
if (header->error_name == NULL)
return NULL;
break;
case G_DBUS_MESSAGE_HEADER_FIELD_REPLY_SERIAL:
if (offset + 4 > end_offset)
return NULL;
header->has_reply_serial = TRUE;
reply_serial_pos = offset;
header->reply_serial = read_uint32 (header, &buffer->data[offset]);
offset += 4;
break;
case G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION:
if (strcmp (signature, "s") != 0)
return NULL;
header->destination = get_string (buffer, header, &offset, end_offset);
if (header->destination == NULL)
return NULL;
break;
case G_DBUS_MESSAGE_HEADER_FIELD_SENDER:
if (strcmp (signature, "s") != 0)
return NULL;
header->sender = get_string (buffer, header, &offset, end_offset);
if (header->sender == NULL)
return NULL;
break;
case G_DBUS_MESSAGE_HEADER_FIELD_SIGNATURE:
if (strcmp (signature, "g") != 0)
return NULL;
header->signature = get_signature (buffer, &offset, end_offset);
if (header->signature == NULL)
return NULL;
break;
case G_DBUS_MESSAGE_HEADER_FIELD_NUM_UNIX_FDS:
if (offset + 4 > end_offset)
return NULL;
header->unix_fds = read_uint32 (header, &buffer->data[offset]);
offset += 4;
break;
default:
/* Unknown header field, for safety, fail parse */
return NULL;
}
}
switch (header->type)
{
case G_DBUS_MESSAGE_TYPE_METHOD_CALL:
if (header->path == NULL || header->member == NULL)
return NULL;
break;
case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
if (!header->has_reply_serial)
return NULL;
break;
case G_DBUS_MESSAGE_TYPE_ERROR:
if (header->error_name == NULL || !header->has_reply_serial)
return NULL;
break;
case G_DBUS_MESSAGE_TYPE_SIGNAL:
if (header->path == NULL ||
header->interface == NULL ||
header->member == NULL)
return NULL;
if (strcmp (header->path, "/org/freedesktop/DBus/Local") == 0 ||
strcmp (header->interface, "org.freedesktop.DBus.Local") == 0)
return NULL;
break;
default:
/* Unknown message type, for safety, fail parse */
return NULL;
}
if (serial_offset > 0)
{
header->serial += serial_offset;
write_uint32 (header, &buffer->data[8], header->serial);
}
if (reply_serial_offset > 0 &&
header->has_reply_serial &&
header->reply_serial > hello_serial + reply_serial_offset)
write_uint32 (header, &buffer->data[reply_serial_pos], header->reply_serial - reply_serial_offset);
return g_steal_pointer (&header);
}
static void
print_outgoing_header (Header *header)
{
switch (header->type)
{
case G_DBUS_MESSAGE_TYPE_METHOD_CALL:
g_print ("C%d: -> %s call %s.%s at %s\n",
header->serial,
header->destination ? header->destination : "(no dest)",
header->interface ? header->interface : "",
header->member ? header->member : "",
header->path ? header->path : "");
break;
case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
g_print ("C%d: -> %s return from B%d\n",
header->serial,
header->destination ? header->destination : "(no dest)",
header->reply_serial);
break;
case G_DBUS_MESSAGE_TYPE_ERROR:
g_print ("C%d: -> %s return error %s from B%d\n",
header->serial,
header->destination ? header->destination : "(no dest)",
header->error_name ? header->error_name : "(no error)",
header->reply_serial);
break;
case G_DBUS_MESSAGE_TYPE_SIGNAL:
g_print ("C%d: -> %s signal %s.%s at %s\n",
header->serial,
header->destination ? header->destination : "all",
header->interface ? header->interface : "",
header->member ? header->member : "",
header->path ? header->path : "");
break;
default:
g_print ("unknown message type\n");
}
}
static void
print_incoming_header (Header *header)
{
switch (header->type)
{
case G_DBUS_MESSAGE_TYPE_METHOD_CALL:
g_print ("B%d: <- %s call %s.%s at %s\n",
header->serial,
header->sender ? header->sender : "(no sender)",
header->interface ? header->interface : "",
header->member ? header->member : "",
header->path ? header->path : "");
break;
case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
g_print ("B%d: <- %s return from C%d\n",
header->serial,
header->sender ? header->sender : "(no sender)",
header->reply_serial);
break;
case G_DBUS_MESSAGE_TYPE_ERROR:
g_print ("B%d: <- %s return error %s from C%d\n",
header->serial,
header->sender ? header->sender : "(no sender)",
header->error_name ? header->error_name : "(no error)",
header->reply_serial);
break;
case G_DBUS_MESSAGE_TYPE_SIGNAL:
g_print ("B%d: <- %s signal %s.%s at %s\n",
header->serial,
header->sender ? header->sender : "(no sender)",
header->interface ? header->interface : "",
header->member ? header->member : "",
header->path ? header->path : "");
break;
default:
g_print ("unknown message type\n");
}
}
static FlatpakPolicy
flatpak_proxy_client_get_policy (FlatpakProxyClient *client, const char *source)
{
if (source == NULL)
return FLATPAK_POLICY_TALK; /* All clients can talk to the bus itself */
if (source[0] == ':')
return GPOINTER_TO_UINT (g_hash_table_lookup (client->unique_id_policy, source));
return flatpak_proxy_get_policy (client->proxy, source);
}
static void
flatpak_proxy_client_update_unique_id_policy (FlatpakProxyClient *client,
const char *unique_id,
FlatpakPolicy policy)
{
if (policy > FLATPAK_POLICY_NONE)
{
FlatpakPolicy old_policy;
old_policy = GPOINTER_TO_UINT (g_hash_table_lookup (client->unique_id_policy, unique_id));
if (policy > old_policy)
g_hash_table_replace (client->unique_id_policy, g_strdup (unique_id), GINT_TO_POINTER (policy));
}
}
static void
flatpak_proxy_client_update_unique_id_policy_from_name (FlatpakProxyClient *client,
const char *unique_id,
const char *as_name)
{
flatpak_proxy_client_update_unique_id_policy (client,
unique_id,
flatpak_proxy_get_policy (client->proxy, as_name));
}
static gboolean
client_message_generates_reply (Header *header)
{
switch (header->type)
{
case G_DBUS_MESSAGE_TYPE_METHOD_CALL:
return (header->flags & G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED) == 0;
case G_DBUS_MESSAGE_TYPE_SIGNAL:
case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
case G_DBUS_MESSAGE_TYPE_ERROR:
default:
return FALSE;
}
}
static Buffer *
message_to_buffer (GDBusMessage *message)
{
Buffer *buffer;
guchar *blob;
gsize blob_size;
blob = g_dbus_message_to_blob (message, &blob_size, G_DBUS_CAPABILITY_FLAGS_NONE, NULL);
buffer = buffer_new (blob_size, NULL);
memcpy (buffer->data, blob, blob_size);
g_free (blob);
return buffer;
}
static GDBusMessage *
get_error_for_header (FlatpakProxyClient *client, Header *header, const char *error)
{
GDBusMessage *reply;
reply = g_dbus_message_new ();
g_dbus_message_set_message_type (reply, G_DBUS_MESSAGE_TYPE_ERROR);
g_dbus_message_set_flags (reply, G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED);
g_dbus_message_set_reply_serial (reply, header->serial - client->serial_offset);
g_dbus_message_set_error_name (reply, error);
g_dbus_message_set_body (reply, g_variant_new ("(s)", error));
return reply;
}
static GDBusMessage *
get_bool_reply_for_header (FlatpakProxyClient *client, Header *header, gboolean val)
{
GDBusMessage *reply;
reply = g_dbus_message_new ();
g_dbus_message_set_message_type (reply, G_DBUS_MESSAGE_TYPE_METHOD_RETURN);
g_dbus_message_set_flags (reply, G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED);
g_dbus_message_set_reply_serial (reply, header->serial - client->serial_offset);
g_dbus_message_set_body (reply, g_variant_new ("(b)", val));
return reply;
}
static Buffer *
get_ping_buffer_for_header (Header *header)
{
Buffer *buffer;
GDBusMessage *dummy;
dummy = g_dbus_message_new_method_call (NULL, "/", "org.freedesktop.DBus.Peer", "Ping");
g_dbus_message_set_serial (dummy, header->serial);
g_dbus_message_set_flags (dummy, header->flags);
buffer = message_to_buffer (dummy);
g_object_unref (dummy);
return buffer;
}
static Buffer *
get_error_for_roundtrip (FlatpakProxyClient *client, Header *header, const char *error_name)
{
Buffer *ping_buffer = get_ping_buffer_for_header (header);
GDBusMessage *reply;
reply = get_error_for_header (client, header, error_name);
g_hash_table_replace (client->rewrite_reply, GINT_TO_POINTER (header->serial), reply);
return ping_buffer;
}
static Buffer *
get_bool_reply_for_roundtrip (FlatpakProxyClient *client, Header *header, gboolean val)
{
Buffer *ping_buffer = get_ping_buffer_for_header (header);
GDBusMessage *reply;
reply = get_bool_reply_for_header (client, header, val);
g_hash_table_replace (client->rewrite_reply, GINT_TO_POINTER (header->serial), reply);
return ping_buffer;
}
typedef enum {
HANDLE_PASS,
HANDLE_DENY,
HANDLE_HIDE,
HANDLE_FILTER_NAME_LIST_REPLY,
HANDLE_FILTER_HAS_OWNER_REPLY,
HANDLE_FILTER_GET_OWNER_REPLY,
HANDLE_VALIDATE_OWN,
HANDLE_VALIDATE_SEE,
HANDLE_VALIDATE_TALK,
HANDLE_VALIDATE_MATCH,
} BusHandler;
static gboolean
is_for_bus (Header *header)
{
return g_strcmp0 (header->destination, "org.freedesktop.DBus") == 0;
}
static gboolean
is_dbus_method_call (Header *header)
{
return
is_for_bus (header) &&
header->type == G_DBUS_MESSAGE_TYPE_METHOD_CALL &&
g_strcmp0 (header->interface, "org.freedesktop.DBus") == 0;
}
static gboolean
is_introspection_call (Header *header)
{
return
header->type == G_DBUS_MESSAGE_TYPE_METHOD_CALL &&
g_strcmp0 (header->interface, "org.freedesktop.DBus.Introspectable") == 0;
}
static BusHandler
get_dbus_method_handler (FlatpakProxyClient *client, Header *header)
{
FlatpakPolicy policy;
const char *method;
if (header->has_reply_serial)
{
ExpectedReplyType expected_reply =
steal_expected_reply (&client->bus_side,
header->reply_serial);
if (expected_reply == EXPECTED_REPLY_NONE)
return HANDLE_DENY;
return HANDLE_PASS;
}
policy = flatpak_proxy_client_get_policy (client, header->destination);
if (policy < FLATPAK_POLICY_SEE)
return HANDLE_HIDE;
if (policy < FLATPAK_POLICY_FILTERED)
return HANDLE_DENY;
if (policy == FLATPAK_POLICY_FILTERED)
{
GList *filters = NULL, *l;
if (header->destination)
filters = g_hash_table_lookup (client->proxy->filters, header->destination);
for (l = filters; l != NULL; l = l->next)
{
Filter *filter = l->data;
if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_CALL &&
(filter->path == NULL || g_strcmp0 (filter->path, header->path) == 0) &&
(filter->interface == NULL || g_strcmp0 (filter->interface, header->interface) == 0) &&
(filter->member == NULL || g_strcmp0 (filter->member, header->member) == 0))
return HANDLE_PASS;
}
return HANDLE_DENY;
}
if (!is_for_bus (header))
return HANDLE_PASS;
if (is_introspection_call (header))
{
return HANDLE_PASS;
}
else if (is_dbus_method_call (header))
{
method = header->member;
if (method == NULL)
return HANDLE_DENY;
if (strcmp (method, "AddMatch") == 0)
return HANDLE_VALIDATE_MATCH;
if (strcmp (method, "Hello") == 0 ||
strcmp (method, "RemoveMatch") == 0 ||
strcmp (method, "GetId") == 0)
return HANDLE_PASS;
if (strcmp (method, "UpdateActivationEnvironment") == 0 ||
strcmp (method, "BecomeMonitor") == 0)
return HANDLE_DENY;
if (strcmp (method, "RequestName") == 0 ||
strcmp (method, "ReleaseName") == 0 ||
strcmp (method, "ListQueuedOwners") == 0)
return HANDLE_VALIDATE_OWN;
if (strcmp (method, "NameHasOwner") == 0)
return HANDLE_FILTER_HAS_OWNER_REPLY;
if (strcmp (method, "GetNameOwner") == 0)
return HANDLE_FILTER_GET_OWNER_REPLY;
if (strcmp (method, "GetConnectionUnixProcessID") == 0 ||
strcmp (method, "GetConnectionCredentials") == 0 ||
strcmp (method, "GetAdtAuditSessionData") == 0 ||
strcmp (method, "GetConnectionSELinuxSecurityContext") == 0 ||
strcmp (method, "GetConnectionUnixUser") == 0)
return HANDLE_VALIDATE_SEE;
if (strcmp (method, "StartServiceByName") == 0)
return HANDLE_VALIDATE_TALK;
if (strcmp (method, "ListNames") == 0 ||
strcmp (method, "ListActivatableNames") == 0)
return HANDLE_FILTER_NAME_LIST_REPLY;
g_warning ("Unknown bus method %s", method);
return HANDLE_DENY;
}
else
{
return HANDLE_DENY;
}
}
static FlatpakPolicy
policy_from_handler (BusHandler handler)
{
switch (handler)
{
case HANDLE_VALIDATE_OWN:
return FLATPAK_POLICY_OWN;
case HANDLE_VALIDATE_TALK:
return FLATPAK_POLICY_TALK;
case HANDLE_VALIDATE_SEE:
return FLATPAK_POLICY_SEE;
default:
return FLATPAK_POLICY_NONE;
}
}
static char *
get_arg0_string (Buffer *buffer)
{
GDBusMessage *message = g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
GVariant *body;
g_autoptr(GVariant) arg0 = NULL;
char *name = NULL;
if (message != NULL &&
(body = g_dbus_message_get_body (message)) != NULL &&
(arg0 = g_variant_get_child_value (body, 0)) != NULL &&
g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING))
name = g_variant_dup_string (arg0, NULL);
g_object_unref (message);
return name;
}
static gboolean
validate_arg0_match (FlatpakProxyClient *client, Buffer *buffer)
{
GDBusMessage *message = g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
GVariant *body, *arg0;
const char *match;
gboolean res = TRUE;
if (message != NULL &&
(body = g_dbus_message_get_body (message)) != NULL &&
(arg0 = g_variant_get_child_value (body, 0)) != NULL &&
g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING))
{
match = g_variant_get_string (arg0, NULL);
if (strstr (match, "eavesdrop=") != NULL)
res = FALSE;
}
g_object_unref (message);
return res;
}
static gboolean
validate_arg0_name (FlatpakProxyClient *client, Buffer *buffer, FlatpakPolicy required_policy, FlatpakPolicy *has_policy)
{
GDBusMessage *message = g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
GVariant *body, *arg0;
const char *name;
FlatpakPolicy name_policy;
gboolean res = FALSE;
if (has_policy)
*has_policy = FLATPAK_POLICY_NONE;
if (message != NULL &&
(body = g_dbus_message_get_body (message)) != NULL &&
(arg0 = g_variant_get_child_value (body, 0)) != NULL &&
g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING))
{
name = g_variant_get_string (arg0, NULL);
name_policy = flatpak_proxy_client_get_policy (client, name);
if (has_policy)
*has_policy = name_policy;
if (name_policy >= required_policy)
res = TRUE;
else if (client->proxy->log_messages)
g_print ("Filtering message due to arg0 %s, policy: %d (required %d)\n", name, name_policy, required_policy);
}
g_object_unref (message);
return res;
}
static Buffer *
filter_names_list (FlatpakProxyClient *client, Buffer *buffer)
{
GDBusMessage *message = g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
GVariant *body, *arg0, *new_names;
const gchar **names;
int i;
GVariantBuilder builder;
Buffer *filtered;
if (message == NULL ||
(body = g_dbus_message_get_body (message)) == NULL ||
(arg0 = g_variant_get_child_value (body, 0)) == NULL ||
!g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING_ARRAY))
return NULL;
names = g_variant_get_strv (arg0, NULL);
g_variant_builder_init (&builder, G_VARIANT_TYPE_STRING_ARRAY);
for (i = 0; names[i] != NULL; i++)
{
if (flatpak_proxy_client_get_policy (client, names[i]) >= FLATPAK_POLICY_SEE)
g_variant_builder_add (&builder, "s", names[i]);
}
g_free (names);
new_names = g_variant_builder_end (&builder);
g_dbus_message_set_body (message,
g_variant_new_tuple (&new_names, 1));
filtered = message_to_buffer (message);
g_object_unref (message);
return filtered;
}
static gboolean
message_is_name_owner_changed (FlatpakProxyClient *client, Header *header)
{
if (header->type == G_DBUS_MESSAGE_TYPE_SIGNAL &&
g_strcmp0 (header->sender, "org.freedesktop.DBus") == 0 &&
g_strcmp0 (header->interface, "org.freedesktop.DBus") == 0 &&
g_strcmp0 (header->member, "NameOwnerChanged") == 0)
return TRUE;
return FALSE;
}
static gboolean
should_filter_name_owner_changed (FlatpakProxyClient *client, Buffer *buffer)
{
GDBusMessage *message = g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
GVariant *body, *arg0, *arg1, *arg2;
const gchar *name, *old, *new;
gboolean filter = TRUE;
if (message == NULL ||
(body = g_dbus_message_get_body (message)) == NULL ||
(arg0 = g_variant_get_child_value (body, 0)) == NULL ||
!g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING) ||
(arg1 = g_variant_get_child_value (body, 1)) == NULL ||
!g_variant_is_of_type (arg1, G_VARIANT_TYPE_STRING) ||
(arg2 = g_variant_get_child_value (body, 2)) == NULL ||
!g_variant_is_of_type (arg2, G_VARIANT_TYPE_STRING))
return TRUE;
name = g_variant_get_string (arg0, NULL);
old = g_variant_get_string (arg1, NULL);
new = g_variant_get_string (arg2, NULL);
if (flatpak_proxy_client_get_policy (client, name) >= FLATPAK_POLICY_SEE ||
(client->proxy->sloppy_names && name[0] == ':'))
{
if (name[0] != ':')
{
if (old[0] != 0)
flatpak_proxy_client_update_unique_id_policy_from_name (client, old, name);
if (new[0] != 0)
flatpak_proxy_client_update_unique_id_policy_from_name (client, new, name);
}
filter = FALSE;
}
g_object_unref (message);
return filter;
}
static GList *
side_get_n_unix_fds (ProxySide *side, int n_fds)
{
GList *res = NULL;
while (side->control_messages != NULL)
{
GSocketControlMessage *control_message = side->control_messages->data;
if (G_IS_UNIX_FD_MESSAGE (control_message))
{
GUnixFDMessage *fd_message = G_UNIX_FD_MESSAGE (control_message);
GUnixFDList *fd_list = g_unix_fd_message_get_fd_list (fd_message);
int len = g_unix_fd_list_get_length (fd_list);
/* I believe that socket control messages are never merged, and
the sender side sends only one unix-fd-list per message, so
at this point there should always be one full fd list
per requested number of fds */
if (len != n_fds)
{
g_warning ("Not right nr of fds in socket message");
return NULL;
}
side->control_messages = g_list_delete_link (side->control_messages, side->control_messages);
return g_list_append (NULL, control_message);
}
g_object_unref (control_message);
side->control_messages = g_list_delete_link (side->control_messages, side->control_messages);
}
return res;
}
static gboolean
update_socket_messages (ProxySide *side, Buffer *buffer, Header *header)
{
/* We may accidentally combine multiple control messages into one
buffer when we receive (since we can do several recvs), so we
keep a list of all we get and then only re-attach the amount
specified in the header to the buffer. */
side->control_messages = g_list_concat (side->control_messages, buffer->control_messages);
buffer->control_messages = NULL;
if (header->unix_fds > 0)
{
buffer->control_messages = side_get_n_unix_fds (side, header->unix_fds);
if (buffer->control_messages == NULL)
{
g_warning ("Not enough fds for message");
side_closed (side);
buffer_unref (buffer);
return FALSE;
}
}
return TRUE;
}
static void
queue_fake_message (FlatpakProxyClient *client, GDBusMessage *message, ExpectedReplyType reply_type)
{
Buffer *buffer;
client->last_serial++;
client->serial_offset++;
g_dbus_message_set_serial (message, client->last_serial);
buffer = message_to_buffer (message);
g_object_unref (message);
queue_outgoing_buffer (&client->bus_side, buffer);
queue_expected_reply (&client->client_side, client->last_serial, reply_type);
}
/* After the first Hello message we need to synthesize a bunch of messages to synchronize the
ownership state for the names in the policy */
static void
queue_initial_name_ops (FlatpakProxyClient *client)
{
GHashTableIter iter;
gpointer key, value;
gboolean has_wildcards = FALSE;
g_hash_table_iter_init (&iter, client->proxy->policy);
while (g_hash_table_iter_next (&iter, &key, &value))
{
const char *name = key;
GDBusMessage *message;
GVariant *match;
if (strcmp (name, "org.freedesktop.DBus") == 0)
continue;
/* AddMatch the name so we get told about ownership changes.
Do it before the GetNameOwner to avoid races */
message = g_dbus_message_new_method_call ("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "AddMatch");
match = g_variant_new_printf ("type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='%s'", name);
g_dbus_message_set_body (message, g_variant_new_tuple (&match, 1));
queue_fake_message (client, message, EXPECTED_REPLY_FILTER);
if (client->proxy->log_messages)
g_print ("C%d: -> org.freedesktop.DBus fake AddMatch for %s\n", client->last_serial, name);
/* Get the current owner of the name (if any) so we can apply policy to it */
message = g_dbus_message_new_method_call ("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "GetNameOwner");
g_dbus_message_set_body (message, g_variant_new ("(s)", name));
queue_fake_message (client, message, EXPECTED_REPLY_FAKE_GET_NAME_OWNER);
g_hash_table_replace (client->get_owner_reply, GINT_TO_POINTER (client->last_serial), g_strdup (name));
if (client->proxy->log_messages)
g_print ("C%d: -> org.freedesktop.DBus fake GetNameOwner for %s\n", client->last_serial, name);
}
/* Same for wildcard proxies. Only here we don't know the actual names to GetNameOwner for, so we have to
list all current names */
g_hash_table_iter_init (&iter, client->proxy->wildcard_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
{
const char *name = key;
GDBusMessage *message;
GVariant *match;
has_wildcards = TRUE;
/* AddMatch the name with arg0namespace so we get told about ownership changes to all subnames.
Do it before the GetNameOwner to avoid races */
message = g_dbus_message_new_method_call ("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "AddMatch");
match = g_variant_new_printf ("type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0namespace='%s'", name);
g_dbus_message_set_body (message, g_variant_new_tuple (&match, 1));
queue_fake_message (client, message, EXPECTED_REPLY_FILTER);
if (client->proxy->log_messages)
g_print ("C%d: -> org.freedesktop.DBus fake AddMatch for %s.*\n", client->last_serial, name);
}
if (has_wildcards)
{
GDBusMessage *message;
/* AddMatch the name so we get told about ownership changes.
Do it before the GetNameOwner to avoid races */
message = g_dbus_message_new_method_call ("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames");
g_dbus_message_set_body (message, g_variant_new ("()"));
queue_fake_message (client, message, EXPECTED_REPLY_FAKE_LIST_NAMES);
if (client->proxy->log_messages)
g_print ("C%d: -> org.freedesktop.DBus fake ListNames\n", client->last_serial);
/* Stop reading from the client, to avoid incoming messages fighting with the ListNames roundtrip.
We will start it again once we have handled the ListNames reply */
stop_reading (&client->client_side);
}
}
static void
queue_wildcard_initial_name_ops (FlatpakProxyClient *client, Header *header, Buffer *buffer)
{
GDBusMessage *decoded_message = g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
GVariant *body, *arg0;
if (decoded_message != NULL &&
header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN &&
(body = g_dbus_message_get_body (decoded_message)) != NULL &&
(arg0 = g_variant_get_child_value (body, 0)) != NULL &&
g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING_ARRAY))
{
const gchar **names = g_variant_get_strv (arg0, NULL);
int i;
/* Loop over all current names and get the owner for all the ones that match our wildcard
policies so that we can update the unique id policies for those */
for (i = 0; names[i] != NULL; i++)
{
const char *name = names[i];
if (name[0] != ':' &&
flatpak_proxy_get_wildcard_policy (client->proxy, name) != FLATPAK_POLICY_NONE)
{
/* Get the current owner of the name (if any) so we can apply policy to it */
GDBusMessage *message = g_dbus_message_new_method_call ("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "GetNameOwner");
g_dbus_message_set_body (message, g_variant_new ("(s)", name));
queue_fake_message (client, message, EXPECTED_REPLY_FAKE_GET_NAME_OWNER);
g_hash_table_replace (client->get_owner_reply, GINT_TO_POINTER (client->last_serial), g_strdup (name));
if (client->proxy->log_messages)
g_print ("C%d: -> org.freedesktop.DBus fake GetNameOwner for %s\n", client->last_serial, name);
}
}
g_free (names);
}
g_object_unref (decoded_message);
}
static void
got_buffer_from_client (FlatpakProxyClient *client, ProxySide *side, Buffer *buffer)
{
ExpectedReplyType expecting_reply = EXPECTED_REPLY_NONE;
if (client->authenticated && client->proxy->filter)
{
g_autoptr(Header) header = NULL;;
BusHandler handler;
/* Filter and rewrite outgoing messages as needed */
header = parse_header (buffer, client->serial_offset, 0, 0);
if (header == NULL)
{
g_warning ("Invalid message header format");
side_closed (side);
buffer_unref (buffer);
return;
}
if (!update_socket_messages (side, buffer, header))
return;
/* Make sure the client is not playing games with the serials, as that
could confuse us. */
if (header->serial <= client->last_serial)
{
g_warning ("Invalid client serial");
side_closed (side);
buffer_unref (buffer);
return;
}
client->last_serial = header->serial;
if (client->proxy->log_messages)
print_outgoing_header (header);
/* Keep track of the initial Hello request so that we can read
the reply which has our assigned unique id */
if (is_dbus_method_call (header) &&
g_strcmp0 (header->member, "Hello") == 0)
{
expecting_reply = EXPECTED_REPLY_HELLO;
client->hello_serial = header->serial;
}
handler = get_dbus_method_handler (client, header);
switch (handler)
{
case HANDLE_FILTER_HAS_OWNER_REPLY:
case HANDLE_FILTER_GET_OWNER_REPLY:
if (!validate_arg0_name (client, buffer, FLATPAK_POLICY_SEE, NULL))
{
g_clear_pointer (&buffer, buffer_unref);
if (handler == HANDLE_FILTER_GET_OWNER_REPLY)
buffer = get_error_for_roundtrip (client, header,
"org.freedesktop.DBus.Error.NameHasNoOwner");
else
buffer = get_bool_reply_for_roundtrip (client, header, FALSE);
expecting_reply = EXPECTED_REPLY_REWRITE;
break;
}
goto handle_pass;
case HANDLE_VALIDATE_MATCH:
if (!validate_arg0_match (client, buffer))
{
if (client->proxy->log_messages)
g_print ("*DENIED* (ping)\n");
g_clear_pointer (&buffer, buffer_unref);
buffer = get_error_for_roundtrip (client, header,
"org.freedesktop.DBus.Error.AccessDenied");
expecting_reply = EXPECTED_REPLY_REWRITE;
break;
}
goto handle_pass;
case HANDLE_VALIDATE_OWN:
case HANDLE_VALIDATE_SEE:
case HANDLE_VALIDATE_TALK:
{
FlatpakPolicy name_policy;
if (validate_arg0_name (client, buffer, policy_from_handler (handler), &name_policy))
goto handle_pass;
if (name_policy < (int) FLATPAK_POLICY_SEE)
goto handle_hide;
else
goto handle_deny;
}
case HANDLE_FILTER_NAME_LIST_REPLY:
expecting_reply = EXPECTED_REPLY_LIST_NAMES;
goto handle_pass;
case HANDLE_PASS:
handle_pass:
if (client_message_generates_reply (header))
{
if (expecting_reply == EXPECTED_REPLY_NONE)
expecting_reply = EXPECTED_REPLY_NORMAL;
}
break;
case HANDLE_HIDE:
handle_hide:
g_clear_pointer (&buffer, buffer_unref);
if (client_message_generates_reply (header))
{
const char *error;
if (client->proxy->log_messages)
g_print ("*HIDDEN* (ping)\n");
if ((header->destination != NULL && header->destination[0] == ':') ||
(header->flags & G_DBUS_MESSAGE_FLAGS_NO_AUTO_START) != 0)
error = "org.freedesktop.DBus.Error.NameHasNoOwner";
else
error = "org.freedesktop.DBus.Error.ServiceUnknown";
buffer = get_error_for_roundtrip (client, header, error);
expecting_reply = EXPECTED_REPLY_REWRITE;
}
else
{
if (client->proxy->log_messages)
g_print ("*HIDDEN*\n");
}
break;
default:
case HANDLE_DENY:
handle_deny:
g_clear_pointer (&buffer, buffer_unref);
if (client_message_generates_reply (header))
{
if (client->proxy->log_messages)
g_print ("*DENIED* (ping)\n");
buffer = get_error_for_roundtrip (client, header,
"org.freedesktop.DBus.Error.AccessDenied");
expecting_reply = EXPECTED_REPLY_REWRITE;
}
else
{
if (client->proxy->log_messages)
g_print ("*DENIED*\n");
}
break;
}
if (buffer != NULL && expecting_reply != EXPECTED_REPLY_NONE)
queue_expected_reply (side, header->serial, expecting_reply);
}
if (buffer)
queue_outgoing_buffer (&client->bus_side, buffer);
if (buffer != NULL && expecting_reply == EXPECTED_REPLY_HELLO)
queue_initial_name_ops (client);
}
static void
got_buffer_from_bus (FlatpakProxyClient *client, ProxySide *side, Buffer *buffer)
{
if (client->authenticated && client->proxy->filter)
{
g_autoptr(Header) header = NULL;;
GDBusMessage *rewritten;
FlatpakPolicy policy;
ExpectedReplyType expected_reply;
/* Filter and rewrite incoming messages as needed */
header = parse_header (buffer, 0, client->serial_offset, client->hello_serial);
if (header == NULL)
{
g_warning ("Invalid message header format");
buffer_unref (buffer);
side_closed (side);
return;
}
if (!update_socket_messages (side, buffer, header))
return;
if (client->proxy->log_messages)
print_incoming_header (header);
if (header->has_reply_serial)
{
expected_reply = steal_expected_reply (get_other_side (side), header->reply_serial);
/* We only allow replies we expect */
if (expected_reply == EXPECTED_REPLY_NONE)
{
if (client->proxy->log_messages)
g_print ("*Unexpected reply*\n");
buffer_unref (buffer);
return;
}
switch (expected_reply)
{
case EXPECTED_REPLY_HELLO:
/* When we get the initial reply to Hello, allow all
further communications to our own unique id. */
if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN)
{
g_autofree char *my_id = get_arg0_string (buffer);
flatpak_proxy_client_update_unique_id_policy (client, my_id, FLATPAK_POLICY_TALK);
break;
}
case EXPECTED_REPLY_REWRITE:
/* Replace a roundtrip ping with the rewritten message */
rewritten = g_hash_table_lookup (client->rewrite_reply,
GINT_TO_POINTER (header->reply_serial));
if (client->proxy->log_messages)
g_print ("*REWRITTEN*\n");
g_dbus_message_set_serial (rewritten, header->serial);
g_clear_pointer (&buffer, buffer_unref);
buffer = message_to_buffer (rewritten);
g_hash_table_remove (client->rewrite_reply,
GINT_TO_POINTER (header->reply_serial));
break;
case EXPECTED_REPLY_FAKE_LIST_NAMES:
/* This is a reply from the bus to a fake ListNames
request, request ownership of any name matching a
wildcard policy */
queue_wildcard_initial_name_ops (client, header, buffer);
/* Don't forward fake replies to the app */
if (client->proxy->log_messages)
g_print ("*SKIPPED*\n");
g_clear_pointer (&buffer, buffer_unref);
/* Start reading the clients requests now that we are done with the names */
start_reading (&client->client_side);
break;
case EXPECTED_REPLY_FAKE_GET_NAME_OWNER:
/* This is a reply from the bus to a fake GetNameOwner
request, update the policy for this unique name based on
the policy */
{
char *requested_name = g_hash_table_lookup (client->get_owner_reply, GINT_TO_POINTER (header->reply_serial));
if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN)
{
g_autofree char *owner = get_arg0_string (buffer);
flatpak_proxy_client_update_unique_id_policy_from_name (client, owner, requested_name);
}
g_hash_table_remove (client->get_owner_reply, GINT_TO_POINTER (header->reply_serial));
/* Don't forward fake replies to the app */
if (client->proxy->log_messages)
g_print ("*SKIPPED*\n");
g_clear_pointer (&buffer, buffer_unref);
break;
}
case EXPECTED_REPLY_FILTER:
if (client->proxy->log_messages)
g_print ("*SKIPPED*\n");
g_clear_pointer (&buffer, buffer_unref);
break;
case EXPECTED_REPLY_LIST_NAMES:
/* This is a reply from the bus to a ListNames request, filter
it according to the policy */
if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN)
{
Buffer *filtered_buffer;
filtered_buffer = filter_names_list (client, buffer);
g_clear_pointer (&buffer, buffer_unref);
buffer = filtered_buffer;
}
break;
case EXPECTED_REPLY_NORMAL:
break;
default:
g_warning ("Unexpected expected reply type %d", expected_reply);
}
}
else /* Not reply */
{
/* Don't allow reply types with no reply_serial */
if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN ||
header->type == G_DBUS_MESSAGE_TYPE_ERROR)
{
if (client->proxy->log_messages)
g_print ("*Invalid reply*\n");
g_clear_pointer (&buffer, buffer_unref);
}
/* We filter all NameOwnerChanged signal according to the policy */
if (message_is_name_owner_changed (client, header))
{
if (should_filter_name_owner_changed (client, buffer))
g_clear_pointer (&buffer, buffer_unref);
}
}
/* All incoming broadcast signals are filtered according to policy */
if (header->type == G_DBUS_MESSAGE_TYPE_SIGNAL && header->destination == NULL)
{
policy = flatpak_proxy_client_get_policy (client, header->sender);
if (policy < FLATPAK_POLICY_TALK)
{
if (client->proxy->log_messages)
g_print ("*FILTERED IN*\n");
g_clear_pointer (&buffer, buffer_unref);
}
}
/* We received and forwarded a message from a trusted peer. Make the policy for
this unique id SEE so that the client can track its lifetime. */
if (buffer && header->sender && header->sender[0] == ':')
flatpak_proxy_client_update_unique_id_policy (client, header->sender, FLATPAK_POLICY_SEE);
if (buffer && client_message_generates_reply (header))
queue_expected_reply (side, header->serial, EXPECTED_REPLY_NORMAL);
}
if (buffer)
queue_outgoing_buffer (&client->client_side, buffer);
}
static void
got_buffer_from_side (ProxySide *side, Buffer *buffer)
{
FlatpakProxyClient *client = side->client;
if (side == &client->client_side)
got_buffer_from_client (client, side, buffer);
else
got_buffer_from_bus (client, side, buffer);
}
#define _DBUS_ISASCII(c) ((c) != '\0' && (((c) & ~0x7f) == 0))
static gboolean
auth_line_is_valid (guint8 *line, guint8 *line_end)
{
guint8 *p;
for (p = line; p < line_end; p++)
{
if (!_DBUS_ISASCII(*p))
return FALSE;
/* Technically, the dbus spec allows all ASCII characters, but for robustness we also
fail if we see any control characters. Such low values will appear in potential attacks,
but will never happen in real sasl (where all binary data is hex encoded). */
if (*p < ' ')
return FALSE;
}
/* For robustness we require the first char of the line to be an upper case letter.
This is not technically required by the dbus spec, but all commands are upper
case, and there is no provisioning for whitespace before the command, so in practice
this is true, and this means we're not confused by e.g. initial whitespace. */
if (line[0] < 'A' || line[0] > 'Z')
return FALSE;
return TRUE;
}
static gboolean
auth_line_is_begin (guint8 *line)
{
guint8 next_char;
if (!g_str_has_prefix ((char *)line, AUTH_BEGIN))
return FALSE;
/* dbus-daemon accepts either nothing, or a whitespace followed by anything as end of auth */
next_char = line[strlen (AUTH_BEGIN)];
return (next_char == 0 ||
next_char == ' ' ||
next_char == '\t');
}
static gssize
find_auth_end (FlatpakProxyClient *client, Buffer *buffer)
{
goffset offset = 0;
gsize original_size = client->auth_buffer->len;
/* Add the new data to the remaining data from last iteration */
g_byte_array_append (client->auth_buffer, buffer->data, buffer->pos);
while (TRUE)
{
guint8 *line_start = client->auth_buffer->data + offset;
gsize remaining_data = client->auth_buffer->len - offset;
guint8 *line_end;
line_end = memmem (line_start, remaining_data,
AUTH_LINE_SENTINEL, strlen (AUTH_LINE_SENTINEL));
if (line_end) /* Found end of line */
{
offset = (line_end + strlen (AUTH_LINE_SENTINEL) - line_start);
if (!auth_line_is_valid (line_start, line_end))
return FIND_AUTH_END_ABORT;
*line_end = 0;
if (auth_line_is_begin (line_start))
return offset - original_size;
/* continue with next line */
}
else
{
/* No end-of-line in this buffer */
g_byte_array_remove_range (client->auth_buffer, 0, offset);
/* Abort if more than 16k before newline, similar to what dbus-daemon does */
if (client->auth_buffer->len >= 16*1024)
return FIND_AUTH_END_ABORT;
return FIND_AUTH_END_CONTINUE;
}
}
}
static gboolean
side_in_cb (GSocket *socket, GIOCondition condition, gpointer user_data)
{
ProxySide *side = user_data;
FlatpakProxyClient *client = side->client;
GError *error = NULL;
Buffer *buffer;
gboolean retval = G_SOURCE_CONTINUE;
g_object_ref (client);
while (!side->closed)
{
if (!side->got_first_byte)
buffer = buffer_new (1, NULL);
else if (!client->authenticated)
buffer = buffer_new (64, NULL);
else
buffer = side->current_read_buffer;
if (!buffer_read (side, buffer, socket))
{
if (buffer != side->current_read_buffer)
buffer_unref (buffer);
break;
}
if (!client->authenticated)
{
if (buffer->pos > 0)
{
gboolean found_auth_end = FALSE;
gsize extra_data;
buffer->size = buffer->pos;
if (!side->got_first_byte)
{
buffer->send_credentials = TRUE;
side->got_first_byte = TRUE;
}
/* Look for end of authentication mechanism */
else if (side == &client->client_side)
{
gssize auth_end = find_auth_end (client, buffer);
if (auth_end >= 0)
{
found_auth_end = TRUE;
buffer->size = auth_end;
extra_data = buffer->pos - buffer->size;
/* We may have gotten some extra data which is not part of
the auth handshake, keep it for the next iteration. */
if (extra_data > 0)
side->extra_input_data = g_bytes_new (buffer->data + buffer->size, extra_data);
}
else if (auth_end == FIND_AUTH_END_ABORT)
{
buffer_unref (buffer);
if (client->proxy->log_messages)
g_print ("Invalid AUTH line, aborting\n");
side_closed (side);
break;
}
}
got_buffer_from_side (side, buffer);
if (found_auth_end)
client->authenticated = TRUE;
}
else
{
buffer_unref (buffer);
}
}
else if (buffer->pos == buffer->size)
{
if (buffer == &side->header_buffer)
{
gssize required;
required = g_dbus_message_bytes_needed (buffer->data, buffer->size, &error);
if (required < 0)
{
g_warning ("Invalid message header read");
side_closed (side);
}
else
{
side->current_read_buffer = buffer_new (required, buffer);
}
}
else
{
got_buffer_from_side (side, buffer);
side->header_buffer.pos = 0;
side->current_read_buffer = &side->header_buffer;
}
}
}
if (side->closed)
{
side->in_source = NULL;
retval = G_SOURCE_REMOVE;
}
g_object_unref (client);
return retval;
}
static void
start_reading (ProxySide *side)
{
GSocket *socket;
socket = g_socket_connection_get_socket (side->connection);
side->in_source = g_socket_create_source (socket, G_IO_IN, NULL);
g_source_set_callback (side->in_source, (GSourceFunc) side_in_cb, side, NULL);
g_source_attach (side->in_source, NULL);
g_source_unref (side->in_source);
}
static void
stop_reading (ProxySide *side)
{
if (side->in_source)
{
g_source_destroy (side->in_source);
side->in_source = NULL;
}
}
static void
client_connected_to_dbus (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
FlatpakProxyClient *client = user_data;
GSocketConnection *connection;
GError *error = NULL;
GIOStream *stream;
stream = g_dbus_address_get_stream_finish (res, NULL, &error);
if (stream == NULL)
{
g_warning ("Failed to connect to bus: %s", error->message);
g_object_unref (client);
return;
}
connection = G_SOCKET_CONNECTION (stream);
g_socket_set_blocking (g_socket_connection_get_socket (connection), FALSE);
client->bus_side.connection = connection;
start_reading (&client->client_side);
start_reading (&client->bus_side);
}
static gboolean
flatpak_proxy_incoming (GSocketService *service,
GSocketConnection *connection,
GObject *source_object)
{
FlatpakProxy *proxy = FLATPAK_PROXY (service);
FlatpakProxyClient *client;
client = flatpak_proxy_client_new (proxy, connection);
g_dbus_address_get_stream (proxy->dbus_address,
NULL,
client_connected_to_dbus,
client);
return TRUE;
}
static void
flatpak_proxy_init (FlatpakProxy *proxy)
{
proxy->policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
proxy->filters = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)filter_list_free);
proxy->wildcard_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
flatpak_proxy_add_policy (proxy, "org.freedesktop.DBus", FLATPAK_POLICY_TALK);
}
static void
flatpak_proxy_class_init (FlatpakProxyClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
GSocketServiceClass *socket_service_class = G_SOCKET_SERVICE_CLASS (klass);
object_class->get_property = flatpak_proxy_get_property;
object_class->set_property = flatpak_proxy_set_property;
object_class->finalize = flatpak_proxy_finalize;
socket_service_class->incoming = flatpak_proxy_incoming;
g_object_class_install_property (object_class,
PROP_DBUS_ADDRESS,
g_param_spec_string ("dbus-address",
"",
"",
NULL,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property (object_class,
PROP_SOCKET_PATH,
g_param_spec_string ("socket-path",
"",
"",
NULL,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
}
FlatpakProxy *
flatpak_proxy_new (const char *dbus_address,
const char *socket_path)
{
FlatpakProxy *proxy;
proxy = g_object_new (FLATPAK_TYPE_PROXY, "dbus-address", dbus_address, "socket-path", socket_path, NULL);
return proxy;
}
gboolean
flatpak_proxy_start (FlatpakProxy *proxy, GError **error)
{
GSocketAddress *address;
gboolean res;
unlink (proxy->socket_path);
address = g_unix_socket_address_new (proxy->socket_path);
error = NULL;
res = g_socket_listener_add_address (G_SOCKET_LISTENER (proxy),
address,
G_SOCKET_TYPE_STREAM,
G_SOCKET_PROTOCOL_DEFAULT,
NULL, /* source_object */
NULL, /* effective_address */
error);
g_object_unref (address);
if (!res)
return FALSE;
g_socket_service_start (G_SOCKET_SERVICE (proxy));
return TRUE;
}
void
flatpak_proxy_stop (FlatpakProxy *proxy)
{
unlink (proxy->socket_path);
g_socket_service_stop (G_SOCKET_SERVICE (proxy));
}
| ./CrossVul/dataset_final_sorted/CWE-436/c/good_608_0 |
crossvul-cpp_data_bad_608_0 | /*
* Copyright © 2015 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Alexander Larsson <alexl@redhat.com>
*/
#include "config.h"
#include <unistd.h>
#include <string.h>
#include "flatpak-proxy.h"
#include <gio/gunixsocketaddress.h>
#include <gio/gunixconnection.h>
#include <gio/gunixfdmessage.h>
/**
* The proxy listens to a unix domain socket, and for each new
* connection it opens up a new connection to a specified dbus bus
* address (typically the session bus) and forwards data between the
* two. During the authentication phase all data is forwarded as
* received, and additionally for the first 1 byte zero we also send
* the proxy credentials to the bus.
*
* Once the connection is authenticated there are two modes, filtered
* and unfiltered. In the unfiltered mode we just send all messages on
* as we receive, but in the in the filtering mode we apply a policy,
* which is similar to the policy supported by kdbus.
*
* The policy for the filtering consists of a mapping from well-known
* names to a policy that is either SEE, TALK or OWN. The default
* initial policy is that the the user is only allowed to TALK to the
* bus itself (org.freedesktop.DBus, or no destination specified), and
* TALK to its own unique id. All other clients are invisible. The
* well-known names can be specified exactly, or as a simple one-level
* wildcard like "org.foo.*" which matches "org.foo.bar", but not
* "org.foobar" or "org.foo.bar.gazonk".
*
* Polices are specified for well-known names, but they also affect
* the owner of that name, so that the policy for a unique id is the
* superset of the polices for all the names it owns. Due to technical
* reasons the policy for a unique name is "sticky", in that we keep
* the highest policy granted by a once-owned name even when the client
* releases that name. This is impossible to avoid in a race-free way
* in a proxy. But this is rarely a problem in practice, as clients
* rarely release names and stay on the bus.
*
* Here is a description of the policy levels:
* (all policy levels also imply the ones before it)
*
* SEE:
* The name/id is visible in the ListNames reply
* The name/id is visible in the ListActivatableNames reply
* You can call GetNameOwner on the name
* You can call NameHasOwner on the name
* You see NameOwnerChanged signals on the name
* You see NameOwnerChanged signals on the id when the client disconnects
* You can call the GetXXX methods on the name/id to get e.g. the peer pid
* You get AccessDenied rather than NameHasNoOwner when sending messages to the name/id
*
* FILTERED:
* You can send *some* method calls to the name (not id)
*
* TALK:
* You can send any method calls and signals to the name/id
* You will receive broadcast signals from the name/id (if you have a match rule for them)
* You can call StartServiceByName on the name
*
* OWN:
* You are allowed to call RequestName/ReleaseName/ListQueuedOwners on the name.
*
* The policy applies only to signals and method calls. All replies
* (errors or method returns) are allowed once for an outstanding
* method call, and never otherwise.
*
* Every peer on the bus is considered priviledged, and we thus trust
* it. So we rely on similar proxies to be running for all untrusted
* clients. Any such priviledged peer is allowed to send method call
* or unicast signal messages to the proxied client. Once another peer
* sends you a message the unique id of that peer is now made visible
* (policy SEE) to the proxied client, allowing the client to track
* caller lifetimes via NameOwnerChanged signals.
*
* Differences to kdbus custom endpoint policies:
*
* * The proxy will return the credentials (like pid) of the proxy,
* not the real client.
*
* * Policy is not dropped when a peer releases a name.
*
* * Peers that call you become visible (SEE) (and get signals for
* NameOwnerChange disconnect) In kdbus currently custom endpoints
* never get NameOwnerChange signals for unique ids, but this is
* problematic as it disallows a services to track lifetimes of its
* clients.
*
* Mode of operation
*
* Once authenticated we receive incoming messages one at a time,
* and then we demarshal the message headers to make routing decisions.
* This means we trust the bus to do message format validation, etc.
* (because we don't parse the body). Also we assume that the bus verifies
* reply_serials, i.e. that a reply can only be sent once and by the real
* recipient of an previously sent method call.
*
* We don't however trust the serials from the client. We verify that
* they are strictly increasing to make sure the code is not confused
* by serials being reused.
*
* In order to track the ownership of the allowed names we hijack the
* connection after the initial Hello message, sending AddMatch,
* ListNames and GetNameOwner messages to get a proper view of who
* owns the names atm. Then we listen to NameOwnerChanged events for
* further updates. This causes a slight offset between serials in the
* client and serials as seen by the bus.
*
* After that the filter is strictly passive, in that we never
* construct our own requests. For each message received from the
* client we look up the type and the destination policy and make a
* decision to either pass it on as is, rewrite it before passing on
* (for instance ListName replies), drop it completely, or return a
* made-up reply/error to the sender.
*
* When returning a made-up reply we replace the actual message with a
* Ping request to the bus with the same serial and replace the resulting
* reply with the made up reply (with the serial from the Ping reply).
* This means we keep the strict message ordering and serial numbers of
* the bus.
*
* Policy is applied to unique ids in the following cases:
* * During startup we call AddWatch for signals on all policy names
* and wildcards (using arg0namespace) so that we get NameOwnerChanged
* events which we use to update the unique id policies.
* * During startup we create synthetic GetNameOwner requests for all
* normal policy names, and if there are wildcarded names we create a
* synthetic ListNames request and use the results of that to do further
* GetNameOwner for the existing names matching the wildcards. When we get
* replies for the GetNameOwner requests the unique id policy is updated.
* * When we get a method call from a unique id, it gets SEE
* * When we get a reply to the initial Hello request we give
* our own assigned unique id policy TALK.
*
* All messages sent to the bus itself are fully demarshalled
* and handled on a per-method basis:
*
* Hello, AddMatch, RemoveMatch, GetId: Always allowed
* ListNames, ListActivatableNames: Always allowed, but response filtered
* UpdateActivationEnvironment, BecomeMonitor: Always denied
* RequestName, ReleaseName, ListQueuedOwners: Only allowed if arg0 is a name with policy OWN
* NameHasOwner, GetNameOwner: Only pass on if arg0 is a name with policy SEE, otherwise return synthetic reply
* StartServiceByName: Only allowed if policy TALK on arg0
* GetConnectionUnixProcessID, GetConnectionCredentials,
* GetAdtAuditSessionData, GetConnectionSELinuxSecurityContext,
* GetConnectionUnixUser: Allowed if policy SEE on arg0
*
* For unknown methods, we return a synthetic error.
*/
typedef struct FlatpakProxyClient FlatpakProxyClient;
/* We start looking ignoring the first cr-lf
since there is no previous line initially */
#define AUTH_END_INIT_OFFSET 2
#define AUTH_END_STRING "\r\nBEGIN\r\n"
typedef enum {
EXPECTED_REPLY_NONE,
EXPECTED_REPLY_NORMAL,
EXPECTED_REPLY_HELLO,
EXPECTED_REPLY_FILTER,
EXPECTED_REPLY_FAKE_GET_NAME_OWNER,
EXPECTED_REPLY_FAKE_LIST_NAMES,
EXPECTED_REPLY_LIST_NAMES,
EXPECTED_REPLY_REWRITE,
} ExpectedReplyType;
typedef struct
{
gsize size;
gsize pos;
int refcount;
gboolean send_credentials;
GList *control_messages;
guchar data[16];
/* data continues here */
} Buffer;
typedef struct
{
Buffer *buffer;
gboolean big_endian;
guchar type;
guchar flags;
guint32 length;
guint32 serial;
const char *path;
const char *interface;
const char *member;
const char *error_name;
const char *destination;
const char *sender;
const char *signature;
gboolean has_reply_serial;
guint32 reply_serial;
guint32 unix_fds;
} Header;
typedef struct
{
char *path;
char *interface;
char *member;
} Filter;
static void header_free (Header *header);
G_DEFINE_AUTOPTR_CLEANUP_FUNC (Header, header_free)
typedef struct
{
gboolean got_first_byte; /* always true on bus side */
gboolean closed; /* always true on bus side */
FlatpakProxyClient *client;
GSocketConnection *connection;
GSource *in_source;
GSource *out_source;
GBytes *extra_input_data;
Buffer *current_read_buffer;
Buffer header_buffer;
GList *buffers; /* to be sent */
GList *control_messages;
GHashTable *expected_replies;
} ProxySide;
struct FlatpakProxyClient
{
GObject parent;
FlatpakProxy *proxy;
gboolean authenticated;
int auth_end_offset;
ProxySide client_side;
ProxySide bus_side;
/* Filtering data: */
guint32 serial_offset;
guint32 hello_serial;
guint32 last_serial;
GHashTable *rewrite_reply;
GHashTable *get_owner_reply;
GHashTable *unique_id_policy;
};
typedef struct
{
GObjectClass parent_class;
} FlatpakProxyClientClass;
struct FlatpakProxy
{
GSocketService parent;
gboolean log_messages;
GList *clients;
char *socket_path;
char *dbus_address;
gboolean filter;
gboolean sloppy_names;
GHashTable *wildcard_policy;
GHashTable *policy;
GHashTable *filters;
};
typedef struct
{
GSocketServiceClass parent_class;
} FlatpakProxyClass;
enum {
PROP_0,
PROP_DBUS_ADDRESS,
PROP_SOCKET_PATH
};
#define FLATPAK_TYPE_PROXY flatpak_proxy_get_type ()
#define FLATPAK_PROXY(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), FLATPAK_TYPE_PROXY, FlatpakProxy))
#define FLATPAK_IS_PROXY(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), FLATPAK_TYPE_PROXY))
#define FLATPAK_TYPE_PROXY_CLIENT flatpak_proxy_client_get_type ()
#define FLATPAK_PROXY_CLIENT(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), FLATPAK_TYPE_PROXY_CLIENT, FlatpakProxyClient))
#define FLATPAK_IS_PROXY_CLIENT(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), FLATPAK_TYPE_PROXY_CLIENT))
GType flatpak_proxy_client_get_type (void);
G_DEFINE_TYPE (FlatpakProxy, flatpak_proxy, G_TYPE_SOCKET_SERVICE)
G_DEFINE_TYPE (FlatpakProxyClient, flatpak_proxy_client, G_TYPE_OBJECT)
static void start_reading (ProxySide *side);
static void stop_reading (ProxySide *side);
static void
buffer_unref (Buffer *buffer)
{
g_assert (buffer->refcount > 0);
buffer->refcount--;
if (buffer->refcount == 0)
{
g_list_free_full (buffer->control_messages, g_object_unref);
g_free (buffer);
}
}
static Buffer *
buffer_ref (Buffer *buffer)
{
g_assert (buffer->refcount > 0);
buffer->refcount++;
return buffer;
}
static void
free_side (ProxySide *side)
{
g_clear_object (&side->connection);
g_clear_pointer (&side->extra_input_data, g_bytes_unref);
g_list_free_full (side->buffers, (GDestroyNotify) buffer_unref);
g_list_free_full (side->control_messages, (GDestroyNotify) g_object_unref);
if (side->in_source)
g_source_destroy (side->in_source);
if (side->out_source)
g_source_destroy (side->out_source);
g_hash_table_destroy (side->expected_replies);
}
static void
flatpak_proxy_client_finalize (GObject *object)
{
FlatpakProxyClient *client = FLATPAK_PROXY_CLIENT (object);
client->proxy->clients = g_list_remove (client->proxy->clients, client);
g_clear_object (&client->proxy);
g_hash_table_destroy (client->rewrite_reply);
g_hash_table_destroy (client->get_owner_reply);
g_hash_table_destroy (client->unique_id_policy);
free_side (&client->client_side);
free_side (&client->bus_side);
G_OBJECT_CLASS (flatpak_proxy_client_parent_class)->finalize (object);
}
static void
flatpak_proxy_client_class_init (FlatpakProxyClientClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->finalize = flatpak_proxy_client_finalize;
}
static void
init_side (FlatpakProxyClient *client, ProxySide *side)
{
side->got_first_byte = (side == &client->bus_side);
side->client = client;
side->header_buffer.size = 16;
side->header_buffer.pos = 0;
side->current_read_buffer = &side->header_buffer;
side->expected_replies = g_hash_table_new (g_direct_hash, g_direct_equal);
}
static void
flatpak_proxy_client_init (FlatpakProxyClient *client)
{
init_side (client, &client->client_side);
init_side (client, &client->bus_side);
client->auth_end_offset = AUTH_END_INIT_OFFSET;
client->rewrite_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref);
client->get_owner_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_free);
client->unique_id_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
}
static FlatpakProxyClient *
flatpak_proxy_client_new (FlatpakProxy *proxy, GSocketConnection *connection)
{
FlatpakProxyClient *client;
g_socket_set_blocking (g_socket_connection_get_socket (connection), FALSE);
client = g_object_new (FLATPAK_TYPE_PROXY_CLIENT, NULL);
client->proxy = g_object_ref (proxy);
client->client_side.connection = g_object_ref (connection);
proxy->clients = g_list_prepend (proxy->clients, client);
return client;
}
static FlatpakPolicy
flatpak_proxy_get_wildcard_policy (FlatpakProxy *proxy,
const char *_name)
{
guint policy, wildcard_policy = 0;
char *dot;
g_autofree char *name = g_strdup (_name);
dot = name + strlen (name);
while (dot)
{
*dot = 0;
policy = GPOINTER_TO_INT (g_hash_table_lookup (proxy->wildcard_policy, name));
wildcard_policy = MAX (wildcard_policy, policy);
dot = strrchr (name, '.');
}
return wildcard_policy;
}
static FlatpakPolicy
flatpak_proxy_get_policy (FlatpakProxy *proxy,
const char *name)
{
guint policy, wildcard_policy;
policy = GPOINTER_TO_INT (g_hash_table_lookup (proxy->policy, name));
wildcard_policy = flatpak_proxy_get_wildcard_policy (proxy, name);
return MAX (policy, wildcard_policy);
}
void
flatpak_proxy_set_filter (FlatpakProxy *proxy,
gboolean filter)
{
proxy->filter = filter;
}
void
flatpak_proxy_set_sloppy_names (FlatpakProxy *proxy,
gboolean sloppy_names)
{
proxy->sloppy_names = sloppy_names;
}
void
flatpak_proxy_set_log_messages (FlatpakProxy *proxy,
gboolean log)
{
proxy->log_messages = log;
}
void
flatpak_proxy_add_policy (FlatpakProxy *proxy,
const char *name,
FlatpakPolicy policy)
{
guint current_policy = GPOINTER_TO_INT (g_hash_table_lookup (proxy->policy, name));
current_policy = MAX (policy, current_policy);
g_hash_table_replace (proxy->policy, g_strdup (name), GINT_TO_POINTER (current_policy));
}
void
flatpak_proxy_add_wildcarded_policy (FlatpakProxy *proxy,
const char *name,
FlatpakPolicy policy)
{
g_hash_table_replace (proxy->wildcard_policy, g_strdup (name), GINT_TO_POINTER (policy));
}
static void
filter_free (Filter *filter)
{
g_free (filter->path);
g_free (filter->interface);
g_free (filter->member);
g_free (filter);
}
static void
filter_list_free (GList *filters)
{
g_list_free_full (filters, (GDestroyNotify)filter_free);
}
/* rules are of the form [org.the.interface.[method|*]][@/obj/path] */
static Filter *
filter_new (const char *rule)
{
Filter *filter = g_new0 (Filter, 1);
const char *obj_path_start = NULL;
const char *method_end = NULL;
obj_path_start = strchr (rule, '@');
if (obj_path_start && obj_path_start[1] != 0)
filter->path = g_strdup (obj_path_start + 1);
if (obj_path_start != NULL)
method_end = obj_path_start;
else
method_end = rule + strlen(rule);
if (rule[0] != '@')
{
filter->interface = g_strndup (rule, method_end - rule);
char *dot = strrchr (filter->interface, '.');
if (dot != NULL)
{
*dot = 0;
if (strcmp (dot+1, "*") != 0)
filter->member = g_strdup (dot + 1);
}
}
return filter;
}
void
flatpak_proxy_add_filter (FlatpakProxy *proxy,
const char *name,
const char *rule)
{
Filter *filter;
GList *filters, *new_filters;
filter = filter_new (rule);
if (g_hash_table_lookup_extended (proxy->filters,
name,
NULL, (void **)&filters))
{
new_filters = g_list_append (filters, filter);
g_assert (new_filters == filters);
}
else
{
filters = g_list_append (NULL, filter);
g_hash_table_insert (proxy->filters, g_strdup (name), filters);
}
}
static void
flatpak_proxy_finalize (GObject *object)
{
FlatpakProxy *proxy = FLATPAK_PROXY (object);
if (g_socket_service_is_active (G_SOCKET_SERVICE (proxy)))
unlink (proxy->socket_path);
g_assert (proxy->clients == NULL);
g_hash_table_destroy (proxy->policy);
g_hash_table_destroy (proxy->wildcard_policy);
g_hash_table_destroy (proxy->filters);
g_free (proxy->socket_path);
g_free (proxy->dbus_address);
G_OBJECT_CLASS (flatpak_proxy_parent_class)->finalize (object);
}
static void
flatpak_proxy_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
FlatpakProxy *proxy = FLATPAK_PROXY (object);
switch (prop_id)
{
case PROP_DBUS_ADDRESS:
proxy->dbus_address = g_value_dup_string (value);
break;
case PROP_SOCKET_PATH:
proxy->socket_path = g_value_dup_string (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
flatpak_proxy_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
FlatpakProxy *proxy = FLATPAK_PROXY (object);
switch (prop_id)
{
case PROP_DBUS_ADDRESS:
g_value_set_string (value, proxy->dbus_address);
break;
case PROP_SOCKET_PATH:
g_value_set_string (value, proxy->socket_path);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static Buffer *
buffer_new (gsize size, Buffer *old)
{
Buffer *buffer = g_malloc0 (sizeof (Buffer) + size - 16);
buffer->control_messages = NULL;
buffer->size = size;
buffer->refcount = 1;
if (old)
{
buffer->pos = old->pos;
/* Takes ownership of any old control messages */
buffer->control_messages = old->control_messages;
old->control_messages = NULL;
g_assert (size >= old->size);
memcpy (buffer->data, old->data, old->size);
}
return buffer;
}
static ProxySide *
get_other_side (ProxySide *side)
{
FlatpakProxyClient *client = side->client;
if (side == &client->client_side)
return &client->bus_side;
return &client->client_side;
}
static void
side_closed (ProxySide *side)
{
GSocket *socket, *other_socket;
ProxySide *other_side = get_other_side (side);
if (side->closed)
return;
socket = g_socket_connection_get_socket (side->connection);
g_socket_close (socket, NULL);
side->closed = TRUE;
other_socket = g_socket_connection_get_socket (other_side->connection);
if (!other_side->closed && other_side->buffers == NULL)
{
g_socket_close (other_socket, NULL);
other_side->closed = TRUE;
}
if (other_side->closed)
{
g_object_unref (side->client);
}
else
{
GError *error = NULL;
if (!g_socket_shutdown (other_socket, TRUE, FALSE, &error))
{
g_warning ("Unable to shutdown read side: %s", error->message);
g_error_free (error);
}
}
}
static gboolean
buffer_read (ProxySide *side,
Buffer *buffer,
GSocket *socket)
{
gssize res;
GInputVector v;
GError *error = NULL;
GSocketControlMessage **messages;
int num_messages, i;
if (side->extra_input_data)
{
gsize extra_size;
const guchar *extra_bytes = g_bytes_get_data (side->extra_input_data, &extra_size);
res = MIN (extra_size, buffer->size - buffer->pos);
memcpy (&buffer->data[buffer->pos], extra_bytes, res);
if (res < extra_size)
{
side->extra_input_data =
g_bytes_new_with_free_func (extra_bytes + res,
extra_size - res,
(GDestroyNotify) g_bytes_unref,
side->extra_input_data);
}
else
{
g_clear_pointer (&side->extra_input_data, g_bytes_unref);
}
}
else
{
int flags = 0;
v.buffer = &buffer->data[buffer->pos];
v.size = buffer->size - buffer->pos;
res = g_socket_receive_message (socket, NULL, &v, 1,
&messages,
&num_messages,
&flags, NULL, &error);
if (res < 0 && g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
{
g_error_free (error);
return FALSE;
}
if (res <= 0)
{
if (res != 0)
{
g_debug ("Error reading from socket: %s", error->message);
g_error_free (error);
}
side_closed (side);
return FALSE;
}
for (i = 0; i < num_messages; i++)
buffer->control_messages = g_list_append (buffer->control_messages, messages[i]);
g_free (messages);
}
buffer->pos += res;
return TRUE;
}
static gboolean
buffer_write (ProxySide *side,
Buffer *buffer,
GSocket *socket)
{
gssize res;
GOutputVector v;
GError *error = NULL;
GSocketControlMessage **messages = NULL;
int i, n_messages;
GList *l;
if (buffer->send_credentials &&
G_IS_UNIX_CONNECTION (side->connection))
{
g_assert (buffer->size == 1);
if (!g_unix_connection_send_credentials (G_UNIX_CONNECTION (side->connection),
NULL,
&error))
{
if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
{
g_error_free (error);
return FALSE;
}
g_warning ("Error writing credentials to socket: %s", error->message);
g_error_free (error);
side_closed (side);
return FALSE;
}
buffer->pos = 1;
return TRUE;
}
n_messages = g_list_length (buffer->control_messages);
messages = g_new (GSocketControlMessage *, n_messages);
for (l = buffer->control_messages, i = 0; l != NULL; l = l->next, i++)
messages[i] = l->data;
v.buffer = &buffer->data[buffer->pos];
v.size = buffer->size - buffer->pos;
res = g_socket_send_message (socket, NULL, &v, 1,
messages, n_messages,
G_SOCKET_MSG_NONE, NULL, &error);
g_free (messages);
if (res < 0 && g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK))
{
g_error_free (error);
return FALSE;
}
if (res <= 0)
{
if (res < 0)
{
g_warning ("Error writing credentials to socket: %s", error->message);
g_error_free (error);
}
side_closed (side);
return FALSE;
}
g_list_free_full (buffer->control_messages, g_object_unref);
buffer->control_messages = NULL;
buffer->pos += res;
return TRUE;
}
static gboolean
side_out_cb (GSocket *socket, GIOCondition condition, gpointer user_data)
{
ProxySide *side = user_data;
FlatpakProxyClient *client = side->client;
gboolean retval = G_SOURCE_CONTINUE;
g_object_ref (client);
while (side->buffers)
{
Buffer *buffer = side->buffers->data;
if (buffer_write (side, buffer, socket))
{
if (buffer->pos == buffer->size)
{
side->buffers = g_list_delete_link (side->buffers, side->buffers);
buffer_unref (buffer);
}
}
else
{
break;
}
}
if (side->buffers == NULL)
{
ProxySide *other_side = get_other_side (side);
side->out_source = NULL;
retval = G_SOURCE_REMOVE;
if (other_side->closed)
side_closed (side);
}
g_object_unref (client);
return retval;
}
static void
queue_expected_reply (ProxySide *side, guint32 serial, ExpectedReplyType type)
{
g_hash_table_replace (side->expected_replies,
GUINT_TO_POINTER (serial),
GUINT_TO_POINTER (type));
}
static ExpectedReplyType
steal_expected_reply (ProxySide *side, guint32 serial)
{
ExpectedReplyType type;
type = GPOINTER_TO_UINT (g_hash_table_lookup (side->expected_replies,
GUINT_TO_POINTER (serial)));
if (type)
g_hash_table_remove (side->expected_replies,
GUINT_TO_POINTER (serial));
return type;
}
static void
queue_outgoing_buffer (ProxySide *side, Buffer *buffer)
{
if (side->out_source == NULL)
{
GSocket *socket;
socket = g_socket_connection_get_socket (side->connection);
side->out_source = g_socket_create_source (socket, G_IO_OUT, NULL);
g_source_set_callback (side->out_source, (GSourceFunc) side_out_cb, side, NULL);
g_source_attach (side->out_source, NULL);
g_source_unref (side->out_source);
}
buffer->pos = 0;
side->buffers = g_list_append (side->buffers, buffer);
}
static guint32
read_uint32 (Header *header, guint8 *ptr)
{
if (header->big_endian)
return GUINT32_FROM_BE (*(guint32 *) ptr);
else
return GUINT32_FROM_LE (*(guint32 *) ptr);
}
static void
write_uint32 (Header *header, guint8 *ptr, guint32 val)
{
if (header->big_endian)
*(guint32 *) ptr = GUINT32_TO_BE (val);
else
*(guint32 *) ptr = GUINT32_TO_LE (val);
}
static inline guint32
align_by_8 (guint32 offset)
{
return (offset + 8 - 1) & ~(8 - 1);
}
static inline guint32
align_by_4 (guint32 offset)
{
return (offset + 4 - 1) & ~(4 - 1);
}
static const char *
get_signature (Buffer *buffer, guint32 *offset, guint32 end_offset)
{
guint8 len;
char *str;
if (*offset >= end_offset)
return FALSE;
len = buffer->data[*offset];
(*offset)++;
if ((*offset) + len + 1 > end_offset)
return FALSE;
if (buffer->data[(*offset) + len] != 0)
return FALSE;
str = (char *) &buffer->data[(*offset)];
*offset += len + 1;
return str;
}
static const char *
get_string (Buffer *buffer, Header *header, guint32 *offset, guint32 end_offset)
{
guint8 len;
char *str;
*offset = align_by_4 (*offset);
if (*offset + 4 >= end_offset)
return FALSE;
len = read_uint32 (header, &buffer->data[*offset]);
*offset += 4;
if ((*offset) + len + 1 > end_offset)
return FALSE;
if (buffer->data[(*offset) + len] != 0)
return FALSE;
str = (char *) &buffer->data[(*offset)];
*offset += len + 1;
return str;
}
static void
header_free (Header *header)
{
if (header->buffer)
buffer_unref (header->buffer);
g_free (header);
}
static Header *
parse_header (Buffer *buffer, guint32 serial_offset, guint32 reply_serial_offset, guint32 hello_serial)
{
guint32 array_len, header_len;
guint32 offset, end_offset;
guint8 header_type;
guint32 reply_serial_pos = 0;
const char *signature;
g_autoptr(Header) header = g_new0 (Header, 1);
header->buffer = buffer_ref (buffer);
if (buffer->size < 16)
return NULL;
if (buffer->data[3] != 1) /* Protocol version */
return NULL;
if (buffer->data[0] == 'B')
header->big_endian = TRUE;
else if (buffer->data[0] == 'l')
header->big_endian = FALSE;
else
return NULL;
header->type = buffer->data[1];
header->flags = buffer->data[2];
header->length = read_uint32 (header, &buffer->data[4]);
header->serial = read_uint32 (header, &buffer->data[8]);
if (header->serial == 0)
return NULL;
array_len = read_uint32 (header, &buffer->data[12]);
header_len = align_by_8 (12 + 4 + array_len);
g_assert (buffer->size >= header_len); /* We should have verified this when reading in the message */
if (header_len > buffer->size)
return NULL;
offset = 12 + 4;
end_offset = offset + array_len;
while (offset < end_offset)
{
offset = align_by_8 (offset); /* Structs must be 8 byte aligned */
if (offset >= end_offset)
return NULL;
header_type = buffer->data[offset++];
if (offset >= end_offset)
return NULL;
signature = get_signature (buffer, &offset, end_offset);
if (signature == NULL)
return NULL;
switch (header_type)
{
case G_DBUS_MESSAGE_HEADER_FIELD_INVALID:
return NULL;
case G_DBUS_MESSAGE_HEADER_FIELD_PATH:
if (strcmp (signature, "o") != 0)
return NULL;
header->path = get_string (buffer, header, &offset, end_offset);
if (header->path == NULL)
return NULL;
break;
case G_DBUS_MESSAGE_HEADER_FIELD_INTERFACE:
if (strcmp (signature, "s") != 0)
return NULL;
header->interface = get_string (buffer, header, &offset, end_offset);
if (header->interface == NULL)
return NULL;
break;
case G_DBUS_MESSAGE_HEADER_FIELD_MEMBER:
if (strcmp (signature, "s") != 0)
return NULL;
header->member = get_string (buffer, header, &offset, end_offset);
if (header->member == NULL)
return NULL;
break;
case G_DBUS_MESSAGE_HEADER_FIELD_ERROR_NAME:
if (strcmp (signature, "s") != 0)
return NULL;
header->error_name = get_string (buffer, header, &offset, end_offset);
if (header->error_name == NULL)
return NULL;
break;
case G_DBUS_MESSAGE_HEADER_FIELD_REPLY_SERIAL:
if (offset + 4 > end_offset)
return NULL;
header->has_reply_serial = TRUE;
reply_serial_pos = offset;
header->reply_serial = read_uint32 (header, &buffer->data[offset]);
offset += 4;
break;
case G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION:
if (strcmp (signature, "s") != 0)
return NULL;
header->destination = get_string (buffer, header, &offset, end_offset);
if (header->destination == NULL)
return NULL;
break;
case G_DBUS_MESSAGE_HEADER_FIELD_SENDER:
if (strcmp (signature, "s") != 0)
return NULL;
header->sender = get_string (buffer, header, &offset, end_offset);
if (header->sender == NULL)
return NULL;
break;
case G_DBUS_MESSAGE_HEADER_FIELD_SIGNATURE:
if (strcmp (signature, "g") != 0)
return NULL;
header->signature = get_signature (buffer, &offset, end_offset);
if (header->signature == NULL)
return NULL;
break;
case G_DBUS_MESSAGE_HEADER_FIELD_NUM_UNIX_FDS:
if (offset + 4 > end_offset)
return NULL;
header->unix_fds = read_uint32 (header, &buffer->data[offset]);
offset += 4;
break;
default:
/* Unknown header field, for safety, fail parse */
return NULL;
}
}
switch (header->type)
{
case G_DBUS_MESSAGE_TYPE_METHOD_CALL:
if (header->path == NULL || header->member == NULL)
return NULL;
break;
case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
if (!header->has_reply_serial)
return NULL;
break;
case G_DBUS_MESSAGE_TYPE_ERROR:
if (header->error_name == NULL || !header->has_reply_serial)
return NULL;
break;
case G_DBUS_MESSAGE_TYPE_SIGNAL:
if (header->path == NULL ||
header->interface == NULL ||
header->member == NULL)
return NULL;
if (strcmp (header->path, "/org/freedesktop/DBus/Local") == 0 ||
strcmp (header->interface, "org.freedesktop.DBus.Local") == 0)
return NULL;
break;
default:
/* Unknown message type, for safety, fail parse */
return NULL;
}
if (serial_offset > 0)
{
header->serial += serial_offset;
write_uint32 (header, &buffer->data[8], header->serial);
}
if (reply_serial_offset > 0 &&
header->has_reply_serial &&
header->reply_serial > hello_serial + reply_serial_offset)
write_uint32 (header, &buffer->data[reply_serial_pos], header->reply_serial - reply_serial_offset);
return g_steal_pointer (&header);
}
static void
print_outgoing_header (Header *header)
{
switch (header->type)
{
case G_DBUS_MESSAGE_TYPE_METHOD_CALL:
g_print ("C%d: -> %s call %s.%s at %s\n",
header->serial,
header->destination ? header->destination : "(no dest)",
header->interface ? header->interface : "",
header->member ? header->member : "",
header->path ? header->path : "");
break;
case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
g_print ("C%d: -> %s return from B%d\n",
header->serial,
header->destination ? header->destination : "(no dest)",
header->reply_serial);
break;
case G_DBUS_MESSAGE_TYPE_ERROR:
g_print ("C%d: -> %s return error %s from B%d\n",
header->serial,
header->destination ? header->destination : "(no dest)",
header->error_name ? header->error_name : "(no error)",
header->reply_serial);
break;
case G_DBUS_MESSAGE_TYPE_SIGNAL:
g_print ("C%d: -> %s signal %s.%s at %s\n",
header->serial,
header->destination ? header->destination : "all",
header->interface ? header->interface : "",
header->member ? header->member : "",
header->path ? header->path : "");
break;
default:
g_print ("unknown message type\n");
}
}
static void
print_incoming_header (Header *header)
{
switch (header->type)
{
case G_DBUS_MESSAGE_TYPE_METHOD_CALL:
g_print ("B%d: <- %s call %s.%s at %s\n",
header->serial,
header->sender ? header->sender : "(no sender)",
header->interface ? header->interface : "",
header->member ? header->member : "",
header->path ? header->path : "");
break;
case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
g_print ("B%d: <- %s return from C%d\n",
header->serial,
header->sender ? header->sender : "(no sender)",
header->reply_serial);
break;
case G_DBUS_MESSAGE_TYPE_ERROR:
g_print ("B%d: <- %s return error %s from C%d\n",
header->serial,
header->sender ? header->sender : "(no sender)",
header->error_name ? header->error_name : "(no error)",
header->reply_serial);
break;
case G_DBUS_MESSAGE_TYPE_SIGNAL:
g_print ("B%d: <- %s signal %s.%s at %s\n",
header->serial,
header->sender ? header->sender : "(no sender)",
header->interface ? header->interface : "",
header->member ? header->member : "",
header->path ? header->path : "");
break;
default:
g_print ("unknown message type\n");
}
}
static FlatpakPolicy
flatpak_proxy_client_get_policy (FlatpakProxyClient *client, const char *source)
{
if (source == NULL)
return FLATPAK_POLICY_TALK; /* All clients can talk to the bus itself */
if (source[0] == ':')
return GPOINTER_TO_UINT (g_hash_table_lookup (client->unique_id_policy, source));
return flatpak_proxy_get_policy (client->proxy, source);
}
static void
flatpak_proxy_client_update_unique_id_policy (FlatpakProxyClient *client,
const char *unique_id,
FlatpakPolicy policy)
{
if (policy > FLATPAK_POLICY_NONE)
{
FlatpakPolicy old_policy;
old_policy = GPOINTER_TO_UINT (g_hash_table_lookup (client->unique_id_policy, unique_id));
if (policy > old_policy)
g_hash_table_replace (client->unique_id_policy, g_strdup (unique_id), GINT_TO_POINTER (policy));
}
}
static void
flatpak_proxy_client_update_unique_id_policy_from_name (FlatpakProxyClient *client,
const char *unique_id,
const char *as_name)
{
flatpak_proxy_client_update_unique_id_policy (client,
unique_id,
flatpak_proxy_get_policy (client->proxy, as_name));
}
static gboolean
client_message_generates_reply (Header *header)
{
switch (header->type)
{
case G_DBUS_MESSAGE_TYPE_METHOD_CALL:
return (header->flags & G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED) == 0;
case G_DBUS_MESSAGE_TYPE_SIGNAL:
case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
case G_DBUS_MESSAGE_TYPE_ERROR:
default:
return FALSE;
}
}
static Buffer *
message_to_buffer (GDBusMessage *message)
{
Buffer *buffer;
guchar *blob;
gsize blob_size;
blob = g_dbus_message_to_blob (message, &blob_size, G_DBUS_CAPABILITY_FLAGS_NONE, NULL);
buffer = buffer_new (blob_size, NULL);
memcpy (buffer->data, blob, blob_size);
g_free (blob);
return buffer;
}
static GDBusMessage *
get_error_for_header (FlatpakProxyClient *client, Header *header, const char *error)
{
GDBusMessage *reply;
reply = g_dbus_message_new ();
g_dbus_message_set_message_type (reply, G_DBUS_MESSAGE_TYPE_ERROR);
g_dbus_message_set_flags (reply, G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED);
g_dbus_message_set_reply_serial (reply, header->serial - client->serial_offset);
g_dbus_message_set_error_name (reply, error);
g_dbus_message_set_body (reply, g_variant_new ("(s)", error));
return reply;
}
static GDBusMessage *
get_bool_reply_for_header (FlatpakProxyClient *client, Header *header, gboolean val)
{
GDBusMessage *reply;
reply = g_dbus_message_new ();
g_dbus_message_set_message_type (reply, G_DBUS_MESSAGE_TYPE_METHOD_RETURN);
g_dbus_message_set_flags (reply, G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED);
g_dbus_message_set_reply_serial (reply, header->serial - client->serial_offset);
g_dbus_message_set_body (reply, g_variant_new ("(b)", val));
return reply;
}
static Buffer *
get_ping_buffer_for_header (Header *header)
{
Buffer *buffer;
GDBusMessage *dummy;
dummy = g_dbus_message_new_method_call (NULL, "/", "org.freedesktop.DBus.Peer", "Ping");
g_dbus_message_set_serial (dummy, header->serial);
g_dbus_message_set_flags (dummy, header->flags);
buffer = message_to_buffer (dummy);
g_object_unref (dummy);
return buffer;
}
static Buffer *
get_error_for_roundtrip (FlatpakProxyClient *client, Header *header, const char *error_name)
{
Buffer *ping_buffer = get_ping_buffer_for_header (header);
GDBusMessage *reply;
reply = get_error_for_header (client, header, error_name);
g_hash_table_replace (client->rewrite_reply, GINT_TO_POINTER (header->serial), reply);
return ping_buffer;
}
static Buffer *
get_bool_reply_for_roundtrip (FlatpakProxyClient *client, Header *header, gboolean val)
{
Buffer *ping_buffer = get_ping_buffer_for_header (header);
GDBusMessage *reply;
reply = get_bool_reply_for_header (client, header, val);
g_hash_table_replace (client->rewrite_reply, GINT_TO_POINTER (header->serial), reply);
return ping_buffer;
}
typedef enum {
HANDLE_PASS,
HANDLE_DENY,
HANDLE_HIDE,
HANDLE_FILTER_NAME_LIST_REPLY,
HANDLE_FILTER_HAS_OWNER_REPLY,
HANDLE_FILTER_GET_OWNER_REPLY,
HANDLE_VALIDATE_OWN,
HANDLE_VALIDATE_SEE,
HANDLE_VALIDATE_TALK,
HANDLE_VALIDATE_MATCH,
} BusHandler;
static gboolean
is_for_bus (Header *header)
{
return g_strcmp0 (header->destination, "org.freedesktop.DBus") == 0;
}
static gboolean
is_dbus_method_call (Header *header)
{
return
is_for_bus (header) &&
header->type == G_DBUS_MESSAGE_TYPE_METHOD_CALL &&
g_strcmp0 (header->interface, "org.freedesktop.DBus") == 0;
}
static gboolean
is_introspection_call (Header *header)
{
return
header->type == G_DBUS_MESSAGE_TYPE_METHOD_CALL &&
g_strcmp0 (header->interface, "org.freedesktop.DBus.Introspectable") == 0;
}
static BusHandler
get_dbus_method_handler (FlatpakProxyClient *client, Header *header)
{
FlatpakPolicy policy;
const char *method;
if (header->has_reply_serial)
{
ExpectedReplyType expected_reply =
steal_expected_reply (&client->bus_side,
header->reply_serial);
if (expected_reply == EXPECTED_REPLY_NONE)
return HANDLE_DENY;
return HANDLE_PASS;
}
policy = flatpak_proxy_client_get_policy (client, header->destination);
if (policy < FLATPAK_POLICY_SEE)
return HANDLE_HIDE;
if (policy < FLATPAK_POLICY_FILTERED)
return HANDLE_DENY;
if (policy == FLATPAK_POLICY_FILTERED)
{
GList *filters = NULL, *l;
if (header->destination)
filters = g_hash_table_lookup (client->proxy->filters, header->destination);
for (l = filters; l != NULL; l = l->next)
{
Filter *filter = l->data;
if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_CALL &&
(filter->path == NULL || g_strcmp0 (filter->path, header->path) == 0) &&
(filter->interface == NULL || g_strcmp0 (filter->interface, header->interface) == 0) &&
(filter->member == NULL || g_strcmp0 (filter->member, header->member) == 0))
return HANDLE_PASS;
}
return HANDLE_DENY;
}
if (!is_for_bus (header))
return HANDLE_PASS;
if (is_introspection_call (header))
{
return HANDLE_PASS;
}
else if (is_dbus_method_call (header))
{
method = header->member;
if (method == NULL)
return HANDLE_DENY;
if (strcmp (method, "AddMatch") == 0)
return HANDLE_VALIDATE_MATCH;
if (strcmp (method, "Hello") == 0 ||
strcmp (method, "RemoveMatch") == 0 ||
strcmp (method, "GetId") == 0)
return HANDLE_PASS;
if (strcmp (method, "UpdateActivationEnvironment") == 0 ||
strcmp (method, "BecomeMonitor") == 0)
return HANDLE_DENY;
if (strcmp (method, "RequestName") == 0 ||
strcmp (method, "ReleaseName") == 0 ||
strcmp (method, "ListQueuedOwners") == 0)
return HANDLE_VALIDATE_OWN;
if (strcmp (method, "NameHasOwner") == 0)
return HANDLE_FILTER_HAS_OWNER_REPLY;
if (strcmp (method, "GetNameOwner") == 0)
return HANDLE_FILTER_GET_OWNER_REPLY;
if (strcmp (method, "GetConnectionUnixProcessID") == 0 ||
strcmp (method, "GetConnectionCredentials") == 0 ||
strcmp (method, "GetAdtAuditSessionData") == 0 ||
strcmp (method, "GetConnectionSELinuxSecurityContext") == 0 ||
strcmp (method, "GetConnectionUnixUser") == 0)
return HANDLE_VALIDATE_SEE;
if (strcmp (method, "StartServiceByName") == 0)
return HANDLE_VALIDATE_TALK;
if (strcmp (method, "ListNames") == 0 ||
strcmp (method, "ListActivatableNames") == 0)
return HANDLE_FILTER_NAME_LIST_REPLY;
g_warning ("Unknown bus method %s", method);
return HANDLE_DENY;
}
else
{
return HANDLE_DENY;
}
}
static FlatpakPolicy
policy_from_handler (BusHandler handler)
{
switch (handler)
{
case HANDLE_VALIDATE_OWN:
return FLATPAK_POLICY_OWN;
case HANDLE_VALIDATE_TALK:
return FLATPAK_POLICY_TALK;
case HANDLE_VALIDATE_SEE:
return FLATPAK_POLICY_SEE;
default:
return FLATPAK_POLICY_NONE;
}
}
static char *
get_arg0_string (Buffer *buffer)
{
GDBusMessage *message = g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
GVariant *body;
g_autoptr(GVariant) arg0 = NULL;
char *name = NULL;
if (message != NULL &&
(body = g_dbus_message_get_body (message)) != NULL &&
(arg0 = g_variant_get_child_value (body, 0)) != NULL &&
g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING))
name = g_variant_dup_string (arg0, NULL);
g_object_unref (message);
return name;
}
static gboolean
validate_arg0_match (FlatpakProxyClient *client, Buffer *buffer)
{
GDBusMessage *message = g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
GVariant *body, *arg0;
const char *match;
gboolean res = TRUE;
if (message != NULL &&
(body = g_dbus_message_get_body (message)) != NULL &&
(arg0 = g_variant_get_child_value (body, 0)) != NULL &&
g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING))
{
match = g_variant_get_string (arg0, NULL);
if (strstr (match, "eavesdrop=") != NULL)
res = FALSE;
}
g_object_unref (message);
return res;
}
static gboolean
validate_arg0_name (FlatpakProxyClient *client, Buffer *buffer, FlatpakPolicy required_policy, FlatpakPolicy *has_policy)
{
GDBusMessage *message = g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
GVariant *body, *arg0;
const char *name;
FlatpakPolicy name_policy;
gboolean res = FALSE;
if (has_policy)
*has_policy = FLATPAK_POLICY_NONE;
if (message != NULL &&
(body = g_dbus_message_get_body (message)) != NULL &&
(arg0 = g_variant_get_child_value (body, 0)) != NULL &&
g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING))
{
name = g_variant_get_string (arg0, NULL);
name_policy = flatpak_proxy_client_get_policy (client, name);
if (has_policy)
*has_policy = name_policy;
if (name_policy >= required_policy)
res = TRUE;
else if (client->proxy->log_messages)
g_print ("Filtering message due to arg0 %s, policy: %d (required %d)\n", name, name_policy, required_policy);
}
g_object_unref (message);
return res;
}
static Buffer *
filter_names_list (FlatpakProxyClient *client, Buffer *buffer)
{
GDBusMessage *message = g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
GVariant *body, *arg0, *new_names;
const gchar **names;
int i;
GVariantBuilder builder;
Buffer *filtered;
if (message == NULL ||
(body = g_dbus_message_get_body (message)) == NULL ||
(arg0 = g_variant_get_child_value (body, 0)) == NULL ||
!g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING_ARRAY))
return NULL;
names = g_variant_get_strv (arg0, NULL);
g_variant_builder_init (&builder, G_VARIANT_TYPE_STRING_ARRAY);
for (i = 0; names[i] != NULL; i++)
{
if (flatpak_proxy_client_get_policy (client, names[i]) >= FLATPAK_POLICY_SEE)
g_variant_builder_add (&builder, "s", names[i]);
}
g_free (names);
new_names = g_variant_builder_end (&builder);
g_dbus_message_set_body (message,
g_variant_new_tuple (&new_names, 1));
filtered = message_to_buffer (message);
g_object_unref (message);
return filtered;
}
static gboolean
message_is_name_owner_changed (FlatpakProxyClient *client, Header *header)
{
if (header->type == G_DBUS_MESSAGE_TYPE_SIGNAL &&
g_strcmp0 (header->sender, "org.freedesktop.DBus") == 0 &&
g_strcmp0 (header->interface, "org.freedesktop.DBus") == 0 &&
g_strcmp0 (header->member, "NameOwnerChanged") == 0)
return TRUE;
return FALSE;
}
static gboolean
should_filter_name_owner_changed (FlatpakProxyClient *client, Buffer *buffer)
{
GDBusMessage *message = g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
GVariant *body, *arg0, *arg1, *arg2;
const gchar *name, *old, *new;
gboolean filter = TRUE;
if (message == NULL ||
(body = g_dbus_message_get_body (message)) == NULL ||
(arg0 = g_variant_get_child_value (body, 0)) == NULL ||
!g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING) ||
(arg1 = g_variant_get_child_value (body, 1)) == NULL ||
!g_variant_is_of_type (arg1, G_VARIANT_TYPE_STRING) ||
(arg2 = g_variant_get_child_value (body, 2)) == NULL ||
!g_variant_is_of_type (arg2, G_VARIANT_TYPE_STRING))
return TRUE;
name = g_variant_get_string (arg0, NULL);
old = g_variant_get_string (arg1, NULL);
new = g_variant_get_string (arg2, NULL);
if (flatpak_proxy_client_get_policy (client, name) >= FLATPAK_POLICY_SEE ||
(client->proxy->sloppy_names && name[0] == ':'))
{
if (name[0] != ':')
{
if (old[0] != 0)
flatpak_proxy_client_update_unique_id_policy_from_name (client, old, name);
if (new[0] != 0)
flatpak_proxy_client_update_unique_id_policy_from_name (client, new, name);
}
filter = FALSE;
}
g_object_unref (message);
return filter;
}
static GList *
side_get_n_unix_fds (ProxySide *side, int n_fds)
{
GList *res = NULL;
while (side->control_messages != NULL)
{
GSocketControlMessage *control_message = side->control_messages->data;
if (G_IS_UNIX_FD_MESSAGE (control_message))
{
GUnixFDMessage *fd_message = G_UNIX_FD_MESSAGE (control_message);
GUnixFDList *fd_list = g_unix_fd_message_get_fd_list (fd_message);
int len = g_unix_fd_list_get_length (fd_list);
/* I believe that socket control messages are never merged, and
the sender side sends only one unix-fd-list per message, so
at this point there should always be one full fd list
per requested number of fds */
if (len != n_fds)
{
g_warning ("Not right nr of fds in socket message");
return NULL;
}
side->control_messages = g_list_delete_link (side->control_messages, side->control_messages);
return g_list_append (NULL, control_message);
}
g_object_unref (control_message);
side->control_messages = g_list_delete_link (side->control_messages, side->control_messages);
}
return res;
}
static gboolean
update_socket_messages (ProxySide *side, Buffer *buffer, Header *header)
{
/* We may accidentally combine multiple control messages into one
buffer when we receive (since we can do several recvs), so we
keep a list of all we get and then only re-attach the amount
specified in the header to the buffer. */
side->control_messages = g_list_concat (side->control_messages, buffer->control_messages);
buffer->control_messages = NULL;
if (header->unix_fds > 0)
{
buffer->control_messages = side_get_n_unix_fds (side, header->unix_fds);
if (buffer->control_messages == NULL)
{
g_warning ("Not enough fds for message");
side_closed (side);
buffer_unref (buffer);
return FALSE;
}
}
return TRUE;
}
static void
queue_fake_message (FlatpakProxyClient *client, GDBusMessage *message, ExpectedReplyType reply_type)
{
Buffer *buffer;
client->last_serial++;
client->serial_offset++;
g_dbus_message_set_serial (message, client->last_serial);
buffer = message_to_buffer (message);
g_object_unref (message);
queue_outgoing_buffer (&client->bus_side, buffer);
queue_expected_reply (&client->client_side, client->last_serial, reply_type);
}
/* After the first Hello message we need to synthesize a bunch of messages to synchronize the
ownership state for the names in the policy */
static void
queue_initial_name_ops (FlatpakProxyClient *client)
{
GHashTableIter iter;
gpointer key, value;
gboolean has_wildcards = FALSE;
g_hash_table_iter_init (&iter, client->proxy->policy);
while (g_hash_table_iter_next (&iter, &key, &value))
{
const char *name = key;
GDBusMessage *message;
GVariant *match;
if (strcmp (name, "org.freedesktop.DBus") == 0)
continue;
/* AddMatch the name so we get told about ownership changes.
Do it before the GetNameOwner to avoid races */
message = g_dbus_message_new_method_call ("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "AddMatch");
match = g_variant_new_printf ("type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='%s'", name);
g_dbus_message_set_body (message, g_variant_new_tuple (&match, 1));
queue_fake_message (client, message, EXPECTED_REPLY_FILTER);
if (client->proxy->log_messages)
g_print ("C%d: -> org.freedesktop.DBus fake AddMatch for %s\n", client->last_serial, name);
/* Get the current owner of the name (if any) so we can apply policy to it */
message = g_dbus_message_new_method_call ("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "GetNameOwner");
g_dbus_message_set_body (message, g_variant_new ("(s)", name));
queue_fake_message (client, message, EXPECTED_REPLY_FAKE_GET_NAME_OWNER);
g_hash_table_replace (client->get_owner_reply, GINT_TO_POINTER (client->last_serial), g_strdup (name));
if (client->proxy->log_messages)
g_print ("C%d: -> org.freedesktop.DBus fake GetNameOwner for %s\n", client->last_serial, name);
}
/* Same for wildcard proxies. Only here we don't know the actual names to GetNameOwner for, so we have to
list all current names */
g_hash_table_iter_init (&iter, client->proxy->wildcard_policy);
while (g_hash_table_iter_next (&iter, &key, &value))
{
const char *name = key;
GDBusMessage *message;
GVariant *match;
has_wildcards = TRUE;
/* AddMatch the name with arg0namespace so we get told about ownership changes to all subnames.
Do it before the GetNameOwner to avoid races */
message = g_dbus_message_new_method_call ("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "AddMatch");
match = g_variant_new_printf ("type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0namespace='%s'", name);
g_dbus_message_set_body (message, g_variant_new_tuple (&match, 1));
queue_fake_message (client, message, EXPECTED_REPLY_FILTER);
if (client->proxy->log_messages)
g_print ("C%d: -> org.freedesktop.DBus fake AddMatch for %s.*\n", client->last_serial, name);
}
if (has_wildcards)
{
GDBusMessage *message;
/* AddMatch the name so we get told about ownership changes.
Do it before the GetNameOwner to avoid races */
message = g_dbus_message_new_method_call ("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames");
g_dbus_message_set_body (message, g_variant_new ("()"));
queue_fake_message (client, message, EXPECTED_REPLY_FAKE_LIST_NAMES);
if (client->proxy->log_messages)
g_print ("C%d: -> org.freedesktop.DBus fake ListNames\n", client->last_serial);
/* Stop reading from the client, to avoid incoming messages fighting with the ListNames roundtrip.
We will start it again once we have handled the ListNames reply */
stop_reading (&client->client_side);
}
}
static void
queue_wildcard_initial_name_ops (FlatpakProxyClient *client, Header *header, Buffer *buffer)
{
GDBusMessage *decoded_message = g_dbus_message_new_from_blob (buffer->data, buffer->size, 0, NULL);
GVariant *body, *arg0;
if (decoded_message != NULL &&
header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN &&
(body = g_dbus_message_get_body (decoded_message)) != NULL &&
(arg0 = g_variant_get_child_value (body, 0)) != NULL &&
g_variant_is_of_type (arg0, G_VARIANT_TYPE_STRING_ARRAY))
{
const gchar **names = g_variant_get_strv (arg0, NULL);
int i;
/* Loop over all current names and get the owner for all the ones that match our wildcard
policies so that we can update the unique id policies for those */
for (i = 0; names[i] != NULL; i++)
{
const char *name = names[i];
if (name[0] != ':' &&
flatpak_proxy_get_wildcard_policy (client->proxy, name) != FLATPAK_POLICY_NONE)
{
/* Get the current owner of the name (if any) so we can apply policy to it */
GDBusMessage *message = g_dbus_message_new_method_call ("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "GetNameOwner");
g_dbus_message_set_body (message, g_variant_new ("(s)", name));
queue_fake_message (client, message, EXPECTED_REPLY_FAKE_GET_NAME_OWNER);
g_hash_table_replace (client->get_owner_reply, GINT_TO_POINTER (client->last_serial), g_strdup (name));
if (client->proxy->log_messages)
g_print ("C%d: -> org.freedesktop.DBus fake GetNameOwner for %s\n", client->last_serial, name);
}
}
g_free (names);
}
g_object_unref (decoded_message);
}
static void
got_buffer_from_client (FlatpakProxyClient *client, ProxySide *side, Buffer *buffer)
{
ExpectedReplyType expecting_reply = EXPECTED_REPLY_NONE;
if (client->authenticated && client->proxy->filter)
{
g_autoptr(Header) header = NULL;;
BusHandler handler;
/* Filter and rewrite outgoing messages as needed */
header = parse_header (buffer, client->serial_offset, 0, 0);
if (header == NULL)
{
g_warning ("Invalid message header format");
side_closed (side);
buffer_unref (buffer);
return;
}
if (!update_socket_messages (side, buffer, header))
return;
/* Make sure the client is not playing games with the serials, as that
could confuse us. */
if (header->serial <= client->last_serial)
{
g_warning ("Invalid client serial");
side_closed (side);
buffer_unref (buffer);
return;
}
client->last_serial = header->serial;
if (client->proxy->log_messages)
print_outgoing_header (header);
/* Keep track of the initial Hello request so that we can read
the reply which has our assigned unique id */
if (is_dbus_method_call (header) &&
g_strcmp0 (header->member, "Hello") == 0)
{
expecting_reply = EXPECTED_REPLY_HELLO;
client->hello_serial = header->serial;
}
handler = get_dbus_method_handler (client, header);
switch (handler)
{
case HANDLE_FILTER_HAS_OWNER_REPLY:
case HANDLE_FILTER_GET_OWNER_REPLY:
if (!validate_arg0_name (client, buffer, FLATPAK_POLICY_SEE, NULL))
{
g_clear_pointer (&buffer, buffer_unref);
if (handler == HANDLE_FILTER_GET_OWNER_REPLY)
buffer = get_error_for_roundtrip (client, header,
"org.freedesktop.DBus.Error.NameHasNoOwner");
else
buffer = get_bool_reply_for_roundtrip (client, header, FALSE);
expecting_reply = EXPECTED_REPLY_REWRITE;
break;
}
goto handle_pass;
case HANDLE_VALIDATE_MATCH:
if (!validate_arg0_match (client, buffer))
{
if (client->proxy->log_messages)
g_print ("*DENIED* (ping)\n");
g_clear_pointer (&buffer, buffer_unref);
buffer = get_error_for_roundtrip (client, header,
"org.freedesktop.DBus.Error.AccessDenied");
expecting_reply = EXPECTED_REPLY_REWRITE;
break;
}
goto handle_pass;
case HANDLE_VALIDATE_OWN:
case HANDLE_VALIDATE_SEE:
case HANDLE_VALIDATE_TALK:
{
FlatpakPolicy name_policy;
if (validate_arg0_name (client, buffer, policy_from_handler (handler), &name_policy))
goto handle_pass;
if (name_policy < (int) FLATPAK_POLICY_SEE)
goto handle_hide;
else
goto handle_deny;
}
case HANDLE_FILTER_NAME_LIST_REPLY:
expecting_reply = EXPECTED_REPLY_LIST_NAMES;
goto handle_pass;
case HANDLE_PASS:
handle_pass:
if (client_message_generates_reply (header))
{
if (expecting_reply == EXPECTED_REPLY_NONE)
expecting_reply = EXPECTED_REPLY_NORMAL;
}
break;
case HANDLE_HIDE:
handle_hide:
g_clear_pointer (&buffer, buffer_unref);
if (client_message_generates_reply (header))
{
const char *error;
if (client->proxy->log_messages)
g_print ("*HIDDEN* (ping)\n");
if ((header->destination != NULL && header->destination[0] == ':') ||
(header->flags & G_DBUS_MESSAGE_FLAGS_NO_AUTO_START) != 0)
error = "org.freedesktop.DBus.Error.NameHasNoOwner";
else
error = "org.freedesktop.DBus.Error.ServiceUnknown";
buffer = get_error_for_roundtrip (client, header, error);
expecting_reply = EXPECTED_REPLY_REWRITE;
}
else
{
if (client->proxy->log_messages)
g_print ("*HIDDEN*\n");
}
break;
default:
case HANDLE_DENY:
handle_deny:
g_clear_pointer (&buffer, buffer_unref);
if (client_message_generates_reply (header))
{
if (client->proxy->log_messages)
g_print ("*DENIED* (ping)\n");
buffer = get_error_for_roundtrip (client, header,
"org.freedesktop.DBus.Error.AccessDenied");
expecting_reply = EXPECTED_REPLY_REWRITE;
}
else
{
if (client->proxy->log_messages)
g_print ("*DENIED*\n");
}
break;
}
if (buffer != NULL && expecting_reply != EXPECTED_REPLY_NONE)
queue_expected_reply (side, header->serial, expecting_reply);
}
if (buffer)
queue_outgoing_buffer (&client->bus_side, buffer);
if (buffer != NULL && expecting_reply == EXPECTED_REPLY_HELLO)
queue_initial_name_ops (client);
}
static void
got_buffer_from_bus (FlatpakProxyClient *client, ProxySide *side, Buffer *buffer)
{
if (client->authenticated && client->proxy->filter)
{
g_autoptr(Header) header = NULL;;
GDBusMessage *rewritten;
FlatpakPolicy policy;
ExpectedReplyType expected_reply;
/* Filter and rewrite incoming messages as needed */
header = parse_header (buffer, 0, client->serial_offset, client->hello_serial);
if (header == NULL)
{
g_warning ("Invalid message header format");
buffer_unref (buffer);
side_closed (side);
return;
}
if (!update_socket_messages (side, buffer, header))
return;
if (client->proxy->log_messages)
print_incoming_header (header);
if (header->has_reply_serial)
{
expected_reply = steal_expected_reply (get_other_side (side), header->reply_serial);
/* We only allow replies we expect */
if (expected_reply == EXPECTED_REPLY_NONE)
{
if (client->proxy->log_messages)
g_print ("*Unexpected reply*\n");
buffer_unref (buffer);
return;
}
switch (expected_reply)
{
case EXPECTED_REPLY_HELLO:
/* When we get the initial reply to Hello, allow all
further communications to our own unique id. */
if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN)
{
g_autofree char *my_id = get_arg0_string (buffer);
flatpak_proxy_client_update_unique_id_policy (client, my_id, FLATPAK_POLICY_TALK);
break;
}
case EXPECTED_REPLY_REWRITE:
/* Replace a roundtrip ping with the rewritten message */
rewritten = g_hash_table_lookup (client->rewrite_reply,
GINT_TO_POINTER (header->reply_serial));
if (client->proxy->log_messages)
g_print ("*REWRITTEN*\n");
g_dbus_message_set_serial (rewritten, header->serial);
g_clear_pointer (&buffer, buffer_unref);
buffer = message_to_buffer (rewritten);
g_hash_table_remove (client->rewrite_reply,
GINT_TO_POINTER (header->reply_serial));
break;
case EXPECTED_REPLY_FAKE_LIST_NAMES:
/* This is a reply from the bus to a fake ListNames
request, request ownership of any name matching a
wildcard policy */
queue_wildcard_initial_name_ops (client, header, buffer);
/* Don't forward fake replies to the app */
if (client->proxy->log_messages)
g_print ("*SKIPPED*\n");
g_clear_pointer (&buffer, buffer_unref);
/* Start reading the clients requests now that we are done with the names */
start_reading (&client->client_side);
break;
case EXPECTED_REPLY_FAKE_GET_NAME_OWNER:
/* This is a reply from the bus to a fake GetNameOwner
request, update the policy for this unique name based on
the policy */
{
char *requested_name = g_hash_table_lookup (client->get_owner_reply, GINT_TO_POINTER (header->reply_serial));
if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN)
{
g_autofree char *owner = get_arg0_string (buffer);
flatpak_proxy_client_update_unique_id_policy_from_name (client, owner, requested_name);
}
g_hash_table_remove (client->get_owner_reply, GINT_TO_POINTER (header->reply_serial));
/* Don't forward fake replies to the app */
if (client->proxy->log_messages)
g_print ("*SKIPPED*\n");
g_clear_pointer (&buffer, buffer_unref);
break;
}
case EXPECTED_REPLY_FILTER:
if (client->proxy->log_messages)
g_print ("*SKIPPED*\n");
g_clear_pointer (&buffer, buffer_unref);
break;
case EXPECTED_REPLY_LIST_NAMES:
/* This is a reply from the bus to a ListNames request, filter
it according to the policy */
if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN)
{
Buffer *filtered_buffer;
filtered_buffer = filter_names_list (client, buffer);
g_clear_pointer (&buffer, buffer_unref);
buffer = filtered_buffer;
}
break;
case EXPECTED_REPLY_NORMAL:
break;
default:
g_warning ("Unexpected expected reply type %d", expected_reply);
}
}
else /* Not reply */
{
/* Don't allow reply types with no reply_serial */
if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN ||
header->type == G_DBUS_MESSAGE_TYPE_ERROR)
{
if (client->proxy->log_messages)
g_print ("*Invalid reply*\n");
g_clear_pointer (&buffer, buffer_unref);
}
/* We filter all NameOwnerChanged signal according to the policy */
if (message_is_name_owner_changed (client, header))
{
if (should_filter_name_owner_changed (client, buffer))
g_clear_pointer (&buffer, buffer_unref);
}
}
/* All incoming broadcast signals are filtered according to policy */
if (header->type == G_DBUS_MESSAGE_TYPE_SIGNAL && header->destination == NULL)
{
policy = flatpak_proxy_client_get_policy (client, header->sender);
if (policy < FLATPAK_POLICY_TALK)
{
if (client->proxy->log_messages)
g_print ("*FILTERED IN*\n");
g_clear_pointer (&buffer, buffer_unref);
}
}
/* We received and forwarded a message from a trusted peer. Make the policy for
this unique id SEE so that the client can track its lifetime. */
if (buffer && header->sender && header->sender[0] == ':')
flatpak_proxy_client_update_unique_id_policy (client, header->sender, FLATPAK_POLICY_SEE);
if (buffer && client_message_generates_reply (header))
queue_expected_reply (side, header->serial, EXPECTED_REPLY_NORMAL);
}
if (buffer)
queue_outgoing_buffer (&client->client_side, buffer);
}
static void
got_buffer_from_side (ProxySide *side, Buffer *buffer)
{
FlatpakProxyClient *client = side->client;
if (side == &client->client_side)
got_buffer_from_client (client, side, buffer);
else
got_buffer_from_bus (client, side, buffer);
}
static gssize
find_auth_end (FlatpakProxyClient *client, Buffer *buffer)
{
guchar *match;
int i;
/* First try to match any leftover at the start */
if (client->auth_end_offset > 0)
{
gsize left = strlen (AUTH_END_STRING) - client->auth_end_offset;
gsize to_match = MIN (left, buffer->pos);
/* Matched at least up to to_match */
if (memcmp (buffer->data, &AUTH_END_STRING[client->auth_end_offset], to_match) == 0)
{
client->auth_end_offset += to_match;
/* Matched all */
if (client->auth_end_offset == strlen (AUTH_END_STRING))
return to_match;
/* Matched to end of buffer */
return -1;
}
/* Did not actually match at start */
client->auth_end_offset = -1;
}
/* Look for whole match inside buffer */
match = memmem (buffer, buffer->pos,
AUTH_END_STRING, strlen (AUTH_END_STRING));
if (match != NULL)
return match - buffer->data + strlen (AUTH_END_STRING);
/* Record longest prefix match at the end */
for (i = MIN (strlen (AUTH_END_STRING) - 1, buffer->pos); i > 0; i--)
{
if (memcmp (buffer->data + buffer->pos - i, AUTH_END_STRING, i) == 0)
{
client->auth_end_offset = i;
break;
}
}
return -1;
}
static gboolean
side_in_cb (GSocket *socket, GIOCondition condition, gpointer user_data)
{
ProxySide *side = user_data;
FlatpakProxyClient *client = side->client;
GError *error = NULL;
Buffer *buffer;
gboolean retval = G_SOURCE_CONTINUE;
g_object_ref (client);
while (!side->closed)
{
if (!side->got_first_byte)
buffer = buffer_new (1, NULL);
else if (!client->authenticated)
buffer = buffer_new (64, NULL);
else
buffer = side->current_read_buffer;
if (!buffer_read (side, buffer, socket))
{
if (buffer != side->current_read_buffer)
buffer_unref (buffer);
break;
}
if (!client->authenticated)
{
if (buffer->pos > 0)
{
gboolean found_auth_end = FALSE;
gsize extra_data;
buffer->size = buffer->pos;
if (!side->got_first_byte)
{
buffer->send_credentials = TRUE;
side->got_first_byte = TRUE;
}
/* Look for end of authentication mechanism */
else if (side == &client->client_side)
{
gssize auth_end = find_auth_end (client, buffer);
if (auth_end >= 0)
{
found_auth_end = TRUE;
buffer->size = auth_end;
extra_data = buffer->pos - buffer->size;
/* We may have gotten some extra data which is not part of
the auth handshake, keep it for the next iteration. */
if (extra_data > 0)
side->extra_input_data = g_bytes_new (buffer->data + buffer->size, extra_data);
}
}
got_buffer_from_side (side, buffer);
if (found_auth_end)
client->authenticated = TRUE;
}
else
{
buffer_unref (buffer);
}
}
else if (buffer->pos == buffer->size)
{
if (buffer == &side->header_buffer)
{
gssize required;
required = g_dbus_message_bytes_needed (buffer->data, buffer->size, &error);
if (required < 0)
{
g_warning ("Invalid message header read");
side_closed (side);
}
else
{
side->current_read_buffer = buffer_new (required, buffer);
}
}
else
{
got_buffer_from_side (side, buffer);
side->header_buffer.pos = 0;
side->current_read_buffer = &side->header_buffer;
}
}
}
if (side->closed)
{
side->in_source = NULL;
retval = G_SOURCE_REMOVE;
}
g_object_unref (client);
return retval;
}
static void
start_reading (ProxySide *side)
{
GSocket *socket;
socket = g_socket_connection_get_socket (side->connection);
side->in_source = g_socket_create_source (socket, G_IO_IN, NULL);
g_source_set_callback (side->in_source, (GSourceFunc) side_in_cb, side, NULL);
g_source_attach (side->in_source, NULL);
g_source_unref (side->in_source);
}
static void
stop_reading (ProxySide *side)
{
if (side->in_source)
{
g_source_destroy (side->in_source);
side->in_source = NULL;
}
}
static void
client_connected_to_dbus (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
FlatpakProxyClient *client = user_data;
GSocketConnection *connection;
GError *error = NULL;
GIOStream *stream;
stream = g_dbus_address_get_stream_finish (res, NULL, &error);
if (stream == NULL)
{
g_warning ("Failed to connect to bus: %s", error->message);
g_object_unref (client);
return;
}
connection = G_SOCKET_CONNECTION (stream);
g_socket_set_blocking (g_socket_connection_get_socket (connection), FALSE);
client->bus_side.connection = connection;
start_reading (&client->client_side);
start_reading (&client->bus_side);
}
static gboolean
flatpak_proxy_incoming (GSocketService *service,
GSocketConnection *connection,
GObject *source_object)
{
FlatpakProxy *proxy = FLATPAK_PROXY (service);
FlatpakProxyClient *client;
client = flatpak_proxy_client_new (proxy, connection);
g_dbus_address_get_stream (proxy->dbus_address,
NULL,
client_connected_to_dbus,
client);
return TRUE;
}
static void
flatpak_proxy_init (FlatpakProxy *proxy)
{
proxy->policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
proxy->filters = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)filter_list_free);
proxy->wildcard_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
flatpak_proxy_add_policy (proxy, "org.freedesktop.DBus", FLATPAK_POLICY_TALK);
}
static void
flatpak_proxy_class_init (FlatpakProxyClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
GSocketServiceClass *socket_service_class = G_SOCKET_SERVICE_CLASS (klass);
object_class->get_property = flatpak_proxy_get_property;
object_class->set_property = flatpak_proxy_set_property;
object_class->finalize = flatpak_proxy_finalize;
socket_service_class->incoming = flatpak_proxy_incoming;
g_object_class_install_property (object_class,
PROP_DBUS_ADDRESS,
g_param_spec_string ("dbus-address",
"",
"",
NULL,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
g_object_class_install_property (object_class,
PROP_SOCKET_PATH,
g_param_spec_string ("socket-path",
"",
"",
NULL,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
}
FlatpakProxy *
flatpak_proxy_new (const char *dbus_address,
const char *socket_path)
{
FlatpakProxy *proxy;
proxy = g_object_new (FLATPAK_TYPE_PROXY, "dbus-address", dbus_address, "socket-path", socket_path, NULL);
return proxy;
}
gboolean
flatpak_proxy_start (FlatpakProxy *proxy, GError **error)
{
GSocketAddress *address;
gboolean res;
unlink (proxy->socket_path);
address = g_unix_socket_address_new (proxy->socket_path);
error = NULL;
res = g_socket_listener_add_address (G_SOCKET_LISTENER (proxy),
address,
G_SOCKET_TYPE_STREAM,
G_SOCKET_PROTOCOL_DEFAULT,
NULL, /* source_object */
NULL, /* effective_address */
error);
g_object_unref (address);
if (!res)
return FALSE;
g_socket_service_start (G_SOCKET_SERVICE (proxy));
return TRUE;
}
void
flatpak_proxy_stop (FlatpakProxy *proxy)
{
unlink (proxy->socket_path);
g_socket_service_stop (G_SOCKET_SERVICE (proxy));
}
| ./CrossVul/dataset_final_sorted/CWE-436/c/bad_608_0 |
crossvul-cpp_data_bad_1395_1 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-216/c/bad_1395_1 |
crossvul-cpp_data_bad_1396_1 |
#define _GNU_SOURCE
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <sched.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <linux/limits.h>
#include <linux/netlink.h>
#include <linux/types.h>
/* Get all of the CLONE_NEW* flags. */
#include "namespace.h"
/* Synchronisation values. */
enum sync_t {
SYNC_USERMAP_PLS = 0x40, /* Request parent to map our users. */
SYNC_USERMAP_ACK = 0x41, /* Mapping finished by the parent. */
SYNC_RECVPID_PLS = 0x42, /* Tell parent we're sending the PID. */
SYNC_RECVPID_ACK = 0x43, /* PID was correctly received by parent. */
SYNC_GRANDCHILD = 0x44, /* The grandchild is ready to run. */
SYNC_CHILD_READY = 0x45, /* The child or grandchild is ready to return. */
/* XXX: This doesn't help with segfaults and other such issues. */
SYNC_ERR = 0xFF, /* Fatal error, no turning back. The error code follows. */
};
/*
* Synchronisation value for cgroup namespace setup.
* The same constant is defined in process_linux.go as "createCgroupns".
*/
#define CREATECGROUPNS 0x80
/* longjmp() arguments. */
#define JUMP_PARENT 0x00
#define JUMP_CHILD 0xA0
#define JUMP_INIT 0xA1
/* JSON buffer. */
#define JSON_MAX 4096
/* Assume the stack grows down, so arguments should be above it. */
struct clone_t {
/*
* Reserve some space for clone() to locate arguments
* and retcode in this place
*/
char stack[4096] __attribute__ ((aligned(16)));
char stack_ptr[0];
/* There's two children. This is used to execute the different code. */
jmp_buf *env;
int jmpval;
};
struct nlconfig_t {
char *data;
/* Process settings. */
uint32_t cloneflags;
char *oom_score_adj;
size_t oom_score_adj_len;
/* User namespace settings. */
char *uidmap;
size_t uidmap_len;
char *gidmap;
size_t gidmap_len;
char *namespaces;
size_t namespaces_len;
uint8_t is_setgroup;
/* Rootless container settings. */
uint8_t is_rootless_euid; /* boolean */
char *uidmappath;
size_t uidmappath_len;
char *gidmappath;
size_t gidmappath_len;
};
/*
* List of netlink message types sent to us as part of bootstrapping the init.
* These constants are defined in libcontainer/message_linux.go.
*/
#define INIT_MSG 62000
#define CLONE_FLAGS_ATTR 27281
#define NS_PATHS_ATTR 27282
#define UIDMAP_ATTR 27283
#define GIDMAP_ATTR 27284
#define SETGROUP_ATTR 27285
#define OOM_SCORE_ADJ_ATTR 27286
#define ROOTLESS_EUID_ATTR 27287
#define UIDMAPPATH_ATTR 27288
#define GIDMAPPATH_ATTR 27289
/*
* Use the raw syscall for versions of glibc which don't include a function for
* it, namely (glibc 2.12).
*/
#if __GLIBC__ == 2 && __GLIBC_MINOR__ < 14
# define _GNU_SOURCE
# include "syscall.h"
# if !defined(SYS_setns) && defined(__NR_setns)
# define SYS_setns __NR_setns
# endif
#ifndef SYS_setns
# error "setns(2) syscall not supported by glibc version"
#endif
int setns(int fd, int nstype)
{
return syscall(SYS_setns, fd, nstype);
}
#endif
/* XXX: This is ugly. */
static int syncfd = -1;
/* TODO(cyphar): Fix this so it correctly deals with syncT. */
#define bail(fmt, ...) \
do { \
int ret = __COUNTER__ + 1; \
fprintf(stderr, "nsenter: " fmt ": %m\n", ##__VA_ARGS__); \
if (syncfd >= 0) { \
enum sync_t s = SYNC_ERR; \
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) \
fprintf(stderr, "nsenter: failed: write(s)"); \
if (write(syncfd, &ret, sizeof(ret)) != sizeof(ret)) \
fprintf(stderr, "nsenter: failed: write(ret)"); \
} \
exit(ret); \
} while(0)
static int write_file(char *data, size_t data_len, char *pathfmt, ...)
{
int fd, len, ret = 0;
char path[PATH_MAX];
va_list ap;
va_start(ap, pathfmt);
len = vsnprintf(path, PATH_MAX, pathfmt, ap);
va_end(ap);
if (len < 0)
return -1;
fd = open(path, O_RDWR);
if (fd < 0) {
return -1;
}
len = write(fd, data, data_len);
if (len != data_len) {
ret = -1;
goto out;
}
out:
close(fd);
return ret;
}
enum policy_t {
SETGROUPS_DEFAULT = 0,
SETGROUPS_ALLOW,
SETGROUPS_DENY,
};
/* This *must* be called before we touch gid_map. */
static void update_setgroups(int pid, enum policy_t setgroup)
{
char *policy;
switch (setgroup) {
case SETGROUPS_ALLOW:
policy = "allow";
break;
case SETGROUPS_DENY:
policy = "deny";
break;
case SETGROUPS_DEFAULT:
default:
/* Nothing to do. */
return;
}
if (write_file(policy, strlen(policy), "/proc/%d/setgroups", pid) < 0) {
/*
* If the kernel is too old to support /proc/pid/setgroups,
* open(2) or write(2) will return ENOENT. This is fine.
*/
if (errno != ENOENT)
bail("failed to write '%s' to /proc/%d/setgroups", policy, pid);
}
}
static int try_mapping_tool(const char *app, int pid, char *map, size_t map_len)
{
int child;
/*
* If @app is NULL, execve will segfault. Just check it here and bail (if
* we're in this path, the caller is already getting desperate and there
* isn't a backup to this failing). This usually would be a configuration
* or programming issue.
*/
if (!app)
bail("mapping tool not present");
child = fork();
if (child < 0)
bail("failed to fork");
if (!child) {
#define MAX_ARGV 20
char *argv[MAX_ARGV];
char *envp[] = { NULL };
char pid_fmt[16];
int argc = 0;
char *next;
snprintf(pid_fmt, 16, "%d", pid);
argv[argc++] = (char *)app;
argv[argc++] = pid_fmt;
/*
* Convert the map string into a list of argument that
* newuidmap/newgidmap can understand.
*/
while (argc < MAX_ARGV) {
if (*map == '\0') {
argv[argc++] = NULL;
break;
}
argv[argc++] = map;
next = strpbrk(map, "\n ");
if (next == NULL)
break;
*next++ = '\0';
map = next + strspn(next, "\n ");
}
execve(app, argv, envp);
bail("failed to execv");
} else {
int status;
while (true) {
if (waitpid(child, &status, 0) < 0) {
if (errno == EINTR)
continue;
bail("failed to waitpid");
}
if (WIFEXITED(status) || WIFSIGNALED(status))
return WEXITSTATUS(status);
}
}
return -1;
}
static void update_uidmap(const char *path, int pid, char *map, size_t map_len)
{
if (map == NULL || map_len <= 0)
return;
if (write_file(map, map_len, "/proc/%d/uid_map", pid) < 0) {
if (errno != EPERM)
bail("failed to update /proc/%d/uid_map", pid);
if (try_mapping_tool(path, pid, map, map_len))
bail("failed to use newuid map on %d", pid);
}
}
static void update_gidmap(const char *path, int pid, char *map, size_t map_len)
{
if (map == NULL || map_len <= 0)
return;
if (write_file(map, map_len, "/proc/%d/gid_map", pid) < 0) {
if (errno != EPERM)
bail("failed to update /proc/%d/gid_map", pid);
if (try_mapping_tool(path, pid, map, map_len))
bail("failed to use newgid map on %d", pid);
}
}
static void update_oom_score_adj(char *data, size_t len)
{
if (data == NULL || len <= 0)
return;
if (write_file(data, len, "/proc/self/oom_score_adj") < 0)
bail("failed to update /proc/self/oom_score_adj");
}
/* A dummy function that just jumps to the given jumpval. */
static int child_func(void *arg) __attribute__ ((noinline));
static int child_func(void *arg)
{
struct clone_t *ca = (struct clone_t *)arg;
longjmp(*ca->env, ca->jmpval);
}
static int clone_parent(jmp_buf *env, int jmpval) __attribute__ ((noinline));
static int clone_parent(jmp_buf *env, int jmpval)
{
struct clone_t ca = {
.env = env,
.jmpval = jmpval,
};
return clone(child_func, ca.stack_ptr, CLONE_PARENT | SIGCHLD, &ca);
}
/*
* Gets the init pipe fd from the environment, which is used to read the
* bootstrap data and tell the parent what the new pid is after we finish
* setting up the environment.
*/
static int initpipe(void)
{
int pipenum;
char *initpipe, *endptr;
initpipe = getenv("_LIBCONTAINER_INITPIPE");
if (initpipe == NULL || *initpipe == '\0')
return -1;
pipenum = strtol(initpipe, &endptr, 10);
if (*endptr != '\0')
bail("unable to parse _LIBCONTAINER_INITPIPE");
return pipenum;
}
/* Returns the clone(2) flag for a namespace, given the name of a namespace. */
static int nsflag(char *name)
{
if (!strcmp(name, "cgroup"))
return CLONE_NEWCGROUP;
else if (!strcmp(name, "ipc"))
return CLONE_NEWIPC;
else if (!strcmp(name, "mnt"))
return CLONE_NEWNS;
else if (!strcmp(name, "net"))
return CLONE_NEWNET;
else if (!strcmp(name, "pid"))
return CLONE_NEWPID;
else if (!strcmp(name, "user"))
return CLONE_NEWUSER;
else if (!strcmp(name, "uts"))
return CLONE_NEWUTS;
/* If we don't recognise a name, fallback to 0. */
return 0;
}
static uint32_t readint32(char *buf)
{
return *(uint32_t *) buf;
}
static uint8_t readint8(char *buf)
{
return *(uint8_t *) buf;
}
static void nl_parse(int fd, struct nlconfig_t *config)
{
size_t len, size;
struct nlmsghdr hdr;
char *data, *current;
/* Retrieve the netlink header. */
len = read(fd, &hdr, NLMSG_HDRLEN);
if (len != NLMSG_HDRLEN)
bail("invalid netlink header length %zu", len);
if (hdr.nlmsg_type == NLMSG_ERROR)
bail("failed to read netlink message");
if (hdr.nlmsg_type != INIT_MSG)
bail("unexpected msg type %d", hdr.nlmsg_type);
/* Retrieve data. */
size = NLMSG_PAYLOAD(&hdr, 0);
current = data = malloc(size);
if (!data)
bail("failed to allocate %zu bytes of memory for nl_payload", size);
len = read(fd, data, size);
if (len != size)
bail("failed to read netlink payload, %zu != %zu", len, size);
/* Parse the netlink payload. */
config->data = data;
while (current < data + size) {
struct nlattr *nlattr = (struct nlattr *)current;
size_t payload_len = nlattr->nla_len - NLA_HDRLEN;
/* Advance to payload. */
current += NLA_HDRLEN;
/* Handle payload. */
switch (nlattr->nla_type) {
case CLONE_FLAGS_ATTR:
config->cloneflags = readint32(current);
break;
case ROOTLESS_EUID_ATTR:
config->is_rootless_euid = readint8(current); /* boolean */
break;
case OOM_SCORE_ADJ_ATTR:
config->oom_score_adj = current;
config->oom_score_adj_len = payload_len;
break;
case NS_PATHS_ATTR:
config->namespaces = current;
config->namespaces_len = payload_len;
break;
case UIDMAP_ATTR:
config->uidmap = current;
config->uidmap_len = payload_len;
break;
case GIDMAP_ATTR:
config->gidmap = current;
config->gidmap_len = payload_len;
break;
case UIDMAPPATH_ATTR:
config->uidmappath = current;
config->uidmappath_len = payload_len;
break;
case GIDMAPPATH_ATTR:
config->gidmappath = current;
config->gidmappath_len = payload_len;
break;
case SETGROUP_ATTR:
config->is_setgroup = readint8(current);
break;
default:
bail("unknown netlink message type %d", nlattr->nla_type);
}
current += NLA_ALIGN(payload_len);
}
}
void nl_free(struct nlconfig_t *config)
{
free(config->data);
}
void join_namespaces(char *nslist)
{
int num = 0, i;
char *saveptr = NULL;
char *namespace = strtok_r(nslist, ",", &saveptr);
struct namespace_t {
int fd;
int ns;
char type[PATH_MAX];
char path[PATH_MAX];
} *namespaces = NULL;
if (!namespace || !strlen(namespace) || !strlen(nslist))
bail("ns paths are empty");
/*
* We have to open the file descriptors first, since after
* we join the mnt namespace we might no longer be able to
* access the paths.
*/
do {
int fd;
char *path;
struct namespace_t *ns;
/* Resize the namespace array. */
namespaces = realloc(namespaces, ++num * sizeof(struct namespace_t));
if (!namespaces)
bail("failed to reallocate namespace array");
ns = &namespaces[num - 1];
/* Split 'ns:path'. */
path = strstr(namespace, ":");
if (!path)
bail("failed to parse %s", namespace);
*path++ = '\0';
fd = open(path, O_RDONLY);
if (fd < 0)
bail("failed to open %s", path);
ns->fd = fd;
ns->ns = nsflag(namespace);
strncpy(ns->path, path, PATH_MAX - 1);
ns->path[PATH_MAX - 1] = '\0';
} while ((namespace = strtok_r(NULL, ",", &saveptr)) != NULL);
/*
* The ordering in which we join namespaces is important. We should
* always join the user namespace *first*. This is all guaranteed
* from the container_linux.go side of this, so we're just going to
* follow the order given to us.
*/
for (i = 0; i < num; i++) {
struct namespace_t ns = namespaces[i];
if (setns(ns.fd, ns.ns) < 0)
bail("failed to setns to %s", ns.path);
close(ns.fd);
}
free(namespaces);
}
void nsexec(void)
{
int pipenum;
jmp_buf env;
int sync_child_pipe[2], sync_grandchild_pipe[2];
struct nlconfig_t config = { 0 };
/*
* If we don't have an init pipe, just return to the go routine.
* We'll only get an init pipe for start or exec.
*/
pipenum = initpipe();
if (pipenum == -1)
return;
/* Parse all of the netlink configuration. */
nl_parse(pipenum, &config);
/* Set oom_score_adj. This has to be done before !dumpable because
* /proc/self/oom_score_adj is not writeable unless you're an privileged
* user (if !dumpable is set). All children inherit their parent's
* oom_score_adj value on fork(2) so this will always be propagated
* properly.
*/
update_oom_score_adj(config.oom_score_adj, config.oom_score_adj_len);
/*
* Make the process non-dumpable, to avoid various race conditions that
* could cause processes in namespaces we're joining to access host
* resources (or potentially execute code).
*
* However, if the number of namespaces we are joining is 0, we are not
* going to be switching to a different security context. Thus setting
* ourselves to be non-dumpable only breaks things (like rootless
* containers), which is the recommendation from the kernel folks.
*/
if (config.namespaces) {
if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) < 0)
bail("failed to set process as non-dumpable");
}
/* Pipe so we can tell the child when we've finished setting up. */
if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sync_child_pipe) < 0)
bail("failed to setup sync pipe between parent and child");
/*
* We need a new socketpair to sync with grandchild so we don't have
* race condition with child.
*/
if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sync_grandchild_pipe) < 0)
bail("failed to setup sync pipe between parent and grandchild");
/* TODO: Currently we aren't dealing with child deaths properly. */
/*
* Okay, so this is quite annoying.
*
* In order for this unsharing code to be more extensible we need to split
* up unshare(CLONE_NEWUSER) and clone() in various ways. The ideal case
* would be if we did clone(CLONE_NEWUSER) and the other namespaces
* separately, but because of SELinux issues we cannot really do that. But
* we cannot just dump the namespace flags into clone(...) because several
* usecases (such as rootless containers) require more granularity around
* the namespace setup. In addition, some older kernels had issues where
* CLONE_NEWUSER wasn't handled before other namespaces (but we cannot
* handle this while also dealing with SELinux so we choose SELinux support
* over broken kernel support).
*
* However, if we unshare(2) the user namespace *before* we clone(2), then
* all hell breaks loose.
*
* The parent no longer has permissions to do many things (unshare(2) drops
* all capabilities in your old namespace), and the container cannot be set
* up to have more than one {uid,gid} mapping. This is obviously less than
* ideal. In order to fix this, we have to first clone(2) and then unshare.
*
* Unfortunately, it's not as simple as that. We have to fork to enter the
* PID namespace (the PID namespace only applies to children). Since we'll
* have to double-fork, this clone_parent() call won't be able to get the
* PID of the _actual_ init process (without doing more synchronisation than
* I can deal with at the moment). So we'll just get the parent to send it
* for us, the only job of this process is to update
* /proc/pid/{setgroups,uid_map,gid_map}.
*
* And as a result of the above, we also need to setns(2) in the first child
* because if we join a PID namespace in the topmost parent then our child
* will be in that namespace (and it will not be able to give us a PID value
* that makes sense without resorting to sending things with cmsg).
*
* This also deals with an older issue caused by dumping cloneflags into
* clone(2): On old kernels, CLONE_PARENT didn't work with CLONE_NEWPID, so
* we have to unshare(2) before clone(2) in order to do this. This was fixed
* in upstream commit 1f7f4dde5c945f41a7abc2285be43d918029ecc5, and was
* introduced by 40a0d32d1eaffe6aac7324ca92604b6b3977eb0e. As far as we're
* aware, the last mainline kernel which had this bug was Linux 3.12.
* However, we cannot comment on which kernels the broken patch was
* backported to.
*
* -- Aleksa "what has my life come to?" Sarai
*/
switch (setjmp(env)) {
/*
* Stage 0: We're in the parent. Our job is just to create a new child
* (stage 1: JUMP_CHILD) process and write its uid_map and
* gid_map. That process will go on to create a new process, then
* it will send us its PID which we will send to the bootstrap
* process.
*/
case JUMP_PARENT:{
int len;
pid_t child, first_child = -1;
bool ready = false;
/* For debugging. */
prctl(PR_SET_NAME, (unsigned long)"runc:[0:PARENT]", 0, 0, 0);
/* Start the process of getting a container. */
child = clone_parent(&env, JUMP_CHILD);
if (child < 0)
bail("unable to fork: child_func");
/*
* State machine for synchronisation with the children.
*
* Father only return when both child and grandchild are
* ready, so we can receive all possible error codes
* generated by children.
*/
while (!ready) {
enum sync_t s;
int ret;
syncfd = sync_child_pipe[1];
close(sync_child_pipe[0]);
if (read(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with child: next state");
switch (s) {
case SYNC_ERR:
/* We have to mirror the error code of the child. */
if (read(syncfd, &ret, sizeof(ret)) != sizeof(ret))
bail("failed to sync with child: read(error code)");
exit(ret);
case SYNC_USERMAP_PLS:
/*
* Enable setgroups(2) if we've been asked to. But we also
* have to explicitly disable setgroups(2) if we're
* creating a rootless container for single-entry mapping.
* i.e. config.is_setgroup == false.
* (this is required since Linux 3.19).
*
* For rootless multi-entry mapping, config.is_setgroup shall be true and
* newuidmap/newgidmap shall be used.
*/
if (config.is_rootless_euid && !config.is_setgroup)
update_setgroups(child, SETGROUPS_DENY);
/* Set up mappings. */
update_uidmap(config.uidmappath, child, config.uidmap, config.uidmap_len);
update_gidmap(config.gidmappath, child, config.gidmap, config.gidmap_len);
s = SYNC_USERMAP_ACK;
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(child, SIGKILL);
bail("failed to sync with child: write(SYNC_USERMAP_ACK)");
}
break;
case SYNC_RECVPID_PLS:{
first_child = child;
/* Get the init_func pid. */
if (read(syncfd, &child, sizeof(child)) != sizeof(child)) {
kill(first_child, SIGKILL);
bail("failed to sync with child: read(childpid)");
}
/* Send ACK. */
s = SYNC_RECVPID_ACK;
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(first_child, SIGKILL);
kill(child, SIGKILL);
bail("failed to sync with child: write(SYNC_RECVPID_ACK)");
}
/* Send the init_func pid back to our parent.
*
* Send the init_func pid and the pid of the first child back to our parent.
* We need to send both back because we can't reap the first child we created (CLONE_PARENT).
* It becomes the responsibility of our parent to reap the first child.
*/
len = dprintf(pipenum, "{\"pid\": %d, \"pid_first\": %d}\n", child, first_child);
if (len < 0) {
kill(child, SIGKILL);
bail("unable to generate JSON for child pid");
}
}
break;
case SYNC_CHILD_READY:
ready = true;
break;
default:
bail("unexpected sync value: %u", s);
}
}
/* Now sync with grandchild. */
ready = false;
while (!ready) {
enum sync_t s;
int ret;
syncfd = sync_grandchild_pipe[1];
close(sync_grandchild_pipe[0]);
s = SYNC_GRANDCHILD;
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(child, SIGKILL);
bail("failed to sync with child: write(SYNC_GRANDCHILD)");
}
if (read(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with child: next state");
switch (s) {
case SYNC_ERR:
/* We have to mirror the error code of the child. */
if (read(syncfd, &ret, sizeof(ret)) != sizeof(ret))
bail("failed to sync with child: read(error code)");
exit(ret);
case SYNC_CHILD_READY:
ready = true;
break;
default:
bail("unexpected sync value: %u", s);
}
}
exit(0);
}
/*
* Stage 1: We're in the first child process. Our job is to join any
* provided namespaces in the netlink payload and unshare all
* of the requested namespaces. If we've been asked to
* CLONE_NEWUSER, we will ask our parent (stage 0) to set up
* our user mappings for us. Then, we create a new child
* (stage 2: JUMP_INIT) for PID namespace. We then send the
* child's PID to our parent (stage 0).
*/
case JUMP_CHILD:{
pid_t child;
enum sync_t s;
/* We're in a child and thus need to tell the parent if we die. */
syncfd = sync_child_pipe[0];
close(sync_child_pipe[1]);
/* For debugging. */
prctl(PR_SET_NAME, (unsigned long)"runc:[1:CHILD]", 0, 0, 0);
/*
* We need to setns first. We cannot do this earlier (in stage 0)
* because of the fact that we forked to get here (the PID of
* [stage 2: JUMP_INIT]) would be meaningless). We could send it
* using cmsg(3) but that's just annoying.
*/
if (config.namespaces)
join_namespaces(config.namespaces);
/*
* Deal with user namespaces first. They are quite special, as they
* affect our ability to unshare other namespaces and are used as
* context for privilege checks.
*
* We don't unshare all namespaces in one go. The reason for this
* is that, while the kernel documentation may claim otherwise,
* there are certain cases where unsharing all namespaces at once
* will result in namespace objects being owned incorrectly.
* Ideally we should just fix these kernel bugs, but it's better to
* be safe than sorry, and fix them separately.
*
* A specific case of this is that the SELinux label of the
* internal kern-mount that mqueue uses will be incorrect if the
* UTS namespace is cloned before the USER namespace is mapped.
* I've also heard of similar problems with the network namespace
* in some scenarios. This also mirrors how LXC deals with this
* problem.
*/
if (config.cloneflags & CLONE_NEWUSER) {
if (unshare(CLONE_NEWUSER) < 0)
bail("failed to unshare user namespace");
config.cloneflags &= ~CLONE_NEWUSER;
/*
* We don't have the privileges to do any mapping here (see the
* clone_parent rant). So signal our parent to hook us up.
*/
/* Switching is only necessary if we joined namespaces. */
if (config.namespaces) {
if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0)
bail("failed to set process as dumpable");
}
s = SYNC_USERMAP_PLS;
if (write(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with parent: write(SYNC_USERMAP_PLS)");
/* ... wait for mapping ... */
if (read(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with parent: read(SYNC_USERMAP_ACK)");
if (s != SYNC_USERMAP_ACK)
bail("failed to sync with parent: SYNC_USERMAP_ACK: got %u", s);
/* Switching is only necessary if we joined namespaces. */
if (config.namespaces) {
if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) < 0)
bail("failed to set process as dumpable");
}
/* Become root in the namespace proper. */
if (setresuid(0, 0, 0) < 0)
bail("failed to become root in user namespace");
}
/*
* Unshare all of the namespaces. Now, it should be noted that this
* ordering might break in the future (especially with rootless
* containers). But for now, it's not possible to split this into
* CLONE_NEWUSER + [the rest] because of some RHEL SELinux issues.
*
* Note that we don't merge this with clone() because there were
* some old kernel versions where clone(CLONE_PARENT | CLONE_NEWPID)
* was broken, so we'll just do it the long way anyway.
*/
if (unshare(config.cloneflags & ~CLONE_NEWCGROUP) < 0)
bail("failed to unshare namespaces");
/*
* TODO: What about non-namespace clone flags that we're dropping here?
*
* We fork again because of PID namespace, setns(2) or unshare(2) don't
* change the PID namespace of the calling process, because doing so
* would change the caller's idea of its own PID (as reported by getpid()),
* which would break many applications and libraries, so we must fork
* to actually enter the new PID namespace.
*/
child = clone_parent(&env, JUMP_INIT);
if (child < 0)
bail("unable to fork: init_func");
/* Send the child to our parent, which knows what it's doing. */
s = SYNC_RECVPID_PLS;
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(child, SIGKILL);
bail("failed to sync with parent: write(SYNC_RECVPID_PLS)");
}
if (write(syncfd, &child, sizeof(child)) != sizeof(child)) {
kill(child, SIGKILL);
bail("failed to sync with parent: write(childpid)");
}
/* ... wait for parent to get the pid ... */
if (read(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(child, SIGKILL);
bail("failed to sync with parent: read(SYNC_RECVPID_ACK)");
}
if (s != SYNC_RECVPID_ACK) {
kill(child, SIGKILL);
bail("failed to sync with parent: SYNC_RECVPID_ACK: got %u", s);
}
s = SYNC_CHILD_READY;
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(child, SIGKILL);
bail("failed to sync with parent: write(SYNC_CHILD_READY)");
}
/* Our work is done. [Stage 2: JUMP_INIT] is doing the rest of the work. */
exit(0);
}
/*
* Stage 2: We're the final child process, and the only process that will
* actually return to the Go runtime. Our job is to just do the
* final cleanup steps and then return to the Go runtime to allow
* init_linux.go to run.
*/
case JUMP_INIT:{
/*
* We're inside the child now, having jumped from the
* start_child() code after forking in the parent.
*/
enum sync_t s;
/* We're in a child and thus need to tell the parent if we die. */
syncfd = sync_grandchild_pipe[0];
close(sync_grandchild_pipe[1]);
close(sync_child_pipe[0]);
close(sync_child_pipe[1]);
/* For debugging. */
prctl(PR_SET_NAME, (unsigned long)"runc:[2:INIT]", 0, 0, 0);
if (read(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with parent: read(SYNC_GRANDCHILD)");
if (s != SYNC_GRANDCHILD)
bail("failed to sync with parent: SYNC_GRANDCHILD: got %u", s);
if (setsid() < 0)
bail("setsid failed");
if (setuid(0) < 0)
bail("setuid failed");
if (setgid(0) < 0)
bail("setgid failed");
if (!config.is_rootless_euid && config.is_setgroup) {
if (setgroups(0, NULL) < 0)
bail("setgroups failed");
}
/* ... wait until our topmost parent has finished cgroup setup in p.manager.Apply() ... */
if (config.cloneflags & CLONE_NEWCGROUP) {
uint8_t value;
if (read(pipenum, &value, sizeof(value)) != sizeof(value))
bail("read synchronisation value failed");
if (value == CREATECGROUPNS) {
if (unshare(CLONE_NEWCGROUP) < 0)
bail("failed to unshare cgroup namespace");
} else
bail("received unknown synchronisation value");
}
s = SYNC_CHILD_READY;
if (write(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with patent: write(SYNC_CHILD_READY)");
/* Close sync pipes. */
close(sync_grandchild_pipe[0]);
/* Free netlink data. */
nl_free(&config);
/* Finish executing, let the Go runtime take over. */
return;
}
default:
bail("unexpected jump value");
}
/* Should never be reached. */
bail("should never be reached");
}
| ./CrossVul/dataset_final_sorted/CWE-216/c/bad_1396_1 |
crossvul-cpp_data_bad_1396_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-216/c/bad_1396_0 |
crossvul-cpp_data_bad_1395_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-216/c/bad_1395_0 |
crossvul-cpp_data_good_1396_0 | /*
* Copyright (C) 2019 Aleksa Sarai <cyphar@cyphar.com>
* Copyright (C) 2019 SUSE LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <limits.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/vfs.h>
#include <sys/mman.h>
#include <sys/sendfile.h>
#include <sys/syscall.h>
/* Use our own wrapper for memfd_create. */
#if !defined(SYS_memfd_create) && defined(__NR_memfd_create)
# define SYS_memfd_create __NR_memfd_create
#endif
#ifdef SYS_memfd_create
# define HAVE_MEMFD_CREATE
/* memfd_create(2) flags -- copied from <linux/memfd.h>. */
# ifndef MFD_CLOEXEC
# define MFD_CLOEXEC 0x0001U
# define MFD_ALLOW_SEALING 0x0002U
# endif
int memfd_create(const char *name, unsigned int flags)
{
return syscall(SYS_memfd_create, name, flags);
}
#endif
/* This comes directly from <linux/fcntl.h>. */
#ifndef F_LINUX_SPECIFIC_BASE
# define F_LINUX_SPECIFIC_BASE 1024
#endif
#ifndef F_ADD_SEALS
# define F_ADD_SEALS (F_LINUX_SPECIFIC_BASE + 9)
# define F_GET_SEALS (F_LINUX_SPECIFIC_BASE + 10)
#endif
#ifndef F_SEAL_SEAL
# define F_SEAL_SEAL 0x0001 /* prevent further seals from being set */
# define F_SEAL_SHRINK 0x0002 /* prevent file from shrinking */
# define F_SEAL_GROW 0x0004 /* prevent file from growing */
# define F_SEAL_WRITE 0x0008 /* prevent writes */
#endif
#define RUNC_SENDFILE_MAX 0x7FFFF000 /* sendfile(2) is limited to 2GB. */
#ifdef HAVE_MEMFD_CREATE
# define RUNC_MEMFD_COMMENT "runc_cloned:/proc/self/exe"
# define RUNC_MEMFD_SEALS \
(F_SEAL_SEAL | F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE)
#endif
static void *must_realloc(void *ptr, size_t size)
{
void *old = ptr;
do {
ptr = realloc(old, size);
} while(!ptr);
return ptr;
}
/*
* Verify whether we are currently in a self-cloned program (namely, is
* /proc/self/exe a memfd). F_GET_SEALS will only succeed for memfds (or rather
* for shmem files), and we want to be sure it's actually sealed.
*/
static int is_self_cloned(void)
{
int fd, ret, is_cloned = 0;
fd = open("/proc/self/exe", O_RDONLY|O_CLOEXEC);
if (fd < 0)
return -ENOTRECOVERABLE;
#ifdef HAVE_MEMFD_CREATE
ret = fcntl(fd, F_GET_SEALS);
is_cloned = (ret == RUNC_MEMFD_SEALS);
#else
struct stat statbuf = {0};
ret = fstat(fd, &statbuf);
if (ret >= 0)
is_cloned = (statbuf.st_nlink == 0);
#endif
close(fd);
return is_cloned;
}
/*
* Basic wrapper around mmap(2) that gives you the file length so you can
* safely treat it as an ordinary buffer. Only gives you read access.
*/
static char *read_file(char *path, size_t *length)
{
int fd;
char buf[4096], *copy = NULL;
if (!length)
return NULL;
fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0)
return NULL;
*length = 0;
for (;;) {
int n;
n = read(fd, buf, sizeof(buf));
if (n < 0)
goto error;
if (!n)
break;
copy = must_realloc(copy, (*length + n) * sizeof(*copy));
memcpy(copy + *length, buf, n);
*length += n;
}
close(fd);
return copy;
error:
close(fd);
free(copy);
return NULL;
}
/*
* A poor-man's version of "xargs -0". Basically parses a given block of
* NUL-delimited data, within the given length and adds a pointer to each entry
* to the array of pointers.
*/
static int parse_xargs(char *data, int data_length, char ***output)
{
int num = 0;
char *cur = data;
if (!data || *output != NULL)
return -1;
while (cur < data + data_length) {
num++;
*output = must_realloc(*output, (num + 1) * sizeof(**output));
(*output)[num - 1] = cur;
cur += strlen(cur) + 1;
}
(*output)[num] = NULL;
return num;
}
/*
* "Parse" out argv and envp from /proc/self/cmdline and /proc/self/environ.
* This is necessary because we are running in a context where we don't have a
* main() that we can just get the arguments from.
*/
static int fetchve(char ***argv, char ***envp)
{
char *cmdline = NULL, *environ = NULL;
size_t cmdline_size, environ_size;
cmdline = read_file("/proc/self/cmdline", &cmdline_size);
if (!cmdline)
goto error;
environ = read_file("/proc/self/environ", &environ_size);
if (!environ)
goto error;
if (parse_xargs(cmdline, cmdline_size, argv) <= 0)
goto error;
if (parse_xargs(environ, environ_size, envp) <= 0)
goto error;
return 0;
error:
free(environ);
free(cmdline);
return -EINVAL;
}
static int clone_binary(void)
{
int binfd, memfd;
ssize_t sent = 0;
#ifdef HAVE_MEMFD_CREATE
memfd = memfd_create(RUNC_MEMFD_COMMENT, MFD_CLOEXEC | MFD_ALLOW_SEALING);
#else
memfd = open("/tmp", O_TMPFILE | O_EXCL | O_RDWR | O_CLOEXEC, 0711);
#endif
if (memfd < 0)
return -ENOTRECOVERABLE;
binfd = open("/proc/self/exe", O_RDONLY | O_CLOEXEC);
if (binfd < 0)
goto error;
sent = sendfile(memfd, binfd, NULL, RUNC_SENDFILE_MAX);
close(binfd);
if (sent < 0)
goto error;
#ifdef HAVE_MEMFD_CREATE
int err = fcntl(memfd, F_ADD_SEALS, RUNC_MEMFD_SEALS);
if (err < 0)
goto error;
#else
/* Need to re-open "memfd" as read-only to avoid execve(2) giving -EXTBUSY. */
int newfd;
char *fdpath = NULL;
if (asprintf(&fdpath, "/proc/self/fd/%d", memfd) < 0)
goto error;
newfd = open(fdpath, O_RDONLY | O_CLOEXEC);
free(fdpath);
if (newfd < 0)
goto error;
close(memfd);
memfd = newfd;
#endif
return memfd;
error:
close(memfd);
return -EIO;
}
int ensure_cloned_binary(void)
{
int execfd;
char **argv = NULL, **envp = NULL;
/* Check that we're not self-cloned, and if we are then bail. */
int cloned = is_self_cloned();
if (cloned > 0 || cloned == -ENOTRECOVERABLE)
return cloned;
if (fetchve(&argv, &envp) < 0)
return -EINVAL;
execfd = clone_binary();
if (execfd < 0)
return -EIO;
fexecve(execfd, argv, envp);
return -ENOEXEC;
}
| ./CrossVul/dataset_final_sorted/CWE-216/c/good_1396_0 |
crossvul-cpp_data_good_1395_1 |
#define _GNU_SOURCE
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <sched.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <linux/limits.h>
#include <linux/netlink.h>
#include <linux/types.h>
/* Get all of the CLONE_NEW* flags. */
#include "namespace.h"
/* Synchronisation values. */
enum sync_t {
SYNC_USERMAP_PLS = 0x40, /* Request parent to map our users. */
SYNC_USERMAP_ACK = 0x41, /* Mapping finished by the parent. */
SYNC_RECVPID_PLS = 0x42, /* Tell parent we're sending the PID. */
SYNC_RECVPID_ACK = 0x43, /* PID was correctly received by parent. */
SYNC_GRANDCHILD = 0x44, /* The grandchild is ready to run. */
SYNC_CHILD_READY = 0x45, /* The child or grandchild is ready to return. */
/* XXX: This doesn't help with segfaults and other such issues. */
SYNC_ERR = 0xFF, /* Fatal error, no turning back. The error code follows. */
};
/*
* Synchronisation value for cgroup namespace setup.
* The same constant is defined in process_linux.go as "createCgroupns".
*/
#define CREATECGROUPNS 0x80
/* longjmp() arguments. */
#define JUMP_PARENT 0x00
#define JUMP_CHILD 0xA0
#define JUMP_INIT 0xA1
/* JSON buffer. */
#define JSON_MAX 4096
/* Assume the stack grows down, so arguments should be above it. */
struct clone_t {
/*
* Reserve some space for clone() to locate arguments
* and retcode in this place
*/
char stack[4096] __attribute__ ((aligned(16)));
char stack_ptr[0];
/* There's two children. This is used to execute the different code. */
jmp_buf *env;
int jmpval;
};
struct nlconfig_t {
char *data;
/* Process settings. */
uint32_t cloneflags;
char *oom_score_adj;
size_t oom_score_adj_len;
/* User namespace settings. */
char *uidmap;
size_t uidmap_len;
char *gidmap;
size_t gidmap_len;
char *namespaces;
size_t namespaces_len;
uint8_t is_setgroup;
/* Rootless container settings. */
uint8_t is_rootless_euid; /* boolean */
char *uidmappath;
size_t uidmappath_len;
char *gidmappath;
size_t gidmappath_len;
};
/*
* List of netlink message types sent to us as part of bootstrapping the init.
* These constants are defined in libcontainer/message_linux.go.
*/
#define INIT_MSG 62000
#define CLONE_FLAGS_ATTR 27281
#define NS_PATHS_ATTR 27282
#define UIDMAP_ATTR 27283
#define GIDMAP_ATTR 27284
#define SETGROUP_ATTR 27285
#define OOM_SCORE_ADJ_ATTR 27286
#define ROOTLESS_EUID_ATTR 27287
#define UIDMAPPATH_ATTR 27288
#define GIDMAPPATH_ATTR 27289
/*
* Use the raw syscall for versions of glibc which don't include a function for
* it, namely (glibc 2.12).
*/
#if __GLIBC__ == 2 && __GLIBC_MINOR__ < 14
# define _GNU_SOURCE
# include "syscall.h"
# if !defined(SYS_setns) && defined(__NR_setns)
# define SYS_setns __NR_setns
# endif
#ifndef SYS_setns
# error "setns(2) syscall not supported by glibc version"
#endif
int setns(int fd, int nstype)
{
return syscall(SYS_setns, fd, nstype);
}
#endif
/* XXX: This is ugly. */
static int syncfd = -1;
/* TODO(cyphar): Fix this so it correctly deals with syncT. */
#define bail(fmt, ...) \
do { \
int ret = __COUNTER__ + 1; \
fprintf(stderr, "nsenter: " fmt ": %m\n", ##__VA_ARGS__); \
if (syncfd >= 0) { \
enum sync_t s = SYNC_ERR; \
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) \
fprintf(stderr, "nsenter: failed: write(s)"); \
if (write(syncfd, &ret, sizeof(ret)) != sizeof(ret)) \
fprintf(stderr, "nsenter: failed: write(ret)"); \
} \
exit(ret); \
} while(0)
static int write_file(char *data, size_t data_len, char *pathfmt, ...)
{
int fd, len, ret = 0;
char path[PATH_MAX];
va_list ap;
va_start(ap, pathfmt);
len = vsnprintf(path, PATH_MAX, pathfmt, ap);
va_end(ap);
if (len < 0)
return -1;
fd = open(path, O_RDWR);
if (fd < 0) {
return -1;
}
len = write(fd, data, data_len);
if (len != data_len) {
ret = -1;
goto out;
}
out:
close(fd);
return ret;
}
enum policy_t {
SETGROUPS_DEFAULT = 0,
SETGROUPS_ALLOW,
SETGROUPS_DENY,
};
/* This *must* be called before we touch gid_map. */
static void update_setgroups(int pid, enum policy_t setgroup)
{
char *policy;
switch (setgroup) {
case SETGROUPS_ALLOW:
policy = "allow";
break;
case SETGROUPS_DENY:
policy = "deny";
break;
case SETGROUPS_DEFAULT:
default:
/* Nothing to do. */
return;
}
if (write_file(policy, strlen(policy), "/proc/%d/setgroups", pid) < 0) {
/*
* If the kernel is too old to support /proc/pid/setgroups,
* open(2) or write(2) will return ENOENT. This is fine.
*/
if (errno != ENOENT)
bail("failed to write '%s' to /proc/%d/setgroups", policy, pid);
}
}
static int try_mapping_tool(const char *app, int pid, char *map, size_t map_len)
{
int child;
/*
* If @app is NULL, execve will segfault. Just check it here and bail (if
* we're in this path, the caller is already getting desperate and there
* isn't a backup to this failing). This usually would be a configuration
* or programming issue.
*/
if (!app)
bail("mapping tool not present");
child = fork();
if (child < 0)
bail("failed to fork");
if (!child) {
#define MAX_ARGV 20
char *argv[MAX_ARGV];
char *envp[] = { NULL };
char pid_fmt[16];
int argc = 0;
char *next;
snprintf(pid_fmt, 16, "%d", pid);
argv[argc++] = (char *)app;
argv[argc++] = pid_fmt;
/*
* Convert the map string into a list of argument that
* newuidmap/newgidmap can understand.
*/
while (argc < MAX_ARGV) {
if (*map == '\0') {
argv[argc++] = NULL;
break;
}
argv[argc++] = map;
next = strpbrk(map, "\n ");
if (next == NULL)
break;
*next++ = '\0';
map = next + strspn(next, "\n ");
}
execve(app, argv, envp);
bail("failed to execv");
} else {
int status;
while (true) {
if (waitpid(child, &status, 0) < 0) {
if (errno == EINTR)
continue;
bail("failed to waitpid");
}
if (WIFEXITED(status) || WIFSIGNALED(status))
return WEXITSTATUS(status);
}
}
return -1;
}
static void update_uidmap(const char *path, int pid, char *map, size_t map_len)
{
if (map == NULL || map_len <= 0)
return;
if (write_file(map, map_len, "/proc/%d/uid_map", pid) < 0) {
if (errno != EPERM)
bail("failed to update /proc/%d/uid_map", pid);
if (try_mapping_tool(path, pid, map, map_len))
bail("failed to use newuid map on %d", pid);
}
}
static void update_gidmap(const char *path, int pid, char *map, size_t map_len)
{
if (map == NULL || map_len <= 0)
return;
if (write_file(map, map_len, "/proc/%d/gid_map", pid) < 0) {
if (errno != EPERM)
bail("failed to update /proc/%d/gid_map", pid);
if (try_mapping_tool(path, pid, map, map_len))
bail("failed to use newgid map on %d", pid);
}
}
static void update_oom_score_adj(char *data, size_t len)
{
if (data == NULL || len <= 0)
return;
if (write_file(data, len, "/proc/self/oom_score_adj") < 0)
bail("failed to update /proc/self/oom_score_adj");
}
/* A dummy function that just jumps to the given jumpval. */
static int child_func(void *arg) __attribute__ ((noinline));
static int child_func(void *arg)
{
struct clone_t *ca = (struct clone_t *)arg;
longjmp(*ca->env, ca->jmpval);
}
static int clone_parent(jmp_buf *env, int jmpval) __attribute__ ((noinline));
static int clone_parent(jmp_buf *env, int jmpval)
{
struct clone_t ca = {
.env = env,
.jmpval = jmpval,
};
return clone(child_func, ca.stack_ptr, CLONE_PARENT | SIGCHLD, &ca);
}
/*
* Gets the init pipe fd from the environment, which is used to read the
* bootstrap data and tell the parent what the new pid is after we finish
* setting up the environment.
*/
static int initpipe(void)
{
int pipenum;
char *initpipe, *endptr;
initpipe = getenv("_LIBCONTAINER_INITPIPE");
if (initpipe == NULL || *initpipe == '\0')
return -1;
pipenum = strtol(initpipe, &endptr, 10);
if (*endptr != '\0')
bail("unable to parse _LIBCONTAINER_INITPIPE");
return pipenum;
}
/* Returns the clone(2) flag for a namespace, given the name of a namespace. */
static int nsflag(char *name)
{
if (!strcmp(name, "cgroup"))
return CLONE_NEWCGROUP;
else if (!strcmp(name, "ipc"))
return CLONE_NEWIPC;
else if (!strcmp(name, "mnt"))
return CLONE_NEWNS;
else if (!strcmp(name, "net"))
return CLONE_NEWNET;
else if (!strcmp(name, "pid"))
return CLONE_NEWPID;
else if (!strcmp(name, "user"))
return CLONE_NEWUSER;
else if (!strcmp(name, "uts"))
return CLONE_NEWUTS;
/* If we don't recognise a name, fallback to 0. */
return 0;
}
static uint32_t readint32(char *buf)
{
return *(uint32_t *) buf;
}
static uint8_t readint8(char *buf)
{
return *(uint8_t *) buf;
}
static void nl_parse(int fd, struct nlconfig_t *config)
{
size_t len, size;
struct nlmsghdr hdr;
char *data, *current;
/* Retrieve the netlink header. */
len = read(fd, &hdr, NLMSG_HDRLEN);
if (len != NLMSG_HDRLEN)
bail("invalid netlink header length %zu", len);
if (hdr.nlmsg_type == NLMSG_ERROR)
bail("failed to read netlink message");
if (hdr.nlmsg_type != INIT_MSG)
bail("unexpected msg type %d", hdr.nlmsg_type);
/* Retrieve data. */
size = NLMSG_PAYLOAD(&hdr, 0);
current = data = malloc(size);
if (!data)
bail("failed to allocate %zu bytes of memory for nl_payload", size);
len = read(fd, data, size);
if (len != size)
bail("failed to read netlink payload, %zu != %zu", len, size);
/* Parse the netlink payload. */
config->data = data;
while (current < data + size) {
struct nlattr *nlattr = (struct nlattr *)current;
size_t payload_len = nlattr->nla_len - NLA_HDRLEN;
/* Advance to payload. */
current += NLA_HDRLEN;
/* Handle payload. */
switch (nlattr->nla_type) {
case CLONE_FLAGS_ATTR:
config->cloneflags = readint32(current);
break;
case ROOTLESS_EUID_ATTR:
config->is_rootless_euid = readint8(current); /* boolean */
break;
case OOM_SCORE_ADJ_ATTR:
config->oom_score_adj = current;
config->oom_score_adj_len = payload_len;
break;
case NS_PATHS_ATTR:
config->namespaces = current;
config->namespaces_len = payload_len;
break;
case UIDMAP_ATTR:
config->uidmap = current;
config->uidmap_len = payload_len;
break;
case GIDMAP_ATTR:
config->gidmap = current;
config->gidmap_len = payload_len;
break;
case UIDMAPPATH_ATTR:
config->uidmappath = current;
config->uidmappath_len = payload_len;
break;
case GIDMAPPATH_ATTR:
config->gidmappath = current;
config->gidmappath_len = payload_len;
break;
case SETGROUP_ATTR:
config->is_setgroup = readint8(current);
break;
default:
bail("unknown netlink message type %d", nlattr->nla_type);
}
current += NLA_ALIGN(payload_len);
}
}
void nl_free(struct nlconfig_t *config)
{
free(config->data);
}
void join_namespaces(char *nslist)
{
int num = 0, i;
char *saveptr = NULL;
char *namespace = strtok_r(nslist, ",", &saveptr);
struct namespace_t {
int fd;
int ns;
char type[PATH_MAX];
char path[PATH_MAX];
} *namespaces = NULL;
if (!namespace || !strlen(namespace) || !strlen(nslist))
bail("ns paths are empty");
/*
* We have to open the file descriptors first, since after
* we join the mnt namespace we might no longer be able to
* access the paths.
*/
do {
int fd;
char *path;
struct namespace_t *ns;
/* Resize the namespace array. */
namespaces = realloc(namespaces, ++num * sizeof(struct namespace_t));
if (!namespaces)
bail("failed to reallocate namespace array");
ns = &namespaces[num - 1];
/* Split 'ns:path'. */
path = strstr(namespace, ":");
if (!path)
bail("failed to parse %s", namespace);
*path++ = '\0';
fd = open(path, O_RDONLY);
if (fd < 0)
bail("failed to open %s", path);
ns->fd = fd;
ns->ns = nsflag(namespace);
strncpy(ns->path, path, PATH_MAX - 1);
ns->path[PATH_MAX - 1] = '\0';
} while ((namespace = strtok_r(NULL, ",", &saveptr)) != NULL);
/*
* The ordering in which we join namespaces is important. We should
* always join the user namespace *first*. This is all guaranteed
* from the container_linux.go side of this, so we're just going to
* follow the order given to us.
*/
for (i = 0; i < num; i++) {
struct namespace_t ns = namespaces[i];
if (setns(ns.fd, ns.ns) < 0)
bail("failed to setns to %s", ns.path);
close(ns.fd);
}
free(namespaces);
}
/* Defined in cloned_binary.c. */
extern int ensure_cloned_binary(void);
void nsexec(void)
{
int pipenum;
jmp_buf env;
int sync_child_pipe[2], sync_grandchild_pipe[2];
struct nlconfig_t config = { 0 };
/*
* If we don't have an init pipe, just return to the go routine.
* We'll only get an init pipe for start or exec.
*/
pipenum = initpipe();
if (pipenum == -1)
return;
/*
* We need to re-exec if we are not in a cloned binary. This is necessary
* to ensure that containers won't be able to access the host binary
* through /proc/self/exe. See CVE-2019-5736.
*/
if (ensure_cloned_binary() < 0)
bail("could not ensure we are a cloned binary");
/* Parse all of the netlink configuration. */
nl_parse(pipenum, &config);
/* Set oom_score_adj. This has to be done before !dumpable because
* /proc/self/oom_score_adj is not writeable unless you're an privileged
* user (if !dumpable is set). All children inherit their parent's
* oom_score_adj value on fork(2) so this will always be propagated
* properly.
*/
update_oom_score_adj(config.oom_score_adj, config.oom_score_adj_len);
/*
* Make the process non-dumpable, to avoid various race conditions that
* could cause processes in namespaces we're joining to access host
* resources (or potentially execute code).
*
* However, if the number of namespaces we are joining is 0, we are not
* going to be switching to a different security context. Thus setting
* ourselves to be non-dumpable only breaks things (like rootless
* containers), which is the recommendation from the kernel folks.
*/
if (config.namespaces) {
if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) < 0)
bail("failed to set process as non-dumpable");
}
/* Pipe so we can tell the child when we've finished setting up. */
if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sync_child_pipe) < 0)
bail("failed to setup sync pipe between parent and child");
/*
* We need a new socketpair to sync with grandchild so we don't have
* race condition with child.
*/
if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sync_grandchild_pipe) < 0)
bail("failed to setup sync pipe between parent and grandchild");
/* TODO: Currently we aren't dealing with child deaths properly. */
/*
* Okay, so this is quite annoying.
*
* In order for this unsharing code to be more extensible we need to split
* up unshare(CLONE_NEWUSER) and clone() in various ways. The ideal case
* would be if we did clone(CLONE_NEWUSER) and the other namespaces
* separately, but because of SELinux issues we cannot really do that. But
* we cannot just dump the namespace flags into clone(...) because several
* usecases (such as rootless containers) require more granularity around
* the namespace setup. In addition, some older kernels had issues where
* CLONE_NEWUSER wasn't handled before other namespaces (but we cannot
* handle this while also dealing with SELinux so we choose SELinux support
* over broken kernel support).
*
* However, if we unshare(2) the user namespace *before* we clone(2), then
* all hell breaks loose.
*
* The parent no longer has permissions to do many things (unshare(2) drops
* all capabilities in your old namespace), and the container cannot be set
* up to have more than one {uid,gid} mapping. This is obviously less than
* ideal. In order to fix this, we have to first clone(2) and then unshare.
*
* Unfortunately, it's not as simple as that. We have to fork to enter the
* PID namespace (the PID namespace only applies to children). Since we'll
* have to double-fork, this clone_parent() call won't be able to get the
* PID of the _actual_ init process (without doing more synchronisation than
* I can deal with at the moment). So we'll just get the parent to send it
* for us, the only job of this process is to update
* /proc/pid/{setgroups,uid_map,gid_map}.
*
* And as a result of the above, we also need to setns(2) in the first child
* because if we join a PID namespace in the topmost parent then our child
* will be in that namespace (and it will not be able to give us a PID value
* that makes sense without resorting to sending things with cmsg).
*
* This also deals with an older issue caused by dumping cloneflags into
* clone(2): On old kernels, CLONE_PARENT didn't work with CLONE_NEWPID, so
* we have to unshare(2) before clone(2) in order to do this. This was fixed
* in upstream commit 1f7f4dde5c945f41a7abc2285be43d918029ecc5, and was
* introduced by 40a0d32d1eaffe6aac7324ca92604b6b3977eb0e. As far as we're
* aware, the last mainline kernel which had this bug was Linux 3.12.
* However, we cannot comment on which kernels the broken patch was
* backported to.
*
* -- Aleksa "what has my life come to?" Sarai
*/
switch (setjmp(env)) {
/*
* Stage 0: We're in the parent. Our job is just to create a new child
* (stage 1: JUMP_CHILD) process and write its uid_map and
* gid_map. That process will go on to create a new process, then
* it will send us its PID which we will send to the bootstrap
* process.
*/
case JUMP_PARENT:{
int len;
pid_t child, first_child = -1;
bool ready = false;
/* For debugging. */
prctl(PR_SET_NAME, (unsigned long)"runc:[0:PARENT]", 0, 0, 0);
/* Start the process of getting a container. */
child = clone_parent(&env, JUMP_CHILD);
if (child < 0)
bail("unable to fork: child_func");
/*
* State machine for synchronisation with the children.
*
* Father only return when both child and grandchild are
* ready, so we can receive all possible error codes
* generated by children.
*/
while (!ready) {
enum sync_t s;
int ret;
syncfd = sync_child_pipe[1];
close(sync_child_pipe[0]);
if (read(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with child: next state");
switch (s) {
case SYNC_ERR:
/* We have to mirror the error code of the child. */
if (read(syncfd, &ret, sizeof(ret)) != sizeof(ret))
bail("failed to sync with child: read(error code)");
exit(ret);
case SYNC_USERMAP_PLS:
/*
* Enable setgroups(2) if we've been asked to. But we also
* have to explicitly disable setgroups(2) if we're
* creating a rootless container for single-entry mapping.
* i.e. config.is_setgroup == false.
* (this is required since Linux 3.19).
*
* For rootless multi-entry mapping, config.is_setgroup shall be true and
* newuidmap/newgidmap shall be used.
*/
if (config.is_rootless_euid && !config.is_setgroup)
update_setgroups(child, SETGROUPS_DENY);
/* Set up mappings. */
update_uidmap(config.uidmappath, child, config.uidmap, config.uidmap_len);
update_gidmap(config.gidmappath, child, config.gidmap, config.gidmap_len);
s = SYNC_USERMAP_ACK;
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(child, SIGKILL);
bail("failed to sync with child: write(SYNC_USERMAP_ACK)");
}
break;
case SYNC_RECVPID_PLS:{
first_child = child;
/* Get the init_func pid. */
if (read(syncfd, &child, sizeof(child)) != sizeof(child)) {
kill(first_child, SIGKILL);
bail("failed to sync with child: read(childpid)");
}
/* Send ACK. */
s = SYNC_RECVPID_ACK;
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(first_child, SIGKILL);
kill(child, SIGKILL);
bail("failed to sync with child: write(SYNC_RECVPID_ACK)");
}
/* Send the init_func pid back to our parent.
*
* Send the init_func pid and the pid of the first child back to our parent.
* We need to send both back because we can't reap the first child we created (CLONE_PARENT).
* It becomes the responsibility of our parent to reap the first child.
*/
len = dprintf(pipenum, "{\"pid\": %d, \"pid_first\": %d}\n", child, first_child);
if (len < 0) {
kill(child, SIGKILL);
bail("unable to generate JSON for child pid");
}
}
break;
case SYNC_CHILD_READY:
ready = true;
break;
default:
bail("unexpected sync value: %u", s);
}
}
/* Now sync with grandchild. */
ready = false;
while (!ready) {
enum sync_t s;
int ret;
syncfd = sync_grandchild_pipe[1];
close(sync_grandchild_pipe[0]);
s = SYNC_GRANDCHILD;
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(child, SIGKILL);
bail("failed to sync with child: write(SYNC_GRANDCHILD)");
}
if (read(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with child: next state");
switch (s) {
case SYNC_ERR:
/* We have to mirror the error code of the child. */
if (read(syncfd, &ret, sizeof(ret)) != sizeof(ret))
bail("failed to sync with child: read(error code)");
exit(ret);
case SYNC_CHILD_READY:
ready = true;
break;
default:
bail("unexpected sync value: %u", s);
}
}
exit(0);
}
/*
* Stage 1: We're in the first child process. Our job is to join any
* provided namespaces in the netlink payload and unshare all
* of the requested namespaces. If we've been asked to
* CLONE_NEWUSER, we will ask our parent (stage 0) to set up
* our user mappings for us. Then, we create a new child
* (stage 2: JUMP_INIT) for PID namespace. We then send the
* child's PID to our parent (stage 0).
*/
case JUMP_CHILD:{
pid_t child;
enum sync_t s;
/* We're in a child and thus need to tell the parent if we die. */
syncfd = sync_child_pipe[0];
close(sync_child_pipe[1]);
/* For debugging. */
prctl(PR_SET_NAME, (unsigned long)"runc:[1:CHILD]", 0, 0, 0);
/*
* We need to setns first. We cannot do this earlier (in stage 0)
* because of the fact that we forked to get here (the PID of
* [stage 2: JUMP_INIT]) would be meaningless). We could send it
* using cmsg(3) but that's just annoying.
*/
if (config.namespaces)
join_namespaces(config.namespaces);
/*
* Deal with user namespaces first. They are quite special, as they
* affect our ability to unshare other namespaces and are used as
* context for privilege checks.
*
* We don't unshare all namespaces in one go. The reason for this
* is that, while the kernel documentation may claim otherwise,
* there are certain cases where unsharing all namespaces at once
* will result in namespace objects being owned incorrectly.
* Ideally we should just fix these kernel bugs, but it's better to
* be safe than sorry, and fix them separately.
*
* A specific case of this is that the SELinux label of the
* internal kern-mount that mqueue uses will be incorrect if the
* UTS namespace is cloned before the USER namespace is mapped.
* I've also heard of similar problems with the network namespace
* in some scenarios. This also mirrors how LXC deals with this
* problem.
*/
if (config.cloneflags & CLONE_NEWUSER) {
if (unshare(CLONE_NEWUSER) < 0)
bail("failed to unshare user namespace");
config.cloneflags &= ~CLONE_NEWUSER;
/*
* We don't have the privileges to do any mapping here (see the
* clone_parent rant). So signal our parent to hook us up.
*/
/* Switching is only necessary if we joined namespaces. */
if (config.namespaces) {
if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0)
bail("failed to set process as dumpable");
}
s = SYNC_USERMAP_PLS;
if (write(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with parent: write(SYNC_USERMAP_PLS)");
/* ... wait for mapping ... */
if (read(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with parent: read(SYNC_USERMAP_ACK)");
if (s != SYNC_USERMAP_ACK)
bail("failed to sync with parent: SYNC_USERMAP_ACK: got %u", s);
/* Switching is only necessary if we joined namespaces. */
if (config.namespaces) {
if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) < 0)
bail("failed to set process as dumpable");
}
/* Become root in the namespace proper. */
if (setresuid(0, 0, 0) < 0)
bail("failed to become root in user namespace");
}
/*
* Unshare all of the namespaces. Now, it should be noted that this
* ordering might break in the future (especially with rootless
* containers). But for now, it's not possible to split this into
* CLONE_NEWUSER + [the rest] because of some RHEL SELinux issues.
*
* Note that we don't merge this with clone() because there were
* some old kernel versions where clone(CLONE_PARENT | CLONE_NEWPID)
* was broken, so we'll just do it the long way anyway.
*/
if (unshare(config.cloneflags & ~CLONE_NEWCGROUP) < 0)
bail("failed to unshare namespaces");
/*
* TODO: What about non-namespace clone flags that we're dropping here?
*
* We fork again because of PID namespace, setns(2) or unshare(2) don't
* change the PID namespace of the calling process, because doing so
* would change the caller's idea of its own PID (as reported by getpid()),
* which would break many applications and libraries, so we must fork
* to actually enter the new PID namespace.
*/
child = clone_parent(&env, JUMP_INIT);
if (child < 0)
bail("unable to fork: init_func");
/* Send the child to our parent, which knows what it's doing. */
s = SYNC_RECVPID_PLS;
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(child, SIGKILL);
bail("failed to sync with parent: write(SYNC_RECVPID_PLS)");
}
if (write(syncfd, &child, sizeof(child)) != sizeof(child)) {
kill(child, SIGKILL);
bail("failed to sync with parent: write(childpid)");
}
/* ... wait for parent to get the pid ... */
if (read(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(child, SIGKILL);
bail("failed to sync with parent: read(SYNC_RECVPID_ACK)");
}
if (s != SYNC_RECVPID_ACK) {
kill(child, SIGKILL);
bail("failed to sync with parent: SYNC_RECVPID_ACK: got %u", s);
}
s = SYNC_CHILD_READY;
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(child, SIGKILL);
bail("failed to sync with parent: write(SYNC_CHILD_READY)");
}
/* Our work is done. [Stage 2: JUMP_INIT] is doing the rest of the work. */
exit(0);
}
/*
* Stage 2: We're the final child process, and the only process that will
* actually return to the Go runtime. Our job is to just do the
* final cleanup steps and then return to the Go runtime to allow
* init_linux.go to run.
*/
case JUMP_INIT:{
/*
* We're inside the child now, having jumped from the
* start_child() code after forking in the parent.
*/
enum sync_t s;
/* We're in a child and thus need to tell the parent if we die. */
syncfd = sync_grandchild_pipe[0];
close(sync_grandchild_pipe[1]);
close(sync_child_pipe[0]);
close(sync_child_pipe[1]);
/* For debugging. */
prctl(PR_SET_NAME, (unsigned long)"runc:[2:INIT]", 0, 0, 0);
if (read(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with parent: read(SYNC_GRANDCHILD)");
if (s != SYNC_GRANDCHILD)
bail("failed to sync with parent: SYNC_GRANDCHILD: got %u", s);
if (setsid() < 0)
bail("setsid failed");
if (setuid(0) < 0)
bail("setuid failed");
if (setgid(0) < 0)
bail("setgid failed");
if (!config.is_rootless_euid && config.is_setgroup) {
if (setgroups(0, NULL) < 0)
bail("setgroups failed");
}
/* ... wait until our topmost parent has finished cgroup setup in p.manager.Apply() ... */
if (config.cloneflags & CLONE_NEWCGROUP) {
uint8_t value;
if (read(pipenum, &value, sizeof(value)) != sizeof(value))
bail("read synchronisation value failed");
if (value == CREATECGROUPNS) {
if (unshare(CLONE_NEWCGROUP) < 0)
bail("failed to unshare cgroup namespace");
} else
bail("received unknown synchronisation value");
}
s = SYNC_CHILD_READY;
if (write(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with patent: write(SYNC_CHILD_READY)");
/* Close sync pipes. */
close(sync_grandchild_pipe[0]);
/* Free netlink data. */
nl_free(&config);
/* Finish executing, let the Go runtime take over. */
return;
}
default:
bail("unexpected jump value");
}
/* Should never be reached. */
bail("should never be reached");
}
| ./CrossVul/dataset_final_sorted/CWE-216/c/good_1395_1 |
crossvul-cpp_data_good_1396_1 |
#define _GNU_SOURCE
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <sched.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <linux/limits.h>
#include <linux/netlink.h>
#include <linux/types.h>
/* Get all of the CLONE_NEW* flags. */
#include "namespace.h"
/* Synchronisation values. */
enum sync_t {
SYNC_USERMAP_PLS = 0x40, /* Request parent to map our users. */
SYNC_USERMAP_ACK = 0x41, /* Mapping finished by the parent. */
SYNC_RECVPID_PLS = 0x42, /* Tell parent we're sending the PID. */
SYNC_RECVPID_ACK = 0x43, /* PID was correctly received by parent. */
SYNC_GRANDCHILD = 0x44, /* The grandchild is ready to run. */
SYNC_CHILD_READY = 0x45, /* The child or grandchild is ready to return. */
/* XXX: This doesn't help with segfaults and other such issues. */
SYNC_ERR = 0xFF, /* Fatal error, no turning back. The error code follows. */
};
/*
* Synchronisation value for cgroup namespace setup.
* The same constant is defined in process_linux.go as "createCgroupns".
*/
#define CREATECGROUPNS 0x80
/* longjmp() arguments. */
#define JUMP_PARENT 0x00
#define JUMP_CHILD 0xA0
#define JUMP_INIT 0xA1
/* JSON buffer. */
#define JSON_MAX 4096
/* Assume the stack grows down, so arguments should be above it. */
struct clone_t {
/*
* Reserve some space for clone() to locate arguments
* and retcode in this place
*/
char stack[4096] __attribute__ ((aligned(16)));
char stack_ptr[0];
/* There's two children. This is used to execute the different code. */
jmp_buf *env;
int jmpval;
};
struct nlconfig_t {
char *data;
/* Process settings. */
uint32_t cloneflags;
char *oom_score_adj;
size_t oom_score_adj_len;
/* User namespace settings. */
char *uidmap;
size_t uidmap_len;
char *gidmap;
size_t gidmap_len;
char *namespaces;
size_t namespaces_len;
uint8_t is_setgroup;
/* Rootless container settings. */
uint8_t is_rootless_euid; /* boolean */
char *uidmappath;
size_t uidmappath_len;
char *gidmappath;
size_t gidmappath_len;
};
/*
* List of netlink message types sent to us as part of bootstrapping the init.
* These constants are defined in libcontainer/message_linux.go.
*/
#define INIT_MSG 62000
#define CLONE_FLAGS_ATTR 27281
#define NS_PATHS_ATTR 27282
#define UIDMAP_ATTR 27283
#define GIDMAP_ATTR 27284
#define SETGROUP_ATTR 27285
#define OOM_SCORE_ADJ_ATTR 27286
#define ROOTLESS_EUID_ATTR 27287
#define UIDMAPPATH_ATTR 27288
#define GIDMAPPATH_ATTR 27289
/*
* Use the raw syscall for versions of glibc which don't include a function for
* it, namely (glibc 2.12).
*/
#if __GLIBC__ == 2 && __GLIBC_MINOR__ < 14
# define _GNU_SOURCE
# include "syscall.h"
# if !defined(SYS_setns) && defined(__NR_setns)
# define SYS_setns __NR_setns
# endif
#ifndef SYS_setns
# error "setns(2) syscall not supported by glibc version"
#endif
int setns(int fd, int nstype)
{
return syscall(SYS_setns, fd, nstype);
}
#endif
/* XXX: This is ugly. */
static int syncfd = -1;
/* TODO(cyphar): Fix this so it correctly deals with syncT. */
#define bail(fmt, ...) \
do { \
int ret = __COUNTER__ + 1; \
fprintf(stderr, "nsenter: " fmt ": %m\n", ##__VA_ARGS__); \
if (syncfd >= 0) { \
enum sync_t s = SYNC_ERR; \
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) \
fprintf(stderr, "nsenter: failed: write(s)"); \
if (write(syncfd, &ret, sizeof(ret)) != sizeof(ret)) \
fprintf(stderr, "nsenter: failed: write(ret)"); \
} \
exit(ret); \
} while(0)
static int write_file(char *data, size_t data_len, char *pathfmt, ...)
{
int fd, len, ret = 0;
char path[PATH_MAX];
va_list ap;
va_start(ap, pathfmt);
len = vsnprintf(path, PATH_MAX, pathfmt, ap);
va_end(ap);
if (len < 0)
return -1;
fd = open(path, O_RDWR);
if (fd < 0) {
return -1;
}
len = write(fd, data, data_len);
if (len != data_len) {
ret = -1;
goto out;
}
out:
close(fd);
return ret;
}
enum policy_t {
SETGROUPS_DEFAULT = 0,
SETGROUPS_ALLOW,
SETGROUPS_DENY,
};
/* This *must* be called before we touch gid_map. */
static void update_setgroups(int pid, enum policy_t setgroup)
{
char *policy;
switch (setgroup) {
case SETGROUPS_ALLOW:
policy = "allow";
break;
case SETGROUPS_DENY:
policy = "deny";
break;
case SETGROUPS_DEFAULT:
default:
/* Nothing to do. */
return;
}
if (write_file(policy, strlen(policy), "/proc/%d/setgroups", pid) < 0) {
/*
* If the kernel is too old to support /proc/pid/setgroups,
* open(2) or write(2) will return ENOENT. This is fine.
*/
if (errno != ENOENT)
bail("failed to write '%s' to /proc/%d/setgroups", policy, pid);
}
}
static int try_mapping_tool(const char *app, int pid, char *map, size_t map_len)
{
int child;
/*
* If @app is NULL, execve will segfault. Just check it here and bail (if
* we're in this path, the caller is already getting desperate and there
* isn't a backup to this failing). This usually would be a configuration
* or programming issue.
*/
if (!app)
bail("mapping tool not present");
child = fork();
if (child < 0)
bail("failed to fork");
if (!child) {
#define MAX_ARGV 20
char *argv[MAX_ARGV];
char *envp[] = { NULL };
char pid_fmt[16];
int argc = 0;
char *next;
snprintf(pid_fmt, 16, "%d", pid);
argv[argc++] = (char *)app;
argv[argc++] = pid_fmt;
/*
* Convert the map string into a list of argument that
* newuidmap/newgidmap can understand.
*/
while (argc < MAX_ARGV) {
if (*map == '\0') {
argv[argc++] = NULL;
break;
}
argv[argc++] = map;
next = strpbrk(map, "\n ");
if (next == NULL)
break;
*next++ = '\0';
map = next + strspn(next, "\n ");
}
execve(app, argv, envp);
bail("failed to execv");
} else {
int status;
while (true) {
if (waitpid(child, &status, 0) < 0) {
if (errno == EINTR)
continue;
bail("failed to waitpid");
}
if (WIFEXITED(status) || WIFSIGNALED(status))
return WEXITSTATUS(status);
}
}
return -1;
}
static void update_uidmap(const char *path, int pid, char *map, size_t map_len)
{
if (map == NULL || map_len <= 0)
return;
if (write_file(map, map_len, "/proc/%d/uid_map", pid) < 0) {
if (errno != EPERM)
bail("failed to update /proc/%d/uid_map", pid);
if (try_mapping_tool(path, pid, map, map_len))
bail("failed to use newuid map on %d", pid);
}
}
static void update_gidmap(const char *path, int pid, char *map, size_t map_len)
{
if (map == NULL || map_len <= 0)
return;
if (write_file(map, map_len, "/proc/%d/gid_map", pid) < 0) {
if (errno != EPERM)
bail("failed to update /proc/%d/gid_map", pid);
if (try_mapping_tool(path, pid, map, map_len))
bail("failed to use newgid map on %d", pid);
}
}
static void update_oom_score_adj(char *data, size_t len)
{
if (data == NULL || len <= 0)
return;
if (write_file(data, len, "/proc/self/oom_score_adj") < 0)
bail("failed to update /proc/self/oom_score_adj");
}
/* A dummy function that just jumps to the given jumpval. */
static int child_func(void *arg) __attribute__ ((noinline));
static int child_func(void *arg)
{
struct clone_t *ca = (struct clone_t *)arg;
longjmp(*ca->env, ca->jmpval);
}
static int clone_parent(jmp_buf *env, int jmpval) __attribute__ ((noinline));
static int clone_parent(jmp_buf *env, int jmpval)
{
struct clone_t ca = {
.env = env,
.jmpval = jmpval,
};
return clone(child_func, ca.stack_ptr, CLONE_PARENT | SIGCHLD, &ca);
}
/*
* Gets the init pipe fd from the environment, which is used to read the
* bootstrap data and tell the parent what the new pid is after we finish
* setting up the environment.
*/
static int initpipe(void)
{
int pipenum;
char *initpipe, *endptr;
initpipe = getenv("_LIBCONTAINER_INITPIPE");
if (initpipe == NULL || *initpipe == '\0')
return -1;
pipenum = strtol(initpipe, &endptr, 10);
if (*endptr != '\0')
bail("unable to parse _LIBCONTAINER_INITPIPE");
return pipenum;
}
/* Returns the clone(2) flag for a namespace, given the name of a namespace. */
static int nsflag(char *name)
{
if (!strcmp(name, "cgroup"))
return CLONE_NEWCGROUP;
else if (!strcmp(name, "ipc"))
return CLONE_NEWIPC;
else if (!strcmp(name, "mnt"))
return CLONE_NEWNS;
else if (!strcmp(name, "net"))
return CLONE_NEWNET;
else if (!strcmp(name, "pid"))
return CLONE_NEWPID;
else if (!strcmp(name, "user"))
return CLONE_NEWUSER;
else if (!strcmp(name, "uts"))
return CLONE_NEWUTS;
/* If we don't recognise a name, fallback to 0. */
return 0;
}
static uint32_t readint32(char *buf)
{
return *(uint32_t *) buf;
}
static uint8_t readint8(char *buf)
{
return *(uint8_t *) buf;
}
static void nl_parse(int fd, struct nlconfig_t *config)
{
size_t len, size;
struct nlmsghdr hdr;
char *data, *current;
/* Retrieve the netlink header. */
len = read(fd, &hdr, NLMSG_HDRLEN);
if (len != NLMSG_HDRLEN)
bail("invalid netlink header length %zu", len);
if (hdr.nlmsg_type == NLMSG_ERROR)
bail("failed to read netlink message");
if (hdr.nlmsg_type != INIT_MSG)
bail("unexpected msg type %d", hdr.nlmsg_type);
/* Retrieve data. */
size = NLMSG_PAYLOAD(&hdr, 0);
current = data = malloc(size);
if (!data)
bail("failed to allocate %zu bytes of memory for nl_payload", size);
len = read(fd, data, size);
if (len != size)
bail("failed to read netlink payload, %zu != %zu", len, size);
/* Parse the netlink payload. */
config->data = data;
while (current < data + size) {
struct nlattr *nlattr = (struct nlattr *)current;
size_t payload_len = nlattr->nla_len - NLA_HDRLEN;
/* Advance to payload. */
current += NLA_HDRLEN;
/* Handle payload. */
switch (nlattr->nla_type) {
case CLONE_FLAGS_ATTR:
config->cloneflags = readint32(current);
break;
case ROOTLESS_EUID_ATTR:
config->is_rootless_euid = readint8(current); /* boolean */
break;
case OOM_SCORE_ADJ_ATTR:
config->oom_score_adj = current;
config->oom_score_adj_len = payload_len;
break;
case NS_PATHS_ATTR:
config->namespaces = current;
config->namespaces_len = payload_len;
break;
case UIDMAP_ATTR:
config->uidmap = current;
config->uidmap_len = payload_len;
break;
case GIDMAP_ATTR:
config->gidmap = current;
config->gidmap_len = payload_len;
break;
case UIDMAPPATH_ATTR:
config->uidmappath = current;
config->uidmappath_len = payload_len;
break;
case GIDMAPPATH_ATTR:
config->gidmappath = current;
config->gidmappath_len = payload_len;
break;
case SETGROUP_ATTR:
config->is_setgroup = readint8(current);
break;
default:
bail("unknown netlink message type %d", nlattr->nla_type);
}
current += NLA_ALIGN(payload_len);
}
}
void nl_free(struct nlconfig_t *config)
{
free(config->data);
}
void join_namespaces(char *nslist)
{
int num = 0, i;
char *saveptr = NULL;
char *namespace = strtok_r(nslist, ",", &saveptr);
struct namespace_t {
int fd;
int ns;
char type[PATH_MAX];
char path[PATH_MAX];
} *namespaces = NULL;
if (!namespace || !strlen(namespace) || !strlen(nslist))
bail("ns paths are empty");
/*
* We have to open the file descriptors first, since after
* we join the mnt namespace we might no longer be able to
* access the paths.
*/
do {
int fd;
char *path;
struct namespace_t *ns;
/* Resize the namespace array. */
namespaces = realloc(namespaces, ++num * sizeof(struct namespace_t));
if (!namespaces)
bail("failed to reallocate namespace array");
ns = &namespaces[num - 1];
/* Split 'ns:path'. */
path = strstr(namespace, ":");
if (!path)
bail("failed to parse %s", namespace);
*path++ = '\0';
fd = open(path, O_RDONLY);
if (fd < 0)
bail("failed to open %s", path);
ns->fd = fd;
ns->ns = nsflag(namespace);
strncpy(ns->path, path, PATH_MAX - 1);
ns->path[PATH_MAX - 1] = '\0';
} while ((namespace = strtok_r(NULL, ",", &saveptr)) != NULL);
/*
* The ordering in which we join namespaces is important. We should
* always join the user namespace *first*. This is all guaranteed
* from the container_linux.go side of this, so we're just going to
* follow the order given to us.
*/
for (i = 0; i < num; i++) {
struct namespace_t ns = namespaces[i];
if (setns(ns.fd, ns.ns) < 0)
bail("failed to setns to %s", ns.path);
close(ns.fd);
}
free(namespaces);
}
/* Defined in cloned_binary.c. */
extern int ensure_cloned_binary(void);
void nsexec(void)
{
int pipenum;
jmp_buf env;
int sync_child_pipe[2], sync_grandchild_pipe[2];
struct nlconfig_t config = { 0 };
/*
* If we don't have an init pipe, just return to the go routine.
* We'll only get an init pipe for start or exec.
*/
pipenum = initpipe();
if (pipenum == -1)
return;
/*
* We need to re-exec if we are not in a cloned binary. This is necessary
* to ensure that containers won't be able to access the host binary
* through /proc/self/exe. See CVE-2019-5736.
*/
if (ensure_cloned_binary() < 0)
bail("could not ensure we are a cloned binary");
/* Parse all of the netlink configuration. */
nl_parse(pipenum, &config);
/* Set oom_score_adj. This has to be done before !dumpable because
* /proc/self/oom_score_adj is not writeable unless you're an privileged
* user (if !dumpable is set). All children inherit their parent's
* oom_score_adj value on fork(2) so this will always be propagated
* properly.
*/
update_oom_score_adj(config.oom_score_adj, config.oom_score_adj_len);
/*
* Make the process non-dumpable, to avoid various race conditions that
* could cause processes in namespaces we're joining to access host
* resources (or potentially execute code).
*
* However, if the number of namespaces we are joining is 0, we are not
* going to be switching to a different security context. Thus setting
* ourselves to be non-dumpable only breaks things (like rootless
* containers), which is the recommendation from the kernel folks.
*/
if (config.namespaces) {
if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) < 0)
bail("failed to set process as non-dumpable");
}
/* Pipe so we can tell the child when we've finished setting up. */
if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sync_child_pipe) < 0)
bail("failed to setup sync pipe between parent and child");
/*
* We need a new socketpair to sync with grandchild so we don't have
* race condition with child.
*/
if (socketpair(AF_LOCAL, SOCK_STREAM, 0, sync_grandchild_pipe) < 0)
bail("failed to setup sync pipe between parent and grandchild");
/* TODO: Currently we aren't dealing with child deaths properly. */
/*
* Okay, so this is quite annoying.
*
* In order for this unsharing code to be more extensible we need to split
* up unshare(CLONE_NEWUSER) and clone() in various ways. The ideal case
* would be if we did clone(CLONE_NEWUSER) and the other namespaces
* separately, but because of SELinux issues we cannot really do that. But
* we cannot just dump the namespace flags into clone(...) because several
* usecases (such as rootless containers) require more granularity around
* the namespace setup. In addition, some older kernels had issues where
* CLONE_NEWUSER wasn't handled before other namespaces (but we cannot
* handle this while also dealing with SELinux so we choose SELinux support
* over broken kernel support).
*
* However, if we unshare(2) the user namespace *before* we clone(2), then
* all hell breaks loose.
*
* The parent no longer has permissions to do many things (unshare(2) drops
* all capabilities in your old namespace), and the container cannot be set
* up to have more than one {uid,gid} mapping. This is obviously less than
* ideal. In order to fix this, we have to first clone(2) and then unshare.
*
* Unfortunately, it's not as simple as that. We have to fork to enter the
* PID namespace (the PID namespace only applies to children). Since we'll
* have to double-fork, this clone_parent() call won't be able to get the
* PID of the _actual_ init process (without doing more synchronisation than
* I can deal with at the moment). So we'll just get the parent to send it
* for us, the only job of this process is to update
* /proc/pid/{setgroups,uid_map,gid_map}.
*
* And as a result of the above, we also need to setns(2) in the first child
* because if we join a PID namespace in the topmost parent then our child
* will be in that namespace (and it will not be able to give us a PID value
* that makes sense without resorting to sending things with cmsg).
*
* This also deals with an older issue caused by dumping cloneflags into
* clone(2): On old kernels, CLONE_PARENT didn't work with CLONE_NEWPID, so
* we have to unshare(2) before clone(2) in order to do this. This was fixed
* in upstream commit 1f7f4dde5c945f41a7abc2285be43d918029ecc5, and was
* introduced by 40a0d32d1eaffe6aac7324ca92604b6b3977eb0e. As far as we're
* aware, the last mainline kernel which had this bug was Linux 3.12.
* However, we cannot comment on which kernels the broken patch was
* backported to.
*
* -- Aleksa "what has my life come to?" Sarai
*/
switch (setjmp(env)) {
/*
* Stage 0: We're in the parent. Our job is just to create a new child
* (stage 1: JUMP_CHILD) process and write its uid_map and
* gid_map. That process will go on to create a new process, then
* it will send us its PID which we will send to the bootstrap
* process.
*/
case JUMP_PARENT:{
int len;
pid_t child, first_child = -1;
bool ready = false;
/* For debugging. */
prctl(PR_SET_NAME, (unsigned long)"runc:[0:PARENT]", 0, 0, 0);
/* Start the process of getting a container. */
child = clone_parent(&env, JUMP_CHILD);
if (child < 0)
bail("unable to fork: child_func");
/*
* State machine for synchronisation with the children.
*
* Father only return when both child and grandchild are
* ready, so we can receive all possible error codes
* generated by children.
*/
while (!ready) {
enum sync_t s;
int ret;
syncfd = sync_child_pipe[1];
close(sync_child_pipe[0]);
if (read(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with child: next state");
switch (s) {
case SYNC_ERR:
/* We have to mirror the error code of the child. */
if (read(syncfd, &ret, sizeof(ret)) != sizeof(ret))
bail("failed to sync with child: read(error code)");
exit(ret);
case SYNC_USERMAP_PLS:
/*
* Enable setgroups(2) if we've been asked to. But we also
* have to explicitly disable setgroups(2) if we're
* creating a rootless container for single-entry mapping.
* i.e. config.is_setgroup == false.
* (this is required since Linux 3.19).
*
* For rootless multi-entry mapping, config.is_setgroup shall be true and
* newuidmap/newgidmap shall be used.
*/
if (config.is_rootless_euid && !config.is_setgroup)
update_setgroups(child, SETGROUPS_DENY);
/* Set up mappings. */
update_uidmap(config.uidmappath, child, config.uidmap, config.uidmap_len);
update_gidmap(config.gidmappath, child, config.gidmap, config.gidmap_len);
s = SYNC_USERMAP_ACK;
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(child, SIGKILL);
bail("failed to sync with child: write(SYNC_USERMAP_ACK)");
}
break;
case SYNC_RECVPID_PLS:{
first_child = child;
/* Get the init_func pid. */
if (read(syncfd, &child, sizeof(child)) != sizeof(child)) {
kill(first_child, SIGKILL);
bail("failed to sync with child: read(childpid)");
}
/* Send ACK. */
s = SYNC_RECVPID_ACK;
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(first_child, SIGKILL);
kill(child, SIGKILL);
bail("failed to sync with child: write(SYNC_RECVPID_ACK)");
}
/* Send the init_func pid back to our parent.
*
* Send the init_func pid and the pid of the first child back to our parent.
* We need to send both back because we can't reap the first child we created (CLONE_PARENT).
* It becomes the responsibility of our parent to reap the first child.
*/
len = dprintf(pipenum, "{\"pid\": %d, \"pid_first\": %d}\n", child, first_child);
if (len < 0) {
kill(child, SIGKILL);
bail("unable to generate JSON for child pid");
}
}
break;
case SYNC_CHILD_READY:
ready = true;
break;
default:
bail("unexpected sync value: %u", s);
}
}
/* Now sync with grandchild. */
ready = false;
while (!ready) {
enum sync_t s;
int ret;
syncfd = sync_grandchild_pipe[1];
close(sync_grandchild_pipe[0]);
s = SYNC_GRANDCHILD;
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(child, SIGKILL);
bail("failed to sync with child: write(SYNC_GRANDCHILD)");
}
if (read(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with child: next state");
switch (s) {
case SYNC_ERR:
/* We have to mirror the error code of the child. */
if (read(syncfd, &ret, sizeof(ret)) != sizeof(ret))
bail("failed to sync with child: read(error code)");
exit(ret);
case SYNC_CHILD_READY:
ready = true;
break;
default:
bail("unexpected sync value: %u", s);
}
}
exit(0);
}
/*
* Stage 1: We're in the first child process. Our job is to join any
* provided namespaces in the netlink payload and unshare all
* of the requested namespaces. If we've been asked to
* CLONE_NEWUSER, we will ask our parent (stage 0) to set up
* our user mappings for us. Then, we create a new child
* (stage 2: JUMP_INIT) for PID namespace. We then send the
* child's PID to our parent (stage 0).
*/
case JUMP_CHILD:{
pid_t child;
enum sync_t s;
/* We're in a child and thus need to tell the parent if we die. */
syncfd = sync_child_pipe[0];
close(sync_child_pipe[1]);
/* For debugging. */
prctl(PR_SET_NAME, (unsigned long)"runc:[1:CHILD]", 0, 0, 0);
/*
* We need to setns first. We cannot do this earlier (in stage 0)
* because of the fact that we forked to get here (the PID of
* [stage 2: JUMP_INIT]) would be meaningless). We could send it
* using cmsg(3) but that's just annoying.
*/
if (config.namespaces)
join_namespaces(config.namespaces);
/*
* Deal with user namespaces first. They are quite special, as they
* affect our ability to unshare other namespaces and are used as
* context for privilege checks.
*
* We don't unshare all namespaces in one go. The reason for this
* is that, while the kernel documentation may claim otherwise,
* there are certain cases where unsharing all namespaces at once
* will result in namespace objects being owned incorrectly.
* Ideally we should just fix these kernel bugs, but it's better to
* be safe than sorry, and fix them separately.
*
* A specific case of this is that the SELinux label of the
* internal kern-mount that mqueue uses will be incorrect if the
* UTS namespace is cloned before the USER namespace is mapped.
* I've also heard of similar problems with the network namespace
* in some scenarios. This also mirrors how LXC deals with this
* problem.
*/
if (config.cloneflags & CLONE_NEWUSER) {
if (unshare(CLONE_NEWUSER) < 0)
bail("failed to unshare user namespace");
config.cloneflags &= ~CLONE_NEWUSER;
/*
* We don't have the privileges to do any mapping here (see the
* clone_parent rant). So signal our parent to hook us up.
*/
/* Switching is only necessary if we joined namespaces. */
if (config.namespaces) {
if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0)
bail("failed to set process as dumpable");
}
s = SYNC_USERMAP_PLS;
if (write(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with parent: write(SYNC_USERMAP_PLS)");
/* ... wait for mapping ... */
if (read(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with parent: read(SYNC_USERMAP_ACK)");
if (s != SYNC_USERMAP_ACK)
bail("failed to sync with parent: SYNC_USERMAP_ACK: got %u", s);
/* Switching is only necessary if we joined namespaces. */
if (config.namespaces) {
if (prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) < 0)
bail("failed to set process as dumpable");
}
/* Become root in the namespace proper. */
if (setresuid(0, 0, 0) < 0)
bail("failed to become root in user namespace");
}
/*
* Unshare all of the namespaces. Now, it should be noted that this
* ordering might break in the future (especially with rootless
* containers). But for now, it's not possible to split this into
* CLONE_NEWUSER + [the rest] because of some RHEL SELinux issues.
*
* Note that we don't merge this with clone() because there were
* some old kernel versions where clone(CLONE_PARENT | CLONE_NEWPID)
* was broken, so we'll just do it the long way anyway.
*/
if (unshare(config.cloneflags & ~CLONE_NEWCGROUP) < 0)
bail("failed to unshare namespaces");
/*
* TODO: What about non-namespace clone flags that we're dropping here?
*
* We fork again because of PID namespace, setns(2) or unshare(2) don't
* change the PID namespace of the calling process, because doing so
* would change the caller's idea of its own PID (as reported by getpid()),
* which would break many applications and libraries, so we must fork
* to actually enter the new PID namespace.
*/
child = clone_parent(&env, JUMP_INIT);
if (child < 0)
bail("unable to fork: init_func");
/* Send the child to our parent, which knows what it's doing. */
s = SYNC_RECVPID_PLS;
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(child, SIGKILL);
bail("failed to sync with parent: write(SYNC_RECVPID_PLS)");
}
if (write(syncfd, &child, sizeof(child)) != sizeof(child)) {
kill(child, SIGKILL);
bail("failed to sync with parent: write(childpid)");
}
/* ... wait for parent to get the pid ... */
if (read(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(child, SIGKILL);
bail("failed to sync with parent: read(SYNC_RECVPID_ACK)");
}
if (s != SYNC_RECVPID_ACK) {
kill(child, SIGKILL);
bail("failed to sync with parent: SYNC_RECVPID_ACK: got %u", s);
}
s = SYNC_CHILD_READY;
if (write(syncfd, &s, sizeof(s)) != sizeof(s)) {
kill(child, SIGKILL);
bail("failed to sync with parent: write(SYNC_CHILD_READY)");
}
/* Our work is done. [Stage 2: JUMP_INIT] is doing the rest of the work. */
exit(0);
}
/*
* Stage 2: We're the final child process, and the only process that will
* actually return to the Go runtime. Our job is to just do the
* final cleanup steps and then return to the Go runtime to allow
* init_linux.go to run.
*/
case JUMP_INIT:{
/*
* We're inside the child now, having jumped from the
* start_child() code after forking in the parent.
*/
enum sync_t s;
/* We're in a child and thus need to tell the parent if we die. */
syncfd = sync_grandchild_pipe[0];
close(sync_grandchild_pipe[1]);
close(sync_child_pipe[0]);
close(sync_child_pipe[1]);
/* For debugging. */
prctl(PR_SET_NAME, (unsigned long)"runc:[2:INIT]", 0, 0, 0);
if (read(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with parent: read(SYNC_GRANDCHILD)");
if (s != SYNC_GRANDCHILD)
bail("failed to sync with parent: SYNC_GRANDCHILD: got %u", s);
if (setsid() < 0)
bail("setsid failed");
if (setuid(0) < 0)
bail("setuid failed");
if (setgid(0) < 0)
bail("setgid failed");
if (!config.is_rootless_euid && config.is_setgroup) {
if (setgroups(0, NULL) < 0)
bail("setgroups failed");
}
/* ... wait until our topmost parent has finished cgroup setup in p.manager.Apply() ... */
if (config.cloneflags & CLONE_NEWCGROUP) {
uint8_t value;
if (read(pipenum, &value, sizeof(value)) != sizeof(value))
bail("read synchronisation value failed");
if (value == CREATECGROUPNS) {
if (unshare(CLONE_NEWCGROUP) < 0)
bail("failed to unshare cgroup namespace");
} else
bail("received unknown synchronisation value");
}
s = SYNC_CHILD_READY;
if (write(syncfd, &s, sizeof(s)) != sizeof(s))
bail("failed to sync with patent: write(SYNC_CHILD_READY)");
/* Close sync pipes. */
close(sync_grandchild_pipe[0]);
/* Free netlink data. */
nl_free(&config);
/* Finish executing, let the Go runtime take over. */
return;
}
default:
bail("unexpected jump value");
}
/* Should never be reached. */
bail("should never be reached");
}
| ./CrossVul/dataset_final_sorted/CWE-216/c/good_1396_1 |
crossvul-cpp_data_good_1395_0 | /*
* Copyright (C) 2019 Aleksa Sarai <cyphar@cyphar.com>
* Copyright (C) 2019 SUSE LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <limits.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/vfs.h>
#include <sys/mman.h>
#include <sys/sendfile.h>
#include <sys/syscall.h>
/* Use our own wrapper for memfd_create. */
#if !defined(SYS_memfd_create) && defined(__NR_memfd_create)
# define SYS_memfd_create __NR_memfd_create
#endif
#ifdef SYS_memfd_create
# define HAVE_MEMFD_CREATE
/* memfd_create(2) flags -- copied from <linux/memfd.h>. */
# ifndef MFD_CLOEXEC
# define MFD_CLOEXEC 0x0001U
# define MFD_ALLOW_SEALING 0x0002U
# endif
int memfd_create(const char *name, unsigned int flags)
{
return syscall(SYS_memfd_create, name, flags);
}
#endif
/* This comes directly from <linux/fcntl.h>. */
#ifndef F_LINUX_SPECIFIC_BASE
# define F_LINUX_SPECIFIC_BASE 1024
#endif
#ifndef F_ADD_SEALS
# define F_ADD_SEALS (F_LINUX_SPECIFIC_BASE + 9)
# define F_GET_SEALS (F_LINUX_SPECIFIC_BASE + 10)
#endif
#ifndef F_SEAL_SEAL
# define F_SEAL_SEAL 0x0001 /* prevent further seals from being set */
# define F_SEAL_SHRINK 0x0002 /* prevent file from shrinking */
# define F_SEAL_GROW 0x0004 /* prevent file from growing */
# define F_SEAL_WRITE 0x0008 /* prevent writes */
#endif
#define RUNC_SENDFILE_MAX 0x7FFFF000 /* sendfile(2) is limited to 2GB. */
#ifdef HAVE_MEMFD_CREATE
# define RUNC_MEMFD_COMMENT "runc_cloned:/proc/self/exe"
# define RUNC_MEMFD_SEALS \
(F_SEAL_SEAL | F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE)
#endif
static void *must_realloc(void *ptr, size_t size)
{
void *old = ptr;
do {
ptr = realloc(old, size);
} while(!ptr);
return ptr;
}
/*
* Verify whether we are currently in a self-cloned program (namely, is
* /proc/self/exe a memfd). F_GET_SEALS will only succeed for memfds (or rather
* for shmem files), and we want to be sure it's actually sealed.
*/
static int is_self_cloned(void)
{
int fd, ret, is_cloned = 0;
fd = open("/proc/self/exe", O_RDONLY|O_CLOEXEC);
if (fd < 0)
return -ENOTRECOVERABLE;
#ifdef HAVE_MEMFD_CREATE
ret = fcntl(fd, F_GET_SEALS);
is_cloned = (ret == RUNC_MEMFD_SEALS);
#else
struct stat statbuf = {0};
ret = fstat(fd, &statbuf);
if (ret >= 0)
is_cloned = (statbuf.st_nlink == 0);
#endif
close(fd);
return is_cloned;
}
/*
* Basic wrapper around mmap(2) that gives you the file length so you can
* safely treat it as an ordinary buffer. Only gives you read access.
*/
static char *read_file(char *path, size_t *length)
{
int fd;
char buf[4096], *copy = NULL;
if (!length)
return NULL;
fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0)
return NULL;
*length = 0;
for (;;) {
int n;
n = read(fd, buf, sizeof(buf));
if (n < 0)
goto error;
if (!n)
break;
copy = must_realloc(copy, (*length + n) * sizeof(*copy));
memcpy(copy + *length, buf, n);
*length += n;
}
close(fd);
return copy;
error:
close(fd);
free(copy);
return NULL;
}
/*
* A poor-man's version of "xargs -0". Basically parses a given block of
* NUL-delimited data, within the given length and adds a pointer to each entry
* to the array of pointers.
*/
static int parse_xargs(char *data, int data_length, char ***output)
{
int num = 0;
char *cur = data;
if (!data || *output != NULL)
return -1;
while (cur < data + data_length) {
num++;
*output = must_realloc(*output, (num + 1) * sizeof(**output));
(*output)[num - 1] = cur;
cur += strlen(cur) + 1;
}
(*output)[num] = NULL;
return num;
}
/*
* "Parse" out argv and envp from /proc/self/cmdline and /proc/self/environ.
* This is necessary because we are running in a context where we don't have a
* main() that we can just get the arguments from.
*/
static int fetchve(char ***argv, char ***envp)
{
char *cmdline = NULL, *environ = NULL;
size_t cmdline_size, environ_size;
cmdline = read_file("/proc/self/cmdline", &cmdline_size);
if (!cmdline)
goto error;
environ = read_file("/proc/self/environ", &environ_size);
if (!environ)
goto error;
if (parse_xargs(cmdline, cmdline_size, argv) <= 0)
goto error;
if (parse_xargs(environ, environ_size, envp) <= 0)
goto error;
return 0;
error:
free(environ);
free(cmdline);
return -EINVAL;
}
static int clone_binary(void)
{
int binfd, memfd;
ssize_t sent = 0;
#ifdef HAVE_MEMFD_CREATE
memfd = memfd_create(RUNC_MEMFD_COMMENT, MFD_CLOEXEC | MFD_ALLOW_SEALING);
#else
memfd = open("/tmp", O_TMPFILE | O_EXCL | O_RDWR | O_CLOEXEC, 0711);
#endif
if (memfd < 0)
return -ENOTRECOVERABLE;
binfd = open("/proc/self/exe", O_RDONLY | O_CLOEXEC);
if (binfd < 0)
goto error;
sent = sendfile(memfd, binfd, NULL, RUNC_SENDFILE_MAX);
close(binfd);
if (sent < 0)
goto error;
#ifdef HAVE_MEMFD_CREATE
int err = fcntl(memfd, F_ADD_SEALS, RUNC_MEMFD_SEALS);
if (err < 0)
goto error;
#else
/* Need to re-open "memfd" as read-only to avoid execve(2) giving -EXTBUSY. */
int newfd;
char *fdpath = NULL;
if (asprintf(&fdpath, "/proc/self/fd/%d", memfd) < 0)
goto error;
newfd = open(fdpath, O_RDONLY | O_CLOEXEC);
free(fdpath);
if (newfd < 0)
goto error;
close(memfd);
memfd = newfd;
#endif
return memfd;
error:
close(memfd);
return -EIO;
}
int ensure_cloned_binary(void)
{
int execfd;
char **argv = NULL, **envp = NULL;
/* Check that we're not self-cloned, and if we are then bail. */
int cloned = is_self_cloned();
if (cloned > 0 || cloned == -ENOTRECOVERABLE)
return cloned;
if (fetchve(&argv, &envp) < 0)
return -EINVAL;
execfd = clone_binary();
if (execfd < 0)
return -EIO;
fexecve(execfd, argv, envp);
return -ENOEXEC;
}
| ./CrossVul/dataset_final_sorted/CWE-216/c/good_1395_0 |
crossvul-cpp_data_bad_5254_2 | /* Generated by re2c 0.13.5 */
#line 1 "ext/standard/var_unserializer.re"
/*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Sascha Schumann <sascha@schumann.cx> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "ext/standard/php_var.h"
#include "php_incomplete_class.h"
/* {{{ reference-handling for unserializer: var_* */
#define VAR_ENTRIES_MAX 1024
#define VAR_ENTRIES_DBG 0
typedef struct {
zval *data[VAR_ENTRIES_MAX];
zend_long used_slots;
void *next;
} var_entries;
typedef struct {
zval data[VAR_ENTRIES_MAX];
zend_long used_slots;
void *next;
} var_dtor_entries;
static inline void var_push(php_unserialize_data_t *var_hashx, zval *rval)
{
var_entries *var_hash = (*var_hashx)->last;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_push(%ld): %d\n", var_hash?var_hash->used_slots:-1L, Z_TYPE_P(rval));
#endif
if (!var_hash || var_hash->used_slots == VAR_ENTRIES_MAX) {
var_hash = emalloc(sizeof(var_entries));
var_hash->used_slots = 0;
var_hash->next = 0;
if (!(*var_hashx)->first) {
(*var_hashx)->first = var_hash;
} else {
((var_entries *) (*var_hashx)->last)->next = var_hash;
}
(*var_hashx)->last = var_hash;
}
var_hash->data[var_hash->used_slots++] = rval;
}
PHPAPI void var_push_dtor(php_unserialize_data_t *var_hashx, zval *rval)
{
zval *tmp_var = var_tmp_var(var_hashx);
if (!tmp_var) {
return;
}
ZVAL_COPY(tmp_var, rval);
}
PHPAPI zval *var_tmp_var(php_unserialize_data_t *var_hashx)
{
var_dtor_entries *var_hash;
if (!var_hashx || !*var_hashx) {
return NULL;
}
var_hash = (*var_hashx)->last_dtor;
if (!var_hash || var_hash->used_slots == VAR_ENTRIES_MAX) {
var_hash = emalloc(sizeof(var_dtor_entries));
var_hash->used_slots = 0;
var_hash->next = 0;
if (!(*var_hashx)->first_dtor) {
(*var_hashx)->first_dtor = var_hash;
} else {
((var_dtor_entries *) (*var_hashx)->last_dtor)->next = var_hash;
}
(*var_hashx)->last_dtor = var_hash;
}
ZVAL_UNDEF(&var_hash->data[var_hash->used_slots]);
return &var_hash->data[var_hash->used_slots++];
}
PHPAPI void var_replace(php_unserialize_data_t *var_hashx, zval *ozval, zval *nzval)
{
zend_long i;
var_entries *var_hash = (*var_hashx)->first;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_replace(%ld): %d\n", var_hash?var_hash->used_slots:-1L, Z_TYPE_P(nzval));
#endif
while (var_hash) {
for (i = 0; i < var_hash->used_slots; i++) {
if (var_hash->data[i] == ozval) {
var_hash->data[i] = nzval;
/* do not break here */
}
}
var_hash = var_hash->next;
}
}
static zval *var_access(php_unserialize_data_t *var_hashx, zend_long id)
{
var_entries *var_hash = (*var_hashx)->first;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_access(%ld): %ld\n", var_hash?var_hash->used_slots:-1L, id);
#endif
while (id >= VAR_ENTRIES_MAX && var_hash && var_hash->used_slots == VAR_ENTRIES_MAX) {
var_hash = var_hash->next;
id -= VAR_ENTRIES_MAX;
}
if (!var_hash) return NULL;
if (id < 0 || id >= var_hash->used_slots) return NULL;
return var_hash->data[id];
}
PHPAPI void var_destroy(php_unserialize_data_t *var_hashx)
{
void *next;
zend_long i;
var_entries *var_hash = (*var_hashx)->first;
var_dtor_entries *var_dtor_hash = (*var_hashx)->first_dtor;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_destroy(%ld)\n", var_hash?var_hash->used_slots:-1L);
#endif
while (var_hash) {
next = var_hash->next;
efree_size(var_hash, sizeof(var_entries));
var_hash = next;
}
while (var_dtor_hash) {
for (i = 0; i < var_dtor_hash->used_slots; i++) {
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_destroy dtor(%p, %ld)\n", var_dtor_hash->data[i], Z_REFCOUNT_P(var_dtor_hash->data[i]));
#endif
zval_ptr_dtor(&var_dtor_hash->data[i]);
}
next = var_dtor_hash->next;
efree_size(var_dtor_hash, sizeof(var_dtor_entries));
var_dtor_hash = next;
}
}
/* }}} */
static zend_string *unserialize_str(const unsigned char **p, size_t len, size_t maxlen)
{
size_t i, j;
zend_string *str = zend_string_safe_alloc(1, len, 0, 0);
unsigned char *end = *(unsigned char **)p+maxlen;
if (end < *p) {
zend_string_free(str);
return NULL;
}
for (i = 0; i < len; i++) {
if (*p >= end) {
zend_string_free(str);
return NULL;
}
if (**p != '\\') {
ZSTR_VAL(str)[i] = (char)**p;
} else {
unsigned char ch = 0;
for (j = 0; j < 2; j++) {
(*p)++;
if (**p >= '0' && **p <= '9') {
ch = (ch << 4) + (**p -'0');
} else if (**p >= 'a' && **p <= 'f') {
ch = (ch << 4) + (**p -'a'+10);
} else if (**p >= 'A' && **p <= 'F') {
ch = (ch << 4) + (**p -'A'+10);
} else {
zend_string_free(str);
return NULL;
}
}
ZSTR_VAL(str)[i] = (char)ch;
}
(*p)++;
}
ZSTR_VAL(str)[i] = 0;
ZSTR_LEN(str) = i;
return str;
}
static inline int unserialize_allowed_class(zend_string *class_name, HashTable *classes)
{
zend_string *lcname;
int res;
ALLOCA_FLAG(use_heap)
if(classes == NULL) {
return 1;
}
if(!zend_hash_num_elements(classes)) {
return 0;
}
ZSTR_ALLOCA_ALLOC(lcname, ZSTR_LEN(class_name), use_heap);
zend_str_tolower_copy(ZSTR_VAL(lcname), ZSTR_VAL(class_name), ZSTR_LEN(class_name));
res = zend_hash_exists(classes, lcname);
ZSTR_ALLOCA_FREE(lcname, use_heap);
return res;
}
#define YYFILL(n) do { } while (0)
#define YYCTYPE unsigned char
#define YYCURSOR cursor
#define YYLIMIT limit
#define YYMARKER marker
#line 246 "ext/standard/var_unserializer.re"
static inline zend_long parse_iv2(const unsigned char *p, const unsigned char **q)
{
char cursor;
zend_long result = 0;
int neg = 0;
switch (*p) {
case '-':
neg++;
/* fall-through */
case '+':
p++;
}
while (1) {
cursor = (char)*p;
if (cursor >= '0' && cursor <= '9') {
result = result * 10 + (size_t)(cursor - (unsigned char)'0');
} else {
break;
}
p++;
}
if (q) *q = p;
if (neg) return -result;
return result;
}
static inline zend_long parse_iv(const unsigned char *p)
{
return parse_iv2(p, NULL);
}
/* no need to check for length - re2c already did */
static inline size_t parse_uiv(const unsigned char *p)
{
unsigned char cursor;
size_t result = 0;
if (*p == '+') {
p++;
}
while (1) {
cursor = *p;
if (cursor >= '0' && cursor <= '9') {
result = result * 10 + (size_t)(cursor - (unsigned char)'0');
} else {
break;
}
p++;
}
return result;
}
#define UNSERIALIZE_PARAMETER zval *rval, const unsigned char **p, const unsigned char *max, php_unserialize_data_t *var_hash, HashTable *classes
#define UNSERIALIZE_PASSTHRU rval, p, max, var_hash, classes
static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER);
static zend_always_inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, zend_long elements, int objprops)
{
while (elements-- > 0) {
zval key, *data, d, *old_data;
zend_ulong idx;
ZVAL_UNDEF(&key);
if (!php_var_unserialize_internal(&key, p, max, NULL, classes)) {
zval_dtor(&key);
return 0;
}
data = NULL;
ZVAL_UNDEF(&d);
if (!objprops) {
if (Z_TYPE(key) == IS_LONG) {
idx = Z_LVAL(key);
numeric_key:
if (UNEXPECTED((old_data = zend_hash_index_find(ht, idx)) != NULL)) {
//??? update hash
var_push_dtor(var_hash, old_data);
data = zend_hash_index_update(ht, idx, &d);
} else {
data = zend_hash_index_add_new(ht, idx, &d);
}
} else if (Z_TYPE(key) == IS_STRING) {
if (UNEXPECTED(ZEND_HANDLE_NUMERIC(Z_STR(key), idx))) {
goto numeric_key;
}
if (UNEXPECTED((old_data = zend_hash_find(ht, Z_STR(key))) != NULL)) {
//??? update hash
var_push_dtor(var_hash, old_data);
data = zend_hash_update(ht, Z_STR(key), &d);
} else {
data = zend_hash_add_new(ht, Z_STR(key), &d);
}
} else {
zval_dtor(&key);
return 0;
}
} else {
if (EXPECTED(Z_TYPE(key) == IS_STRING)) {
string_key:
if ((old_data = zend_hash_find(ht, Z_STR(key))) != NULL) {
if (Z_TYPE_P(old_data) == IS_INDIRECT) {
old_data = Z_INDIRECT_P(old_data);
}
var_push_dtor(var_hash, old_data);
data = zend_hash_update_ind(ht, Z_STR(key), &d);
} else {
data = zend_hash_add_new(ht, Z_STR(key), &d);
}
} else if (Z_TYPE(key) == IS_LONG) {
/* object properties should include no integers */
convert_to_string(&key);
goto string_key;
} else {
zval_dtor(&key);
return 0;
}
}
if (!php_var_unserialize_internal(data, p, max, var_hash, classes)) {
zval_dtor(&key);
return 0;
}
if (UNEXPECTED(Z_ISUNDEF_P(data))) {
if (Z_TYPE(key) == IS_LONG) {
zend_hash_index_del(ht, Z_LVAL(key));
} else {
zend_hash_del_ind(ht, Z_STR(key));
}
} else {
var_push_dtor(var_hash, data);
}
zval_dtor(&key);
if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
(*p)--;
return 0;
}
}
return 1;
}
static inline int finish_nested_data(UNSERIALIZE_PARAMETER)
{
if (*((*p)++) == '}')
return 1;
#if SOMETHING_NEW_MIGHT_LEAD_TO_CRASH_ENABLE_IF_YOU_ARE_BRAVE
zval_ptr_dtor(rval);
#endif
return 0;
}
static inline int object_custom(UNSERIALIZE_PARAMETER, zend_class_entry *ce)
{
zend_long datalen;
datalen = parse_iv2((*p) + 2, p);
(*p) += 2;
if (datalen < 0 || (max - (*p)) <= datalen) {
zend_error(E_WARNING, "Insufficient data for unserializing - %pd required, %pd present", datalen, (zend_long)(max - (*p)));
return 0;
}
if (ce->unserialize == NULL) {
zend_error(E_WARNING, "Class %s has no unserializer", ZSTR_VAL(ce->name));
object_init_ex(rval, ce);
} else if (ce->unserialize(rval, ce, (const unsigned char*)*p, datalen, (zend_unserialize_data *)var_hash) != SUCCESS) {
return 0;
}
(*p) += datalen;
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
static inline zend_long object_common1(UNSERIALIZE_PARAMETER, zend_class_entry *ce)
{
zend_long elements;
elements = parse_iv2((*p) + 2, p);
(*p) += 2;
if (ce->serialize == NULL) {
object_init_ex(rval, ce);
} else {
/* If this class implements Serializable, it should not land here but in object_custom(). The passed string
obviously doesn't descend from the regular serializer. */
zend_error(E_WARNING, "Erroneous data format for unserializing '%s'", ZSTR_VAL(ce->name));
return 0;
}
return elements;
}
#ifdef PHP_WIN32
# pragma optimize("", off)
#endif
static inline int object_common2(UNSERIALIZE_PARAMETER, zend_long elements)
{
zval retval;
zval fname;
HashTable *ht;
zend_bool has_wakeup;
if (Z_TYPE_P(rval) != IS_OBJECT) {
return 0;
}
has_wakeup = Z_OBJCE_P(rval) != PHP_IC_ENTRY
&& zend_hash_str_exists(&Z_OBJCE_P(rval)->function_table, "__wakeup", sizeof("__wakeup")-1);
ht = Z_OBJPROP_P(rval);
zend_hash_extend(ht, zend_hash_num_elements(ht) + elements, (ht->u.flags & HASH_FLAG_PACKED));
if (!process_nested_data(UNSERIALIZE_PASSTHRU, ht, elements, 1)) {
if (has_wakeup) {
ZVAL_DEREF(rval);
GC_FLAGS(Z_OBJ_P(rval)) |= IS_OBJ_DESTRUCTOR_CALLED;
}
return 0;
}
ZVAL_DEREF(rval);
if (has_wakeup) {
ZVAL_STRINGL(&fname, "__wakeup", sizeof("__wakeup") - 1);
BG(serialize_lock)++;
if (call_user_function_ex(CG(function_table), rval, &fname, &retval, 0, 0, 1, NULL) == FAILURE || Z_ISUNDEF(retval)) {
GC_FLAGS(Z_OBJ_P(rval)) |= IS_OBJ_DESTRUCTOR_CALLED;
}
BG(serialize_lock)--;
zval_dtor(&fname);
zval_dtor(&retval);
}
if (EG(exception)) {
return 0;
}
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
#ifdef PHP_WIN32
# pragma optimize("", on)
#endif
PHPAPI int php_var_unserialize(zval *rval, const unsigned char **p, const unsigned char *max, php_unserialize_data_t *var_hash)
{
HashTable *classes = NULL;
return php_var_unserialize_ex(UNSERIALIZE_PASSTHRU);
}
PHPAPI int php_var_unserialize_ex(UNSERIALIZE_PARAMETER)
{
var_entries *orig_var_entries = (*var_hash)->last;
zend_long orig_used_slots = orig_var_entries ? orig_var_entries->used_slots : 0;
int result;
result = php_var_unserialize_internal(UNSERIALIZE_PASSTHRU);
if (!result) {
/* If the unserialization failed, mark all elements that have been added to var_hash
* as NULL. This will forbid their use by other unserialize() calls in the same
* unserialization context. */
var_entries *e = orig_var_entries;
zend_long s = orig_used_slots;
while (e) {
for (; s < e->used_slots; s++) {
e->data[s] = NULL;
}
e = e->next;
s = 0;
}
}
return result;
}
static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)
{
const unsigned char *cursor, *limit, *marker, *start;
zval *rval_ref;
limit = max;
cursor = *p;
if (YYCURSOR >= YYLIMIT) {
return 0;
}
if (var_hash && (*p)[0] != 'R') {
var_push(var_hash, rval);
}
start = cursor;
#line 554 "ext/standard/var_unserializer.c"
{
YYCTYPE yych;
static const unsigned char yybm[] = {
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, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 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, 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, 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, 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, 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, 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,
};
if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7);
yych = *YYCURSOR;
switch (yych) {
case 'C':
case 'O': goto yy13;
case 'N': goto yy5;
case 'R': goto yy2;
case 'S': goto yy10;
case 'a': goto yy11;
case 'b': goto yy6;
case 'd': goto yy8;
case 'i': goto yy7;
case 'o': goto yy12;
case 'r': goto yy4;
case 's': goto yy9;
case '}': goto yy14;
default: goto yy16;
}
yy2:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy95;
yy3:
#line 884 "ext/standard/var_unserializer.re"
{ return 0; }
#line 580 "ext/standard/var_unserializer.c"
yy4:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy89;
goto yy3;
yy5:
yych = *++YYCURSOR;
if (yych == ';') goto yy87;
goto yy3;
yy6:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy83;
goto yy3;
yy7:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy77;
goto yy3;
yy8:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy53;
goto yy3;
yy9:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy46;
goto yy3;
yy10:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy39;
goto yy3;
yy11:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy32;
goto yy3;
yy12:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy25;
goto yy3;
yy13:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy17;
goto yy3;
yy14:
++YYCURSOR;
#line 878 "ext/standard/var_unserializer.re"
{
/* this is the case where we have less data than planned */
php_error_docref(NULL, E_NOTICE, "Unexpected end of serialized data");
return 0; /* not sure if it should be 0 or 1 here? */
}
#line 629 "ext/standard/var_unserializer.c"
yy16:
yych = *++YYCURSOR;
goto yy3;
yy17:
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
if (yych == '+') goto yy19;
yy18:
YYCURSOR = YYMARKER;
goto yy3;
yy19:
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
goto yy18;
yy20:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
if (yych != ':') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 733 "ext/standard/var_unserializer.re"
{
size_t len, len2, len3, maxlen;
zend_long elements;
char *str;
zend_string *class_name;
zend_class_entry *ce;
int incomplete_class = 0;
int custom_object = 0;
zval user_func;
zval retval;
zval args[1];
if (!var_hash) return 0;
if (*start == 'C') {
custom_object = 1;
}
len2 = len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len || len == 0) {
*p = start + 2;
return 0;
}
str = (char*)YYCURSOR;
YYCURSOR += len;
if (*(YYCURSOR) != '"') {
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR+1) != ':') {
*p = YYCURSOR+1;
return 0;
}
len3 = strspn(str, "0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\\");
if (len3 != len)
{
*p = YYCURSOR + len3 - len;
return 0;
}
class_name = zend_string_init(str, len, 0);
do {
if(!unserialize_allowed_class(class_name, classes)) {
incomplete_class = 1;
ce = PHP_IC_ENTRY;
break;
}
/* Try to find class directly */
BG(serialize_lock)++;
ce = zend_lookup_class(class_name);
if (ce) {
BG(serialize_lock)--;
if (EG(exception)) {
zend_string_release(class_name);
return 0;
}
break;
}
BG(serialize_lock)--;
if (EG(exception)) {
zend_string_release(class_name);
return 0;
}
/* Check for unserialize callback */
if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\0')) {
incomplete_class = 1;
ce = PHP_IC_ENTRY;
break;
}
/* Call unserialize callback */
ZVAL_STRING(&user_func, PG(unserialize_callback_func));
ZVAL_STR_COPY(&args[0], class_name);
BG(serialize_lock)++;
if (call_user_function_ex(CG(function_table), NULL, &user_func, &retval, 1, args, 0, NULL) != SUCCESS) {
BG(serialize_lock)--;
if (EG(exception)) {
zend_string_release(class_name);
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&args[0]);
return 0;
}
php_error_docref(NULL, E_WARNING, "defined (%s) but not found", Z_STRVAL(user_func));
incomplete_class = 1;
ce = PHP_IC_ENTRY;
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&args[0]);
break;
}
BG(serialize_lock)--;
zval_ptr_dtor(&retval);
if (EG(exception)) {
zend_string_release(class_name);
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&args[0]);
return 0;
}
/* The callback function may have defined the class */
if ((ce = zend_lookup_class(class_name)) == NULL) {
php_error_docref(NULL, E_WARNING, "Function %s() hasn't defined the class it was called for", Z_STRVAL(user_func));
incomplete_class = 1;
ce = PHP_IC_ENTRY;
}
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&args[0]);
break;
} while (1);
*p = YYCURSOR;
if (custom_object) {
int ret;
ret = object_custom(UNSERIALIZE_PASSTHRU, ce);
if (ret && incomplete_class) {
php_store_class_name(rval, ZSTR_VAL(class_name), len2);
}
zend_string_release(class_name);
return ret;
}
elements = object_common1(UNSERIALIZE_PASSTHRU, ce);
if (incomplete_class) {
php_store_class_name(rval, ZSTR_VAL(class_name), len2);
}
zend_string_release(class_name);
return object_common2(UNSERIALIZE_PASSTHRU, elements);
}
#line 804 "ext/standard/var_unserializer.c"
yy25:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy26;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy27;
goto yy18;
}
yy26:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy27:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy27;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 726 "ext/standard/var_unserializer.re"
{
if (!var_hash) return 0;
return object_common2(UNSERIALIZE_PASSTHRU,
object_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR));
}
#line 836 "ext/standard/var_unserializer.c"
yy32:
yych = *++YYCURSOR;
if (yych == '+') goto yy33;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy34;
goto yy18;
yy33:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy34:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy34;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '{') goto yy18;
++YYCURSOR;
#line 702 "ext/standard/var_unserializer.re"
{
zend_long elements = parse_iv(start + 2);
/* use iv() not uiv() in order to check data range */
*p = YYCURSOR;
if (!var_hash) return 0;
if (elements < 0) {
return 0;
}
array_init_size(rval, elements);
if (elements) {
/* we can't convert from packed to hash during unserialization, because
reference to some zvals might be keept in var_hash (to support references) */
zend_hash_real_init(Z_ARRVAL_P(rval), 0);
}
if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_ARRVAL_P(rval), elements, 0)) {
return 0;
}
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
#line 881 "ext/standard/var_unserializer.c"
yy39:
yych = *++YYCURSOR;
if (yych == '+') goto yy40;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy41;
goto yy18;
yy40:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy41:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy41;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 668 "ext/standard/var_unserializer.re"
{
size_t len, maxlen;
zend_string *str;
len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len) {
*p = start + 2;
return 0;
}
if ((str = unserialize_str(&YYCURSOR, len, maxlen)) == NULL) {
return 0;
}
if (*(YYCURSOR) != '"') {
zend_string_free(str);
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR + 1) != ';') {
efree(str);
*p = YYCURSOR + 1;
return 0;
}
YYCURSOR += 2;
*p = YYCURSOR;
ZVAL_STR(rval, str);
return 1;
}
#line 936 "ext/standard/var_unserializer.c"
yy46:
yych = *++YYCURSOR;
if (yych == '+') goto yy47;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy48;
goto yy18;
yy47:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy48:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy48;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 636 "ext/standard/var_unserializer.re"
{
size_t len, maxlen;
char *str;
len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len) {
*p = start + 2;
return 0;
}
str = (char*)YYCURSOR;
YYCURSOR += len;
if (*(YYCURSOR) != '"') {
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR + 1) != ';') {
*p = YYCURSOR + 1;
return 0;
}
YYCURSOR += 2;
*p = YYCURSOR;
ZVAL_STRINGL(rval, str, len);
return 1;
}
#line 989 "ext/standard/var_unserializer.c"
yy53:
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych <= ',') {
if (yych == '+') goto yy57;
goto yy18;
} else {
if (yych <= '-') goto yy55;
if (yych <= '.') goto yy60;
goto yy18;
}
} else {
if (yych <= 'I') {
if (yych <= '9') goto yy58;
if (yych <= 'H') goto yy18;
goto yy56;
} else {
if (yych != 'N') goto yy18;
}
}
yych = *++YYCURSOR;
if (yych == 'A') goto yy76;
goto yy18;
yy55:
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych == '.') goto yy60;
goto yy18;
} else {
if (yych <= '9') goto yy58;
if (yych != 'I') goto yy18;
}
yy56:
yych = *++YYCURSOR;
if (yych == 'N') goto yy72;
goto yy18;
yy57:
yych = *++YYCURSOR;
if (yych == '.') goto yy60;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy58:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ':') {
if (yych <= '.') {
if (yych <= '-') goto yy18;
goto yy70;
} else {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy58;
goto yy18;
}
} else {
if (yych <= 'E') {
if (yych <= ';') goto yy63;
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy60:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy61:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ';') {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy61;
if (yych <= ':') goto yy18;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy63:
++YYCURSOR;
#line 627 "ext/standard/var_unserializer.re"
{
#if SIZEOF_ZEND_LONG == 4
use_double:
#endif
*p = YYCURSOR;
ZVAL_DOUBLE(rval, zend_strtod((const char *)start + 2, NULL));
return 1;
}
#line 1086 "ext/standard/var_unserializer.c"
yy65:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy66;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
goto yy18;
}
yy66:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych == '+') goto yy69;
goto yy18;
} else {
if (yych <= '-') goto yy69;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
}
yy67:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
if (yych == ';') goto yy63;
goto yy18;
yy69:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
goto yy18;
yy70:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ';') {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy70;
if (yych <= ':') goto yy18;
goto yy63;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy72:
yych = *++YYCURSOR;
if (yych != 'F') goto yy18;
yy73:
yych = *++YYCURSOR;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 611 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
if (!strncmp((char*)start + 2, "NAN", 3)) {
ZVAL_DOUBLE(rval, php_get_nan());
} else if (!strncmp((char*)start + 2, "INF", 3)) {
ZVAL_DOUBLE(rval, php_get_inf());
} else if (!strncmp((char*)start + 2, "-INF", 4)) {
ZVAL_DOUBLE(rval, -php_get_inf());
} else {
ZVAL_NULL(rval);
}
return 1;
}
#line 1161 "ext/standard/var_unserializer.c"
yy76:
yych = *++YYCURSOR;
if (yych == 'N') goto yy73;
goto yy18;
yy77:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy78;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy79;
goto yy18;
}
yy78:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy79:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy79;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 585 "ext/standard/var_unserializer.re"
{
#if SIZEOF_ZEND_LONG == 4
int digits = YYCURSOR - start - 3;
if (start[2] == '-' || start[2] == '+') {
digits--;
}
/* Use double for large zend_long values that were serialized on a 64-bit system */
if (digits >= MAX_LENGTH_OF_LONG - 1) {
if (digits == MAX_LENGTH_OF_LONG - 1) {
int cmp = strncmp((char*)YYCURSOR - MAX_LENGTH_OF_LONG, long_min_digits, MAX_LENGTH_OF_LONG - 1);
if (!(cmp < 0 || (cmp == 0 && start[2] == '-'))) {
goto use_double;
}
} else {
goto use_double;
}
}
#endif
*p = YYCURSOR;
ZVAL_LONG(rval, parse_iv(start + 2));
return 1;
}
#line 1214 "ext/standard/var_unserializer.c"
yy83:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= '2') goto yy18;
yych = *++YYCURSOR;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 579 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
ZVAL_BOOL(rval, parse_iv(start + 2));
return 1;
}
#line 1228 "ext/standard/var_unserializer.c"
yy87:
++YYCURSOR;
#line 573 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
ZVAL_NULL(rval);
return 1;
}
#line 1237 "ext/standard/var_unserializer.c"
yy89:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy90;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy91;
goto yy18;
}
yy90:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy91:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy91;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 548 "ext/standard/var_unserializer.re"
{
zend_long id;
*p = YYCURSOR;
if (!var_hash) return 0;
id = parse_iv(start + 2) - 1;
if (id == -1 || (rval_ref = var_access(var_hash, id)) == NULL) {
return 0;
}
if (rval_ref == rval) {
return 0;
}
if (Z_ISUNDEF_P(rval_ref) || (Z_ISREF_P(rval_ref) && Z_ISUNDEF_P(Z_REFVAL_P(rval_ref)))) {
ZVAL_UNDEF(rval);
return 1;
}
ZVAL_COPY(rval, rval_ref);
return 1;
}
#line 1285 "ext/standard/var_unserializer.c"
yy95:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy96;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy97;
goto yy18;
}
yy96:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy97:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy97;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 522 "ext/standard/var_unserializer.re"
{
zend_long id;
*p = YYCURSOR;
if (!var_hash) return 0;
id = parse_iv(start + 2) - 1;
if (id == -1 || (rval_ref = var_access(var_hash, id)) == NULL) {
return 0;
}
zval_ptr_dtor(rval);
if (Z_ISUNDEF_P(rval_ref) || (Z_ISREF_P(rval_ref) && Z_ISUNDEF_P(Z_REFVAL_P(rval_ref)))) {
ZVAL_UNDEF(rval);
return 1;
}
if (Z_ISREF_P(rval_ref)) {
ZVAL_COPY(rval, rval_ref);
} else {
ZVAL_NEW_REF(rval_ref, rval_ref);
ZVAL_COPY(rval, rval_ref);
}
return 1;
}
#line 1334 "ext/standard/var_unserializer.c"
}
#line 886 "ext/standard/var_unserializer.re"
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-502/c/bad_5254_2 |
crossvul-cpp_data_bad_297_0 | /*
+----------------------------------------------------------------------+
| Swoole |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| license@swoole.com so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: xinhua.guo <woshiguo35@gmail.com> |
+----------------------------------------------------------------------+
*/
#include "php_swoole.h"
#include "swoole_serialize.h"
#ifdef __SSE2__
#include <emmintrin.h>
#endif
#if PHP_MAJOR_VERSION >= 7
#define CPINLINE sw_inline
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_serialize_pack, 0, 0, 1)
ZEND_ARG_INFO(0, data)
ZEND_ARG_INFO(0, flag)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_serialize_unpack, 0, 0, 1)
ZEND_ARG_INFO(0, string)
ZEND_ARG_INFO(0, args)
ZEND_END_ARG_INFO()
static void swoole_serialize_object(seriaString *buffer, zval *zvalue, size_t start);
static void swoole_serialize_arr(seriaString *buffer, zend_array *zvalue);
static void* swoole_unserialize_arr(void *buffer, zval *zvalue, uint32_t num, long flag);
static void* swoole_unserialize_object(void *buffer, zval *return_value, zend_uchar bucket_len, zval *args, long flag);
static PHP_METHOD(swoole_serialize, pack);
static PHP_METHOD(swoole_serialize, unpack);
static const zend_function_entry swoole_serialize_methods[] = {
PHP_ME(swoole_serialize, pack, arginfo_swoole_serialize_pack, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME(swoole_serialize, unpack, arginfo_swoole_serialize_unpack, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_FE_END
};
zend_class_entry swoole_serialize_ce;
zend_class_entry *swoole_serialize_class_entry_ptr;
#define SWOOLE_SERI_EOF "EOF"
static struct _swSeriaG swSeriaG;
void swoole_serialize_init(int module_number TSRMLS_DC)
{
SWOOLE_INIT_CLASS_ENTRY(swoole_serialize_ce, "swoole_serialize", "Swoole\\Serialize", swoole_serialize_methods);
swoole_serialize_class_entry_ptr = zend_register_internal_class(&swoole_serialize_ce TSRMLS_CC);
SWOOLE_CLASS_ALIAS(swoole_serialize, "Swoole\\Serialize");
// ZVAL_STRING(&swSeriaG.sleep_fname, "__sleep");
zend_string *zstr_sleep = zend_string_init("__sleep", sizeof ("__sleep") - 1, 1);
zend_string *zstr_weekup = zend_string_init("__weekup", sizeof ("__weekup") - 1, 1);
ZVAL_STR(&swSeriaG.sleep_fname, zstr_sleep);
ZVAL_STR(&swSeriaG.weekup_fname, zstr_weekup);
// ZVAL_STRING(&swSeriaG.weekup_fname, "__weekup");
memset(&swSeriaG.filter, 0, sizeof (swSeriaG.filter));
memset(&mini_filter, 0, sizeof (mini_filter));
REGISTER_LONG_CONSTANT("SWOOLE_FAST_PACK", SW_FAST_PACK, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("UNSERIALIZE_OBJECT_TO_ARRAY", UNSERIALIZE_OBJECT_TO_ARRAY, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("UNSERIALIZE_OBJECT_TO_STDCLASS", UNSERIALIZE_OBJECT_TO_STDCLASS, CONST_CS | CONST_PERSISTENT);
}
static CPINLINE int swoole_string_new(size_t size, seriaString *str, zend_uchar type)
{
int total = ZEND_MM_ALIGNED_SIZE(_STR_HEADER_SIZE + size + 1);
str->total = total;
//escape the header for later
str->offset = _STR_HEADER_SIZE;
//zend string addr
str->buffer = ecalloc(1, total);
if (!str->buffer)
{
php_error_docref(NULL TSRMLS_CC, E_ERROR, "malloc Error: %s [%d]", strerror(errno), errno);
}
SBucketType real_type = {0};
real_type.data_type = type;
*(SBucketType*) (str->buffer + str->offset) = real_type;
str->offset += sizeof (SBucketType);
return 0;
}
static CPINLINE void swoole_check_size(seriaString *str, size_t len)
{
int new_size = len + str->offset;
// int new_size = len + str->offset + 3 + sizeof (zend_ulong); //space 1 for the type and 2 for key string len or index len and(zend_ulong) for key h
if (str->total < new_size)
{//extend it
new_size = ZEND_MM_ALIGNED_SIZE(new_size + SERIA_SIZE);
str->buffer = erealloc2(str->buffer, new_size, str->offset);
if (!str->buffer)
{
php_error_docref(NULL TSRMLS_CC, E_ERROR, "realloc Error: %s [%d]", strerror(errno), errno);
}
str->total = new_size;
}
}
#ifdef __SSE2__
void CPINLINE swoole_mini_memcpy(void *dst, const void *src, size_t len)
{
register unsigned char *dd = (unsigned char*) dst + len;
register const unsigned char *ss = (const unsigned char*) src + len;
switch (len)
{
case 68: *((int*) (dd - 68)) = *((int*) (ss - 68));
/* no break */
case 64: *((int*) (dd - 64)) = *((int*) (ss - 64));
/* no break */
case 60: *((int*) (dd - 60)) = *((int*) (ss - 60));
/* no break */
case 56: *((int*) (dd - 56)) = *((int*) (ss - 56));
/* no break */
case 52: *((int*) (dd - 52)) = *((int*) (ss - 52));
/* no break */
case 48: *((int*) (dd - 48)) = *((int*) (ss - 48));
/* no break */
case 44: *((int*) (dd - 44)) = *((int*) (ss - 44));
/* no break */
case 40: *((int*) (dd - 40)) = *((int*) (ss - 40));
/* no break */
case 36: *((int*) (dd - 36)) = *((int*) (ss - 36));
/* no break */
case 32: *((int*) (dd - 32)) = *((int*) (ss - 32));
/* no break */
case 28: *((int*) (dd - 28)) = *((int*) (ss - 28));
/* no break */
case 24: *((int*) (dd - 24)) = *((int*) (ss - 24));
/* no break */
case 20: *((int*) (dd - 20)) = *((int*) (ss - 20));
/* no break */
case 16: *((int*) (dd - 16)) = *((int*) (ss - 16));
/* no break */
case 12: *((int*) (dd - 12)) = *((int*) (ss - 12));
/* no break */
case 8: *((int*) (dd - 8)) = *((int*) (ss - 8));
/* no break */
case 4: *((int*) (dd - 4)) = *((int*) (ss - 4));
break;
case 67: *((int*) (dd - 67)) = *((int*) (ss - 67));
/* no break */
case 63: *((int*) (dd - 63)) = *((int*) (ss - 63));
/* no break */
case 59: *((int*) (dd - 59)) = *((int*) (ss - 59));
/* no break */
case 55: *((int*) (dd - 55)) = *((int*) (ss - 55));
/* no break */
case 51: *((int*) (dd - 51)) = *((int*) (ss - 51));
/* no break */
case 47: *((int*) (dd - 47)) = *((int*) (ss - 47));
/* no break */
case 43: *((int*) (dd - 43)) = *((int*) (ss - 43));
/* no break */
case 39: *((int*) (dd - 39)) = *((int*) (ss - 39));
/* no break */
case 35: *((int*) (dd - 35)) = *((int*) (ss - 35));
/* no break */
case 31: *((int*) (dd - 31)) = *((int*) (ss - 31));
/* no break */
case 27: *((int*) (dd - 27)) = *((int*) (ss - 27));
/* no break */
case 23: *((int*) (dd - 23)) = *((int*) (ss - 23));
/* no break */
case 19: *((int*) (dd - 19)) = *((int*) (ss - 19));
/* no break */
case 15: *((int*) (dd - 15)) = *((int*) (ss - 15));
/* no break */
case 11: *((int*) (dd - 11)) = *((int*) (ss - 11));
/* no break */
case 7: *((int*) (dd - 7)) = *((int*) (ss - 7));
*((int*) (dd - 4)) = *((int*) (ss - 4));
break;
case 3: *((short*) (dd - 3)) = *((short*) (ss - 3));
dd[-1] = ss[-1];
break;
case 66: *((int*) (dd - 66)) = *((int*) (ss - 66));
/* no break */
case 62: *((int*) (dd - 62)) = *((int*) (ss - 62));
/* no break */
case 58: *((int*) (dd - 58)) = *((int*) (ss - 58));
/* no break */
case 54: *((int*) (dd - 54)) = *((int*) (ss - 54));
/* no break */
case 50: *((int*) (dd - 50)) = *((int*) (ss - 50));
/* no break */
case 46: *((int*) (dd - 46)) = *((int*) (ss - 46));
/* no break */
case 42: *((int*) (dd - 42)) = *((int*) (ss - 42));
/* no break */
case 38: *((int*) (dd - 38)) = *((int*) (ss - 38));
/* no break */
case 34: *((int*) (dd - 34)) = *((int*) (ss - 34));
/* no break */
case 30: *((int*) (dd - 30)) = *((int*) (ss - 30));
/* no break */
case 26: *((int*) (dd - 26)) = *((int*) (ss - 26));
/* no break */
case 22: *((int*) (dd - 22)) = *((int*) (ss - 22));
/* no break */
case 18: *((int*) (dd - 18)) = *((int*) (ss - 18));
/* no break */
case 14: *((int*) (dd - 14)) = *((int*) (ss - 14));
/* no break */
case 10: *((int*) (dd - 10)) = *((int*) (ss - 10));
/* no break */
case 6: *((int*) (dd - 6)) = *((int*) (ss - 6));
/* no break */
case 2: *((short*) (dd - 2)) = *((short*) (ss - 2));
break;
case 65: *((int*) (dd - 65)) = *((int*) (ss - 65));
/* no break */
case 61: *((int*) (dd - 61)) = *((int*) (ss - 61));
/* no break */
case 57: *((int*) (dd - 57)) = *((int*) (ss - 57));
/* no break */
case 53: *((int*) (dd - 53)) = *((int*) (ss - 53));
/* no break */
case 49: *((int*) (dd - 49)) = *((int*) (ss - 49));
/* no break */
case 45: *((int*) (dd - 45)) = *((int*) (ss - 45));
/* no break */
case 41: *((int*) (dd - 41)) = *((int*) (ss - 41));
/* no break */
case 37: *((int*) (dd - 37)) = *((int*) (ss - 37));
/* no break */
case 33: *((int*) (dd - 33)) = *((int*) (ss - 33));
/* no break */
case 29: *((int*) (dd - 29)) = *((int*) (ss - 29));
/* no break */
case 25: *((int*) (dd - 25)) = *((int*) (ss - 25));
/* no break */
case 21: *((int*) (dd - 21)) = *((int*) (ss - 21));
/* no break */
case 17: *((int*) (dd - 17)) = *((int*) (ss - 17));
/* no break */
case 13: *((int*) (dd - 13)) = *((int*) (ss - 13));
/* no break */
case 9: *((int*) (dd - 9)) = *((int*) (ss - 9));
/* no break */
case 5: *((int*) (dd - 5)) = *((int*) (ss - 5));
/* no break */
case 1: dd[-1] = ss[-1];
break;
case 0:
default: break;
}
}
void CPINLINE swoole_memcpy_fast(void *destination, const void *source, size_t size)
{
unsigned char *dst = (unsigned char*) destination;
const unsigned char *src = (const unsigned char*) source;
// small memory copy
if (size < 64)
{
swoole_mini_memcpy(dst, src, size);
return;
}
size_t diff = (((size_t) dst + 15L) & (~15L)) - ((size_t) dst);
if (diff > 0)
{
swoole_mini_memcpy(dst, src, diff);
dst += diff;
src += diff;
size -= diff;
}
// 4个寄存器
__m128i c1, c2, c3, c4;
if ((((size_t) src) & 15L) == 0)
{
for(; size >= 64; size -= 64)
{
//load 时候将下次要用的数据提前fetch
_mm_prefetch((const char*) (src + 64), _MM_HINT_NTA);
_mm_prefetch((const char*) (dst + 64), _MM_HINT_T0);
//从内存中load到寄存器
c1 = _mm_load_si128(((const __m128i*) src) + 0);
c2 = _mm_load_si128(((const __m128i*) src) + 1);
c3 = _mm_load_si128(((const __m128i*) src) + 2);
c4 = _mm_load_si128(((const __m128i*) src) + 3);
src += 64;
//写回内存
_mm_store_si128((((__m128i*) dst) + 0), c1);
_mm_store_si128((((__m128i*) dst) + 1), c2);
_mm_store_si128((((__m128i*) dst) + 2), c3);
_mm_store_si128((((__m128i*) dst) + 3), c4);
dst += 64;
}
}
else
{
for(; size >= 64; size -= 64)
{
_mm_prefetch((const char*) (src + 64), _MM_HINT_NTA);
_mm_prefetch((const char*) (dst + 64), _MM_HINT_T0);
c1 = _mm_loadu_si128(((const __m128i*) src) + 0);
c2 = _mm_loadu_si128(((const __m128i*) src) + 1);
c3 = _mm_loadu_si128(((const __m128i*) src) + 2);
c4 = _mm_loadu_si128(((const __m128i*) src) + 3);
src += 64;
_mm_store_si128((((__m128i*) dst) + 0), c1);
_mm_store_si128((((__m128i*) dst) + 1), c2);
_mm_store_si128((((__m128i*) dst) + 2), c3);
_mm_store_si128((((__m128i*) dst) + 3), c4);
dst += 64;
}
}
// _mm_sfence();
// return memcpy_tiny(dst, src, size);
}
#endif
static CPINLINE void swoole_string_cpy(seriaString *str, void *mem, size_t len)
{
swoole_check_size(str, len + 15L);
//example:13+15=28 28& 11111111 11111111 11111111 11110000
//str->offset = ((str->offset + 15L) & ~15L);
// swoole_memcspy_fast(str->buffer + str->offset, mem, len);
memcpy(str->buffer + str->offset, mem, len);
str->offset = len + str->offset;
}
static CPINLINE void swoole_set_zend_value(seriaString *str, void *value)
{
swoole_check_size(str, sizeof (zend_value));
*(zend_value*) (str->buffer + str->offset) = *((zend_value*) value);
str->offset = sizeof (zend_value) + str->offset;
}
static CPINLINE void swoole_serialize_long(seriaString *buffer, zval *zvalue, SBucketType* type)
{
zend_long value = Z_LVAL_P(zvalue);
//01111111 - 11111111
if (value <= 0x7f && value >= -0x7f)
{
type->data_len = 0;
SERIA_SET_ENTRY_TYPE_WITH_MINUS(buffer, value);
}
else if (value <= 0x7fff && value >= -0x7fff)
{
type->data_len = 1;
SERIA_SET_ENTRY_SHORT_WITH_MINUS(buffer, value);
}
else if (value <= 0x7fffffff && value >= -0x7fffffff)
{
type->data_len = 2;
SERIA_SET_ENTRY_SIZE4_WITH_MINUS(buffer, value);
}
else
{
type->data_len = 3;
swoole_string_cpy(buffer, &zvalue->value, sizeof (zend_value));
}
}
static CPINLINE void* swoole_unserialize_long(void *buffer, zval *ret_value, SBucketType type)
{
if (type.data_len == 0)
{//1 byte
Z_LVAL_P(ret_value) = *((char*) buffer);
buffer += sizeof (char);
}
else if (type.data_len == 1)
{//2 byte
Z_LVAL_P(ret_value) = *((short*) buffer);
buffer += sizeof (short);
}
else if (type.data_len == 2)
{//4 byte
Z_LVAL_P(ret_value) = *((int32_t *) buffer);
buffer += sizeof (int32_t);
}
else
{//8 byte
ret_value->value = *((zend_value*) buffer);
buffer += sizeof (zend_value);
}
return buffer;
}
static uint32_t CPINLINE cp_zend_hash_check_size(uint32_t nSize)
{
#if defined(ZEND_WIN32)
unsigned long index;
#endif
/* Use big enough power of 2 */
/* size should be between HT_MIN_SIZE and HT_MAX_SIZE */
if (nSize < HT_MIN_SIZE)
{
nSize = HT_MIN_SIZE;
}// else if (UNEXPECTED(nSize >= 1000000))
else if (UNEXPECTED(nSize >= HT_MAX_SIZE))
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid unserialize data");
return 0;
}
#if defined(ZEND_WIN32)
if (BitScanReverse(&index, nSize - 1))
{
return 0x2 << ((31 - index) ^ 0x1f);
}
else
{
/* nSize is ensured to be in the valid range, fall back to it
rather than using an undefined bis scan result. */
return nSize;
}
#elif (defined(__GNUC__) || __has_builtin(__builtin_clz)) && defined(PHP_HAVE_BUILTIN_CLZ)
return 0x2 << (__builtin_clz(nSize - 1) ^ 0x1f);
#else
nSize -= 1;
nSize |= (nSize >> 1);
nSize |= (nSize >> 2);
nSize |= (nSize >> 4);
nSize |= (nSize >> 8);
nSize |= (nSize >> 16);
return nSize + 1;
#endif
}
static CPINLINE void swoole_mini_filter_clear()
{
if (swSeriaG.pack_string)
{
memset(&mini_filter, 0, sizeof (mini_filter));
if (bigger_filter)
{
efree(bigger_filter);
bigger_filter = NULL;
}
memset(&swSeriaG.filter, 0, sizeof (struct _swMinFilter));
}
}
static CPINLINE void swoole_make_bigger_filter_size()
{
if (FILTER_SIZE <= swSeriaG.filter.mini_fillter_miss_cnt &&
swSeriaG.filter.mini_fillter_find_cnt < swSeriaG.filter.mini_fillter_miss_cnt)
// if (FILTER_SIZE <= swSeriaG.filter.mini_fillter_miss_cnt &&
// (swSeriaG.filter.mini_fillter_find_cnt / swSeriaG.filter.mini_fillter_miss_cnt) < 1)
{
swSeriaG.filter.bigger_fillter_size = swSeriaG.filter.mini_fillter_miss_cnt * 128;
bigger_filter = (swPoolstr*) ecalloc(1, sizeof (swPoolstr) * swSeriaG.filter.bigger_fillter_size);
memcpy(bigger_filter, &mini_filter, sizeof (mini_filter));
}
}
static CPINLINE void swoole_mini_filter_add(zend_string *zstr, size_t offset, zend_uchar byte)
{
if (swSeriaG.pack_string)
{
offset -= _STR_HEADER_SIZE;
//head 3bit is overhead
if (offset >= 0x1fffffff)
{
return;
}
if (bigger_filter)
{
uint32_t mod_big = zstr->h & (swSeriaG.filter.bigger_fillter_size - 1);
bigger_filter[mod_big].offset = offset << 3;
if (offset <= 0x1fff)
{
bigger_filter[mod_big].offset |= byte;
}
else
{
bigger_filter[mod_big].offset |= (byte | 4);
}
bigger_filter[mod_big].str = zstr;
}
else
{
uint16_t mod = zstr->h & (FILTER_SIZE - 1);
//repalce it is effective,cause the principle of locality
mini_filter[mod].offset = offset << 3;
if (offset <= 0x1fff)
{
mini_filter[mod].offset |= byte;
}
else
{
mini_filter[mod].offset |= (byte | 4);
}
mini_filter[mod].str = zstr;
swSeriaG.filter.mini_fillter_miss_cnt++;
swoole_make_bigger_filter_size();
}
}
}
static CPINLINE swPoolstr* swoole_mini_filter_find(zend_string *zstr)
{
if (swSeriaG.pack_string)
{
zend_ulong h = zend_string_hash_val(zstr);
swPoolstr* str = NULL;
if (bigger_filter)
{
str = &bigger_filter[h & (swSeriaG.filter.bigger_fillter_size - 1)];
}
else
{
str = &mini_filter[h & (FILTER_SIZE - 1)];
}
if (!str->str)
{
return NULL;
}
if (str->str->h == h &&
zstr->len == str->str->len &&
memcmp(zstr->val, str->str->val, zstr->len) == 0)
{
swSeriaG.filter.mini_fillter_find_cnt++;
return str;
}
else
{
return NULL;
}
}
else
{
return NULL;
}
}
/*
* arr layout
* type|key?|bucketlen|buckets
*/
static CPINLINE void seria_array_type(zend_array *ht, seriaString *buffer, size_t type_offset, size_t blen_offset)
{
buffer->offset = blen_offset;
if (ht->nNumOfElements <= 0xff)
{
((SBucketType*) (buffer->buffer + type_offset))->data_len = 1;
SERIA_SET_ENTRY_TYPE(buffer, ht->nNumOfElements)
}
else if (ht->nNumOfElements <= 0xffff)
{
((SBucketType*) (buffer->buffer + type_offset))->data_len = 2;
SERIA_SET_ENTRY_SHORT(buffer, ht->nNumOfElements);
}
else
{
((SBucketType*) (buffer->buffer + type_offset))->data_len = 0;
swoole_string_cpy(buffer, &ht->nNumOfElements, sizeof (uint32_t));
}
}
/*
* buffer is bucket len addr
*/
static CPINLINE void* get_array_real_len(void *buffer, zend_uchar data_len, uint32_t *nNumOfElements)
{
if (data_len == 1)
{
*nNumOfElements = *((zend_uchar*) buffer);
return buffer + sizeof (zend_uchar);
}
else if (data_len == 2)
{
*nNumOfElements = *((unsigned short*) buffer);
return buffer + sizeof (short);
}
else
{
*nNumOfElements = *((uint32_t*) buffer);
return buffer + sizeof (uint32_t);
}
}
static CPINLINE void * get_pack_string_len_addr(void ** buffer, size_t *strlen)
{
uint8_t overhead = (*(uint8_t*) * buffer);
uint32_t real_offset;
uint8_t len_byte;
if (overhead & 4)
{
real_offset = (*(uint32_t*) * buffer) >> 3;
len_byte = overhead & 3;
(*buffer) += 4;
}
else
{
real_offset = (*(uint16_t*) * buffer) >> 3;
len_byte = overhead & 3;
(*buffer) += 2;
}
void *str_pool_addr = unser_start + real_offset;
if (len_byte == 1)
{
*strlen = *((zend_uchar*) str_pool_addr);
str_pool_addr = str_pool_addr + sizeof (zend_uchar);
}
else if (len_byte == 2)
{
*strlen = *((unsigned short*) str_pool_addr);
str_pool_addr = str_pool_addr + sizeof (unsigned short);
}
else
{
*strlen = *((size_t*) str_pool_addr);
str_pool_addr = str_pool_addr + sizeof (size_t);
}
// size_t tmp = *strlen;
return str_pool_addr;
}
/*
* array
*/
static void* swoole_unserialize_arr(void *buffer, zval *zvalue, uint32_t nNumOfElements, long flag)
{
//Initialize zend array
zend_ulong h, nIndex, max_index = 0;
uint32_t size = cp_zend_hash_check_size(nNumOfElements);
if (!size)
{
return NULL;
}
if (!buffer)
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "illegal unserialize data");
return NULL;
}
ZVAL_NEW_ARR(zvalue);
//Initialize buckets
zend_array *ht = Z_ARR_P(zvalue);
ht->nTableSize = size;
ht->nNumUsed = nNumOfElements;
ht->nNumOfElements = nNumOfElements;
ht->nNextFreeElement = 0;
#ifdef HASH_FLAG_APPLY_PROTECTION
ht->u.flags = HASH_FLAG_APPLY_PROTECTION;
#endif
ht->nTableMask = -(ht->nTableSize);
ht->pDestructor = ZVAL_PTR_DTOR;
GC_SET_REFCOUNT(ht, 1);
GC_TYPE_INFO(ht) = IS_ARRAY;
// if (ht->nNumUsed)
//{
// void *arData = ecalloc(1, len);
HT_SET_DATA_ADDR(ht, emalloc(HT_SIZE(ht)));
ht->u.flags |= HASH_FLAG_INITIALIZED;
int ht_hash_size = HT_HASH_SIZE((ht)->nTableMask);
if (ht_hash_size <= 0)
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "illegal unserialize data");
return NULL;
}
HT_HASH_RESET(ht);
//}
int idx;
Bucket *p;
for(idx = 0; idx < nNumOfElements; idx++)
{
if (!buffer)
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "illegal array unserialize data");
return NULL;
}
SBucketType type = *((SBucketType*) buffer);
buffer += sizeof (SBucketType);
p = ht->arData + idx;
/* Initialize key */
if (type.key_type == KEY_TYPE_STRING)
{
size_t key_len;
if (type.key_len == 3)
{//read the same mem
void *str_pool_addr = get_pack_string_len_addr(&buffer, &key_len);
p->key = zend_string_init((char*) str_pool_addr, key_len, 0);
h = zend_inline_hash_func((char*) str_pool_addr, key_len);
p->key->h = p->h = h;
}
else
{//move step
if (type.key_len == 1)
{
key_len = *((zend_uchar*) buffer);
buffer += sizeof (zend_uchar);
}
else if (type.key_len == 2)
{
key_len = *((unsigned short*) buffer);
buffer += sizeof (unsigned short);
}
else
{
key_len = *((size_t*) buffer);
buffer += sizeof (size_t);
}
p->key = zend_string_init((char*) buffer, key_len, 0);
// h = zend_inline_hash_func((char*) buffer, key_len);
h = zend_inline_hash_func((char*) buffer, key_len);
buffer += key_len;
p->key->h = p->h = h;
}
}
else
{
if (type.key_len == 0)
{
//means pack
h = p->h = idx;
p->key = NULL;
max_index = p->h + 1;
// ht->u.flags |= HASH_FLAG_PACKED;
}
else
{
if (type.key_len == 1)
{
h = *((zend_uchar*) buffer);
buffer += sizeof (zend_uchar);
}
else if (type.key_len == 2)
{
h = *((unsigned short*) buffer);
buffer += sizeof (unsigned short);
}
else
{
h = *((zend_ulong*) buffer);
buffer += sizeof (zend_ulong);
}
p->h = h;
p->key = NULL;
if (h >= max_index)
{
max_index = h + 1;
}
}
}
/* Initialize hash */
nIndex = h | ht->nTableMask;
Z_NEXT(p->val) = HT_HASH(ht, nIndex);
HT_HASH(ht, nIndex) = HT_IDX_TO_HASH(idx);
/* Initialize data type */
p->val.u1.v.type = type.data_type;
Z_TYPE_FLAGS(p->val) = 0;
/* Initialize data */
if (type.data_type == IS_STRING)
{
size_t data_len;
if (type.data_len == 3)
{//read the same mem
void *str_pool_addr = get_pack_string_len_addr(&buffer, &data_len);
p->val.value.str = zend_string_init((char*) str_pool_addr, data_len, 0);
}
else
{
if (type.data_len == 1)
{
data_len = *((zend_uchar*) buffer);
buffer += sizeof (zend_uchar);
}
else if (type.data_len == 2)
{
data_len = *((unsigned short*) buffer);
buffer += sizeof (unsigned short);
}
else
{
data_len = *((size_t*) buffer);
buffer += sizeof (size_t);
}
p->val.value.str = zend_string_init((char*) buffer, data_len, 0);
buffer += data_len;
}
Z_TYPE_INFO(p->val) = IS_STRING_EX;
}
else if (type.data_type == IS_ARRAY)
{
uint32_t num = 0;
buffer = get_array_real_len(buffer, type.data_len, &num);
buffer = swoole_unserialize_arr(buffer, &p->val, num, flag);
}
else if (type.data_type == IS_LONG)
{
buffer = swoole_unserialize_long(buffer, &p->val, type);
}
else if (type.data_type == IS_DOUBLE)
{
p->val.value = *((zend_value*) buffer);
buffer += sizeof (zend_value);
}
else if (type.data_type == IS_UNDEF)
{
buffer = swoole_unserialize_object(buffer, &p->val, type.data_len, NULL, flag);
Z_TYPE_INFO(p->val) = IS_OBJECT_EX;
}
}
ht->nNextFreeElement = max_index;
return buffer;
}
/*
* arr layout
* type|key?|bucketlen|buckets
*/
static void swoole_serialize_arr(seriaString *buffer, zend_array *zvalue)
{
zval *data;
zend_string *key;
zend_ulong index;
swPoolstr *swStr = NULL;
zend_uchar is_pack = zvalue->u.flags & HASH_FLAG_PACKED;
ZEND_HASH_FOREACH_KEY_VAL(zvalue, index, key, data)
{
SBucketType type = {0};
type.data_type = Z_TYPE_P(data);
//start point
size_t p = buffer->offset;
if (is_pack && zvalue->nNextFreeElement == zvalue->nNumOfElements)
{
type.key_type = KEY_TYPE_INDEX;
type.key_len = 0;
SERIA_SET_ENTRY_TYPE(buffer, type);
}
else
{
//seria key
if (key)
{
type.key_type = KEY_TYPE_STRING;
if ((swStr = swoole_mini_filter_find(key)))
{
type.key_len = 3; //means use same string
SERIA_SET_ENTRY_TYPE(buffer, type);
if (swStr->offset & 4)
{
SERIA_SET_ENTRY_SIZE4(buffer, swStr->offset);
}
else
{
SERIA_SET_ENTRY_SHORT(buffer, swStr->offset);
}
}
else
{
if (key->len <= 0xff)
{
type.key_len = 1;
SERIA_SET_ENTRY_TYPE(buffer, type);
swoole_mini_filter_add(key, buffer->offset, 1);
SERIA_SET_ENTRY_TYPE(buffer, key->len);
swoole_string_cpy(buffer, key->val, key->len);
}
else if (key->len <= 0xffff)
{//if more than this don't need optimize
type.key_len = 2;
SERIA_SET_ENTRY_TYPE(buffer, type);
swoole_mini_filter_add(key, buffer->offset, 2);
SERIA_SET_ENTRY_SHORT(buffer, key->len);
swoole_string_cpy(buffer, key->val, key->len);
}
else
{
type.key_len = 0;
SERIA_SET_ENTRY_TYPE(buffer, type);
swoole_mini_filter_add(key, buffer->offset, 3);
swoole_string_cpy(buffer, key + XtOffsetOf(zend_string, len), sizeof (size_t) + key->len);
}
}
}
else
{
type.key_type = KEY_TYPE_INDEX;
if (index <= 0xff)
{
type.key_len = 1;
SERIA_SET_ENTRY_TYPE(buffer, type);
SERIA_SET_ENTRY_TYPE(buffer, index);
}
else if (index <= 0xffff)
{
type.key_len = 2;
SERIA_SET_ENTRY_TYPE(buffer, type);
SERIA_SET_ENTRY_SHORT(buffer, index);
}
else
{
type.key_len = 3;
SERIA_SET_ENTRY_TYPE(buffer, type);
SERIA_SET_ENTRY_ULONG(buffer, index);
}
}
}
//seria data
try_again:
switch (Z_TYPE_P(data))
{
case IS_STRING:
{
if ((swStr = swoole_mini_filter_find(Z_STR_P(data))))
{
((SBucketType*) (buffer->buffer + p))->data_len = 3; //means use same string
if (swStr->offset & 4)
{
SERIA_SET_ENTRY_SIZE4(buffer, swStr->offset);
}
else
{
SERIA_SET_ENTRY_SHORT(buffer, swStr->offset);
}
}
else
{
if (Z_STRLEN_P(data) <= 0xff)
{
((SBucketType*) (buffer->buffer + p))->data_len = 1;
swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 1);
SERIA_SET_ENTRY_TYPE(buffer, Z_STRLEN_P(data));
swoole_string_cpy(buffer, Z_STRVAL_P(data), Z_STRLEN_P(data));
}
else if (Z_STRLEN_P(data) <= 0xffff)
{
((SBucketType*) (buffer->buffer + p))->data_len = 2;
swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 2);
SERIA_SET_ENTRY_SHORT(buffer, Z_STRLEN_P(data));
swoole_string_cpy(buffer, Z_STRVAL_P(data), Z_STRLEN_P(data));
}
else
{//if more than this don't need optimize
((SBucketType*) (buffer->buffer + p))->data_len = 0;
swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 3);
swoole_string_cpy(buffer, (char*) Z_STR_P(data) + XtOffsetOf(zend_string, len), sizeof (size_t) + Z_STRLEN_P(data));
}
}
break;
}
case IS_LONG:
{
SBucketType* long_type = (SBucketType*) (buffer->buffer + p);
swoole_serialize_long(buffer, data, long_type);
break;
}
case IS_DOUBLE:
swoole_set_zend_value(buffer, &(data->value));
break;
case IS_REFERENCE:
data = Z_REFVAL_P(data);
((SBucketType*) (buffer->buffer + p))->data_type = Z_TYPE_P(data);
goto try_again;
break;
case IS_ARRAY:
{
zend_array *ht = Z_ARRVAL_P(data);
if (GC_IS_RECURSIVE(ht))
{
((SBucketType*) (buffer->buffer + p))->data_type = IS_NULL;//reset type null
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "the array has cycle ref");
}
else
{
seria_array_type(ht, buffer, p, buffer->offset);
if (ZEND_HASH_APPLY_PROTECTION(ht))
{
GC_PROTECT_RECURSION(ht);
swoole_serialize_arr(buffer, ht);
GC_UNPROTECT_RECURSION(ht);
}
else
{
swoole_serialize_arr(buffer, ht);
}
}
break;
}
//object propterty table is this type
case IS_INDIRECT:
data = Z_INDIRECT_P(data);
zend_uchar type = Z_TYPE_P(data);
((SBucketType*) (buffer->buffer + p))->data_type = (type == IS_UNDEF ? IS_NULL : type);
goto try_again;
break;
case IS_OBJECT:
{
/*
* layout
* type | key | namelen | name | bucket len |buckets
*/
((SBucketType*) (buffer->buffer + p))->data_type = IS_UNDEF;
if (ZEND_HASH_APPLY_PROTECTION(Z_OBJPROP_P(data)))
{
GC_PROTECT_RECURSION(Z_OBJPROP_P(data));
swoole_serialize_object(buffer, data, p);
GC_UNPROTECT_RECURSION(Z_OBJPROP_P(data));
}
else
{
swoole_serialize_object(buffer, data, p);
}
break;
}
default://
break;
}
}
ZEND_HASH_FOREACH_END();
}
/*
* string
*/
static CPINLINE void swoole_serialize_string(seriaString *buffer, zval *zvalue)
{
swoole_string_cpy(buffer, Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue));
}
static CPINLINE zend_string* swoole_unserialize_string(void *buffer, size_t len)
{
return zend_string_init(buffer, len, 0);
}
/*
* raw
*/
static CPINLINE void swoole_unserialize_raw(void *buffer, zval *zvalue)
{
memcpy(&zvalue->value, buffer, sizeof (zend_value));
}
#if 0
/*
* null
*/
static CPINLINE void swoole_unserialize_null(void *buffer, zval *zvalue)
{
memcpy(&zvalue->value, buffer, sizeof (zend_value));
}
#endif
static CPINLINE void swoole_serialize_raw(seriaString *buffer, zval *zvalue)
{
swoole_string_cpy(buffer, &zvalue->value, sizeof (zend_value));
}
/*
* obj layout
* type|bucket key|name len| name| buket len |buckets
*/
static void swoole_serialize_object(seriaString *buffer, zval *obj, size_t start)
{
zend_string *name = Z_OBJCE_P(obj)->name;
if (GC_IS_RECURSIVE(Z_OBJPROP_P(obj)))
{
zend_throw_exception_ex(NULL, 0, "the object %s has cycle ref.", name->val);
return;
}
if (name->len > 0xffff)
{//so long?
zend_throw_exception_ex(NULL, 0, "the object name is too long.");
}
else
{
SERIA_SET_ENTRY_SHORT(buffer, name->len);
swoole_string_cpy(buffer, name->val, name->len);
}
zend_class_entry *ce = Z_OBJ_P(obj)->ce;
if (ce && zend_hash_exists(&ce->function_table, Z_STR(swSeriaG.sleep_fname)))
{
zval retval;
if (call_user_function_ex(NULL, obj, &swSeriaG.sleep_fname, &retval, 0, 0, 1, NULL) == SUCCESS)
{
if (EG(exception))
{
zval_dtor(&retval);
return;
}
if (Z_TYPE(retval) == IS_ARRAY)
{
zend_string *prop_key;
zval *prop_value, *sleep_value;
const char *prop_name, *class_name;
size_t prop_key_len;
int got_num = 0;
//for the zero malloc
zend_array tmp_arr;
zend_array *ht = (zend_array *) & tmp_arr;
#if PHP_VERSION_ID >= 70300
_zend_hash_init(ht, zend_hash_num_elements(Z_ARRVAL(retval)), ZVAL_PTR_DTOR, 0);
#else
_zend_hash_init(ht, zend_hash_num_elements(Z_ARRVAL(retval)), ZVAL_PTR_DTOR, 0 ZEND_FILE_LINE_CC);
#endif
ht->nTableMask = -(ht)->nTableSize;
ALLOCA_FLAG(use_heap);
void *ht_addr = do_alloca(HT_SIZE(ht), use_heap);
HT_SET_DATA_ADDR(ht, ht_addr);
ht->u.flags |= HASH_FLAG_INITIALIZED;
HT_HASH_RESET(ht);
//just clean property do not add null when does not exist
//we double for each, cause we do not malloc and release it
ZEND_HASH_FOREACH_STR_KEY_VAL(Z_OBJPROP_P(obj), prop_key, prop_value)
{
//get origin property name
zend_unmangle_property_name_ex(prop_key, &class_name, &prop_name, &prop_key_len);
ZEND_HASH_FOREACH_VAL(Z_ARRVAL(retval), sleep_value)
{
if (Z_TYPE_P(sleep_value) == IS_STRING &&
Z_STRLEN_P(sleep_value) == prop_key_len &&
memcmp(Z_STRVAL_P(sleep_value), prop_name, prop_key_len) == 0)
{
got_num++;
//add mangle key,unmangle in unseria
_zend_hash_add_or_update(ht, prop_key, prop_value, HASH_UPDATE ZEND_FILE_LINE_CC);
break;
}
}
ZEND_HASH_FOREACH_END();
}
ZEND_HASH_FOREACH_END();
//there some member not in property
if (zend_hash_num_elements(Z_ARRVAL(retval)) > got_num)
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep() retrun a member but does not exist in property");
}
seria_array_type(ht, buffer, start, buffer->offset);
swoole_serialize_arr(buffer, ht);
ZSTR_ALLOCA_FREE(ht_addr, use_heap);
zval_dtor(&retval);
return;
}
else
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, " __sleep should return an array only containing the "
"names of instance-variables to serialize");
zval_dtor(&retval);
}
}
}
seria_array_type(Z_OBJPROP_P(obj), buffer, start, buffer->offset);
swoole_serialize_arr(buffer, Z_OBJPROP_P(obj));
// printf("hash2 %u\n",ce->properties_info.arData[0].key->h);
}
/*
* for the zero malloc
*/
static CPINLINE zend_string * swoole_string_init(const char *str, size_t len)
{
#ifdef ZEND_DEBUG
return zend_string_init(str, len, 0);
#else
ALLOCA_FLAG(use_heap);
zend_string *ret;
ZSTR_ALLOCA_INIT(ret, str, len, use_heap);
return ret;
#endif
}
/*
* for the zero malloc
*/
static CPINLINE void swoole_string_release(zend_string *str)
{
#ifdef ZEND_DEBUG
zend_string_release(str);
#else
//if dont support alloc 0 will ignore
//if support alloc size is definitely < ZEND_ALLOCA_MAX_SIZE
ZSTR_ALLOCA_FREE(str, 0);
#endif
}
static CPINLINE zend_class_entry* swoole_try_get_ce(zend_string *class_name)
{
//user class , do not support incomplete class now
zend_class_entry *ce = zend_lookup_class(class_name);
if (ce)
{
return ce;
}
// try call unserialize callback and retry lookup
zval user_func, args[1], retval;
/* Check for unserialize callback */
if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\0'))
{
zend_throw_exception_ex(NULL, 0, "can not find class %s", class_name->val TSRMLS_CC);
return NULL;
}
zend_string *fname = swoole_string_init(ZEND_STRL(PG(unserialize_callback_func)));
Z_STR(user_func) = fname;
Z_TYPE_INFO(user_func) = IS_STRING_EX;
ZVAL_STR(&args[0], class_name);
call_user_function_ex(CG(function_table), NULL, &user_func, &retval, 1, args, 0, NULL);
swoole_string_release(fname);
//user class , do not support incomplete class now
ce = zend_lookup_class(class_name);
if (!ce)
{
zend_throw_exception_ex(NULL, 0, "can not find class %s", class_name->val TSRMLS_CC);
return NULL;
}
else
{
return ce;
}
}
/*
* obj layout
* type| key[0|1] |name len| name| buket len |buckets
*/
static void* swoole_unserialize_object(void *buffer, zval *return_value, zend_uchar bucket_len, zval *args, long flag)
{
zval property;
uint32_t arr_num = 0;
size_t name_len = *((unsigned short*) buffer);
if (!name_len)
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "illegal unserialize data");
return NULL;
}
buffer += 2;
zend_string *class_name;
if (flag == UNSERIALIZE_OBJECT_TO_STDCLASS)
{
class_name = swoole_string_init(ZEND_STRL("StdClass"));
}
else
{
class_name = swoole_string_init((char*) buffer, name_len);
}
buffer += name_len;
zend_class_entry *ce = swoole_try_get_ce(class_name);
swoole_string_release(class_name);
if (!ce)
{
return NULL;
}
buffer = get_array_real_len(buffer, bucket_len, &arr_num);
buffer = swoole_unserialize_arr(buffer, &property, arr_num, flag);
object_init_ex(return_value, ce);
zval *data,*d;
zend_string *key;
zend_ulong index;
ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL(property), index, key, data)
{
const char *prop_name, *tmp;
size_t prop_len;
if (key)
{
if ((d = zend_hash_find(Z_OBJPROP_P(return_value), key)) != NULL)
{
if (Z_TYPE_P(d) == IS_INDIRECT)
{
d = Z_INDIRECT_P(d);
}
zval_dtor(d);
ZVAL_COPY(d, data);
}
else
{
zend_unmangle_property_name_ex(key, &tmp, &prop_name, &prop_len);
zend_update_property(ce, return_value, prop_name, prop_len, data);
}
// zend_hash_update(Z_OBJPROP_P(return_value),key,data);
// zend_update_property(ce, return_value, ZSTR_VAL(key), ZSTR_LEN(key), data);
}
else
{
zend_hash_next_index_insert(Z_OBJPROP_P(return_value), data);
}
}
ZEND_HASH_FOREACH_END();
zval_dtor(&property);
if (ce->constructor)
{
// zend_fcall_info fci = {0};
// zend_fcall_info_cache fcc = {0};
// fci.size = sizeof (zend_fcall_info);
// zval retval;
// ZVAL_UNDEF(&fci.function_name);
// fci.retval = &retval;
// fci.param_count = 0;
// fci.params = NULL;
// fci.no_separation = 1;
// fci.object = Z_OBJ_P(return_value);
//
// zend_fcall_info_args_ex(&fci, ce->constructor, args);
//
// fcc.initialized = 1;
// fcc.function_handler = ce->constructor;
// // fcc.calling_scope = EG(scope);
// fcc.called_scope = Z_OBJCE_P(return_value);
// fcc.object = Z_OBJ_P(return_value);
//
// if (zend_call_function(&fci, &fcc) == FAILURE)
// {
// zend_throw_exception_ex(NULL, 0, "could not call class constructor");
// }
// zend_fcall_info_args_clear(&fci, 1);
}
//call object __wakeup
if (zend_hash_str_exists(&ce->function_table, ZEND_STRL("__wakeup")))
{
zval ret, wakeup;
zend_string *fname = swoole_string_init(ZEND_STRL("__wakeup"));
Z_STR(wakeup) = fname;
Z_TYPE_INFO(wakeup) = IS_STRING_EX;
call_user_function_ex(CG(function_table), return_value, &wakeup, &ret, 0, NULL, 1, NULL);
swoole_string_release(fname);
zval_ptr_dtor(&ret);
}
return buffer;
}
/*
* dispatch
*/
static CPINLINE void swoole_seria_dispatch(seriaString *buffer, zval *zvalue)
{
again:
switch (Z_TYPE_P(zvalue))
{
case IS_NULL:
case IS_TRUE:
case IS_FALSE:
break;
case IS_LONG:
{
SBucketType* type = (SBucketType*) (buffer->buffer + _STR_HEADER_SIZE);
swoole_serialize_long(buffer, zvalue, type);
break;
}
case IS_DOUBLE:
swoole_serialize_raw(buffer, zvalue);
break;
case IS_STRING:
swoole_serialize_string(buffer, zvalue);
break;
case IS_ARRAY:
{
seria_array_type(Z_ARRVAL_P(zvalue), buffer, _STR_HEADER_SIZE, _STR_HEADER_SIZE + 1);
swoole_serialize_arr(buffer, Z_ARRVAL_P(zvalue));
swoole_string_cpy(buffer, SWOOLE_SERI_EOF, 3);
swoole_mini_filter_clear();
break;
}
case IS_REFERENCE:
zvalue = Z_REFVAL_P(zvalue);
goto again;
break;
case IS_OBJECT:
{
SBucketType* type = (SBucketType*) (buffer->buffer + _STR_HEADER_SIZE);
type->data_type = IS_UNDEF;
swoole_serialize_object(buffer, zvalue, _STR_HEADER_SIZE);
swoole_string_cpy(buffer, SWOOLE_SERI_EOF, 3);
swoole_mini_filter_clear();
break;
}
default:
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "the type is not supported by swoole serialize.");
break;
}
}
PHPAPI zend_string* php_swoole_serialize(zval *zvalue)
{
seriaString str;
swoole_string_new(SERIA_SIZE, &str, Z_TYPE_P(zvalue));
swoole_seria_dispatch(&str, zvalue); //serialize into a string
zend_string *z_str = (zend_string *) str.buffer;
z_str->len = str.offset - _STR_HEADER_SIZE;
z_str->val[z_str->len] = '\0';
z_str->h = 0;
GC_SET_REFCOUNT(z_str, 1);
GC_TYPE_INFO(z_str) = IS_STRING_EX;
return z_str;
}
static CPINLINE int swoole_seria_check_eof(void *buffer, size_t len)
{
void *eof_str = buffer - sizeof (SBucketType) + len - 3;
if (memcmp(eof_str, SWOOLE_SERI_EOF, 3) == 0)
{
return 0;
}
else
{
return -1;
}
}
/*
* buffer is seria string buffer
* len is string len
* return_value is unseria bucket
* args is for the object ctor (can be NULL)
*/
PHPAPI int php_swoole_unserialize(void *buffer, size_t len, zval *return_value, zval *object_args, long flag)
{
SBucketType type = *(SBucketType*) (buffer);
zend_uchar real_type = type.data_type;
buffer += sizeof (SBucketType);
switch (real_type)
{
case IS_NULL:
case IS_TRUE:
case IS_FALSE:
Z_TYPE_INFO_P(return_value) = real_type;
break;
case IS_LONG:
swoole_unserialize_long(buffer, return_value, type);
Z_TYPE_INFO_P(return_value) = real_type;
break;
case IS_DOUBLE:
swoole_unserialize_raw(buffer, return_value);
Z_TYPE_INFO_P(return_value) = real_type;
break;
case IS_STRING:
len -= sizeof (SBucketType);
zend_string *str = swoole_unserialize_string(buffer, len);
ZVAL_STR(return_value, str);
break;
case IS_ARRAY:
{
if (swoole_seria_check_eof(buffer, len) < 0)
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "detect the error eof");
return SW_FALSE;
}
unser_start = buffer - sizeof (SBucketType);
uint32_t num = 0;
buffer = get_array_real_len(buffer, type.data_len, &num);
if (!swoole_unserialize_arr(buffer, return_value, num, flag))
{
return SW_FALSE;
}
break;
}
case IS_UNDEF:
if (swoole_seria_check_eof(buffer, len) < 0)
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "detect the error eof");
return SW_FALSE;
}
unser_start = buffer - sizeof (SBucketType);
if (!swoole_unserialize_object(buffer, return_value, type.data_len, object_args, flag))
{
return SW_FALSE;
}
break;
default:
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "the type is not supported by swoole serialize.");
return SW_FALSE;
}
return SW_TRUE;
}
static PHP_METHOD(swoole_serialize, pack)
{
zval *zvalue;
zend_size_t is_fast = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", &zvalue, &is_fast) == FAILURE)
{
RETURN_FALSE;
}
swSeriaG.pack_string = !is_fast;
zend_string *z_str = php_swoole_serialize(zvalue);
RETURN_STR(z_str);
}
static PHP_METHOD(swoole_serialize, unpack)
{
char *buffer = NULL;
size_t arg_len;
zval *args = NULL; //for object
long flag = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|la", &buffer, &arg_len, &flag, &args) == FAILURE)
{
RETURN_FALSE;
}
if (!php_swoole_unserialize(buffer, arg_len, return_value, args, flag))
{
RETURN_FALSE;
}
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-502/c/bad_297_0 |
crossvul-cpp_data_good_297_0 | /*
+----------------------------------------------------------------------+
| Swoole |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| license@swoole.com so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: xinhua.guo <woshiguo35@gmail.com> |
+----------------------------------------------------------------------+
*/
#include "php_swoole.h"
#include "swoole_serialize.h"
#ifdef __SSE2__
#include <emmintrin.h>
#endif
#if PHP_MAJOR_VERSION >= 7
#define CPINLINE sw_inline
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_serialize_pack, 0, 0, 1)
ZEND_ARG_INFO(0, data)
ZEND_ARG_INFO(0, flag)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_serialize_unpack, 0, 0, 1)
ZEND_ARG_INFO(0, string)
ZEND_ARG_INFO(0, args)
ZEND_END_ARG_INFO()
static void swoole_serialize_object(seriaString *buffer, zval *zvalue, size_t start);
static void swoole_serialize_arr(seriaString *buffer, zend_array *zvalue);
static void* swoole_unserialize_arr(void *buffer, zval *zvalue, uint32_t num, long flag);
static void* swoole_unserialize_object(void *buffer, zval *return_value, zend_uchar bucket_len, zval *args, long flag);
static PHP_METHOD(swoole_serialize, pack);
static PHP_METHOD(swoole_serialize, unpack);
static const zend_function_entry swoole_serialize_methods[] = {
PHP_ME(swoole_serialize, pack, arginfo_swoole_serialize_pack, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_ME(swoole_serialize, unpack, arginfo_swoole_serialize_unpack, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC)
PHP_FE_END
};
zend_class_entry swoole_serialize_ce;
zend_class_entry *swoole_serialize_class_entry_ptr;
#define SWOOLE_SERI_EOF "EOF"
#define CHECK_STEP if(buffer>unseri_buffer_end){ php_error_docref(NULL TSRMLS_CC, E_ERROR, "illegal unserialize data"); return NULL;}
static struct _swSeriaG swSeriaG;
char *unseri_buffer_end = NULL;
void swoole_serialize_init(int module_number TSRMLS_DC)
{
SWOOLE_INIT_CLASS_ENTRY(swoole_serialize_ce, "swoole_serialize", "Swoole\\Serialize", swoole_serialize_methods);
swoole_serialize_class_entry_ptr = zend_register_internal_class(&swoole_serialize_ce TSRMLS_CC);
SWOOLE_CLASS_ALIAS(swoole_serialize, "Swoole\\Serialize");
// ZVAL_STRING(&swSeriaG.sleep_fname, "__sleep");
zend_string *zstr_sleep = zend_string_init("__sleep", sizeof ("__sleep") - 1, 1);
zend_string *zstr_weekup = zend_string_init("__weekup", sizeof ("__weekup") - 1, 1);
ZVAL_STR(&swSeriaG.sleep_fname, zstr_sleep);
ZVAL_STR(&swSeriaG.weekup_fname, zstr_weekup);
// ZVAL_STRING(&swSeriaG.weekup_fname, "__weekup");
memset(&swSeriaG.filter, 0, sizeof (swSeriaG.filter));
memset(&mini_filter, 0, sizeof (mini_filter));
REGISTER_LONG_CONSTANT("SWOOLE_FAST_PACK", SW_FAST_PACK, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("UNSERIALIZE_OBJECT_TO_ARRAY", UNSERIALIZE_OBJECT_TO_ARRAY, CONST_CS | CONST_PERSISTENT);
REGISTER_LONG_CONSTANT("UNSERIALIZE_OBJECT_TO_STDCLASS", UNSERIALIZE_OBJECT_TO_STDCLASS, CONST_CS | CONST_PERSISTENT);
}
static CPINLINE int swoole_string_new(size_t size, seriaString *str, zend_uchar type)
{
int total = ZEND_MM_ALIGNED_SIZE(_STR_HEADER_SIZE + size + 1);
str->total = total;
//escape the header for later
str->offset = _STR_HEADER_SIZE;
//zend string addr
str->buffer = ecalloc(1, total);
if (!str->buffer)
{
php_error_docref(NULL TSRMLS_CC, E_ERROR, "malloc Error: %s [%d]", strerror(errno), errno);
}
SBucketType real_type = {0};
real_type.data_type = type;
*(SBucketType*) (str->buffer + str->offset) = real_type;
str->offset += sizeof (SBucketType);
return 0;
}
static CPINLINE void swoole_check_size(seriaString *str, size_t len)
{
int new_size = len + str->offset;
// int new_size = len + str->offset + 3 + sizeof (zend_ulong); //space 1 for the type and 2 for key string len or index len and(zend_ulong) for key h
if (str->total < new_size)
{//extend it
new_size = ZEND_MM_ALIGNED_SIZE(new_size + SERIA_SIZE);
str->buffer = erealloc2(str->buffer, new_size, str->offset);
if (!str->buffer)
{
php_error_docref(NULL TSRMLS_CC, E_ERROR, "realloc Error: %s [%d]", strerror(errno), errno);
}
str->total = new_size;
}
}
#ifdef __SSE2__
void CPINLINE swoole_mini_memcpy(void *dst, const void *src, size_t len)
{
register unsigned char *dd = (unsigned char*) dst + len;
register const unsigned char *ss = (const unsigned char*) src + len;
switch (len)
{
case 68: *((int*) (dd - 68)) = *((int*) (ss - 68));
/* no break */
case 64: *((int*) (dd - 64)) = *((int*) (ss - 64));
/* no break */
case 60: *((int*) (dd - 60)) = *((int*) (ss - 60));
/* no break */
case 56: *((int*) (dd - 56)) = *((int*) (ss - 56));
/* no break */
case 52: *((int*) (dd - 52)) = *((int*) (ss - 52));
/* no break */
case 48: *((int*) (dd - 48)) = *((int*) (ss - 48));
/* no break */
case 44: *((int*) (dd - 44)) = *((int*) (ss - 44));
/* no break */
case 40: *((int*) (dd - 40)) = *((int*) (ss - 40));
/* no break */
case 36: *((int*) (dd - 36)) = *((int*) (ss - 36));
/* no break */
case 32: *((int*) (dd - 32)) = *((int*) (ss - 32));
/* no break */
case 28: *((int*) (dd - 28)) = *((int*) (ss - 28));
/* no break */
case 24: *((int*) (dd - 24)) = *((int*) (ss - 24));
/* no break */
case 20: *((int*) (dd - 20)) = *((int*) (ss - 20));
/* no break */
case 16: *((int*) (dd - 16)) = *((int*) (ss - 16));
/* no break */
case 12: *((int*) (dd - 12)) = *((int*) (ss - 12));
/* no break */
case 8: *((int*) (dd - 8)) = *((int*) (ss - 8));
/* no break */
case 4: *((int*) (dd - 4)) = *((int*) (ss - 4));
break;
case 67: *((int*) (dd - 67)) = *((int*) (ss - 67));
/* no break */
case 63: *((int*) (dd - 63)) = *((int*) (ss - 63));
/* no break */
case 59: *((int*) (dd - 59)) = *((int*) (ss - 59));
/* no break */
case 55: *((int*) (dd - 55)) = *((int*) (ss - 55));
/* no break */
case 51: *((int*) (dd - 51)) = *((int*) (ss - 51));
/* no break */
case 47: *((int*) (dd - 47)) = *((int*) (ss - 47));
/* no break */
case 43: *((int*) (dd - 43)) = *((int*) (ss - 43));
/* no break */
case 39: *((int*) (dd - 39)) = *((int*) (ss - 39));
/* no break */
case 35: *((int*) (dd - 35)) = *((int*) (ss - 35));
/* no break */
case 31: *((int*) (dd - 31)) = *((int*) (ss - 31));
/* no break */
case 27: *((int*) (dd - 27)) = *((int*) (ss - 27));
/* no break */
case 23: *((int*) (dd - 23)) = *((int*) (ss - 23));
/* no break */
case 19: *((int*) (dd - 19)) = *((int*) (ss - 19));
/* no break */
case 15: *((int*) (dd - 15)) = *((int*) (ss - 15));
/* no break */
case 11: *((int*) (dd - 11)) = *((int*) (ss - 11));
/* no break */
case 7: *((int*) (dd - 7)) = *((int*) (ss - 7));
*((int*) (dd - 4)) = *((int*) (ss - 4));
break;
case 3: *((short*) (dd - 3)) = *((short*) (ss - 3));
dd[-1] = ss[-1];
break;
case 66: *((int*) (dd - 66)) = *((int*) (ss - 66));
/* no break */
case 62: *((int*) (dd - 62)) = *((int*) (ss - 62));
/* no break */
case 58: *((int*) (dd - 58)) = *((int*) (ss - 58));
/* no break */
case 54: *((int*) (dd - 54)) = *((int*) (ss - 54));
/* no break */
case 50: *((int*) (dd - 50)) = *((int*) (ss - 50));
/* no break */
case 46: *((int*) (dd - 46)) = *((int*) (ss - 46));
/* no break */
case 42: *((int*) (dd - 42)) = *((int*) (ss - 42));
/* no break */
case 38: *((int*) (dd - 38)) = *((int*) (ss - 38));
/* no break */
case 34: *((int*) (dd - 34)) = *((int*) (ss - 34));
/* no break */
case 30: *((int*) (dd - 30)) = *((int*) (ss - 30));
/* no break */
case 26: *((int*) (dd - 26)) = *((int*) (ss - 26));
/* no break */
case 22: *((int*) (dd - 22)) = *((int*) (ss - 22));
/* no break */
case 18: *((int*) (dd - 18)) = *((int*) (ss - 18));
/* no break */
case 14: *((int*) (dd - 14)) = *((int*) (ss - 14));
/* no break */
case 10: *((int*) (dd - 10)) = *((int*) (ss - 10));
/* no break */
case 6: *((int*) (dd - 6)) = *((int*) (ss - 6));
/* no break */
case 2: *((short*) (dd - 2)) = *((short*) (ss - 2));
break;
case 65: *((int*) (dd - 65)) = *((int*) (ss - 65));
/* no break */
case 61: *((int*) (dd - 61)) = *((int*) (ss - 61));
/* no break */
case 57: *((int*) (dd - 57)) = *((int*) (ss - 57));
/* no break */
case 53: *((int*) (dd - 53)) = *((int*) (ss - 53));
/* no break */
case 49: *((int*) (dd - 49)) = *((int*) (ss - 49));
/* no break */
case 45: *((int*) (dd - 45)) = *((int*) (ss - 45));
/* no break */
case 41: *((int*) (dd - 41)) = *((int*) (ss - 41));
/* no break */
case 37: *((int*) (dd - 37)) = *((int*) (ss - 37));
/* no break */
case 33: *((int*) (dd - 33)) = *((int*) (ss - 33));
/* no break */
case 29: *((int*) (dd - 29)) = *((int*) (ss - 29));
/* no break */
case 25: *((int*) (dd - 25)) = *((int*) (ss - 25));
/* no break */
case 21: *((int*) (dd - 21)) = *((int*) (ss - 21));
/* no break */
case 17: *((int*) (dd - 17)) = *((int*) (ss - 17));
/* no break */
case 13: *((int*) (dd - 13)) = *((int*) (ss - 13));
/* no break */
case 9: *((int*) (dd - 9)) = *((int*) (ss - 9));
/* no break */
case 5: *((int*) (dd - 5)) = *((int*) (ss - 5));
/* no break */
case 1: dd[-1] = ss[-1];
break;
case 0:
default: break;
}
}
void CPINLINE swoole_memcpy_fast(void *destination, const void *source, size_t size)
{
unsigned char *dst = (unsigned char*) destination;
const unsigned char *src = (const unsigned char*) source;
// small memory copy
if (size < 64)
{
swoole_mini_memcpy(dst, src, size);
return;
}
size_t diff = (((size_t) dst + 15L) & (~15L)) - ((size_t) dst);
if (diff > 0)
{
swoole_mini_memcpy(dst, src, diff);
dst += diff;
src += diff;
size -= diff;
}
// 4个寄存器
__m128i c1, c2, c3, c4;
if ((((size_t) src) & 15L) == 0)
{
for(; size >= 64; size -= 64)
{
//load 时候将下次要用的数据提前fetch
_mm_prefetch((const char*) (src + 64), _MM_HINT_NTA);
_mm_prefetch((const char*) (dst + 64), _MM_HINT_T0);
//从内存中load到寄存器
c1 = _mm_load_si128(((const __m128i*) src) + 0);
c2 = _mm_load_si128(((const __m128i*) src) + 1);
c3 = _mm_load_si128(((const __m128i*) src) + 2);
c4 = _mm_load_si128(((const __m128i*) src) + 3);
src += 64;
//写回内存
_mm_store_si128((((__m128i*) dst) + 0), c1);
_mm_store_si128((((__m128i*) dst) + 1), c2);
_mm_store_si128((((__m128i*) dst) + 2), c3);
_mm_store_si128((((__m128i*) dst) + 3), c4);
dst += 64;
}
}
else
{
for(; size >= 64; size -= 64)
{
_mm_prefetch((const char*) (src + 64), _MM_HINT_NTA);
_mm_prefetch((const char*) (dst + 64), _MM_HINT_T0);
c1 = _mm_loadu_si128(((const __m128i*) src) + 0);
c2 = _mm_loadu_si128(((const __m128i*) src) + 1);
c3 = _mm_loadu_si128(((const __m128i*) src) + 2);
c4 = _mm_loadu_si128(((const __m128i*) src) + 3);
src += 64;
_mm_store_si128((((__m128i*) dst) + 0), c1);
_mm_store_si128((((__m128i*) dst) + 1), c2);
_mm_store_si128((((__m128i*) dst) + 2), c3);
_mm_store_si128((((__m128i*) dst) + 3), c4);
dst += 64;
}
}
// _mm_sfence();
// return memcpy_tiny(dst, src, size);
}
#endif
static CPINLINE void swoole_string_cpy(seriaString *str, void *mem, size_t len)
{
swoole_check_size(str, len + 15L);
//example:13+15=28 28& 11111111 11111111 11111111 11110000
//str->offset = ((str->offset + 15L) & ~15L);
// swoole_memcspy_fast(str->buffer + str->offset, mem, len);
memcpy(str->buffer + str->offset, mem, len);
str->offset = len + str->offset;
}
static CPINLINE void swoole_set_zend_value(seriaString *str, void *value)
{
swoole_check_size(str, sizeof (zend_value));
*(zend_value*) (str->buffer + str->offset) = *((zend_value*) value);
str->offset = sizeof (zend_value) + str->offset;
}
static CPINLINE void swoole_serialize_long(seriaString *buffer, zval *zvalue, SBucketType* type)
{
zend_long value = Z_LVAL_P(zvalue);
//01111111 - 11111111
if (value <= 0x7f && value >= -0x7f)
{
type->data_len = 0;
SERIA_SET_ENTRY_TYPE_WITH_MINUS(buffer, value);
}
else if (value <= 0x7fff && value >= -0x7fff)
{
type->data_len = 1;
SERIA_SET_ENTRY_SHORT_WITH_MINUS(buffer, value);
}
else if (value <= 0x7fffffff && value >= -0x7fffffff)
{
type->data_len = 2;
SERIA_SET_ENTRY_SIZE4_WITH_MINUS(buffer, value);
}
else
{
type->data_len = 3;
swoole_string_cpy(buffer, &zvalue->value, sizeof (zend_value));
}
}
static CPINLINE void* swoole_unserialize_long(void *buffer, zval *ret_value, SBucketType type)
{
if (type.data_len == 0)
{//1 byte
Z_LVAL_P(ret_value) = *((char*) buffer);
buffer += sizeof (char);
}
else if (type.data_len == 1)
{//2 byte
Z_LVAL_P(ret_value) = *((short*) buffer);
buffer += sizeof (short);
}
else if (type.data_len == 2)
{//4 byte
Z_LVAL_P(ret_value) = *((int32_t *) buffer);
buffer += sizeof (int32_t);
}
else
{//8 byte
ret_value->value = *((zend_value*) buffer);
buffer += sizeof (zend_value);
}
return buffer;
}
static uint32_t CPINLINE cp_zend_hash_check_size(uint32_t nSize)
{
#if defined(ZEND_WIN32)
unsigned long index;
#endif
/* Use big enough power of 2 */
/* size should be between HT_MIN_SIZE and HT_MAX_SIZE */
if (nSize < HT_MIN_SIZE)
{
nSize = HT_MIN_SIZE;
}// else if (UNEXPECTED(nSize >= 1000000))
else if (UNEXPECTED(nSize >= HT_MAX_SIZE))
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "invalid unserialize data");
return 0;
}
#if defined(ZEND_WIN32)
if (BitScanReverse(&index, nSize - 1))
{
return 0x2 << ((31 - index) ^ 0x1f);
}
else
{
/* nSize is ensured to be in the valid range, fall back to it
rather than using an undefined bis scan result. */
return nSize;
}
#elif (defined(__GNUC__) || __has_builtin(__builtin_clz)) && defined(PHP_HAVE_BUILTIN_CLZ)
return 0x2 << (__builtin_clz(nSize - 1) ^ 0x1f);
#else
nSize -= 1;
nSize |= (nSize >> 1);
nSize |= (nSize >> 2);
nSize |= (nSize >> 4);
nSize |= (nSize >> 8);
nSize |= (nSize >> 16);
return nSize + 1;
#endif
}
static CPINLINE void swoole_mini_filter_clear()
{
if (swSeriaG.pack_string)
{
memset(&mini_filter, 0, sizeof (mini_filter));
if (bigger_filter)
{
efree(bigger_filter);
bigger_filter = NULL;
}
memset(&swSeriaG.filter, 0, sizeof (struct _swMinFilter));
}
}
static CPINLINE void swoole_make_bigger_filter_size()
{
if (FILTER_SIZE <= swSeriaG.filter.mini_fillter_miss_cnt &&
swSeriaG.filter.mini_fillter_find_cnt < swSeriaG.filter.mini_fillter_miss_cnt)
// if (FILTER_SIZE <= swSeriaG.filter.mini_fillter_miss_cnt &&
// (swSeriaG.filter.mini_fillter_find_cnt / swSeriaG.filter.mini_fillter_miss_cnt) < 1)
{
swSeriaG.filter.bigger_fillter_size = swSeriaG.filter.mini_fillter_miss_cnt * 128;
bigger_filter = (swPoolstr*) ecalloc(1, sizeof (swPoolstr) * swSeriaG.filter.bigger_fillter_size);
memcpy(bigger_filter, &mini_filter, sizeof (mini_filter));
}
}
static CPINLINE void swoole_mini_filter_add(zend_string *zstr, size_t offset, zend_uchar byte)
{
if (swSeriaG.pack_string)
{
offset -= _STR_HEADER_SIZE;
//head 3bit is overhead
if (offset >= 0x1fffffff)
{
return;
}
if (bigger_filter)
{
uint32_t mod_big = zstr->h & (swSeriaG.filter.bigger_fillter_size - 1);
bigger_filter[mod_big].offset = offset << 3;
if (offset <= 0x1fff)
{
bigger_filter[mod_big].offset |= byte;
}
else
{
bigger_filter[mod_big].offset |= (byte | 4);
}
bigger_filter[mod_big].str = zstr;
}
else
{
uint16_t mod = zstr->h & (FILTER_SIZE - 1);
//repalce it is effective,cause the principle of locality
mini_filter[mod].offset = offset << 3;
if (offset <= 0x1fff)
{
mini_filter[mod].offset |= byte;
}
else
{
mini_filter[mod].offset |= (byte | 4);
}
mini_filter[mod].str = zstr;
swSeriaG.filter.mini_fillter_miss_cnt++;
swoole_make_bigger_filter_size();
}
}
}
static CPINLINE swPoolstr* swoole_mini_filter_find(zend_string *zstr)
{
if (swSeriaG.pack_string)
{
zend_ulong h = zend_string_hash_val(zstr);
swPoolstr* str = NULL;
if (bigger_filter)
{
str = &bigger_filter[h & (swSeriaG.filter.bigger_fillter_size - 1)];
}
else
{
str = &mini_filter[h & (FILTER_SIZE - 1)];
}
if (!str->str)
{
return NULL;
}
if (str->str->h == h &&
zstr->len == str->str->len &&
memcmp(zstr->val, str->str->val, zstr->len) == 0)
{
swSeriaG.filter.mini_fillter_find_cnt++;
return str;
}
else
{
return NULL;
}
}
else
{
return NULL;
}
}
/*
* arr layout
* type|key?|bucketlen|buckets
*/
static CPINLINE void seria_array_type(zend_array *ht, seriaString *buffer, size_t type_offset, size_t blen_offset)
{
buffer->offset = blen_offset;
if (ht->nNumOfElements <= 0xff)
{
((SBucketType*) (buffer->buffer + type_offset))->data_len = 1;
SERIA_SET_ENTRY_TYPE(buffer, ht->nNumOfElements)
}
else if (ht->nNumOfElements <= 0xffff)
{
((SBucketType*) (buffer->buffer + type_offset))->data_len = 2;
SERIA_SET_ENTRY_SHORT(buffer, ht->nNumOfElements);
}
else
{
((SBucketType*) (buffer->buffer + type_offset))->data_len = 0;
swoole_string_cpy(buffer, &ht->nNumOfElements, sizeof (uint32_t));
}
}
/*
* buffer is bucket len addr
*/
static CPINLINE void* get_array_real_len(void *buffer, zend_uchar data_len, uint32_t *nNumOfElements)
{
if (data_len == 1)
{
*nNumOfElements = *((zend_uchar*) buffer);
return buffer + sizeof (zend_uchar);
}
else if (data_len == 2)
{
*nNumOfElements = *((unsigned short*) buffer);
return buffer + sizeof (short);
}
else
{
*nNumOfElements = *((uint32_t*) buffer);
return buffer + sizeof (uint32_t);
}
}
static CPINLINE void * get_pack_string_len_addr(void ** buffer, size_t *strlen)
{
uint8_t overhead = (*(uint8_t*) * buffer);
uint32_t real_offset;
uint8_t len_byte;
if (overhead & 4)
{
real_offset = (*(uint32_t*) * buffer) >> 3;
len_byte = overhead & 3;
(*buffer) += 4;
}
else
{
real_offset = (*(uint16_t*) * buffer) >> 3;
len_byte = overhead & 3;
(*buffer) += 2;
}
void *str_pool_addr = unser_start + real_offset;
if (len_byte == 1)
{
*strlen = *((zend_uchar*) str_pool_addr);
str_pool_addr = str_pool_addr + sizeof (zend_uchar);
}
else if (len_byte == 2)
{
*strlen = *((unsigned short*) str_pool_addr);
str_pool_addr = str_pool_addr + sizeof (unsigned short);
}
else
{
*strlen = *((size_t*) str_pool_addr);
str_pool_addr = str_pool_addr + sizeof (size_t);
}
// size_t tmp = *strlen;
return str_pool_addr;
}
/*
* array
*/
static void* swoole_unserialize_arr(void *buffer, zval *zvalue, uint32_t nNumOfElements, long flag)
{
//Initialize zend array
zend_ulong h, nIndex, max_index = 0;
uint32_t size = cp_zend_hash_check_size(nNumOfElements);
CHECK_STEP;
if (!size)
{
return NULL;
}
if (!buffer)
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "illegal unserialize data");
return NULL;
}
ZVAL_NEW_ARR(zvalue);
//Initialize buckets
zend_array *ht = Z_ARR_P(zvalue);
ht->nTableSize = size;
ht->nNumUsed = nNumOfElements;
ht->nNumOfElements = nNumOfElements;
ht->nNextFreeElement = 0;
#ifdef HASH_FLAG_APPLY_PROTECTION
ht->u.flags = HASH_FLAG_APPLY_PROTECTION;
#endif
ht->nTableMask = -(ht->nTableSize);
ht->pDestructor = ZVAL_PTR_DTOR;
GC_SET_REFCOUNT(ht, 1);
GC_TYPE_INFO(ht) = IS_ARRAY;
// if (ht->nNumUsed)
//{
// void *arData = ecalloc(1, len);
HT_SET_DATA_ADDR(ht, emalloc(HT_SIZE(ht)));
ht->u.flags |= HASH_FLAG_INITIALIZED;
int ht_hash_size = HT_HASH_SIZE((ht)->nTableMask);
if (ht_hash_size <= 0)
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "illegal unserialize data");
return NULL;
}
HT_HASH_RESET(ht);
//}
int idx;
Bucket *p;
for(idx = 0; idx < nNumOfElements; idx++)
{
if (!buffer)
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "illegal array unserialize data");
return NULL;
}
SBucketType type = *((SBucketType*) buffer);
buffer += sizeof (SBucketType);
p = ht->arData + idx;
/* Initialize key */
if (type.key_type == KEY_TYPE_STRING)
{
size_t key_len;
if (type.key_len == 3)
{//read the same mem
void *str_pool_addr = get_pack_string_len_addr(&buffer, &key_len);
p->key = zend_string_init((char*) str_pool_addr, key_len, 0);
h = zend_inline_hash_func((char*) str_pool_addr, key_len);
p->key->h = p->h = h;
}
else
{//move step
if (type.key_len == 1)
{
key_len = *((zend_uchar*) buffer);
buffer += sizeof (zend_uchar);
}
else if (type.key_len == 2)
{
key_len = *((unsigned short*) buffer);
buffer += sizeof (unsigned short);
}
else
{
key_len = *((size_t*) buffer);
buffer += sizeof (size_t);
}
CHECK_STEP;
p->key = zend_string_init((char*) buffer, key_len, 0);
// h = zend_inline_hash_func((char*) buffer, key_len);
h = zend_inline_hash_func((char*) buffer, key_len);
buffer += key_len;
p->key->h = p->h = h;
}
}
else
{
if (type.key_len == 0)
{
//means pack
h = p->h = idx;
p->key = NULL;
max_index = p->h + 1;
// ht->u.flags |= HASH_FLAG_PACKED;
}
else
{
if (type.key_len == 1)
{
h = *((zend_uchar*) buffer);
buffer += sizeof (zend_uchar);
}
else if (type.key_len == 2)
{
h = *((unsigned short*) buffer);
buffer += sizeof (unsigned short);
}
else
{
h = *((zend_ulong*) buffer);
buffer += sizeof (zend_ulong);
}
p->h = h;
p->key = NULL;
if (h >= max_index)
{
max_index = h + 1;
}
}
}
/* Initialize hash */
nIndex = h | ht->nTableMask;
Z_NEXT(p->val) = HT_HASH(ht, nIndex);
HT_HASH(ht, nIndex) = HT_IDX_TO_HASH(idx);
/* Initialize data type */
p->val.u1.v.type = type.data_type;
Z_TYPE_FLAGS(p->val) = 0;
/* Initialize data */
if (type.data_type == IS_STRING)
{
size_t data_len;
if (type.data_len == 3)
{//read the same mem
void *str_pool_addr = get_pack_string_len_addr(&buffer, &data_len);
p->val.value.str = zend_string_init((char*) str_pool_addr, data_len, 0);
}
else
{
if (type.data_len == 1)
{
data_len = *((zend_uchar*) buffer);
buffer += sizeof (zend_uchar);
}
else if (type.data_len == 2)
{
data_len = *((unsigned short*) buffer);
buffer += sizeof (unsigned short);
}
else
{
data_len = *((size_t*) buffer);
buffer += sizeof (size_t);
}
CHECK_STEP;
p->val.value.str = zend_string_init((char*) buffer, data_len, 0);
buffer += data_len;
}
Z_TYPE_INFO(p->val) = IS_STRING_EX;
}
else if (type.data_type == IS_ARRAY)
{
uint32_t num = 0;
buffer = get_array_real_len(buffer, type.data_len, &num);
buffer = swoole_unserialize_arr(buffer, &p->val, num, flag);
}
else if (type.data_type == IS_LONG)
{
buffer = swoole_unserialize_long(buffer, &p->val, type);
}
else if (type.data_type == IS_DOUBLE)
{
p->val.value = *((zend_value*) buffer);
buffer += sizeof (zend_value);
}
else if (type.data_type == IS_UNDEF)
{
buffer = swoole_unserialize_object(buffer, &p->val, type.data_len, NULL, flag);
Z_TYPE_INFO(p->val) = IS_OBJECT_EX;
}
}
ht->nNextFreeElement = max_index;
CHECK_STEP;
return buffer;
}
/*
* arr layout
* type|key?|bucketlen|buckets
*/
static void swoole_serialize_arr(seriaString *buffer, zend_array *zvalue)
{
zval *data;
zend_string *key;
zend_ulong index;
swPoolstr *swStr = NULL;
zend_uchar is_pack = zvalue->u.flags & HASH_FLAG_PACKED;
ZEND_HASH_FOREACH_KEY_VAL(zvalue, index, key, data)
{
SBucketType type = {0};
type.data_type = Z_TYPE_P(data);
//start point
size_t p = buffer->offset;
if (is_pack && zvalue->nNextFreeElement == zvalue->nNumOfElements)
{
type.key_type = KEY_TYPE_INDEX;
type.key_len = 0;
SERIA_SET_ENTRY_TYPE(buffer, type);
}
else
{
//seria key
if (key)
{
type.key_type = KEY_TYPE_STRING;
if ((swStr = swoole_mini_filter_find(key)))
{
type.key_len = 3; //means use same string
SERIA_SET_ENTRY_TYPE(buffer, type);
if (swStr->offset & 4)
{
SERIA_SET_ENTRY_SIZE4(buffer, swStr->offset);
}
else
{
SERIA_SET_ENTRY_SHORT(buffer, swStr->offset);
}
}
else
{
if (key->len <= 0xff)
{
type.key_len = 1;
SERIA_SET_ENTRY_TYPE(buffer, type);
swoole_mini_filter_add(key, buffer->offset, 1);
SERIA_SET_ENTRY_TYPE(buffer, key->len);
swoole_string_cpy(buffer, key->val, key->len);
}
else if (key->len <= 0xffff)
{//if more than this don't need optimize
type.key_len = 2;
SERIA_SET_ENTRY_TYPE(buffer, type);
swoole_mini_filter_add(key, buffer->offset, 2);
SERIA_SET_ENTRY_SHORT(buffer, key->len);
swoole_string_cpy(buffer, key->val, key->len);
}
else
{
type.key_len = 0;
SERIA_SET_ENTRY_TYPE(buffer, type);
swoole_mini_filter_add(key, buffer->offset, 3);
swoole_string_cpy(buffer, key + XtOffsetOf(zend_string, len), sizeof (size_t) + key->len);
}
}
}
else
{
type.key_type = KEY_TYPE_INDEX;
if (index <= 0xff)
{
type.key_len = 1;
SERIA_SET_ENTRY_TYPE(buffer, type);
SERIA_SET_ENTRY_TYPE(buffer, index);
}
else if (index <= 0xffff)
{
type.key_len = 2;
SERIA_SET_ENTRY_TYPE(buffer, type);
SERIA_SET_ENTRY_SHORT(buffer, index);
}
else
{
type.key_len = 3;
SERIA_SET_ENTRY_TYPE(buffer, type);
SERIA_SET_ENTRY_ULONG(buffer, index);
}
}
}
//seria data
try_again:
switch (Z_TYPE_P(data))
{
case IS_STRING:
{
if ((swStr = swoole_mini_filter_find(Z_STR_P(data))))
{
((SBucketType*) (buffer->buffer + p))->data_len = 3; //means use same string
if (swStr->offset & 4)
{
SERIA_SET_ENTRY_SIZE4(buffer, swStr->offset);
}
else
{
SERIA_SET_ENTRY_SHORT(buffer, swStr->offset);
}
}
else
{
if (Z_STRLEN_P(data) <= 0xff)
{
((SBucketType*) (buffer->buffer + p))->data_len = 1;
swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 1);
SERIA_SET_ENTRY_TYPE(buffer, Z_STRLEN_P(data));
swoole_string_cpy(buffer, Z_STRVAL_P(data), Z_STRLEN_P(data));
}
else if (Z_STRLEN_P(data) <= 0xffff)
{
((SBucketType*) (buffer->buffer + p))->data_len = 2;
swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 2);
SERIA_SET_ENTRY_SHORT(buffer, Z_STRLEN_P(data));
swoole_string_cpy(buffer, Z_STRVAL_P(data), Z_STRLEN_P(data));
}
else
{//if more than this don't need optimize
((SBucketType*) (buffer->buffer + p))->data_len = 0;
swoole_mini_filter_add(Z_STR_P(data), buffer->offset, 3);
swoole_string_cpy(buffer, (char*) Z_STR_P(data) + XtOffsetOf(zend_string, len), sizeof (size_t) + Z_STRLEN_P(data));
}
}
break;
}
case IS_LONG:
{
SBucketType* long_type = (SBucketType*) (buffer->buffer + p);
swoole_serialize_long(buffer, data, long_type);
break;
}
case IS_DOUBLE:
swoole_set_zend_value(buffer, &(data->value));
break;
case IS_REFERENCE:
data = Z_REFVAL_P(data);
((SBucketType*) (buffer->buffer + p))->data_type = Z_TYPE_P(data);
goto try_again;
break;
case IS_ARRAY:
{
zend_array *ht = Z_ARRVAL_P(data);
if (GC_IS_RECURSIVE(ht))
{
((SBucketType*) (buffer->buffer + p))->data_type = IS_NULL; //reset type null
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "the array has cycle ref");
}
else
{
seria_array_type(ht, buffer, p, buffer->offset);
if (ZEND_HASH_APPLY_PROTECTION(ht))
{
GC_PROTECT_RECURSION(ht);
swoole_serialize_arr(buffer, ht);
GC_UNPROTECT_RECURSION(ht);
}
else
{
swoole_serialize_arr(buffer, ht);
}
}
break;
}
//object propterty table is this type
case IS_INDIRECT:
data = Z_INDIRECT_P(data);
zend_uchar type = Z_TYPE_P(data);
((SBucketType*) (buffer->buffer + p))->data_type = (type == IS_UNDEF ? IS_NULL : type);
goto try_again;
break;
case IS_OBJECT:
{
/*
* layout
* type | key | namelen | name | bucket len |buckets
*/
((SBucketType*) (buffer->buffer + p))->data_type = IS_UNDEF;
if (ZEND_HASH_APPLY_PROTECTION(Z_OBJPROP_P(data)))
{
GC_PROTECT_RECURSION(Z_OBJPROP_P(data));
swoole_serialize_object(buffer, data, p);
GC_UNPROTECT_RECURSION(Z_OBJPROP_P(data));
}
else
{
swoole_serialize_object(buffer, data, p);
}
break;
}
default://
break;
}
}
ZEND_HASH_FOREACH_END();
}
/*
* string
*/
static CPINLINE void swoole_serialize_string(seriaString *buffer, zval *zvalue)
{
swoole_string_cpy(buffer, Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue));
}
static CPINLINE zend_string* swoole_unserialize_string(void *buffer, size_t len)
{
return zend_string_init(buffer, len, 0);
}
/*
* raw
*/
static CPINLINE void swoole_unserialize_raw(void *buffer, zval *zvalue)
{
memcpy(&zvalue->value, buffer, sizeof (zend_value));
}
#if 0
/*
* null
*/
static CPINLINE void swoole_unserialize_null(void *buffer, zval *zvalue)
{
memcpy(&zvalue->value, buffer, sizeof (zend_value));
}
#endif
static CPINLINE void swoole_serialize_raw(seriaString *buffer, zval *zvalue)
{
swoole_string_cpy(buffer, &zvalue->value, sizeof (zend_value));
}
/*
* obj layout
* type|bucket key|name len| name| buket len |buckets
*/
static void swoole_serialize_object(seriaString *buffer, zval *obj, size_t start)
{
zend_string *name = Z_OBJCE_P(obj)->name;
if (GC_IS_RECURSIVE(Z_OBJPROP_P(obj)))
{
zend_throw_exception_ex(NULL, 0, "the object %s has cycle ref.", name->val);
return;
}
if (name->len > 0xffff)
{//so long?
zend_throw_exception_ex(NULL, 0, "the object name is too long.");
}
else
{
SERIA_SET_ENTRY_SHORT(buffer, name->len);
swoole_string_cpy(buffer, name->val, name->len);
}
zend_class_entry *ce = Z_OBJ_P(obj)->ce;
if (ce && zend_hash_exists(&ce->function_table, Z_STR(swSeriaG.sleep_fname)))
{
zval retval;
if (call_user_function_ex(NULL, obj, &swSeriaG.sleep_fname, &retval, 0, 0, 1, NULL) == SUCCESS)
{
if (EG(exception))
{
zval_dtor(&retval);
return;
}
if (Z_TYPE(retval) == IS_ARRAY)
{
zend_string *prop_key;
zval *prop_value, *sleep_value;
const char *prop_name, *class_name;
size_t prop_key_len;
int got_num = 0;
//for the zero malloc
zend_array tmp_arr;
zend_array *ht = (zend_array *) & tmp_arr;
#if PHP_VERSION_ID >= 70300
_zend_hash_init(ht, zend_hash_num_elements(Z_ARRVAL(retval)), ZVAL_PTR_DTOR, 0);
#else
_zend_hash_init(ht, zend_hash_num_elements(Z_ARRVAL(retval)), ZVAL_PTR_DTOR, 0 ZEND_FILE_LINE_CC);
#endif
ht->nTableMask = -(ht)->nTableSize;
ALLOCA_FLAG(use_heap);
void *ht_addr = do_alloca(HT_SIZE(ht), use_heap);
HT_SET_DATA_ADDR(ht, ht_addr);
ht->u.flags |= HASH_FLAG_INITIALIZED;
HT_HASH_RESET(ht);
//just clean property do not add null when does not exist
//we double for each, cause we do not malloc and release it
ZEND_HASH_FOREACH_STR_KEY_VAL(Z_OBJPROP_P(obj), prop_key, prop_value)
{
//get origin property name
zend_unmangle_property_name_ex(prop_key, &class_name, &prop_name, &prop_key_len);
ZEND_HASH_FOREACH_VAL(Z_ARRVAL(retval), sleep_value)
{
if (Z_TYPE_P(sleep_value) == IS_STRING &&
Z_STRLEN_P(sleep_value) == prop_key_len &&
memcmp(Z_STRVAL_P(sleep_value), prop_name, prop_key_len) == 0)
{
got_num++;
//add mangle key,unmangle in unseria
_zend_hash_add_or_update(ht, prop_key, prop_value, HASH_UPDATE ZEND_FILE_LINE_CC);
break;
}
}
ZEND_HASH_FOREACH_END();
}
ZEND_HASH_FOREACH_END();
//there some member not in property
if (zend_hash_num_elements(Z_ARRVAL(retval)) > got_num)
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep() retrun a member but does not exist in property");
}
seria_array_type(ht, buffer, start, buffer->offset);
swoole_serialize_arr(buffer, ht);
ZSTR_ALLOCA_FREE(ht_addr, use_heap);
zval_dtor(&retval);
return;
}
else
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, " __sleep should return an array only containing the "
"names of instance-variables to serialize");
zval_dtor(&retval);
}
}
}
seria_array_type(Z_OBJPROP_P(obj), buffer, start, buffer->offset);
swoole_serialize_arr(buffer, Z_OBJPROP_P(obj));
// printf("hash2 %u\n",ce->properties_info.arData[0].key->h);
}
/*
* for the zero malloc
*/
static CPINLINE zend_string * swoole_string_init(const char *str, size_t len)
{
#ifdef ZEND_DEBUG
return zend_string_init(str, len, 0);
#else
ALLOCA_FLAG(use_heap);
zend_string *ret;
ZSTR_ALLOCA_INIT(ret, str, len, use_heap);
return ret;
#endif
}
/*
* for the zero malloc
*/
static CPINLINE void swoole_string_release(zend_string *str)
{
#ifdef ZEND_DEBUG
zend_string_release(str);
#else
//if dont support alloc 0 will ignore
//if support alloc size is definitely < ZEND_ALLOCA_MAX_SIZE
ZSTR_ALLOCA_FREE(str, 0);
#endif
}
static CPINLINE zend_class_entry* swoole_try_get_ce(zend_string *class_name)
{
//user class , do not support incomplete class now
zend_class_entry *ce = zend_lookup_class(class_name);
if (ce)
{
return ce;
}
// try call unserialize callback and retry lookup
zval user_func, args[1], retval;
/* Check for unserialize callback */
if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\0'))
{
zend_throw_exception_ex(NULL, 0, "can not find class %s", class_name->val TSRMLS_CC);
return NULL;
}
zend_string *fname = swoole_string_init(ZEND_STRL(PG(unserialize_callback_func)));
Z_STR(user_func) = fname;
Z_TYPE_INFO(user_func) = IS_STRING_EX;
ZVAL_STR(&args[0], class_name);
call_user_function_ex(CG(function_table), NULL, &user_func, &retval, 1, args, 0, NULL);
swoole_string_release(fname);
//user class , do not support incomplete class now
ce = zend_lookup_class(class_name);
if (!ce)
{
zend_throw_exception_ex(NULL, 0, "can not find class %s", class_name->val TSRMLS_CC);
return NULL;
}
else
{
return ce;
}
}
/*
* obj layout
* type| key[0|1] |name len| name| buket len |buckets
*/
static void* swoole_unserialize_object(void *buffer, zval *return_value, zend_uchar bucket_len, zval *args, long flag)
{
zval property;
uint32_t arr_num = 0;
size_t name_len = *((unsigned short*) buffer);
CHECK_STEP;
if (!name_len)
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "illegal unserialize data");
return NULL;
}
buffer += 2;
zend_string *class_name;
if (flag == UNSERIALIZE_OBJECT_TO_STDCLASS)
{
class_name = swoole_string_init(ZEND_STRL("StdClass"));
}
else
{
class_name = swoole_string_init((char*) buffer, name_len);
}
buffer += name_len;
zend_class_entry *ce = swoole_try_get_ce(class_name);
swoole_string_release(class_name);
CHECK_STEP;
if (!ce)
{
return NULL;
}
buffer = get_array_real_len(buffer, bucket_len, &arr_num);
buffer = swoole_unserialize_arr(buffer, &property, arr_num, flag);
object_init_ex(return_value, ce);
zval *data, *d;
zend_string *key;
zend_ulong index;
ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL(property), index, key, data)
{
const char *prop_name, *tmp;
size_t prop_len;
if (key)
{
if ((d = zend_hash_find(Z_OBJPROP_P(return_value), key)) != NULL)
{
if (Z_TYPE_P(d) == IS_INDIRECT)
{
d = Z_INDIRECT_P(d);
}
zval_dtor(d);
ZVAL_COPY(d, data);
}
else
{
zend_unmangle_property_name_ex(key, &tmp, &prop_name, &prop_len);
zend_update_property(ce, return_value, prop_name, prop_len, data);
}
// zend_hash_update(Z_OBJPROP_P(return_value),key,data);
// zend_update_property(ce, return_value, ZSTR_VAL(key), ZSTR_LEN(key), data);
}
else
{
zend_hash_next_index_insert(Z_OBJPROP_P(return_value), data);
}
}
ZEND_HASH_FOREACH_END();
zval_dtor(&property);
if (ce->constructor)
{
// zend_fcall_info fci = {0};
// zend_fcall_info_cache fcc = {0};
// fci.size = sizeof (zend_fcall_info);
// zval retval;
// ZVAL_UNDEF(&fci.function_name);
// fci.retval = &retval;
// fci.param_count = 0;
// fci.params = NULL;
// fci.no_separation = 1;
// fci.object = Z_OBJ_P(return_value);
//
// zend_fcall_info_args_ex(&fci, ce->constructor, args);
//
// fcc.initialized = 1;
// fcc.function_handler = ce->constructor;
// // fcc.calling_scope = EG(scope);
// fcc.called_scope = Z_OBJCE_P(return_value);
// fcc.object = Z_OBJ_P(return_value);
//
// if (zend_call_function(&fci, &fcc) == FAILURE)
// {
// zend_throw_exception_ex(NULL, 0, "could not call class constructor");
// }
// zend_fcall_info_args_clear(&fci, 1);
}
//call object __wakeup
if (zend_hash_str_exists(&ce->function_table, ZEND_STRL("__wakeup")))
{
zval ret, wakeup;
zend_string *fname = swoole_string_init(ZEND_STRL("__wakeup"));
Z_STR(wakeup) = fname;
Z_TYPE_INFO(wakeup) = IS_STRING_EX;
call_user_function_ex(CG(function_table), return_value, &wakeup, &ret, 0, NULL, 1, NULL);
swoole_string_release(fname);
zval_ptr_dtor(&ret);
}
CHECK_STEP;
return buffer;
}
/*
* dispatch
*/
static CPINLINE void swoole_seria_dispatch(seriaString *buffer, zval *zvalue)
{
again:
switch (Z_TYPE_P(zvalue))
{
case IS_NULL:
case IS_TRUE:
case IS_FALSE:
break;
case IS_LONG:
{
SBucketType* type = (SBucketType*) (buffer->buffer + _STR_HEADER_SIZE);
swoole_serialize_long(buffer, zvalue, type);
break;
}
case IS_DOUBLE:
swoole_serialize_raw(buffer, zvalue);
break;
case IS_STRING:
swoole_serialize_string(buffer, zvalue);
break;
case IS_ARRAY:
{
seria_array_type(Z_ARRVAL_P(zvalue), buffer, _STR_HEADER_SIZE, _STR_HEADER_SIZE + 1);
swoole_serialize_arr(buffer, Z_ARRVAL_P(zvalue));
swoole_string_cpy(buffer, SWOOLE_SERI_EOF, 3);
swoole_mini_filter_clear();
break;
}
case IS_REFERENCE:
zvalue = Z_REFVAL_P(zvalue);
goto again;
break;
case IS_OBJECT:
{
SBucketType* type = (SBucketType*) (buffer->buffer + _STR_HEADER_SIZE);
type->data_type = IS_UNDEF;
swoole_serialize_object(buffer, zvalue, _STR_HEADER_SIZE);
swoole_string_cpy(buffer, SWOOLE_SERI_EOF, 3);
swoole_mini_filter_clear();
break;
}
default:
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "the type is not supported by swoole serialize.");
break;
}
}
PHPAPI zend_string* php_swoole_serialize(zval *zvalue)
{
seriaString str;
swoole_string_new(SERIA_SIZE, &str, Z_TYPE_P(zvalue));
swoole_seria_dispatch(&str, zvalue); //serialize into a string
zend_string *z_str = (zend_string *) str.buffer;
z_str->len = str.offset - _STR_HEADER_SIZE;
z_str->val[z_str->len] = '\0';
z_str->h = 0;
GC_SET_REFCOUNT(z_str, 1);
GC_TYPE_INFO(z_str) = IS_STRING_EX;
return z_str;
}
static CPINLINE int swoole_seria_check_eof(void *buffer, size_t len)
{
void *eof_str = buffer - sizeof (SBucketType) + len - 3;
if (memcmp(eof_str, SWOOLE_SERI_EOF, 3) == 0)
{
return 0;
}
else
{
return -1;
}
}
/*
* buffer is seria string buffer
* len is string len
* return_value is unseria bucket
* args is for the object ctor (can be NULL)
*/
PHPAPI int php_swoole_unserialize(void *buffer, size_t len, zval *return_value, zval *object_args, long flag)
{
SBucketType type = *(SBucketType*) (buffer);
zend_uchar real_type = type.data_type;
unseri_buffer_end = buffer + len;
buffer += sizeof (SBucketType);
switch (real_type)
{
case IS_NULL:
case IS_TRUE:
case IS_FALSE:
Z_TYPE_INFO_P(return_value) = real_type;
break;
case IS_LONG:
swoole_unserialize_long(buffer, return_value, type);
Z_TYPE_INFO_P(return_value) = real_type;
break;
case IS_DOUBLE:
swoole_unserialize_raw(buffer, return_value);
Z_TYPE_INFO_P(return_value) = real_type;
break;
case IS_STRING:
len -= sizeof (SBucketType);
zend_string *str = swoole_unserialize_string(buffer, len);
ZVAL_STR(return_value, str);
break;
case IS_ARRAY:
{
if (swoole_seria_check_eof(buffer, len) < 0)
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "detect the error eof");
return SW_FALSE;
}
unser_start = buffer - sizeof (SBucketType);
uint32_t num = 0;
buffer = get_array_real_len(buffer, type.data_len, &num);
if (!swoole_unserialize_arr(buffer, return_value, num, flag))
{
return SW_FALSE;
}
break;
}
case IS_UNDEF:
if (swoole_seria_check_eof(buffer, len) < 0)
{
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "detect the error eof");
return SW_FALSE;
}
unser_start = buffer - sizeof (SBucketType);
if (!swoole_unserialize_object(buffer, return_value, type.data_len, object_args, flag))
{
return SW_FALSE;
}
break;
default:
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "the type is not supported by swoole serialize.");
return SW_FALSE;
}
return SW_TRUE;
}
static PHP_METHOD(swoole_serialize, pack)
{
zval *zvalue;
zend_size_t is_fast = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|l", &zvalue, &is_fast) == FAILURE)
{
RETURN_FALSE;
}
swSeriaG.pack_string = !is_fast;
zend_string *z_str = php_swoole_serialize(zvalue);
RETURN_STR(z_str);
}
static PHP_METHOD(swoole_serialize, unpack)
{
char *buffer = NULL;
size_t arg_len;
zval *args = NULL; //for object
long flag = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|la", &buffer, &arg_len, &flag, &args) == FAILURE)
{
RETURN_FALSE;
}
if (!php_swoole_unserialize(buffer, arg_len, return_value, args, flag))
{
RETURN_FALSE;
}
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-502/c/good_297_0 |
crossvul-cpp_data_good_5254_2 | /* Generated by re2c 0.13.7.5 */
#line 1 "ext/standard/var_unserializer.re"
/*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Sascha Schumann <sascha@schumann.cx> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include "php.h"
#include "ext/standard/php_var.h"
#include "php_incomplete_class.h"
/* {{{ reference-handling for unserializer: var_* */
#define VAR_ENTRIES_MAX 1024
#define VAR_ENTRIES_DBG 0
typedef struct {
zval *data[VAR_ENTRIES_MAX];
zend_long used_slots;
void *next;
} var_entries;
typedef struct {
zval data[VAR_ENTRIES_MAX];
zend_long used_slots;
void *next;
} var_dtor_entries;
static inline void var_push(php_unserialize_data_t *var_hashx, zval *rval)
{
var_entries *var_hash = (*var_hashx)->last;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_push(%ld): %d\n", var_hash?var_hash->used_slots:-1L, Z_TYPE_P(rval));
#endif
if (!var_hash || var_hash->used_slots == VAR_ENTRIES_MAX) {
var_hash = emalloc(sizeof(var_entries));
var_hash->used_slots = 0;
var_hash->next = 0;
if (!(*var_hashx)->first) {
(*var_hashx)->first = var_hash;
} else {
((var_entries *) (*var_hashx)->last)->next = var_hash;
}
(*var_hashx)->last = var_hash;
}
var_hash->data[var_hash->used_slots++] = rval;
}
PHPAPI void var_push_dtor(php_unserialize_data_t *var_hashx, zval *rval)
{
zval *tmp_var = var_tmp_var(var_hashx);
if (!tmp_var) {
return;
}
ZVAL_COPY(tmp_var, rval);
}
PHPAPI zval *var_tmp_var(php_unserialize_data_t *var_hashx)
{
var_dtor_entries *var_hash;
if (!var_hashx || !*var_hashx) {
return NULL;
}
var_hash = (*var_hashx)->last_dtor;
if (!var_hash || var_hash->used_slots == VAR_ENTRIES_MAX) {
var_hash = emalloc(sizeof(var_dtor_entries));
var_hash->used_slots = 0;
var_hash->next = 0;
if (!(*var_hashx)->first_dtor) {
(*var_hashx)->first_dtor = var_hash;
} else {
((var_dtor_entries *) (*var_hashx)->last_dtor)->next = var_hash;
}
(*var_hashx)->last_dtor = var_hash;
}
ZVAL_UNDEF(&var_hash->data[var_hash->used_slots]);
return &var_hash->data[var_hash->used_slots++];
}
PHPAPI void var_replace(php_unserialize_data_t *var_hashx, zval *ozval, zval *nzval)
{
zend_long i;
var_entries *var_hash = (*var_hashx)->first;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_replace(%ld): %d\n", var_hash?var_hash->used_slots:-1L, Z_TYPE_P(nzval));
#endif
while (var_hash) {
for (i = 0; i < var_hash->used_slots; i++) {
if (var_hash->data[i] == ozval) {
var_hash->data[i] = nzval;
/* do not break here */
}
}
var_hash = var_hash->next;
}
}
static zval *var_access(php_unserialize_data_t *var_hashx, zend_long id)
{
var_entries *var_hash = (*var_hashx)->first;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_access(%ld): %ld\n", var_hash?var_hash->used_slots:-1L, id);
#endif
while (id >= VAR_ENTRIES_MAX && var_hash && var_hash->used_slots == VAR_ENTRIES_MAX) {
var_hash = var_hash->next;
id -= VAR_ENTRIES_MAX;
}
if (!var_hash) return NULL;
if (id < 0 || id >= var_hash->used_slots) return NULL;
return var_hash->data[id];
}
PHPAPI void var_destroy(php_unserialize_data_t *var_hashx)
{
void *next;
zend_long i;
var_entries *var_hash = (*var_hashx)->first;
var_dtor_entries *var_dtor_hash = (*var_hashx)->first_dtor;
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_destroy(%ld)\n", var_hash?var_hash->used_slots:-1L);
#endif
while (var_hash) {
next = var_hash->next;
efree_size(var_hash, sizeof(var_entries));
var_hash = next;
}
while (var_dtor_hash) {
for (i = 0; i < var_dtor_hash->used_slots; i++) {
#if VAR_ENTRIES_DBG
fprintf(stderr, "var_destroy dtor(%p, %ld)\n", var_dtor_hash->data[i], Z_REFCOUNT_P(var_dtor_hash->data[i]));
#endif
zval_ptr_dtor(&var_dtor_hash->data[i]);
}
next = var_dtor_hash->next;
efree_size(var_dtor_hash, sizeof(var_dtor_entries));
var_dtor_hash = next;
}
}
/* }}} */
static zend_string *unserialize_str(const unsigned char **p, size_t len, size_t maxlen)
{
size_t i, j;
zend_string *str = zend_string_safe_alloc(1, len, 0, 0);
unsigned char *end = *(unsigned char **)p+maxlen;
if (end < *p) {
zend_string_free(str);
return NULL;
}
for (i = 0; i < len; i++) {
if (*p >= end) {
zend_string_free(str);
return NULL;
}
if (**p != '\\') {
ZSTR_VAL(str)[i] = (char)**p;
} else {
unsigned char ch = 0;
for (j = 0; j < 2; j++) {
(*p)++;
if (**p >= '0' && **p <= '9') {
ch = (ch << 4) + (**p -'0');
} else if (**p >= 'a' && **p <= 'f') {
ch = (ch << 4) + (**p -'a'+10);
} else if (**p >= 'A' && **p <= 'F') {
ch = (ch << 4) + (**p -'A'+10);
} else {
zend_string_free(str);
return NULL;
}
}
ZSTR_VAL(str)[i] = (char)ch;
}
(*p)++;
}
ZSTR_VAL(str)[i] = 0;
ZSTR_LEN(str) = i;
return str;
}
static inline int unserialize_allowed_class(zend_string *class_name, HashTable *classes)
{
zend_string *lcname;
int res;
ALLOCA_FLAG(use_heap)
if(classes == NULL) {
return 1;
}
if(!zend_hash_num_elements(classes)) {
return 0;
}
ZSTR_ALLOCA_ALLOC(lcname, ZSTR_LEN(class_name), use_heap);
zend_str_tolower_copy(ZSTR_VAL(lcname), ZSTR_VAL(class_name), ZSTR_LEN(class_name));
res = zend_hash_exists(classes, lcname);
ZSTR_ALLOCA_FREE(lcname, use_heap);
return res;
}
#define YYFILL(n) do { } while (0)
#define YYCTYPE unsigned char
#define YYCURSOR cursor
#define YYLIMIT limit
#define YYMARKER marker
#line 246 "ext/standard/var_unserializer.re"
static inline zend_long parse_iv2(const unsigned char *p, const unsigned char **q)
{
char cursor;
zend_long result = 0;
int neg = 0;
switch (*p) {
case '-':
neg++;
/* fall-through */
case '+':
p++;
}
while (1) {
cursor = (char)*p;
if (cursor >= '0' && cursor <= '9') {
result = result * 10 + (size_t)(cursor - (unsigned char)'0');
} else {
break;
}
p++;
}
if (q) *q = p;
if (neg) return -result;
return result;
}
static inline zend_long parse_iv(const unsigned char *p)
{
return parse_iv2(p, NULL);
}
/* no need to check for length - re2c already did */
static inline size_t parse_uiv(const unsigned char *p)
{
unsigned char cursor;
size_t result = 0;
if (*p == '+') {
p++;
}
while (1) {
cursor = *p;
if (cursor >= '0' && cursor <= '9') {
result = result * 10 + (size_t)(cursor - (unsigned char)'0');
} else {
break;
}
p++;
}
return result;
}
#define UNSERIALIZE_PARAMETER zval *rval, const unsigned char **p, const unsigned char *max, php_unserialize_data_t *var_hash, HashTable *classes
#define UNSERIALIZE_PASSTHRU rval, p, max, var_hash, classes
static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER);
static zend_always_inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, zend_long elements, int objprops)
{
while (elements-- > 0) {
zval key, *data, d, *old_data;
zend_ulong idx;
ZVAL_UNDEF(&key);
if (!php_var_unserialize_internal(&key, p, max, NULL, classes)) {
zval_dtor(&key);
return 0;
}
data = NULL;
ZVAL_UNDEF(&d);
if (!objprops) {
if (Z_TYPE(key) == IS_LONG) {
idx = Z_LVAL(key);
numeric_key:
if (UNEXPECTED((old_data = zend_hash_index_find(ht, idx)) != NULL)) {
//??? update hash
var_push_dtor(var_hash, old_data);
data = zend_hash_index_update(ht, idx, &d);
} else {
data = zend_hash_index_add_new(ht, idx, &d);
}
} else if (Z_TYPE(key) == IS_STRING) {
if (UNEXPECTED(ZEND_HANDLE_NUMERIC(Z_STR(key), idx))) {
goto numeric_key;
}
if (UNEXPECTED((old_data = zend_hash_find(ht, Z_STR(key))) != NULL)) {
//??? update hash
var_push_dtor(var_hash, old_data);
data = zend_hash_update(ht, Z_STR(key), &d);
} else {
data = zend_hash_add_new(ht, Z_STR(key), &d);
}
} else {
zval_dtor(&key);
return 0;
}
} else {
if (EXPECTED(Z_TYPE(key) == IS_STRING)) {
string_key:
if ((old_data = zend_hash_find(ht, Z_STR(key))) != NULL) {
if (Z_TYPE_P(old_data) == IS_INDIRECT) {
old_data = Z_INDIRECT_P(old_data);
}
var_push_dtor(var_hash, old_data);
data = zend_hash_update_ind(ht, Z_STR(key), &d);
} else {
data = zend_hash_add_new(ht, Z_STR(key), &d);
}
} else if (Z_TYPE(key) == IS_LONG) {
/* object properties should include no integers */
convert_to_string(&key);
goto string_key;
} else {
zval_dtor(&key);
return 0;
}
}
if (!php_var_unserialize_internal(data, p, max, var_hash, classes)) {
zval_dtor(&key);
return 0;
}
if (UNEXPECTED(Z_ISUNDEF_P(data))) {
if (Z_TYPE(key) == IS_LONG) {
zend_hash_index_del(ht, Z_LVAL(key));
} else {
zend_hash_del_ind(ht, Z_STR(key));
}
} else {
var_push_dtor(var_hash, data);
}
zval_dtor(&key);
if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
(*p)--;
return 0;
}
}
return 1;
}
static inline int finish_nested_data(UNSERIALIZE_PARAMETER)
{
if (*((*p)++) == '}')
return 1;
#if SOMETHING_NEW_MIGHT_LEAD_TO_CRASH_ENABLE_IF_YOU_ARE_BRAVE
zval_ptr_dtor(rval);
#endif
return 0;
}
static inline int object_custom(UNSERIALIZE_PARAMETER, zend_class_entry *ce)
{
zend_long datalen;
datalen = parse_iv2((*p) + 2, p);
(*p) += 2;
if (datalen < 0 || (max - (*p)) <= datalen) {
zend_error(E_WARNING, "Insufficient data for unserializing - %pd required, %pd present", datalen, (zend_long)(max - (*p)));
return 0;
}
if (ce->unserialize == NULL) {
zend_error(E_WARNING, "Class %s has no unserializer", ZSTR_VAL(ce->name));
object_init_ex(rval, ce);
} else if (ce->unserialize(rval, ce, (const unsigned char*)*p, datalen, (zend_unserialize_data *)var_hash) != SUCCESS) {
return 0;
}
(*p) += datalen;
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
static inline zend_long object_common1(UNSERIALIZE_PARAMETER, zend_class_entry *ce)
{
zend_long elements;
elements = parse_iv2((*p) + 2, p);
(*p) += 2;
if (ce->serialize == NULL) {
object_init_ex(rval, ce);
} else {
/* If this class implements Serializable, it should not land here but in object_custom(). The passed string
obviously doesn't descend from the regular serializer. */
zend_error(E_WARNING, "Erroneous data format for unserializing '%s'", ZSTR_VAL(ce->name));
return 0;
}
return elements;
}
#ifdef PHP_WIN32
# pragma optimize("", off)
#endif
static inline int object_common2(UNSERIALIZE_PARAMETER, zend_long elements)
{
zval retval;
zval fname;
HashTable *ht;
zend_bool has_wakeup;
if (Z_TYPE_P(rval) != IS_OBJECT) {
return 0;
}
has_wakeup = Z_OBJCE_P(rval) != PHP_IC_ENTRY
&& zend_hash_str_exists(&Z_OBJCE_P(rval)->function_table, "__wakeup", sizeof("__wakeup")-1);
ht = Z_OBJPROP_P(rval);
zend_hash_extend(ht, zend_hash_num_elements(ht) + elements, (ht->u.flags & HASH_FLAG_PACKED));
if (!process_nested_data(UNSERIALIZE_PASSTHRU, ht, elements, 1)) {
if (has_wakeup) {
ZVAL_DEREF(rval);
GC_FLAGS(Z_OBJ_P(rval)) |= IS_OBJ_DESTRUCTOR_CALLED;
}
return 0;
}
ZVAL_DEREF(rval);
if (has_wakeup) {
ZVAL_STRINGL(&fname, "__wakeup", sizeof("__wakeup") - 1);
BG(serialize_lock)++;
if (call_user_function_ex(CG(function_table), rval, &fname, &retval, 0, 0, 1, NULL) == FAILURE || Z_ISUNDEF(retval)) {
GC_FLAGS(Z_OBJ_P(rval)) |= IS_OBJ_DESTRUCTOR_CALLED;
}
BG(serialize_lock)--;
zval_dtor(&fname);
zval_dtor(&retval);
}
if (EG(exception)) {
return 0;
}
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
#ifdef PHP_WIN32
# pragma optimize("", on)
#endif
PHPAPI int php_var_unserialize(zval *rval, const unsigned char **p, const unsigned char *max, php_unserialize_data_t *var_hash)
{
HashTable *classes = NULL;
return php_var_unserialize_ex(UNSERIALIZE_PASSTHRU);
}
PHPAPI int php_var_unserialize_ex(UNSERIALIZE_PARAMETER)
{
var_entries *orig_var_entries = (*var_hash)->last;
zend_long orig_used_slots = orig_var_entries ? orig_var_entries->used_slots : 0;
int result;
result = php_var_unserialize_internal(UNSERIALIZE_PASSTHRU);
if (!result) {
/* If the unserialization failed, mark all elements that have been added to var_hash
* as NULL. This will forbid their use by other unserialize() calls in the same
* unserialization context. */
var_entries *e = orig_var_entries;
zend_long s = orig_used_slots;
while (e) {
for (; s < e->used_slots; s++) {
e->data[s] = NULL;
}
e = e->next;
s = 0;
}
}
return result;
}
static int php_var_unserialize_internal(UNSERIALIZE_PARAMETER)
{
const unsigned char *cursor, *limit, *marker, *start;
zval *rval_ref;
limit = max;
cursor = *p;
if (YYCURSOR >= YYLIMIT) {
return 0;
}
if (var_hash && (*p)[0] != 'R') {
var_push(var_hash, rval);
}
start = cursor;
#line 554 "ext/standard/var_unserializer.c"
{
YYCTYPE yych;
static const unsigned char yybm[] = {
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, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 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, 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, 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, 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, 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, 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,
};
if ((YYLIMIT - YYCURSOR) < 7) YYFILL(7);
yych = *YYCURSOR;
switch (yych) {
case 'C':
case 'O': goto yy13;
case 'N': goto yy5;
case 'R': goto yy2;
case 'S': goto yy10;
case 'a': goto yy11;
case 'b': goto yy6;
case 'd': goto yy8;
case 'i': goto yy7;
case 'o': goto yy12;
case 'r': goto yy4;
case 's': goto yy9;
case '}': goto yy14;
default: goto yy16;
}
yy2:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy95;
yy3:
#line 884 "ext/standard/var_unserializer.re"
{ return 0; }
#line 580 "ext/standard/var_unserializer.c"
yy4:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy89;
goto yy3;
yy5:
yych = *++YYCURSOR;
if (yych == ';') goto yy87;
goto yy3;
yy6:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy83;
goto yy3;
yy7:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy77;
goto yy3;
yy8:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy53;
goto yy3;
yy9:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy46;
goto yy3;
yy10:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy39;
goto yy3;
yy11:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy32;
goto yy3;
yy12:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy25;
goto yy3;
yy13:
yych = *(YYMARKER = ++YYCURSOR);
if (yych == ':') goto yy17;
goto yy3;
yy14:
++YYCURSOR;
#line 878 "ext/standard/var_unserializer.re"
{
/* this is the case where we have less data than planned */
php_error_docref(NULL, E_NOTICE, "Unexpected end of serialized data");
return 0; /* not sure if it should be 0 or 1 here? */
}
#line 629 "ext/standard/var_unserializer.c"
yy16:
yych = *++YYCURSOR;
goto yy3;
yy17:
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
if (yych == '+') goto yy19;
yy18:
YYCURSOR = YYMARKER;
goto yy3;
yy19:
yych = *++YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
goto yy18;
yy20:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yybm[0+yych] & 128) {
goto yy20;
}
if (yych <= '/') goto yy18;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 733 "ext/standard/var_unserializer.re"
{
size_t len, len2, len3, maxlen;
zend_long elements;
char *str;
zend_string *class_name;
zend_class_entry *ce;
int incomplete_class = 0;
int custom_object = 0;
zval user_func;
zval retval;
zval args[1];
if (!var_hash) return 0;
if (*start == 'C') {
custom_object = 1;
}
len2 = len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len || len == 0) {
*p = start + 2;
return 0;
}
str = (char*)YYCURSOR;
YYCURSOR += len;
if (*(YYCURSOR) != '"') {
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR+1) != ':') {
*p = YYCURSOR+1;
return 0;
}
len3 = strspn(str, "0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377\\");
if (len3 != len)
{
*p = YYCURSOR + len3 - len;
return 0;
}
class_name = zend_string_init(str, len, 0);
do {
if(!unserialize_allowed_class(class_name, classes)) {
incomplete_class = 1;
ce = PHP_IC_ENTRY;
break;
}
/* Try to find class directly */
BG(serialize_lock)++;
ce = zend_lookup_class(class_name);
if (ce) {
BG(serialize_lock)--;
if (EG(exception)) {
zend_string_release(class_name);
return 0;
}
break;
}
BG(serialize_lock)--;
if (EG(exception)) {
zend_string_release(class_name);
return 0;
}
/* Check for unserialize callback */
if ((PG(unserialize_callback_func) == NULL) || (PG(unserialize_callback_func)[0] == '\0')) {
incomplete_class = 1;
ce = PHP_IC_ENTRY;
break;
}
/* Call unserialize callback */
ZVAL_STRING(&user_func, PG(unserialize_callback_func));
ZVAL_STR_COPY(&args[0], class_name);
BG(serialize_lock)++;
if (call_user_function_ex(CG(function_table), NULL, &user_func, &retval, 1, args, 0, NULL) != SUCCESS) {
BG(serialize_lock)--;
if (EG(exception)) {
zend_string_release(class_name);
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&args[0]);
return 0;
}
php_error_docref(NULL, E_WARNING, "defined (%s) but not found", Z_STRVAL(user_func));
incomplete_class = 1;
ce = PHP_IC_ENTRY;
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&args[0]);
break;
}
BG(serialize_lock)--;
zval_ptr_dtor(&retval);
if (EG(exception)) {
zend_string_release(class_name);
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&args[0]);
return 0;
}
/* The callback function may have defined the class */
if ((ce = zend_lookup_class(class_name)) == NULL) {
php_error_docref(NULL, E_WARNING, "Function %s() hasn't defined the class it was called for", Z_STRVAL(user_func));
incomplete_class = 1;
ce = PHP_IC_ENTRY;
}
zval_ptr_dtor(&user_func);
zval_ptr_dtor(&args[0]);
break;
} while (1);
*p = YYCURSOR;
if (custom_object) {
int ret;
ret = object_custom(UNSERIALIZE_PASSTHRU, ce);
if (ret && incomplete_class) {
php_store_class_name(rval, ZSTR_VAL(class_name), len2);
}
zend_string_release(class_name);
return ret;
}
elements = object_common1(UNSERIALIZE_PASSTHRU, ce);
if (incomplete_class) {
php_store_class_name(rval, ZSTR_VAL(class_name), len2);
}
zend_string_release(class_name);
return object_common2(UNSERIALIZE_PASSTHRU, elements);
}
#line 805 "ext/standard/var_unserializer.c"
yy25:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy26;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy27;
goto yy18;
}
yy26:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy27:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy27;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 726 "ext/standard/var_unserializer.re"
{
if (!var_hash) return 0;
return object_common2(UNSERIALIZE_PASSTHRU,
object_common1(UNSERIALIZE_PASSTHRU, ZEND_STANDARD_CLASS_DEF_PTR));
}
#line 837 "ext/standard/var_unserializer.c"
yy32:
yych = *++YYCURSOR;
if (yych == '+') goto yy33;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy34;
goto yy18;
yy33:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy34:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy34;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '{') goto yy18;
++YYCURSOR;
#line 702 "ext/standard/var_unserializer.re"
{
zend_long elements = parse_iv(start + 2);
/* use iv() not uiv() in order to check data range */
*p = YYCURSOR;
if (!var_hash) return 0;
if (elements < 0) {
return 0;
}
array_init_size(rval, elements);
if (elements) {
/* we can't convert from packed to hash during unserialization, because
reference to some zvals might be keept in var_hash (to support references) */
zend_hash_real_init(Z_ARRVAL_P(rval), 0);
}
if (!process_nested_data(UNSERIALIZE_PASSTHRU, Z_ARRVAL_P(rval), elements, 0)) {
return 0;
}
return finish_nested_data(UNSERIALIZE_PASSTHRU);
}
#line 882 "ext/standard/var_unserializer.c"
yy39:
yych = *++YYCURSOR;
if (yych == '+') goto yy40;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy41;
goto yy18;
yy40:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy41:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy41;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 668 "ext/standard/var_unserializer.re"
{
size_t len, maxlen;
zend_string *str;
len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len) {
*p = start + 2;
return 0;
}
if ((str = unserialize_str(&YYCURSOR, len, maxlen)) == NULL) {
return 0;
}
if (*(YYCURSOR) != '"') {
zend_string_free(str);
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR + 1) != ';') {
efree(str);
*p = YYCURSOR + 1;
return 0;
}
YYCURSOR += 2;
*p = YYCURSOR;
ZVAL_STR(rval, str);
return 1;
}
#line 937 "ext/standard/var_unserializer.c"
yy46:
yych = *++YYCURSOR;
if (yych == '+') goto yy47;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy48;
goto yy18;
yy47:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy48:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy48;
if (yych >= ';') goto yy18;
yych = *++YYCURSOR;
if (yych != '"') goto yy18;
++YYCURSOR;
#line 636 "ext/standard/var_unserializer.re"
{
size_t len, maxlen;
char *str;
len = parse_uiv(start + 2);
maxlen = max - YYCURSOR;
if (maxlen < len) {
*p = start + 2;
return 0;
}
str = (char*)YYCURSOR;
YYCURSOR += len;
if (*(YYCURSOR) != '"') {
*p = YYCURSOR;
return 0;
}
if (*(YYCURSOR + 1) != ';') {
*p = YYCURSOR + 1;
return 0;
}
YYCURSOR += 2;
*p = YYCURSOR;
ZVAL_STRINGL(rval, str, len);
return 1;
}
#line 990 "ext/standard/var_unserializer.c"
yy53:
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych <= ',') {
if (yych == '+') goto yy57;
goto yy18;
} else {
if (yych <= '-') goto yy55;
if (yych <= '.') goto yy60;
goto yy18;
}
} else {
if (yych <= 'I') {
if (yych <= '9') goto yy58;
if (yych <= 'H') goto yy18;
goto yy56;
} else {
if (yych != 'N') goto yy18;
}
}
yych = *++YYCURSOR;
if (yych == 'A') goto yy76;
goto yy18;
yy55:
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych == '.') goto yy60;
goto yy18;
} else {
if (yych <= '9') goto yy58;
if (yych != 'I') goto yy18;
}
yy56:
yych = *++YYCURSOR;
if (yych == 'N') goto yy72;
goto yy18;
yy57:
yych = *++YYCURSOR;
if (yych == '.') goto yy60;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy58:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ':') {
if (yych <= '.') {
if (yych <= '-') goto yy18;
goto yy70;
} else {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy58;
goto yy18;
}
} else {
if (yych <= 'E') {
if (yych <= ';') goto yy63;
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy60:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy61:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ';') {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy61;
if (yych <= ':') goto yy18;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy63:
++YYCURSOR;
#line 627 "ext/standard/var_unserializer.re"
{
#if SIZEOF_ZEND_LONG == 4
use_double:
#endif
*p = YYCURSOR;
ZVAL_DOUBLE(rval, zend_strtod((const char *)start + 2, NULL));
return 1;
}
#line 1087 "ext/standard/var_unserializer.c"
yy65:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy66;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
goto yy18;
}
yy66:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych == '+') goto yy69;
goto yy18;
} else {
if (yych <= '-') goto yy69;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
}
yy67:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
if (yych == ';') goto yy63;
goto yy18;
yy69:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy67;
goto yy18;
yy70:
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 4) YYFILL(4);
yych = *YYCURSOR;
if (yych <= ';') {
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy70;
if (yych <= ':') goto yy18;
goto yy63;
} else {
if (yych <= 'E') {
if (yych <= 'D') goto yy18;
goto yy65;
} else {
if (yych == 'e') goto yy65;
goto yy18;
}
}
yy72:
yych = *++YYCURSOR;
if (yych != 'F') goto yy18;
yy73:
yych = *++YYCURSOR;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 611 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
if (!strncmp((char*)start + 2, "NAN", 3)) {
ZVAL_DOUBLE(rval, php_get_nan());
} else if (!strncmp((char*)start + 2, "INF", 3)) {
ZVAL_DOUBLE(rval, php_get_inf());
} else if (!strncmp((char*)start + 2, "-INF", 4)) {
ZVAL_DOUBLE(rval, -php_get_inf());
} else {
ZVAL_NULL(rval);
}
return 1;
}
#line 1162 "ext/standard/var_unserializer.c"
yy76:
yych = *++YYCURSOR;
if (yych == 'N') goto yy73;
goto yy18;
yy77:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy78;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy79;
goto yy18;
}
yy78:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy79:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy79;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 585 "ext/standard/var_unserializer.re"
{
#if SIZEOF_ZEND_LONG == 4
int digits = YYCURSOR - start - 3;
if (start[2] == '-' || start[2] == '+') {
digits--;
}
/* Use double for large zend_long values that were serialized on a 64-bit system */
if (digits >= MAX_LENGTH_OF_LONG - 1) {
if (digits == MAX_LENGTH_OF_LONG - 1) {
int cmp = strncmp((char*)YYCURSOR - MAX_LENGTH_OF_LONG, long_min_digits, MAX_LENGTH_OF_LONG - 1);
if (!(cmp < 0 || (cmp == 0 && start[2] == '-'))) {
goto use_double;
}
} else {
goto use_double;
}
}
#endif
*p = YYCURSOR;
ZVAL_LONG(rval, parse_iv(start + 2));
return 1;
}
#line 1215 "ext/standard/var_unserializer.c"
yy83:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= '2') goto yy18;
yych = *++YYCURSOR;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 579 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
ZVAL_BOOL(rval, parse_iv(start + 2));
return 1;
}
#line 1229 "ext/standard/var_unserializer.c"
yy87:
++YYCURSOR;
#line 573 "ext/standard/var_unserializer.re"
{
*p = YYCURSOR;
ZVAL_NULL(rval);
return 1;
}
#line 1238 "ext/standard/var_unserializer.c"
yy89:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy90;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy91;
goto yy18;
}
yy90:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy91:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy91;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 548 "ext/standard/var_unserializer.re"
{
zend_long id;
*p = YYCURSOR;
if (!var_hash) return 0;
id = parse_iv(start + 2) - 1;
if (id == -1 || (rval_ref = var_access(var_hash, id)) == NULL) {
return 0;
}
if (rval_ref == rval) {
return 0;
}
if (Z_ISUNDEF_P(rval_ref) || (Z_ISREF_P(rval_ref) && Z_ISUNDEF_P(Z_REFVAL_P(rval_ref)))) {
ZVAL_UNDEF(rval);
return 1;
}
ZVAL_COPY(rval, rval_ref);
return 1;
}
#line 1286 "ext/standard/var_unserializer.c"
yy95:
yych = *++YYCURSOR;
if (yych <= ',') {
if (yych != '+') goto yy18;
} else {
if (yych <= '-') goto yy96;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy97;
goto yy18;
}
yy96:
yych = *++YYCURSOR;
if (yych <= '/') goto yy18;
if (yych >= ':') goto yy18;
yy97:
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
if (yych <= '/') goto yy18;
if (yych <= '9') goto yy97;
if (yych != ';') goto yy18;
++YYCURSOR;
#line 522 "ext/standard/var_unserializer.re"
{
zend_long id;
*p = YYCURSOR;
if (!var_hash) return 0;
id = parse_iv(start + 2) - 1;
if (id == -1 || (rval_ref = var_access(var_hash, id)) == NULL) {
return 0;
}
zval_ptr_dtor(rval);
if (Z_ISUNDEF_P(rval_ref) || (Z_ISREF_P(rval_ref) && Z_ISUNDEF_P(Z_REFVAL_P(rval_ref)))) {
ZVAL_UNDEF(rval);
return 1;
}
if (Z_ISREF_P(rval_ref)) {
ZVAL_COPY(rval, rval_ref);
} else {
ZVAL_NEW_REF(rval_ref, rval_ref);
ZVAL_COPY(rval, rval_ref);
}
return 1;
}
#line 1335 "ext/standard/var_unserializer.c"
}
#line 886 "ext/standard/var_unserializer.re"
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-502/c/good_5254_2 |
crossvul-cpp_data_good_1384_1 | /*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/portability/GTest.h>
#include <wangle/codec/FixedLengthFrameDecoder.h>
#include <wangle/codec/LengthFieldBasedFrameDecoder.h>
#include <wangle/codec/LengthFieldPrepender.h>
#include <wangle/codec/LineBasedFrameDecoder.h>
#include <wangle/codec/test/CodecTestUtils.h>
using namespace folly;
using namespace wangle;
using namespace folly::io;
namespace {
auto createZeroedBuffer(size_t size) {
auto ret = IOBuf::create(size);
ret->append(size);
std::memset(ret->writableData(), 0x00, size);
return ret;
}
}
TEST(FixedLengthFrameDecoder, FailWhenLengthFieldEndOffset) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(FixedLengthFrameDecoder(10))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
auto sz = buf->computeChainDataLength();
called++;
EXPECT_EQ(sz, 10);
}))
.finalize();
auto buf3 = createZeroedBuffer(3);
auto buf11 = createZeroedBuffer(11);
auto buf16 = createZeroedBuffer(16);
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(buf3));
pipeline->read(q);
EXPECT_EQ(called, 0);
q.append(std::move(buf11));
pipeline->read(q);
EXPECT_EQ(called, 1);
q.append(std::move(buf16));
pipeline->read(q);
EXPECT_EQ(called, 3);
}
TEST(LengthFieldFramePipeline, SimpleTest) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(test::BytesReflector())
.addBack(LengthFieldPrepender())
.addBack(LengthFieldBasedFrameDecoder())
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
auto sz = buf->computeChainDataLength();
called++;
EXPECT_EQ(sz, 2);
}))
.finalize();
auto buf = createZeroedBuffer(2);
pipeline->write(std::move(buf));
EXPECT_EQ(called, 1);
}
TEST(LengthFieldFramePipeline, LittleEndian) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(test::BytesReflector())
.addBack(LengthFieldBasedFrameDecoder(4, 100, 0, 0, 4, false))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
auto sz = buf->computeChainDataLength();
called++;
EXPECT_EQ(sz, 1);
}))
.addBack(LengthFieldPrepender(4, 0, false, false))
.finalize();
auto buf = createZeroedBuffer(1);
pipeline->write(std::move(buf));
EXPECT_EQ(called, 1);
}
TEST(LengthFieldFrameDecoder, Simple) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LengthFieldBasedFrameDecoder())
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
auto sz = buf->computeChainDataLength();
called++;
EXPECT_EQ(sz, 1);
}))
.finalize();
auto bufFrame = createZeroedBuffer(4);
RWPrivateCursor c(bufFrame.get());
c.writeBE((uint32_t)1);
auto bufData = createZeroedBuffer(1);
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(bufFrame));
pipeline->read(q);
EXPECT_EQ(called, 0);
q.append(std::move(bufData));
pipeline->read(q);
EXPECT_EQ(called, 1);
}
TEST(LengthFieldFrameDecoder, NoStrip) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LengthFieldBasedFrameDecoder(2, 10, 0, 0, 0))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
auto sz = buf->computeChainDataLength();
called++;
EXPECT_EQ(sz, 3);
}))
.finalize();
auto bufFrame = createZeroedBuffer(2);
RWPrivateCursor c(bufFrame.get());
c.writeBE((uint16_t)1);
auto bufData = createZeroedBuffer(1);
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(bufFrame));
pipeline->read(q);
EXPECT_EQ(called, 0);
q.append(std::move(bufData));
pipeline->read(q);
EXPECT_EQ(called, 1);
}
TEST(LengthFieldFrameDecoder, Adjustment) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LengthFieldBasedFrameDecoder(2, 10, 0, -2, 0))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
auto sz = buf->computeChainDataLength();
called++;
EXPECT_EQ(sz, 3);
}))
.finalize();
auto bufFrame = createZeroedBuffer(2);
RWPrivateCursor c(bufFrame.get());
c.writeBE((uint16_t)3); // includes frame size
auto bufData = createZeroedBuffer(1);
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(bufFrame));
pipeline->read(q);
EXPECT_EQ(called, 0);
q.append(std::move(bufData));
pipeline->read(q);
EXPECT_EQ(called, 1);
}
TEST(LengthFieldFrameDecoder, PreHeader) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LengthFieldBasedFrameDecoder(2, 10, 2, 0, 0))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
auto sz = buf->computeChainDataLength();
called++;
EXPECT_EQ(sz, 5);
}))
.finalize();
auto bufFrame = createZeroedBuffer(4);
RWPrivateCursor c(bufFrame.get());
c.write((uint16_t)100); // header
c.writeBE((uint16_t)1); // frame size
auto bufData = createZeroedBuffer(1);
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(bufFrame));
pipeline->read(q);
EXPECT_EQ(called, 0);
q.append(std::move(bufData));
pipeline->read(q);
EXPECT_EQ(called, 1);
}
TEST(LengthFieldFrameDecoder, PostHeader) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LengthFieldBasedFrameDecoder(2, 10, 0, 2, 0))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
auto sz = buf->computeChainDataLength();
called++;
EXPECT_EQ(sz, 5);
}))
.finalize();
auto bufFrame = createZeroedBuffer(4);
RWPrivateCursor c(bufFrame.get());
c.writeBE((uint16_t)1); // frame size
c.write((uint16_t)100); // header
auto bufData = createZeroedBuffer(1);
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(bufFrame));
pipeline->read(q);
EXPECT_EQ(called, 0);
q.append(std::move(bufData));
pipeline->read(q);
EXPECT_EQ(called, 1);
}
TEST(LengthFieldFrameDecoderStrip, PrePostHeader) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LengthFieldBasedFrameDecoder(2, 10, 2, 2, 4))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
auto sz = buf->computeChainDataLength();
called++;
EXPECT_EQ(sz, 3);
}))
.finalize();
auto bufFrame = createZeroedBuffer(6);
RWPrivateCursor c(bufFrame.get());
c.write((uint16_t)100); // pre header
c.writeBE((uint16_t)1); // frame size
c.write((uint16_t)100); // post header
auto bufData = createZeroedBuffer(1);
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(bufFrame));
pipeline->read(q);
EXPECT_EQ(called, 0);
q.append(std::move(bufData));
pipeline->read(q);
EXPECT_EQ(called, 1);
}
TEST(LengthFieldFrameDecoder, StripPrePostHeaderFrameInclHeader) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LengthFieldBasedFrameDecoder(2, 10, 2, -2, 4))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
auto sz = buf->computeChainDataLength();
called++;
EXPECT_EQ(sz, 3);
}))
.finalize();
auto bufFrame = createZeroedBuffer(6);
RWPrivateCursor c(bufFrame.get());
c.write((uint16_t)100); // pre header
c.writeBE((uint16_t)5); // frame size
c.write((uint16_t)100); // post header
auto bufData = createZeroedBuffer(1);
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(bufFrame));
pipeline->read(q);
EXPECT_EQ(called, 0);
q.append(std::move(bufData));
pipeline->read(q);
EXPECT_EQ(called, 1);
}
TEST(LengthFieldFrameDecoder, FailTestLengthFieldEndOffset) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LengthFieldBasedFrameDecoder(4, 10, 4, -2, 4))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
ASSERT_EQ(nullptr, buf);
called++;
}))
.finalize();
auto bufFrame = createZeroedBuffer(8);
RWPrivateCursor c(bufFrame.get());
c.writeBE((uint32_t)0); // frame size
c.write((uint32_t)0); // crap
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(bufFrame));
pipeline->read(q);
EXPECT_EQ(called, 1);
}
TEST(LengthFieldFrameDecoder, FailTestLengthFieldFrameSize) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LengthFieldBasedFrameDecoder(4, 10, 0, 0, 4))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
ASSERT_EQ(nullptr, buf);
called++;
}))
.finalize();
auto bufFrame = createZeroedBuffer(16);
RWPrivateCursor c(bufFrame.get());
c.writeBE((uint32_t)12); // frame size
c.write((uint32_t)0); // nothing
c.write((uint32_t)0); // nothing
c.write((uint32_t)0); // nothing
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(bufFrame));
pipeline->read(q);
EXPECT_EQ(called, 1);
}
TEST(LengthFieldFrameDecoder, FailTestLengthFieldInitialBytes) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LengthFieldBasedFrameDecoder(4, 10, 0, 0, 10))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
ASSERT_EQ(nullptr, buf);
called++;
}))
.finalize();
auto bufFrame = createZeroedBuffer(16);
RWPrivateCursor c(bufFrame.get());
c.writeBE((uint32_t)4); // frame size
c.write((uint32_t)0); // nothing
c.write((uint32_t)0); // nothing
c.write((uint32_t)0); // nothing
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(bufFrame));
pipeline->read(q);
EXPECT_EQ(called, 1);
}
TEST(LengthFieldFrameDecoder, FailTestNotEnoughBytes) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LengthFieldBasedFrameDecoder(4, 10, 0, 0, 0))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
ASSERT_EQ(nullptr, buf);
called++;
}))
.finalize();
auto bufFrame = createZeroedBuffer(16);
RWPrivateCursor c(bufFrame.get());
c.writeBE((uint32_t)7); // frame size - 1 byte too large (7 > 10 - 4)
c.write((uint32_t)0); // nothing
c.write((uint32_t)0); // nothing
c.write((uint32_t)0); // nothing
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(bufFrame));
pipeline->read(q);
EXPECT_EQ(called, 1);
}
TEST(LineBasedFrameDecoder, Simple) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LineBasedFrameDecoder(10))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
auto sz = buf->computeChainDataLength();
called++;
EXPECT_EQ(sz, 3);
}))
.finalize();
auto buf = createZeroedBuffer(3);
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(buf));
pipeline->read(q);
EXPECT_EQ(called, 0);
buf = createZeroedBuffer(1);
RWPrivateCursor c(buf.get());
c.write<char>('\n');
q.append(std::move(buf));
pipeline->read(q);
EXPECT_EQ(called, 1);
buf = createZeroedBuffer(4);
RWPrivateCursor c1(buf.get());
c1.write(' ');
c1.write(' ');
c1.write(' ');
c1.write('\r');
q.append(std::move(buf));
pipeline->read(q);
EXPECT_EQ(called, 1);
buf = createZeroedBuffer(1);
RWPrivateCursor c2(buf.get());
c2.write('\n');
q.append(std::move(buf));
pipeline->read(q);
EXPECT_EQ(called, 2);
}
TEST(LineBasedFrameDecoder, SaveDelimiter) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LineBasedFrameDecoder(10, false))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
auto sz = buf->computeChainDataLength();
called++;
EXPECT_EQ(sz, 4);
}))
.finalize();
auto buf = createZeroedBuffer(3);
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(buf));
pipeline->read(q);
EXPECT_EQ(called, 0);
buf = createZeroedBuffer(1);
RWPrivateCursor c(buf.get());
c.write<char>('\n');
q.append(std::move(buf));
pipeline->read(q);
EXPECT_EQ(called, 1);
buf = createZeroedBuffer(3);
RWPrivateCursor c1(buf.get());
c1.write(' ');
c1.write(' ');
c1.write('\r');
q.append(std::move(buf));
pipeline->read(q);
EXPECT_EQ(called, 1);
buf = createZeroedBuffer(1);
RWPrivateCursor c2(buf.get());
c2.write('\n');
q.append(std::move(buf));
pipeline->read(q);
EXPECT_EQ(called, 2);
}
TEST(LineBasedFrameDecoder, Fail) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LineBasedFrameDecoder(10))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
ASSERT_EQ(nullptr, buf);
called++;
}))
.finalize();
auto buf = createZeroedBuffer(11);
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(buf));
pipeline->read(q);
EXPECT_EQ(called, 1);
buf = createZeroedBuffer(1);
q.append(std::move(buf));
pipeline->read(q);
EXPECT_EQ(called, 1);
buf = createZeroedBuffer(2);
RWPrivateCursor c(buf.get());
c.write(' ');
c.write<char>('\n');
q.append(std::move(buf));
pipeline->read(q);
EXPECT_EQ(called, 1);
buf = createZeroedBuffer(12);
RWPrivateCursor c2(buf.get());
for (int i = 0; i < 11; i++) {
c2.write(' ');
}
c2.write<char>('\n');
q.append(std::move(buf));
pipeline->read(q);
EXPECT_EQ(called, 2);
}
TEST(LineBasedFrameDecoder, NewLineOnly) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LineBasedFrameDecoder(
10, true, LineBasedFrameDecoder::TerminatorType::NEWLINE))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
auto sz = buf->computeChainDataLength();
called++;
EXPECT_EQ(sz, 1);
}))
.finalize();
auto buf = createZeroedBuffer(2);
RWPrivateCursor c(buf.get());
c.write<char>('\r');
c.write<char>('\n');
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(buf));
pipeline->read(q);
EXPECT_EQ(called, 1);
}
TEST(LineBasedFrameDecoder, CarriageNewLineOnly) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LineBasedFrameDecoder(
10, true, LineBasedFrameDecoder::TerminatorType::CARRIAGENEWLINE))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
auto sz = buf->computeChainDataLength();
called++;
EXPECT_EQ(sz, 1);
}))
.finalize();
auto buf = createZeroedBuffer(3);
RWPrivateCursor c(buf.get());
c.write<char>('\n');
c.write<char>('\r');
c.write<char>('\n');
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(std::move(buf));
pipeline->read(q);
EXPECT_EQ(called, 1);
}
TEST(LineBasedFrameDecoder, CarriageOnly) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
(*pipeline)
.addBack(LineBasedFrameDecoder(
10, true, LineBasedFrameDecoder::TerminatorType::CARRIAGENEWLINE))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf>) { FAIL(); }))
.finalize();
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(IOBuf::copyBuffer("\raa"));
pipeline->read(q);
}
TEST(LineBasedFrameDecoder, DoubleCarriage) {
auto pipeline = Pipeline<IOBufQueue&, std::unique_ptr<IOBuf>>::create();
int called = 0;
(*pipeline)
.addBack(LineBasedFrameDecoder(
10, true, LineBasedFrameDecoder::TerminatorType::CARRIAGENEWLINE))
.addBack(test::FrameTester([&](std::unique_ptr<IOBuf> buf) {
auto sz = buf->computeChainDataLength();
called++;
EXPECT_EQ(sz, 1);
}))
.finalize();
IOBufQueue q(IOBufQueue::cacheChainLength());
q.append(IOBuf::copyBuffer("\r\r\na\r\n"));
pipeline->read(q);
EXPECT_EQ(called, 2);
}
| ./CrossVul/dataset_final_sorted/CWE-119/cpp/good_1384_1 |
crossvul-cpp_data_bad_578_2 | /*
Copyright 2008-2017 LibRaw LLC (info@libraw.org)
LibRaw is free software; you can redistribute it and/or modify
it under the terms of the one of two licenses as you choose:
1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1
(See file LICENSE.LGPL provided in LibRaw distribution archive for details).
2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
(See file LICENSE.CDDL provided in LibRaw distribution archive for details).
This file is generated from Dave Coffin's dcraw.c
dcraw.c -- Dave Coffin's raw photo decoder
Copyright 1997-2010 by Dave Coffin, dcoffin a cybercom o net
Look into dcraw homepage (probably http://cybercom.net/~dcoffin/dcraw/)
for more information
*/
#include <math.h>
#define CLASS LibRaw::
#include "libraw/libraw_types.h"
#define LIBRAW_LIBRARY_BUILD
#define LIBRAW_IO_REDEFINED
#include "libraw/libraw.h"
#include "internal/defines.h"
#include "internal/var_defines.h"
int CLASS fcol(int row, int col)
{
static const char filter[16][16] = {
{2, 1, 1, 3, 2, 3, 2, 0, 3, 2, 3, 0, 1, 2, 1, 0}, {0, 3, 0, 2, 0, 1, 3, 1, 0, 1, 1, 2, 0, 3, 3, 2},
{2, 3, 3, 2, 3, 1, 1, 3, 3, 1, 2, 1, 2, 0, 0, 3}, {0, 1, 0, 1, 0, 2, 0, 2, 2, 0, 3, 0, 1, 3, 2, 1},
{3, 1, 1, 2, 0, 1, 0, 2, 1, 3, 1, 3, 0, 1, 3, 0}, {2, 0, 0, 3, 3, 2, 3, 1, 2, 0, 2, 0, 3, 2, 2, 1},
{2, 3, 3, 1, 2, 1, 2, 1, 2, 1, 1, 2, 3, 0, 0, 1}, {1, 0, 0, 2, 3, 0, 0, 3, 0, 3, 0, 3, 2, 1, 2, 3},
{2, 3, 3, 1, 1, 2, 1, 0, 3, 2, 3, 0, 2, 3, 1, 3}, {1, 0, 2, 0, 3, 0, 3, 2, 0, 1, 1, 2, 0, 1, 0, 2},
{0, 1, 1, 3, 3, 2, 2, 1, 1, 3, 3, 0, 2, 1, 3, 2}, {2, 3, 2, 0, 0, 1, 3, 0, 2, 0, 1, 2, 3, 0, 1, 0},
{1, 3, 1, 2, 3, 2, 3, 2, 0, 2, 0, 1, 1, 0, 3, 0}, {0, 2, 0, 3, 1, 0, 0, 1, 1, 3, 3, 2, 3, 2, 2, 1},
{2, 1, 3, 2, 3, 1, 2, 1, 0, 3, 0, 2, 0, 2, 0, 2}, {0, 3, 1, 0, 0, 2, 0, 3, 2, 1, 3, 1, 1, 3, 1, 3}};
if (filters == 1)
return filter[(row + top_margin) & 15][(col + left_margin) & 15];
if (filters == 9)
return xtrans[(row + 6) % 6][(col + 6) % 6];
return FC(row, col);
}
#if !defined(__FreeBSD__)
static size_t local_strnlen(const char *s, size_t n)
{
const char *p = (const char *)memchr(s, 0, n);
return (p ? p - s : n);
}
/* add OS X version check here ?? */
#define strnlen(a, b) local_strnlen(a, b)
#endif
#ifdef LIBRAW_LIBRARY_BUILD
static int Fuji_wb_list1[] = {LIBRAW_WBI_FineWeather, LIBRAW_WBI_Shade, LIBRAW_WBI_FL_D,
LIBRAW_WBI_FL_L, LIBRAW_WBI_FL_W, LIBRAW_WBI_Tungsten};
static int nFuji_wb_list1 = sizeof(Fuji_wb_list1) / sizeof(int);
static int FujiCCT_K[31] = {2500, 2550, 2650, 2700, 2800, 2850, 2950, 3000, 3100, 3200, 3300,
3400, 3600, 3700, 3800, 4000, 4200, 4300, 4500, 4800, 5000, 5300,
5600, 5900, 6300, 6700, 7100, 7700, 8300, 9100, 10000};
static int Fuji_wb_list2[] = {LIBRAW_WBI_Auto, 0, LIBRAW_WBI_Custom, 6, LIBRAW_WBI_FineWeather, 1,
LIBRAW_WBI_Shade, 8, LIBRAW_WBI_FL_D, 10, LIBRAW_WBI_FL_L, 11,
LIBRAW_WBI_FL_W, 12, LIBRAW_WBI_Tungsten, 2, LIBRAW_WBI_Underwater, 35,
LIBRAW_WBI_Ill_A, 82, LIBRAW_WBI_D65, 83};
static int nFuji_wb_list2 = sizeof(Fuji_wb_list2) / sizeof(int);
static int Oly_wb_list1[] = {LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_FineWeather,
LIBRAW_WBI_Tungsten, LIBRAW_WBI_Sunset, LIBRAW_WBI_FL_D,
LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_FL_WW};
static int Oly_wb_list2[] = {LIBRAW_WBI_Auto,
0,
LIBRAW_WBI_Tungsten,
3000,
0x100,
3300,
0x100,
3600,
0x100,
3900,
LIBRAW_WBI_FL_W,
4000,
0x100,
4300,
LIBRAW_WBI_FL_D,
4500,
0x100,
4800,
LIBRAW_WBI_FineWeather,
5300,
LIBRAW_WBI_Cloudy,
6000,
LIBRAW_WBI_FL_N,
6600,
LIBRAW_WBI_Shade,
7500,
LIBRAW_WBI_Custom1,
0,
LIBRAW_WBI_Custom2,
0,
LIBRAW_WBI_Custom3,
0,
LIBRAW_WBI_Custom4,
0};
static int Pentax_wb_list1[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_Tungsten,
LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash};
static int Pentax_wb_list2[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy,
LIBRAW_WBI_Tungsten, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N,
LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash, LIBRAW_WBI_FL_L};
static int nPentax_wb_list2 = sizeof(Pentax_wb_list2) / sizeof(int);
static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp)
{
int r = fp->read(buf, len, 1);
buf[len - 1] = 0;
return r;
}
#define stmread(buf, maxlen, fp) stread(buf, MIN(maxlen, sizeof(buf)), fp)
#endif
#if !defined(__GLIBC__) && !defined(__FreeBSD__)
char *my_memmem(char *haystack, size_t haystacklen, char *needle, size_t needlelen)
{
char *c;
for (c = haystack; c <= haystack + haystacklen - needlelen; c++)
if (!memcmp(c, needle, needlelen))
return c;
return 0;
}
#define memmem my_memmem
char *my_strcasestr(char *haystack, const char *needle)
{
char *c;
for (c = haystack; *c; c++)
if (!strncasecmp(c, needle, strlen(needle)))
return c;
return 0;
}
#define strcasestr my_strcasestr
#endif
#define strbuflen(buf) strnlen(buf, sizeof(buf) - 1)
ushort CLASS sget2(uchar *s)
{
if (order == 0x4949) /* "II" means little-endian */
return s[0] | s[1] << 8;
else /* "MM" means big-endian */
return s[0] << 8 | s[1];
}
// DNG was written by:
#define nonDNG 0
#define CameraDNG 1
#define AdobeDNG 2
#ifdef LIBRAW_LIBRARY_BUILD
static int getwords(char *line, char *words[], int maxwords, int maxlen)
{
line[maxlen - 1] = 0;
char *p = line;
int nwords = 0;
while (1)
{
while (isspace(*p))
p++;
if (*p == '\0')
return nwords;
words[nwords++] = p;
while (!isspace(*p) && *p != '\0')
p++;
if (*p == '\0')
return nwords;
*p++ = '\0';
if (nwords >= maxwords)
return nwords;
}
}
static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f)
{
if ((a >> 4) > 9)
return 0;
else if ((a & 0x0f) > 9)
return 0;
else if ((b >> 4) > 9)
return 0;
else if ((b & 0x0f) > 9)
return 0;
else if ((c >> 4) > 9)
return 0;
else if ((c & 0x0f) > 9)
return 0;
else if ((d >> 4) > 9)
return 0;
else if ((d & 0x0f) > 9)
return 0;
else if ((e >> 4) > 9)
return 0;
else if ((e & 0x0f) > 9)
return 0;
else if ((f >> 4) > 9)
return 0;
else if ((f & 0x0f) > 9)
return 0;
return 1;
}
static ushort bcd2dec(uchar data)
{
if ((data >> 4) > 9)
return 0;
else if ((data & 0x0f) > 9)
return 0;
else
return (data >> 4) * 10 + (data & 0x0f);
}
static uchar SonySubstitution[257] =
"\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03"
"\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5"
"\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53"
"\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea"
"\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3"
"\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7"
"\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63"
"\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd"
"\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb"
"\xfc\xfd\xfe\xff";
ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse
{
if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */
return s[0] | s[1] << 8;
else /* "MM" means big-endian... */
return s[0] << 8 | s[1];
}
#endif
ushort CLASS get2()
{
uchar str[2] = {0xff, 0xff};
fread(str, 1, 2, ifp);
return sget2(str);
}
unsigned CLASS sget4(uchar *s)
{
if (order == 0x4949)
return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24;
else
return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3];
}
#define sget4(s) sget4((uchar *)s)
unsigned CLASS get4()
{
uchar str[4] = {0xff, 0xff, 0xff, 0xff};
fread(str, 1, 4, ifp);
return sget4(str);
}
unsigned CLASS getint(int type) { return type == 3 ? get2() : get4(); }
float CLASS int_to_float(int i)
{
union {
int i;
float f;
} u;
u.i = i;
return u.f;
}
double CLASS getreal(int type)
{
union {
char c[8];
double d;
} u, v;
int i, rev;
switch (type)
{
case 3:
return (unsigned short)get2();
case 4:
return (unsigned int)get4();
case 5:
u.d = (unsigned int)get4();
v.d = (unsigned int)get4();
return u.d / (v.d ? v.d : 1);
case 8:
return (signed short)get2();
case 9:
return (signed int)get4();
case 10:
u.d = (signed int)get4();
v.d = (signed int)get4();
return u.d / (v.d ? v.d : 1);
case 11:
return int_to_float(get4());
case 12:
rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234));
for (i = 0; i < 8; i++)
u.c[i ^ rev] = fgetc(ifp);
return u.d;
default:
return fgetc(ifp);
}
}
void CLASS read_shorts(ushort *pixel, int count)
{
if (fread(pixel, 2, count, ifp) < count)
derror();
if ((order == 0x4949) == (ntohs(0x1234) == 0x1234))
swab((char *)pixel, (char *)pixel, count * 2);
}
void CLASS cubic_spline(const int *x_, const int *y_, const int len)
{
float **A, *b, *c, *d, *x, *y;
int i, j;
A = (float **)calloc(((2 * len + 4) * sizeof **A + sizeof *A), 2 * len);
if (!A)
return;
A[0] = (float *)(A + 2 * len);
for (i = 1; i < 2 * len; i++)
A[i] = A[0] + 2 * len * i;
y = len + (x = i + (d = i + (c = i + (b = A[0] + i * i))));
for (i = 0; i < len; i++)
{
x[i] = x_[i] / 65535.0;
y[i] = y_[i] / 65535.0;
}
for (i = len - 1; i > 0; i--)
{
b[i] = (y[i] - y[i - 1]) / (x[i] - x[i - 1]);
d[i - 1] = x[i] - x[i - 1];
}
for (i = 1; i < len - 1; i++)
{
A[i][i] = 2 * (d[i - 1] + d[i]);
if (i > 1)
{
A[i][i - 1] = d[i - 1];
A[i - 1][i] = d[i - 1];
}
A[i][len - 1] = 6 * (b[i + 1] - b[i]);
}
for (i = 1; i < len - 2; i++)
{
float v = A[i + 1][i] / A[i][i];
for (j = 1; j <= len - 1; j++)
A[i + 1][j] -= v * A[i][j];
}
for (i = len - 2; i > 0; i--)
{
float acc = 0;
for (j = i; j <= len - 2; j++)
acc += A[i][j] * c[j];
c[i] = (A[i][len - 1] - acc) / A[i][i];
}
for (i = 0; i < 0x10000; i++)
{
float x_out = (float)(i / 65535.0);
float y_out = 0;
for (j = 0; j < len - 1; j++)
{
if (x[j] <= x_out && x_out <= x[j + 1])
{
float v = x_out - x[j];
y_out = y[j] + ((y[j + 1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j + 1] * d[j]) / 6) * v + (c[j] * 0.5) * v * v +
((c[j + 1] - c[j]) / (6 * d[j])) * v * v * v;
}
}
curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5));
}
free(A);
}
void CLASS canon_600_fixed_wb(int temp)
{
static const short mul[4][5] = {
{667, 358, 397, 565, 452}, {731, 390, 367, 499, 517}, {1119, 396, 348, 448, 537}, {1399, 485, 431, 508, 688}};
int lo, hi, i;
float frac = 0;
for (lo = 4; --lo;)
if (*mul[lo] <= temp)
break;
for (hi = 0; hi < 3; hi++)
if (*mul[hi] >= temp)
break;
if (lo != hi)
frac = (float)(temp - *mul[lo]) / (*mul[hi] - *mul[lo]);
for (i = 1; i < 5; i++)
pre_mul[i - 1] = 1 / (frac * mul[hi][i] + (1 - frac) * mul[lo][i]);
}
/* Return values: 0 = white 1 = near white 2 = not white */
int CLASS canon_600_color(int ratio[2], int mar)
{
int clipped = 0, target, miss;
if (flash_used)
{
if (ratio[1] < -104)
{
ratio[1] = -104;
clipped = 1;
}
if (ratio[1] > 12)
{
ratio[1] = 12;
clipped = 1;
}
}
else
{
if (ratio[1] < -264 || ratio[1] > 461)
return 2;
if (ratio[1] < -50)
{
ratio[1] = -50;
clipped = 1;
}
if (ratio[1] > 307)
{
ratio[1] = 307;
clipped = 1;
}
}
target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10);
if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped)
return 0;
miss = target - ratio[0];
if (abs(miss) >= mar * 4)
return 2;
if (miss < -20)
miss = -20;
if (miss > mar)
miss = mar;
ratio[0] = target - miss;
return 1;
}
void CLASS canon_600_auto_wb()
{
int mar, row, col, i, j, st, count[] = {0, 0};
int test[8], total[2][8], ratio[2][2], stat[2];
memset(&total, 0, sizeof total);
i = canon_ev + 0.5;
if (i < 10)
mar = 150;
else if (i > 12)
mar = 20;
else
mar = 280 - 20 * i;
if (flash_used)
mar = 80;
for (row = 14; row < height - 14; row += 4)
for (col = 10; col < width; col += 2)
{
for (i = 0; i < 8; i++)
test[(i & 4) + FC(row + (i >> 1), col + (i & 1))] = BAYER(row + (i >> 1), col + (i & 1));
for (i = 0; i < 8; i++)
if (test[i] < 150 || test[i] > 1500)
goto next;
for (i = 0; i < 4; i++)
if (abs(test[i] - test[i + 4]) > 50)
goto next;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 4; j += 2)
ratio[i][j >> 1] = ((test[i * 4 + j + 1] - test[i * 4 + j]) << 10) / test[i * 4 + j];
stat[i] = canon_600_color(ratio[i], mar);
}
if ((st = stat[0] | stat[1]) > 1)
goto next;
for (i = 0; i < 2; i++)
if (stat[i])
for (j = 0; j < 2; j++)
test[i * 4 + j * 2 + 1] = test[i * 4 + j * 2] * (0x400 + ratio[i][j]) >> 10;
for (i = 0; i < 8; i++)
total[st][i] += test[i];
count[st]++;
next:;
}
if (count[0] | count[1])
{
st = count[0] * 200 < count[1];
for (i = 0; i < 4; i++)
pre_mul[i] = 1.0 / (total[st][i] + total[st][i + 4]);
}
}
void CLASS canon_600_coeff()
{
static const short table[6][12] = {{-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105},
{-1203, 1715, -1136, 1648, 1388, -876, 267, 245, -1641, 2153, 3921, -3409},
{-615, 1127, -1563, 2075, 1437, -925, 509, 3, -756, 1268, 2519, -2007},
{-190, 702, -1886, 2398, 2153, -1641, 763, -251, -452, 964, 3040, -2528},
{-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105},
{-807, 1319, -1785, 2297, 1388, -876, 769, -257, -230, 742, 2067, -1555}};
int t = 0, i, c;
float mc, yc;
mc = pre_mul[1] / pre_mul[2];
yc = pre_mul[3] / pre_mul[2];
if (mc > 1 && mc <= 1.28 && yc < 0.8789)
t = 1;
if (mc > 1.28 && mc <= 2)
{
if (yc < 0.8789)
t = 3;
else if (yc <= 2)
t = 4;
}
if (flash_used)
t = 5;
for (raw_color = i = 0; i < 3; i++)
FORCC rgb_cam[i][c] = table[t][i * 4 + c] / 1024.0;
}
void CLASS canon_600_load_raw()
{
uchar data[1120], *dp;
ushort *pix;
int irow, row;
for (irow = row = 0; irow < height; irow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread(data, 1, 1120, ifp) < 1120)
derror();
pix = raw_image + row * raw_width;
for (dp = data; dp < data + 1120; dp += 10, pix += 8)
{
pix[0] = (dp[0] << 2) + (dp[1] >> 6);
pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3);
pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3);
pix[3] = (dp[4] << 2) + (dp[1] & 3);
pix[4] = (dp[5] << 2) + (dp[9] & 3);
pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3);
pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3);
pix[7] = (dp[8] << 2) + (dp[9] >> 6);
}
if ((row += 2) > height)
row = 1;
}
}
void CLASS canon_600_correct()
{
int row, col, val;
static const short mul[4][2] = {{1141, 1145}, {1128, 1109}, {1178, 1149}, {1128, 1109}};
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col++)
{
if ((val = BAYER(row, col) - black) < 0)
val = 0;
val = val * mul[row & 3][col & 1] >> 9;
BAYER(row, col) = val;
}
}
canon_600_fixed_wb(1311);
canon_600_auto_wb();
canon_600_coeff();
maximum = (0x3ff - black) * 1109 >> 9;
black = 0;
}
int CLASS canon_s2is()
{
unsigned row;
for (row = 0; row < 100; row++)
{
fseek(ifp, row * 3340 + 3284, SEEK_SET);
if (getc(ifp) > 15)
return 1;
}
return 0;
}
unsigned CLASS getbithuff(int nbits, ushort *huff)
{
#ifdef LIBRAW_NOTHREADS
static unsigned bitbuf = 0;
static int vbits = 0, reset = 0;
#else
#define bitbuf tls->getbits.bitbuf
#define vbits tls->getbits.vbits
#define reset tls->getbits.reset
#endif
unsigned c;
if (nbits > 25)
return 0;
if (nbits < 0)
return bitbuf = vbits = reset = 0;
if (nbits == 0 || vbits < 0)
return 0;
while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp)))
{
bitbuf = (bitbuf << 8) + (uchar)c;
vbits += 8;
}
c = bitbuf << (32 - vbits) >> (32 - nbits);
if (huff)
{
vbits -= huff[c] >> 8;
c = (uchar)huff[c];
}
else
vbits -= nbits;
if (vbits < 0)
derror();
return c;
#ifndef LIBRAW_NOTHREADS
#undef bitbuf
#undef vbits
#undef reset
#endif
}
#define getbits(n) getbithuff(n, 0)
#define gethuff(h) getbithuff(*h, h + 1)
/*
Construct a decode tree according the specification in *source.
The first 16 bytes specify how many codes should be 1-bit, 2-bit
3-bit, etc. Bytes after that are the leaf values.
For example, if the source is
{ 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff },
then the code is
00 0x04
010 0x03
011 0x05
100 0x06
101 0x02
1100 0x07
1101 0x01
11100 0x08
11101 0x09
11110 0x00
111110 0x0a
1111110 0x0b
1111111 0xff
*/
ushort *CLASS make_decoder_ref(const uchar **source)
{
int max, len, h, i, j;
const uchar *count;
ushort *huff;
count = (*source += 16) - 17;
for (max = 16; max && !count[max]; max--)
;
huff = (ushort *)calloc(1 + (1 << max), sizeof *huff);
merror(huff, "make_decoder()");
huff[0] = max;
for (h = len = 1; len <= max; len++)
for (i = 0; i < count[len]; i++, ++*source)
for (j = 0; j < 1 << (max - len); j++)
if (h <= 1 << max)
huff[h++] = len << 8 | **source;
return huff;
}
ushort *CLASS make_decoder(const uchar *source) { return make_decoder_ref(&source); }
void CLASS crw_init_tables(unsigned table, ushort *huff[2])
{
static const uchar first_tree[3][29] = {
{0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0x04, 0x03, 0x05, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x00, 0x0a, 0x0b, 0xff},
{0, 2, 2, 3, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0,
0, 0x03, 0x02, 0x04, 0x01, 0x05, 0x00, 0x06, 0x07, 0x09, 0x08, 0x0a, 0x0b, 0xff},
{0, 0, 6, 3, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0x06, 0x05, 0x07, 0x04, 0x08, 0x03, 0x09, 0x02, 0x00, 0x0a, 0x01, 0x0b, 0xff},
};
static const uchar second_tree[3][180] = {
{0, 2, 2, 2, 1, 4, 2, 1, 2, 5, 1, 1, 0, 0, 0, 139, 0x03, 0x04,
0x02, 0x05, 0x01, 0x06, 0x07, 0x08, 0x12, 0x13, 0x11, 0x14, 0x09, 0x15, 0x22, 0x00, 0x21, 0x16, 0x0a, 0xf0,
0x23, 0x17, 0x24, 0x31, 0x32, 0x18, 0x19, 0x33, 0x25, 0x41, 0x34, 0x42, 0x35, 0x51, 0x36, 0x37, 0x38, 0x29,
0x79, 0x26, 0x1a, 0x39, 0x56, 0x57, 0x28, 0x27, 0x52, 0x55, 0x58, 0x43, 0x76, 0x59, 0x77, 0x54, 0x61, 0xf9,
0x71, 0x78, 0x75, 0x96, 0x97, 0x49, 0xb7, 0x53, 0xd7, 0x74, 0xb6, 0x98, 0x47, 0x48, 0x95, 0x69, 0x99, 0x91,
0xfa, 0xb8, 0x68, 0xb5, 0xb9, 0xd6, 0xf7, 0xd8, 0x67, 0x46, 0x45, 0x94, 0x89, 0xf8, 0x81, 0xd5, 0xf6, 0xb4,
0x88, 0xb1, 0x2a, 0x44, 0x72, 0xd9, 0x87, 0x66, 0xd4, 0xf5, 0x3a, 0xa7, 0x73, 0xa9, 0xa8, 0x86, 0x62, 0xc7,
0x65, 0xc8, 0xc9, 0xa1, 0xf4, 0xd1, 0xe9, 0x5a, 0x92, 0x85, 0xa6, 0xe7, 0x93, 0xe8, 0xc1, 0xc6, 0x7a, 0x64,
0xe1, 0x4a, 0x6a, 0xe6, 0xb3, 0xf1, 0xd3, 0xa5, 0x8a, 0xb2, 0x9a, 0xba, 0x84, 0xa4, 0x63, 0xe5, 0xc5, 0xf3,
0xd2, 0xc4, 0x82, 0xaa, 0xda, 0xe4, 0xf2, 0xca, 0x83, 0xa3, 0xa2, 0xc3, 0xea, 0xc2, 0xe2, 0xe3, 0xff, 0xff},
{0, 2, 2, 1, 4, 1, 4, 1, 3, 3, 1, 0, 0, 0, 0, 140, 0x02, 0x03,
0x01, 0x04, 0x05, 0x12, 0x11, 0x06, 0x13, 0x07, 0x08, 0x14, 0x22, 0x09, 0x21, 0x00, 0x23, 0x15, 0x31, 0x32,
0x0a, 0x16, 0xf0, 0x24, 0x33, 0x41, 0x42, 0x19, 0x17, 0x25, 0x18, 0x51, 0x34, 0x43, 0x52, 0x29, 0x35, 0x61,
0x39, 0x71, 0x62, 0x36, 0x53, 0x26, 0x38, 0x1a, 0x37, 0x81, 0x27, 0x91, 0x79, 0x55, 0x45, 0x28, 0x72, 0x59,
0xa1, 0xb1, 0x44, 0x69, 0x54, 0x58, 0xd1, 0xfa, 0x57, 0xe1, 0xf1, 0xb9, 0x49, 0x47, 0x63, 0x6a, 0xf9, 0x56,
0x46, 0xa8, 0x2a, 0x4a, 0x78, 0x99, 0x3a, 0x75, 0x74, 0x86, 0x65, 0xc1, 0x76, 0xb6, 0x96, 0xd6, 0x89, 0x85,
0xc9, 0xf5, 0x95, 0xb4, 0xc7, 0xf7, 0x8a, 0x97, 0xb8, 0x73, 0xb7, 0xd8, 0xd9, 0x87, 0xa7, 0x7a, 0x48, 0x82,
0x84, 0xea, 0xf4, 0xa6, 0xc5, 0x5a, 0x94, 0xa4, 0xc6, 0x92, 0xc3, 0x68, 0xb5, 0xc8, 0xe4, 0xe5, 0xe6, 0xe9,
0xa2, 0xa3, 0xe3, 0xc2, 0x66, 0x67, 0x93, 0xaa, 0xd4, 0xd5, 0xe7, 0xf8, 0x88, 0x9a, 0xd7, 0x77, 0xc4, 0x64,
0xe2, 0x98, 0xa5, 0xca, 0xda, 0xe8, 0xf3, 0xf6, 0xa9, 0xb2, 0xb3, 0xf2, 0xd2, 0x83, 0xba, 0xd3, 0xff, 0xff},
{0, 0, 6, 2, 1, 3, 3, 2, 5, 1, 2, 2, 8, 10, 0, 117, 0x04, 0x05,
0x03, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x12, 0x13, 0x14, 0x11, 0x15, 0x0a, 0x16, 0x17, 0xf0, 0x00, 0x22,
0x21, 0x18, 0x23, 0x19, 0x24, 0x32, 0x31, 0x25, 0x33, 0x38, 0x37, 0x34, 0x35, 0x36, 0x39, 0x79, 0x57, 0x58,
0x59, 0x28, 0x56, 0x78, 0x27, 0x41, 0x29, 0x77, 0x26, 0x42, 0x76, 0x99, 0x1a, 0x55, 0x98, 0x97, 0xf9, 0x48,
0x54, 0x96, 0x89, 0x47, 0xb7, 0x49, 0xfa, 0x75, 0x68, 0xb6, 0x67, 0x69, 0xb9, 0xb8, 0xd8, 0x52, 0xd7, 0x88,
0xb5, 0x74, 0x51, 0x46, 0xd9, 0xf8, 0x3a, 0xd6, 0x87, 0x45, 0x7a, 0x95, 0xd5, 0xf6, 0x86, 0xb4, 0xa9, 0x94,
0x53, 0x2a, 0xa8, 0x43, 0xf5, 0xf7, 0xd4, 0x66, 0xa7, 0x5a, 0x44, 0x8a, 0xc9, 0xe8, 0xc8, 0xe7, 0x9a, 0x6a,
0x73, 0x4a, 0x61, 0xc7, 0xf4, 0xc6, 0x65, 0xe9, 0x72, 0xe6, 0x71, 0x91, 0x93, 0xa6, 0xda, 0x92, 0x85, 0x62,
0xf3, 0xc5, 0xb2, 0xa4, 0x84, 0xba, 0x64, 0xa5, 0xb3, 0xd2, 0x81, 0xe5, 0xd3, 0xaa, 0xc4, 0xca, 0xf2, 0xb1,
0xe4, 0xd1, 0x83, 0x63, 0xea, 0xc3, 0xe2, 0x82, 0xf1, 0xa3, 0xc2, 0xa1, 0xc1, 0xe3, 0xa2, 0xe1, 0xff, 0xff}};
if (table > 2)
table = 2;
huff[0] = make_decoder(first_tree[table]);
huff[1] = make_decoder(second_tree[table]);
}
/*
Return 0 if the image starts with compressed data,
1 if it starts with uncompressed low-order bits.
In Canon compressed data, 0xff is always followed by 0x00.
*/
int CLASS canon_has_lowbits()
{
uchar test[0x4000];
int ret = 1, i;
fseek(ifp, 0, SEEK_SET);
fread(test, 1, sizeof test, ifp);
for (i = 540; i < sizeof test - 1; i++)
if (test[i] == 0xff)
{
if (test[i + 1])
return 1;
ret = 0;
}
return ret;
}
void CLASS canon_load_raw()
{
ushort *pixel, *prow, *huff[2];
int nblocks, lowbits, i, c, row, r, save, val;
int block, diffbuf[64], leaf, len, diff, carry = 0, pnum = 0, base[2];
crw_init_tables(tiff_compress, huff);
lowbits = canon_has_lowbits();
if (!lowbits)
maximum = 0x3ff;
fseek(ifp, 540 + lowbits * raw_height * raw_width / 4, SEEK_SET);
zero_after_ff = 1;
getbits(-1);
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row += 8)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
pixel = raw_image + row * raw_width;
nblocks = MIN(8, raw_height - row) * raw_width >> 6;
for (block = 0; block < nblocks; block++)
{
memset(diffbuf, 0, sizeof diffbuf);
for (i = 0; i < 64; i++)
{
leaf = gethuff(huff[i > 0]);
if (leaf == 0 && i)
break;
if (leaf == 0xff)
continue;
i += leaf >> 4;
len = leaf & 15;
if (len == 0)
continue;
diff = getbits(len);
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - 1;
if (i < 64)
diffbuf[i] = diff;
}
diffbuf[0] += carry;
carry = diffbuf[0];
for (i = 0; i < 64; i++)
{
if (pnum++ % raw_width == 0)
base[0] = base[1] = 512;
if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10)
derror();
}
}
if (lowbits)
{
save = ftell(ifp);
fseek(ifp, 26 + row * raw_width / 4, SEEK_SET);
for (prow = pixel, i = 0; i < raw_width * 2; i++)
{
c = fgetc(ifp);
for (r = 0; r < 8; r += 2, prow++)
{
val = (*prow << 2) + ((c >> r) & 3);
if (raw_width == 2672 && val < 512)
val += 2;
*prow = val;
}
}
fseek(ifp, save, SEEK_SET);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
FORC(2) free(huff[c]);
throw;
}
#endif
FORC(2) free(huff[c]);
}
int CLASS ljpeg_start(struct jhead *jh, int info_only)
{
ushort c, tag, len;
int cnt = 0;
uchar data[0x10000];
const uchar *dp;
memset(jh, 0, sizeof *jh);
jh->restart = INT_MAX;
if ((fgetc(ifp), fgetc(ifp)) != 0xd8)
return 0;
do
{
if (feof(ifp))
return 0;
if (cnt++ > 1024)
return 0; // 1024 tags limit
if (!fread(data, 2, 2, ifp))
return 0;
tag = data[0] << 8 | data[1];
len = (data[2] << 8 | data[3]) - 2;
if (tag <= 0xff00)
return 0;
fread(data, 1, len, ifp);
switch (tag)
{
case 0xffc3: // start of frame; lossless, Huffman
jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;
case 0xffc1:
case 0xffc0:
jh->algo = tag & 0xff;
jh->bits = data[0];
jh->high = data[1] << 8 | data[2];
jh->wide = data[3] << 8 | data[4];
jh->clrs = data[5] + jh->sraw;
if (len == 9 && !dng_version)
getc(ifp);
break;
case 0xffc4: // define Huffman tables
if (info_only)
break;
for (dp = data; dp < data + len && !((c = *dp++) & -20);)
jh->free[c] = jh->huff[c] = make_decoder_ref(&dp);
break;
case 0xffda: // start of scan
jh->psv = data[1 + data[0] * 2];
jh->bits -= data[3 + data[0] * 2] & 15;
break;
case 0xffdb:
FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2];
break;
case 0xffdd:
jh->restart = data[0] << 8 | data[1];
}
} while (tag != 0xffda);
if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs)
return 0;
if (info_only)
return 1;
if (!jh->huff[0])
return 0;
FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c];
if (jh->sraw)
{
FORC(4) jh->huff[2 + c] = jh->huff[1];
FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0];
}
jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4);
merror(jh->row, "ljpeg_start()");
return zero_after_ff = 1;
}
void CLASS ljpeg_end(struct jhead *jh)
{
int c;
FORC4 if (jh->free[c]) free(jh->free[c]);
free(jh->row);
}
int CLASS ljpeg_diff(ushort *huff)
{
int len, diff;
if (!huff)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 2);
#endif
len = gethuff(huff);
if (len == 16 && (!dng_version || dng_version >= 0x1010000))
return -32768;
diff = getbits(len);
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - 1;
return diff;
}
ushort *CLASS ljpeg_row(int jrow, struct jhead *jh)
{
int col, c, diff, pred, spred = 0;
ushort mark = 0, *row[3];
if (jrow * jh->wide % jh->restart == 0)
{
FORC(6) jh->vpred[c] = 1 << (jh->bits - 1);
if (jrow)
{
fseek(ifp, -2, SEEK_CUR);
do
mark = (mark << 8) + (c = fgetc(ifp));
while (c != EOF && mark >> 4 != 0xffd);
}
getbits(-1);
}
FORC3 row[c] = jh->row + jh->wide * jh->clrs * ((jrow + c) & 1);
for (col = 0; col < jh->wide; col++)
FORC(jh->clrs)
{
diff = ljpeg_diff(jh->huff[c]);
if (jh->sraw && c <= jh->sraw && (col | c))
pred = spred;
else if (col)
pred = row[0][-jh->clrs];
else
pred = (jh->vpred[c] += diff) - diff;
if (jrow && col)
switch (jh->psv)
{
case 1:
break;
case 2:
pred = row[1][0];
break;
case 3:
pred = row[1][-jh->clrs];
break;
case 4:
pred = pred + row[1][0] - row[1][-jh->clrs];
break;
case 5:
pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1);
break;
case 6:
pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1);
break;
case 7:
pred = (pred + row[1][0]) >> 1;
break;
default:
pred = 0;
}
if ((**row = pred + diff) >> jh->bits)
derror();
if (c <= jh->sraw)
spred = **row;
row[0]++;
row[1]++;
}
return row[2];
}
void CLASS lossless_jpeg_load_raw()
{
int jwide, jhigh, jrow, jcol, val, jidx, i, j, row = 0, col = 0;
struct jhead jh;
ushort *rp;
if (!ljpeg_start(&jh, 0))
return;
if (jh.wide < 1 || jh.high < 1 || jh.clrs < 1 || jh.bits < 1)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 2);
#endif
jwide = jh.wide * jh.clrs;
jhigh = jh.high;
if (jh.clrs == 4 && jwide >= raw_width * 2)
jhigh *= 2;
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (jrow = 0; jrow < jh.high; jrow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
rp = ljpeg_row(jrow, &jh);
if (load_flags & 1)
row = jrow & 1 ? height - 1 - jrow / 2 : jrow / 2;
for (jcol = 0; jcol < jwide; jcol++)
{
val = curve[*rp++];
if (cr2_slice[0])
{
jidx = jrow * jwide + jcol;
i = jidx / (cr2_slice[1] * raw_height);
if ((j = i >= cr2_slice[0]))
i = cr2_slice[0];
jidx -= i * (cr2_slice[1] * raw_height);
row = jidx / cr2_slice[1 + j];
col = jidx % cr2_slice[1 + j] + i * cr2_slice[1];
}
if (raw_width == 3984 && (col -= 2) < 0)
col += (row--, raw_width);
if (row > raw_height)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp(failure, 3);
#endif
if ((unsigned)row < raw_height)
RAW(row, col) = val;
if (++col >= raw_width)
col = (row++, 0);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
ljpeg_end(&jh);
}
void CLASS canon_sraw_load_raw()
{
struct jhead jh;
short *rp = 0, (*ip)[4];
int jwide, slice, scol, ecol, row, col, jrow = 0, jcol = 0, pix[3], c;
int v[3] = {0, 0, 0}, ver, hue;
#ifdef LIBRAW_LIBRARY_BUILD
int saved_w = width, saved_h = height;
#endif
char *cp;
if (!ljpeg_start(&jh, 0) || jh.clrs < 4)
return;
jwide = (jh.wide >>= 1) * jh.clrs;
#ifdef LIBRAW_LIBRARY_BUILD
if (load_flags & 256)
{
width = raw_width;
height = raw_height;
}
try
{
#endif
for (ecol = slice = 0; slice <= cr2_slice[0]; slice++)
{
scol = ecol;
ecol += cr2_slice[1] * 2 / jh.clrs;
if (!cr2_slice[0] || ecol > raw_width - 1)
ecol = raw_width & -2;
for (row = 0; row < height; row += (jh.clrs >> 1) - 1)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
ip = (short(*)[4])image + row * width;
for (col = scol; col < ecol; col += 2, jcol += jh.clrs)
{
if ((jcol %= jwide) == 0)
rp = (short *)ljpeg_row(jrow++, &jh);
if (col >= width)
continue;
#ifdef LIBRAW_LIBRARY_BUILD
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE)
{
FORC(jh.clrs - 2)
{
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col + (c >> 1) * width + (c & 1)][1] = ip[col + (c >> 1) * width + (c & 1)][2] = 8192;
}
ip[col][1] = rp[jcol + jh.clrs - 2] - 8192;
ip[col][2] = rp[jcol + jh.clrs - 1] - 8192;
}
else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB)
{
FORC(jh.clrs - 2)
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col][1] = rp[jcol + jh.clrs - 2] - 8192;
ip[col][2] = rp[jcol + jh.clrs - 1] - 8192;
}
else
#endif
{
FORC(jh.clrs - 2)
ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c];
ip[col][1] = rp[jcol + jh.clrs - 2] - 16384;
ip[col][2] = rp[jcol + jh.clrs - 1] - 16384;
}
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE)
{
ljpeg_end(&jh);
maximum = 0x3fff;
height = saved_h;
width = saved_w;
return;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (cp = model2; *cp && !isdigit(*cp); cp++)
;
sscanf(cp, "%d.%d.%d", v, v + 1, v + 2);
ver = (v[0] * 1000 + v[1]) * 1000 + v[2];
hue = (jh.sraw + 1) << 2;
if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006))
hue = jh.sraw << 1;
ip = (short(*)[4])image;
rp = ip[0];
for (row = 0; row < height; row++, ip += width)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (row & (jh.sraw >> 1))
{
for (col = 0; col < width; col += 2)
for (c = 1; c < 3; c++)
if (row == height - 1)
{
ip[col][c] = ip[col - width][c];
}
else
{
ip[col][c] = (ip[col - width][c] + ip[col + width][c] + 1) >> 1;
}
}
for (col = 1; col < width; col += 2)
for (c = 1; c < 3; c++)
if (col == width - 1)
ip[col][c] = ip[col - 1][c];
else
ip[col][c] = (ip[col - 1][c] + ip[col + 1][c] + 1) >> 1;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB))
#endif
for (; rp < ip[0]; rp += 4)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 ||
unique_id == 0x80000287)
{
rp[1] = (rp[1] << 2) + hue;
rp[2] = (rp[2] << 2) + hue;
pix[0] = rp[0] + ((50 * rp[1] + 22929 * rp[2]) >> 14);
pix[1] = rp[0] + ((-5640 * rp[1] - 11751 * rp[2]) >> 14);
pix[2] = rp[0] + ((29040 * rp[1] - 101 * rp[2]) >> 14);
}
else
{
if (unique_id < 0x80000218)
rp[0] -= 512;
pix[0] = rp[0] + rp[2];
pix[2] = rp[0] + rp[1];
pix[1] = rp[0] + ((-778 * rp[1] - (rp[2] << 11)) >> 12);
}
FORC3 rp[c] = CLIP(pix[c] * sraw_mul[c] >> 10);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
height = saved_h;
width = saved_w;
#endif
ljpeg_end(&jh);
maximum = 0x3fff;
}
void CLASS adobe_copy_pixel(unsigned row, unsigned col, ushort **rp)
{
int c;
if (tiff_samples == 2 && shot_select)
(*rp)++;
if (raw_image)
{
if (row < raw_height && col < raw_width)
RAW(row, col) = curve[**rp];
*rp += tiff_samples;
}
else
{
#ifdef LIBRAW_LIBRARY_BUILD
FORC(tiff_samples)
image[row * raw_width + col][c] = curve[(*rp)[c]];
*rp += tiff_samples;
#else
if (row < height && col < width)
FORC(tiff_samples)
image[row * width + col][c] = curve[(*rp)[c]];
*rp += tiff_samples;
#endif
}
if (tiff_samples == 2 && shot_select)
(*rp)--;
}
void CLASS ljpeg_idct(struct jhead *jh)
{
int c, i, j, len, skip, coef;
float work[3][8][8];
static float cs[106] = {0};
static const uchar zigzag[80] = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33,
40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54,
47, 55, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63};
if (!cs[0])
FORC(106) cs[c] = cos((c & 31) * M_PI / 16) / 2;
memset(work, 0, sizeof work);
work[0][0][0] = jh->vpred[0] += ljpeg_diff(jh->huff[0]) * jh->quant[0];
for (i = 1; i < 64; i++)
{
len = gethuff(jh->huff[16]);
i += skip = len >> 4;
if (!(len &= 15) && skip < 15)
break;
coef = getbits(len);
if ((coef & (1 << (len - 1))) == 0)
coef -= (1 << len) - 1;
((float *)work)[zigzag[i]] = coef * jh->quant[i];
}
FORC(8) work[0][0][c] *= M_SQRT1_2;
FORC(8) work[0][c][0] *= M_SQRT1_2;
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++)
FORC(8) work[1][i][j] += work[0][i][c] * cs[(j * 2 + 1) * c];
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++)
FORC(8) work[2][i][j] += work[1][c][j] * cs[(i * 2 + 1) * c];
FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c] + 0.5);
}
void CLASS lossless_dng_load_raw()
{
unsigned save, trow = 0, tcol = 0, jwide, jrow, jcol, row, col, i, j;
struct jhead jh;
ushort *rp;
while (trow < raw_height)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
save = ftell(ifp);
if (tile_length < INT_MAX)
fseek(ifp, get4(), SEEK_SET);
if (!ljpeg_start(&jh, 0))
break;
jwide = jh.wide;
if (filters)
jwide *= jh.clrs;
jwide /= MIN(is_raw, tiff_samples);
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
switch (jh.algo)
{
case 0xc1:
jh.vpred[0] = 16384;
getbits(-1);
for (jrow = 0; jrow + 7 < jh.high; jrow += 8)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (jcol = 0; jcol + 7 < jh.wide; jcol += 8)
{
ljpeg_idct(&jh);
rp = jh.idct;
row = trow + jcol / tile_width + jrow * 2;
col = tcol + jcol % tile_width;
for (i = 0; i < 16; i += 2)
for (j = 0; j < 8; j++)
adobe_copy_pixel(row + i, col + j, &rp);
}
}
break;
case 0xc3:
for (row = col = jrow = 0; jrow < jh.high; jrow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
rp = ljpeg_row(jrow, &jh);
for (jcol = 0; jcol < jwide; jcol++)
{
adobe_copy_pixel(trow + row, tcol + col, &rp);
if (++col >= tile_width || col >= raw_width)
row += 1 + (col = 0);
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
ljpeg_end(&jh);
throw;
}
#endif
fseek(ifp, save + 4, SEEK_SET);
if ((tcol += tile_width) >= raw_width)
trow += tile_length + (tcol = 0);
ljpeg_end(&jh);
}
}
void CLASS packed_dng_load_raw()
{
ushort *pixel, *rp;
int row, col;
pixel = (ushort *)calloc(raw_width, tiff_samples * sizeof *pixel);
merror(pixel, "packed_dng_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (tiff_bps == 16)
read_shorts(pixel, raw_width * tiff_samples);
else
{
getbits(-1);
for (col = 0; col < raw_width * tiff_samples; col++)
pixel[col] = getbits(tiff_bps);
}
for (rp = pixel, col = 0; col < raw_width; col++)
adobe_copy_pixel(row, col, &rp);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
}
void CLASS pentax_load_raw()
{
ushort bit[2][15], huff[4097];
int dep, row, col, diff, c, i;
ushort vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2];
fseek(ifp, meta_offset, SEEK_SET);
dep = (get2() + 12) & 15;
fseek(ifp, 12, SEEK_CUR);
FORC(dep) bit[0][c] = get2();
FORC(dep) bit[1][c] = fgetc(ifp);
FORC(dep)
for (i = bit[0][c]; i <= ((bit[0][c] + (4096 >> bit[1][c]) - 1) & 4095);)
huff[++i] = bit[1][c] << 8 | c;
huff[0] = 12;
fseek(ifp, data_offset, SEEK_SET);
getbits(-1);
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
diff = ljpeg_diff(huff);
if (col < 2)
hpred[col] = vpred[row & 1][col] += diff;
else
hpred[col & 1] += diff;
RAW(row, col) = hpred[col & 1];
if (hpred[col & 1] >> tiff_bps)
derror();
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS nikon_coolscan_load_raw()
{
int bufsize = width * 3 * tiff_bps / 8;
if (tiff_bps <= 8)
gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255);
else
gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 65535);
fseek(ifp, data_offset, SEEK_SET);
unsigned char *buf = (unsigned char *)malloc(bufsize);
unsigned short *ubuf = (unsigned short *)buf;
for (int row = 0; row < raw_height; row++)
{
int red = fread(buf, 1, bufsize, ifp);
unsigned short(*ip)[4] = (unsigned short(*)[4])image + row * width;
if (tiff_bps <= 8)
for (int col = 0; col < width; col++)
{
ip[col][0] = curve[buf[col * 3]];
ip[col][1] = curve[buf[col * 3 + 1]];
ip[col][2] = curve[buf[col * 3 + 2]];
ip[col][3] = 0;
}
else
for (int col = 0; col < width; col++)
{
ip[col][0] = curve[ubuf[col * 3]];
ip[col][1] = curve[ubuf[col * 3 + 1]];
ip[col][2] = curve[ubuf[col * 3 + 2]];
ip[col][3] = 0;
}
}
free(buf);
}
#endif
void CLASS nikon_load_raw()
{
static const uchar nikon_tree[][32] = {
{0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy */
5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12},
{0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy after split */
0x39, 0x5a, 0x38, 0x27, 0x16, 5, 4, 3, 2, 1, 0, 11, 12, 12},
{0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 12-bit lossless */
5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12},
{0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 14-bit lossy */
5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14},
{0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, /* 14-bit lossy after split */
8, 0x5c, 0x4b, 0x3a, 0x29, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14},
{0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, /* 14-bit lossless */
7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14}};
ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize;
int i, min, max, step = 0, tree = 0, split = 0, row, col, len, shl, diff;
fseek(ifp, meta_offset, SEEK_SET);
ver0 = fgetc(ifp);
ver1 = fgetc(ifp);
if (ver0 == 0x49 || ver1 == 0x58)
fseek(ifp, 2110, SEEK_CUR);
if (ver0 == 0x46)
tree = 2;
if (tiff_bps == 14)
tree += 3;
read_shorts(vpred[0], 4);
max = 1 << tiff_bps & 0x7fff;
if ((csize = get2()) > 1)
step = max / (csize - 1);
if (ver0 == 0x44 && ver1 == 0x20 && step > 0)
{
for (i = 0; i < csize; i++)
curve[i * step] = get2();
for (i = 0; i < max; i++)
curve[i] = (curve[i - i % step] * (step - i % step) + curve[i - i % step + step] * (i % step)) / step;
fseek(ifp, meta_offset + 562, SEEK_SET);
split = get2();
}
else if (ver0 != 0x46 && csize <= 0x4001)
read_shorts(curve, max = csize);
while (curve[max - 2] == curve[max - 1])
max--;
huff = make_decoder(nikon_tree[tree]);
fseek(ifp, data_offset, SEEK_SET);
getbits(-1);
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (min = row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (split && row == split)
{
free(huff);
huff = make_decoder(nikon_tree[tree + 1]);
max += (min = 16) << 1;
}
for (col = 0; col < raw_width; col++)
{
i = gethuff(huff);
len = i & 15;
shl = i >> 4;
diff = ((getbits(len - shl) << 1) + 1) << shl >> 1;
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - !shl;
if (col < 2)
hpred[col] = vpred[row & 1][col] += diff;
else
hpred[col & 1] += diff;
if ((ushort)(hpred[col & 1] + min) >= max)
derror();
RAW(row, col) = curve[LIM((short)hpred[col & 1], 0, 0x3fff)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(huff);
throw;
}
#endif
free(huff);
}
void CLASS nikon_yuv_load_raw()
{
int row, col, yuv[4], rgb[3], b, c;
UINT64 bitbuf = 0;
float cmul[4];
FORC4 { cmul[c] = cam_mul[c] > 0.001f ? cam_mul[c] : 1.f; }
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
if (!(b = col & 1))
{
bitbuf = 0;
FORC(6) bitbuf |= (UINT64)fgetc(ifp) << c * 8;
FORC(4) yuv[c] = (bitbuf >> c * 12 & 0xfff) - (c >> 1 << 11);
}
rgb[0] = yuv[b] + 1.370705 * yuv[3];
rgb[1] = yuv[b] - 0.337633 * yuv[2] - 0.698001 * yuv[3];
rgb[2] = yuv[b] + 1.732446 * yuv[2];
FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 0xfff)] / cmul[c];
}
}
}
/*
Returns 1 for a Coolpix 995, 0 for anything else.
*/
int CLASS nikon_e995()
{
int i, histo[256];
const uchar often[] = {0x00, 0x55, 0xaa, 0xff};
memset(histo, 0, sizeof histo);
fseek(ifp, -2000, SEEK_END);
for (i = 0; i < 2000; i++)
histo[fgetc(ifp)]++;
for (i = 0; i < 4; i++)
if (histo[often[i]] < 200)
return 0;
return 1;
}
/*
Returns 1 for a Coolpix 2100, 0 for anything else.
*/
int CLASS nikon_e2100()
{
uchar t[12];
int i;
fseek(ifp, 0, SEEK_SET);
for (i = 0; i < 1024; i++)
{
fread(t, 1, 12, ifp);
if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3)
return 0;
}
return 1;
}
void CLASS nikon_3700()
{
int bits, i;
uchar dp[24];
static const struct
{
int bits;
char t_make[12], t_model[15];
} table[] = {
{0x00, "Pentax", "Optio 33WR"}, {0x03, "Nikon", "E3200"}, {0x32, "Nikon", "E3700"}, {0x33, "Olympus", "C740UZ"}};
fseek(ifp, 3072, SEEK_SET);
fread(dp, 1, 24, ifp);
bits = (dp[8] & 3) << 4 | (dp[20] & 3);
for (i = 0; i < sizeof table / sizeof *table; i++)
if (bits == table[i].bits)
{
strcpy(make, table[i].t_make);
strcpy(model, table[i].t_model);
}
}
/*
Separates a Minolta DiMAGE Z2 from a Nikon E4300.
*/
int CLASS minolta_z2()
{
int i, nz;
char tail[424];
fseek(ifp, -sizeof tail, SEEK_END);
fread(tail, 1, sizeof tail, ifp);
for (nz = i = 0; i < sizeof tail; i++)
if (tail[i])
nz++;
return nz > 20;
}
void CLASS ppm_thumb()
{
char *thumb;
thumb_length = thumb_width * thumb_height * 3;
thumb = (char *)malloc(thumb_length);
merror(thumb, "ppm_thumb()");
fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
fread(thumb, 1, thumb_length, ifp);
fwrite(thumb, 1, thumb_length, ofp);
free(thumb);
}
void CLASS ppm16_thumb()
{
int i;
char *thumb;
thumb_length = thumb_width * thumb_height * 3;
thumb = (char *)calloc(thumb_length, 2);
merror(thumb, "ppm16_thumb()");
read_shorts((ushort *)thumb, thumb_length);
for (i = 0; i < thumb_length; i++)
thumb[i] = ((ushort *)thumb)[i] >> 8;
fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
fwrite(thumb, 1, thumb_length, ofp);
free(thumb);
}
void CLASS layer_thumb()
{
int i, c;
char *thumb, map[][4] = {"012", "102"};
colors = thumb_misc >> 5 & 7;
thumb_length = thumb_width * thumb_height;
thumb = (char *)calloc(colors, thumb_length);
merror(thumb, "layer_thumb()");
fprintf(ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height);
fread(thumb, thumb_length, colors, ifp);
for (i = 0; i < thumb_length; i++)
FORCC putc(thumb[i + thumb_length * (map[thumb_misc >> 8][c] - '0')], ofp);
free(thumb);
}
void CLASS rollei_thumb()
{
unsigned i;
ushort *thumb;
thumb_length = thumb_width * thumb_height;
thumb = (ushort *)calloc(thumb_length, 2);
merror(thumb, "rollei_thumb()");
fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
read_shorts(thumb, thumb_length);
for (i = 0; i < thumb_length; i++)
{
putc(thumb[i] << 3, ofp);
putc(thumb[i] >> 5 << 2, ofp);
putc(thumb[i] >> 11 << 3, ofp);
}
free(thumb);
}
void CLASS rollei_load_raw()
{
uchar pixel[10];
unsigned iten = 0, isix, i, buffer = 0, todo[16];
isix = raw_width * raw_height * 5 / 8;
while (fread(pixel, 1, 10, ifp) == 10)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (i = 0; i < 10; i += 2)
{
todo[i] = iten++;
todo[i + 1] = pixel[i] << 8 | pixel[i + 1];
buffer = pixel[i] >> 2 | buffer << 6;
}
for (; i < 16; i += 2)
{
todo[i] = isix++;
todo[i + 1] = buffer >> (14 - i) * 5;
}
for (i = 0; i < 16; i += 2)
raw_image[todo[i]] = (todo[i + 1] & 0x3ff);
}
maximum = 0x3ff;
}
int CLASS raw(unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row, col) : 0; }
void CLASS phase_one_flat_field(int is_float, int nc)
{
ushort head[8];
unsigned wide, high, y, x, c, rend, cend, row, col;
float *mrow, num, mult[4];
read_shorts(head, 8);
if (head[2] * head[3] * head[4] * head[5] == 0)
return;
wide = head[2] / head[4] + (head[2] % head[4] != 0);
high = head[3] / head[5] + (head[3] % head[5] != 0);
mrow = (float *)calloc(nc * wide, sizeof *mrow);
merror(mrow, "phase_one_flat_field()");
for (y = 0; y < high; y++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (x = 0; x < wide; x++)
for (c = 0; c < nc; c += 2)
{
num = is_float ? getreal(11) : get2() / 32768.0;
if (y == 0)
mrow[c * wide + x] = num;
else
mrow[(c + 1) * wide + x] = (num - mrow[c * wide + x]) / head[5];
}
if (y == 0)
continue;
rend = head[1] + y * head[5];
for (row = rend - head[5]; row < raw_height && row < rend && row < head[1] + head[3] - head[5]; row++)
{
for (x = 1; x < wide; x++)
{
for (c = 0; c < nc; c += 2)
{
mult[c] = mrow[c * wide + x - 1];
mult[c + 1] = (mrow[c * wide + x] - mult[c]) / head[4];
}
cend = head[0] + x * head[4];
for (col = cend - head[4]; col < raw_width && col < cend && col < head[0] + head[2] - head[4]; col++)
{
c = nc > 2 ? FC(row - top_margin, col - left_margin) : 0;
if (!(c & 1))
{
c = RAW(row, col) * mult[c];
RAW(row, col) = LIM(c, 0, 65535);
}
for (c = 0; c < nc; c += 2)
mult[c] += mult[c + 1];
}
}
for (x = 0; x < wide; x++)
for (c = 0; c < nc; c += 2)
mrow[c * wide + x] += mrow[(c + 1) * wide + x];
}
}
free(mrow);
}
int CLASS phase_one_correct()
{
unsigned entries, tag, data, save, col, row, type;
int len, i, j, k, cip, val[4], dev[4], sum, max;
int head[9], diff, mindiff = INT_MAX, off_412 = 0;
/* static */ const signed char dir[12][2] = {{-1, -1}, {-1, 1}, {1, -1}, {1, 1}, {-2, 0}, {0, -2},
{0, 2}, {2, 0}, {-2, -2}, {-2, 2}, {2, -2}, {2, 2}};
float poly[8], num, cfrac, frac, mult[2], *yval[2] = {NULL, NULL};
ushort *xval[2];
int qmult_applied = 0, qlin_applied = 0;
#ifdef LIBRAW_LIBRARY_BUILD
if (!meta_length)
#else
if (half_size || !meta_length)
#endif
return 0;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Phase One correction...\n"));
#endif
fseek(ifp, meta_offset, SEEK_SET);
order = get2();
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, meta_offset + get4(), SEEK_SET);
entries = get4();
get4();
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
while (entries--)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
tag = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek(ifp, meta_offset + data, SEEK_SET);
if (tag == 0x419)
{ /* Polynomial curve */
for (get4(), i = 0; i < 8; i++)
poly[i] = getreal(11);
poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1;
for (i = 0; i < 0x10000; i++)
{
num = (poly[5] * i + poly[3]) * i + poly[1];
curve[i] = LIM(num, 0, 65535);
}
goto apply; /* apply to right half */
}
else if (tag == 0x41a)
{ /* Polynomial curve */
for (i = 0; i < 4; i++)
poly[i] = getreal(11);
for (i = 0; i < 0x10000; i++)
{
for (num = 0, j = 4; j--;)
num = num * i + poly[j];
curve[i] = LIM(num + i, 0, 65535);
}
apply: /* apply to whole image */
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = (tag & 1) * ph1.split_col; col < raw_width; col++)
RAW(row, col) = curve[RAW(row, col)];
}
}
else if (tag == 0x400)
{ /* Sensor defects */
while ((len -= 8) >= 0)
{
col = get2();
row = get2();
type = get2();
get2();
if (col >= raw_width)
continue;
if (type == 131 || type == 137) /* Bad column */
for (row = 0; row < raw_height; row++)
if (FC(row - top_margin, col - left_margin) == 1)
{
for (sum = i = 0; i < 4; i++)
sum += val[i] = raw(row + dir[i][0], col + dir[i][1]);
for (max = i = 0; i < 4; i++)
{
dev[i] = abs((val[i] << 2) - sum);
if (dev[max] < dev[i])
max = i;
}
RAW(row, col) = (sum - val[max]) / 3.0 + 0.5;
}
else
{
for (sum = 0, i = 8; i < 12; i++)
sum += raw(row + dir[i][0], col + dir[i][1]);
RAW(row, col) = 0.5 + sum * 0.0732233 + (raw(row, col - 2) + raw(row, col + 2)) * 0.3535534;
}
else if (type == 129)
{ /* Bad pixel */
if (row >= raw_height)
continue;
j = (FC(row - top_margin, col - left_margin) != 1) * 4;
for (sum = 0, i = j; i < j + 8; i++)
sum += raw(row + dir[i][0], col + dir[i][1]);
RAW(row, col) = (sum + 4) >> 3;
}
}
}
else if (tag == 0x401)
{ /* All-color flat fields */
phase_one_flat_field(1, 2);
}
else if (tag == 0x416 || tag == 0x410)
{
phase_one_flat_field(0, 2);
}
else if (tag == 0x40b)
{ /* Red+blue flat field */
phase_one_flat_field(0, 4);
}
else if (tag == 0x412)
{
fseek(ifp, 36, SEEK_CUR);
diff = abs(get2() - ph1.tag_21a);
if (mindiff > diff)
{
mindiff = diff;
off_412 = ftell(ifp) - 38;
}
}
else if (tag == 0x41f && !qlin_applied)
{ /* Quadrant linearization */
ushort lc[2][2][16], ref[16];
int qr, qc;
for (qr = 0; qr < 2; qr++)
for (qc = 0; qc < 2; qc++)
for (i = 0; i < 16; i++)
lc[qr][qc][i] = get4();
for (i = 0; i < 16; i++)
{
int v = 0;
for (qr = 0; qr < 2; qr++)
for (qc = 0; qc < 2; qc++)
v += lc[qr][qc][i];
ref[i] = (v + 2) >> 2;
}
for (qr = 0; qr < 2; qr++)
{
for (qc = 0; qc < 2; qc++)
{
int cx[19], cf[19];
for (i = 0; i < 16; i++)
{
cx[1 + i] = lc[qr][qc][i];
cf[1 + i] = ref[i];
}
cx[0] = cf[0] = 0;
cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15];
cf[18] = cx[18] = 65535;
cubic_spline(cx, cf, 19);
for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++)
RAW(row, col) = curve[RAW(row, col)];
}
}
}
qlin_applied = 1;
}
else if (tag == 0x41e && !qmult_applied)
{ /* Quadrant multipliers */
float qmult[2][2] = {{1, 1}, {1, 1}};
get4();
get4();
get4();
get4();
qmult[0][0] = 1.0 + getreal(11);
get4();
get4();
get4();
get4();
get4();
qmult[0][1] = 1.0 + getreal(11);
get4();
get4();
get4();
qmult[1][0] = 1.0 + getreal(11);
get4();
get4();
get4();
qmult[1][1] = 1.0 + getreal(11);
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row, col);
RAW(row, col) = LIM(i, 0, 65535);
}
}
qmult_applied = 1;
}
else if (tag == 0x431 && !qmult_applied)
{ /* Quadrant combined */
ushort lc[2][2][7], ref[7];
int qr, qc;
for (i = 0; i < 7; i++)
ref[i] = get4();
for (qr = 0; qr < 2; qr++)
for (qc = 0; qc < 2; qc++)
for (i = 0; i < 7; i++)
lc[qr][qc][i] = get4();
for (qr = 0; qr < 2; qr++)
{
for (qc = 0; qc < 2; qc++)
{
int cx[9], cf[9];
for (i = 0; i < 7; i++)
{
cx[1 + i] = ref[i];
cf[1 + i] = ((unsigned)ref[i] * lc[qr][qc][i]) / 10000;
}
cx[0] = cf[0] = 0;
cx[8] = cf[8] = 65535;
cubic_spline(cx, cf, 9);
for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++)
RAW(row, col) = curve[RAW(row, col)];
}
}
}
qmult_applied = 1;
qlin_applied = 1;
}
fseek(ifp, save, SEEK_SET);
}
if (off_412)
{
fseek(ifp, off_412, SEEK_SET);
for (i = 0; i < 9; i++)
head[i] = get4() & 0x7fff;
yval[0] = (float *)calloc(head[1] * head[3] + head[2] * head[4], 6);
merror(yval[0], "phase_one_correct()");
yval[1] = (float *)(yval[0] + head[1] * head[3]);
xval[0] = (ushort *)(yval[1] + head[2] * head[4]);
xval[1] = (ushort *)(xval[0] + head[1] * head[3]);
get2();
for (i = 0; i < 2; i++)
for (j = 0; j < head[i + 1] * head[i + 3]; j++)
yval[i][j] = getreal(11);
for (i = 0; i < 2; i++)
for (j = 0; j < head[i + 1] * head[i + 3]; j++)
xval[i][j] = get2();
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
cfrac = (float)col * head[3] / raw_width;
cfrac -= cip = cfrac;
num = RAW(row, col) * 0.5;
for (i = cip; i < cip + 2; i++)
{
for (k = j = 0; j < head[1]; j++)
if (num < xval[0][k = head[1] * i + j])
break;
frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k - 1]);
mult[i - cip] = yval[0][k - 1] * frac + yval[0][k] * (1 - frac);
}
i = ((mult[0] * (1 - cfrac) + mult[1] * cfrac) * row + num) * 2;
RAW(row, col) = LIM(i, 0, 65535);
}
}
free(yval[0]);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
if (yval[0])
free(yval[0]);
return LIBRAW_CANCELLED_BY_CALLBACK;
}
#endif
return 0;
}
void CLASS phase_one_load_raw()
{
int a, b, i;
ushort akey, bkey, t_mask;
fseek(ifp, ph1.key_off, SEEK_SET);
akey = get2();
bkey = get2();
t_mask = ph1.format == 1 ? 0x5555 : 0x1354;
#ifdef LIBRAW_LIBRARY_BUILD
if (ph1.black_col || ph1.black_row)
{
imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort));
merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw()");
imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort));
merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw()");
if (ph1.black_col)
{
fseek(ifp, ph1.black_col, SEEK_SET);
read_shorts((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height * 2);
}
if (ph1.black_row)
{
fseek(ifp, ph1.black_row, SEEK_SET);
read_shorts((ushort *)imgdata.rawdata.ph1_rblack[0], raw_width * 2);
}
}
#endif
fseek(ifp, data_offset, SEEK_SET);
read_shorts(raw_image, raw_width * raw_height);
if (ph1.format)
for (i = 0; i < raw_width * raw_height; i += 2)
{
a = raw_image[i + 0] ^ akey;
b = raw_image[i + 1] ^ bkey;
raw_image[i + 0] = (a & t_mask) | (b & ~t_mask);
raw_image[i + 1] = (b & t_mask) | (a & ~t_mask);
}
}
unsigned CLASS ph1_bithuff(int nbits, ushort *huff)
{
#ifndef LIBRAW_NOTHREADS
#define bitbuf tls->ph1_bits.bitbuf
#define vbits tls->ph1_bits.vbits
#else
static UINT64 bitbuf = 0;
static int vbits = 0;
#endif
unsigned c;
if (nbits == -1)
return bitbuf = vbits = 0;
if (nbits == 0)
return 0;
if (vbits < nbits)
{
bitbuf = bitbuf << 32 | get4();
vbits += 32;
}
c = bitbuf << (64 - vbits) >> (64 - nbits);
if (huff)
{
vbits -= huff[c] >> 8;
return (uchar)huff[c];
}
vbits -= nbits;
return c;
#ifndef LIBRAW_NOTHREADS
#undef bitbuf
#undef vbits
#endif
}
#define ph1_bits(n) ph1_bithuff(n, 0)
#define ph1_huff(h) ph1_bithuff(*h, h + 1)
void CLASS phase_one_load_raw_c()
{
static const int length[] = {8, 7, 6, 9, 11, 10, 5, 12, 14, 13};
int *offset, len[2], pred[2], row, col, i, j;
ushort *pixel;
short(*c_black)[2], (*r_black)[2];
#ifdef LIBRAW_LIBRARY_BUILD
if (ph1.format == 6)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
pixel = (ushort *)calloc(raw_width * 3 + raw_height * 4, 2);
merror(pixel, "phase_one_load_raw_c()");
offset = (int *)(pixel + raw_width);
fseek(ifp, strip_offset, SEEK_SET);
for (row = 0; row < raw_height; row++)
offset[row] = get4();
c_black = (short(*)[2])(offset + raw_height);
fseek(ifp, ph1.black_col, SEEK_SET);
if (ph1.black_col)
read_shorts((ushort *)c_black[0], raw_height * 2);
r_black = c_black + raw_height;
fseek(ifp, ph1.black_row, SEEK_SET);
if (ph1.black_row)
read_shorts((ushort *)r_black[0], raw_width * 2);
#ifdef LIBRAW_LIBRARY_BUILD
// Copy data to internal copy (ever if not read)
if (ph1.black_col || ph1.black_row)
{
imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort));
merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw_c()");
memmove(imgdata.rawdata.ph1_cblack, (ushort *)c_black[0], raw_height * 2 * sizeof(ushort));
imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort));
merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw_c()");
memmove(imgdata.rawdata.ph1_rblack, (ushort *)r_black[0], raw_width * 2 * sizeof(ushort));
}
#endif
for (i = 0; i < 256; i++)
curve[i] = i * i / 3.969 + 0.5;
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fseek(ifp, data_offset + offset[row], SEEK_SET);
ph1_bits(-1);
pred[0] = pred[1] = 0;
for (col = 0; col < raw_width; col++)
{
if (col >= (raw_width & -8))
len[0] = len[1] = 14;
else if ((col & 7) == 0)
for (i = 0; i < 2; i++)
{
for (j = 0; j < 5 && !ph1_bits(1); j++)
;
if (j--)
len[i] = length[j * 2 + ph1_bits(1)];
}
if ((i = len[col & 1]) == 14)
pixel[col] = pred[col & 1] = ph1_bits(16);
else
pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1));
if (pred[col & 1] >> 16)
derror();
if (ph1.format == 5 && pixel[col] < 256)
pixel[col] = curve[pixel[col]];
}
#ifndef LIBRAW_LIBRARY_BUILD
for (col = 0; col < raw_width; col++)
{
int shift = ph1.format == 8 ? 0 : 2;
i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] +
r_black[col][row >= ph1.split_row];
if (i > 0)
RAW(row, col) = i;
}
#else
if (ph1.format == 8)
memmove(&RAW(row, 0), &pixel[0], raw_width * 2);
else
for (col = 0; col < raw_width; col++)
RAW(row, col) = pixel[col] << 2;
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
maximum = 0xfffc - ph1.t_black;
}
void CLASS hasselblad_load_raw()
{
struct jhead jh;
int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c;
unsigned upix, urow, ucol;
ushort *ip;
if (!ljpeg_start(&jh, 0))
return;
order = 0x4949;
ph1_bits(-1);
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
back[4] = (int *)calloc(raw_width, 3 * sizeof **back);
merror(back[4], "hasselblad_load_raw()");
FORC3 back[c] = back[4] + c * raw_width;
cblack[6] >>= sh = tiff_samples > 1;
shot = LIM(shot_select, 1, tiff_samples) - 1;
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
FORC4 back[(c + 3) & 3] = back[c];
for (col = 0; col < raw_width; col += 2)
{
for (s = 0; s < tiff_samples * 2; s += 2)
{
FORC(2) len[c] = ph1_huff(jh.huff[0]);
FORC(2)
{
diff[s + c] = ph1_bits(len[c]);
if ((diff[s + c] & (1 << (len[c] - 1))) == 0)
diff[s + c] -= (1 << len[c]) - 1;
if (diff[s + c] == 65535)
diff[s + c] = -32768;
}
}
for (s = col; s < col + 2; s++)
{
pred = 0x8000 + load_flags;
if (col)
pred = back[2][s - 2];
if (col && row > 1)
switch (jh.psv)
{
case 11:
pred += back[0][s] / 2 - back[0][s - 2] / 2;
break;
}
f = (row & 1) * 3 ^ ((col + s) & 1);
FORC(tiff_samples)
{
pred += diff[(s & 1) * tiff_samples + c];
upix = pred >> sh & 0xffff;
if (raw_image && c == shot)
RAW(row, s) = upix;
if (image)
{
urow = row - top_margin + (c & 1);
ucol = col - left_margin - ((c >> 1) & 1);
ip = &image[urow * width + ucol][f];
if (urow < height && ucol < width)
*ip = c < 4 ? upix : (*ip + upix) >> 1;
}
}
back[2][s] = pred;
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(back[4]);
ljpeg_end(&jh);
throw;
}
#endif
free(back[4]);
ljpeg_end(&jh);
if (image)
mix_green = 1;
}
void CLASS leaf_hdr_load_raw()
{
ushort *pixel = 0;
unsigned tile = 0, r, c, row, col;
if (!filters || !raw_image)
{
pixel = (ushort *)calloc(raw_width, sizeof *pixel);
merror(pixel, "leaf_hdr_load_raw()");
}
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
FORC(tiff_samples)
for (r = 0; r < raw_height; r++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (r % tile_length == 0)
{
fseek(ifp, data_offset + 4 * tile++, SEEK_SET);
fseek(ifp, get4(), SEEK_SET);
}
if (filters && c != shot_select)
continue;
if (filters && raw_image)
pixel = raw_image + r * raw_width;
read_shorts(pixel, raw_width);
if (!filters && image && (row = r - top_margin) < height)
for (col = 0; col < width; col++)
image[row * width + col][c] = pixel[col + left_margin];
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
if (!filters)
free(pixel);
throw;
}
#endif
if (!filters)
{
maximum = 0xffff;
raw_color = 1;
free(pixel);
}
}
void CLASS unpacked_load_raw()
{
int row, col, bits = 0;
while (1 << ++bits < maximum)
;
read_shorts(raw_image, raw_width * raw_height);
if (maximum < 0xffff || load_flags)
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height &&
(unsigned)(col - left_margin) < width)
derror();
}
}
void CLASS unpacked_load_raw_reversed()
{
int row, col, bits = 0;
while (1 << ++bits < maximum)
;
for (row = raw_height - 1; row >= 0; row--)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
read_shorts(&raw_image[row * raw_width], raw_width);
for (col = 0; col < raw_width; col++)
if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height &&
(unsigned)(col - left_margin) < width)
derror();
}
}
void CLASS sinar_4shot_load_raw()
{
ushort *pixel;
unsigned shot, row, col, r, c;
if (raw_image)
{
shot = LIM(shot_select, 1, 4) - 1;
fseek(ifp, data_offset + shot * 4, SEEK_SET);
fseek(ifp, get4(), SEEK_SET);
unpacked_load_raw();
return;
}
pixel = (ushort *)calloc(raw_width, sizeof *pixel);
merror(pixel, "sinar_4shot_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (shot = 0; shot < 4; shot++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fseek(ifp, data_offset + shot * 4, SEEK_SET);
fseek(ifp, get4(), SEEK_SET);
for (row = 0; row < raw_height; row++)
{
read_shorts(pixel, raw_width);
if ((r = row - top_margin - (shot >> 1 & 1)) >= height)
continue;
for (col = 0; col < raw_width; col++)
{
if ((c = col - left_margin - (shot & 1)) >= width)
continue;
image[r * width + c][(row & 1) * 3 ^ (~col & 1)] = pixel[col];
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
mix_green = 1;
}
void CLASS imacon_full_load_raw()
{
int row, col;
if (!image)
return;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned short *buf = (unsigned short *)malloc(width * 3 * sizeof(unsigned short));
merror(buf, "imacon_full_load_raw");
#endif
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
read_shorts(buf, width * 3);
unsigned short(*rowp)[4] = &image[row * width];
for (col = 0; col < width; col++)
{
rowp[col][0] = buf[col * 3];
rowp[col][1] = buf[col * 3 + 1];
rowp[col][2] = buf[col * 3 + 2];
rowp[col][3] = 0;
}
#else
for (col = 0; col < width; col++)
read_shorts(image[row * width + col], 3);
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
free(buf);
#endif
}
void CLASS packed_load_raw()
{
int vbits = 0, bwide, rbits, bite, half, irow, row, col, val, i;
UINT64 bitbuf = 0;
bwide = raw_width * tiff_bps / 8;
bwide += bwide & load_flags >> 7;
rbits = bwide * 8 - raw_width * tiff_bps;
if (load_flags & 1)
bwide = bwide * 16 / 15;
bite = 8 + (load_flags & 24);
half = (raw_height + 1) >> 1;
for (irow = 0; irow < raw_height; irow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
row = irow;
if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4)
{
if (vbits = 0, tiff_compress)
fseek(ifp, data_offset - (-half * bwide & -2048), SEEK_SET);
else
{
fseek(ifp, 0, SEEK_END);
fseek(ifp, ftell(ifp) >> 3 << 2, SEEK_SET);
}
}
for (col = 0; col < raw_width; col++)
{
for (vbits -= tiff_bps; vbits < 0; vbits += bite)
{
bitbuf <<= bite;
for (i = 0; i < bite; i += 8)
bitbuf |= (unsigned)(fgetc(ifp) << i);
}
val = bitbuf << (64 - tiff_bps - vbits) >> (64 - tiff_bps);
RAW(row, col ^ (load_flags >> 6 & 1)) = val;
if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height + top_margin && col < width + left_margin)
derror();
}
vbits -= rbits;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
ushort raw_stride;
void CLASS parse_broadcom()
{
/* This structure is at offset 0xb0 from the 'BRCM' ident. */
struct
{
uint8_t umode[32];
uint16_t uwidth;
uint16_t uheight;
uint16_t padding_right;
uint16_t padding_down;
uint32_t unknown_block[6];
uint16_t transform;
uint16_t format;
uint8_t bayer_order;
uint8_t bayer_format;
} header;
header.bayer_order = 0;
fseek(ifp, 0xb0 - 0x20, SEEK_CUR);
fread(&header, 1, sizeof(header), ifp);
raw_stride = ((((((header.uwidth + header.padding_right) * 5) + 3) >> 2) + 0x1f) & (~0x1f));
raw_width = width = header.uwidth;
raw_height = height = header.uheight;
filters = 0x16161616; /* default Bayer order is 2, BGGR */
switch (header.bayer_order)
{
case 0: /* RGGB */
filters = 0x94949494;
break;
case 1: /* GBRG */
filters = 0x49494949;
break;
case 3: /* GRBG */
filters = 0x61616161;
break;
}
}
void CLASS broadcom_load_raw()
{
uchar *data, *dp;
int rev, row, col, c;
rev = 3 * (order == 0x4949);
data = (uchar *)malloc(raw_stride * 2);
merror(data, "broadcom_load_raw()");
for (row = 0; row < raw_height; row++)
{
if (fread(data + raw_stride, 1, raw_stride, ifp) < raw_stride)
derror();
FORC(raw_stride) data[c] = data[raw_stride + (c ^ rev)];
for (dp = data, col = 0; col < raw_width; dp += 5, col += 4)
FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3);
}
free(data);
}
#endif
void CLASS nokia_load_raw()
{
uchar *data, *dp;
int rev, dwide, row, col, c;
double sum[] = {0, 0};
rev = 3 * (order == 0x4949);
dwide = (raw_width * 5 + 1) / 4;
data = (uchar *)malloc(dwide * 2);
merror(data, "nokia_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread(data + dwide, 1, dwide, ifp) < dwide)
derror();
FORC(dwide) data[c] = data[dwide + (c ^ rev)];
for (dp = data, col = 0; col < raw_width; dp += 5, col += 4)
FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(data);
throw;
}
#endif
free(data);
maximum = 0x3ff;
if (strncmp(make, "OmniVision", 10))
return;
row = raw_height / 2;
FORC(width - 1)
{
sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1));
sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1));
}
if (sum[1] > sum[0])
filters = 0x4b4b4b4b;
}
void CLASS android_tight_load_raw()
{
uchar *data, *dp;
int bwide, row, col, c;
bwide = -(-5 * raw_width >> 5) << 3;
data = (uchar *)malloc(bwide);
merror(data, "android_tight_load_raw()");
for (row = 0; row < raw_height; row++)
{
if (fread(data, 1, bwide, ifp) < bwide)
derror();
for (dp = data, col = 0; col < raw_width; dp += 5, col += 4)
FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3);
}
free(data);
}
void CLASS android_loose_load_raw()
{
uchar *data, *dp;
int bwide, row, col, c;
UINT64 bitbuf = 0;
bwide = (raw_width + 5) / 6 << 3;
data = (uchar *)malloc(bwide);
merror(data, "android_loose_load_raw()");
for (row = 0; row < raw_height; row++)
{
if (fread(data, 1, bwide, ifp) < bwide)
derror();
for (dp = data, col = 0; col < raw_width; dp += 8, col += 6)
{
FORC(8) bitbuf = (bitbuf << 8) | dp[c ^ 7];
FORC(6) RAW(row, col + c) = (bitbuf >> c * 10) & 0x3ff;
}
}
free(data);
}
void CLASS canon_rmf_load_raw()
{
int row, col, bits, orow, ocol, c;
#ifdef LIBRAW_LIBRARY_BUILD
int *words = (int *)malloc(sizeof(int) * (raw_width / 3 + 1));
merror(words, "canon_rmf_load_raw");
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
fread(words, sizeof(int), raw_width / 3, ifp);
for (col = 0; col < raw_width - 2; col += 3)
{
bits = words[col / 3];
FORC3
{
orow = row;
if ((ocol = col + c - 4) < 0)
{
ocol += raw_width;
if ((orow -= 2) < 0)
orow += raw_height;
}
RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff];
}
}
#else
for (col = 0; col < raw_width - 2; col += 3)
{
bits = get4();
FORC3
{
orow = row;
if ((ocol = col + c - 4) < 0)
{
ocol += raw_width;
if ((orow -= 2) < 0)
orow += raw_height;
}
RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff];
}
}
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
free(words);
#endif
maximum = curve[0x3ff];
}
unsigned CLASS pana_bits(int nbits)
{
#ifndef LIBRAW_NOTHREADS
#define buf tls->pana_bits.buf
#define vbits tls->pana_bits.vbits
#else
static uchar buf[0x4000];
static int vbits;
#endif
int byte;
if (!nbits)
return vbits = 0;
if (!vbits)
{
fread(buf + load_flags, 1, 0x4000 - load_flags, ifp);
fread(buf, 1, load_flags, ifp);
}
vbits = (vbits - nbits) & 0x1ffff;
byte = vbits >> 3 ^ 0x3ff0;
return (buf[byte] | buf[byte + 1] << 8) >> (vbits & 7) & ~((~0u) << nbits);
#ifndef LIBRAW_NOTHREADS
#undef buf
#undef vbits
#endif
}
void CLASS panasonic_load_raw()
{
int row, col, i, j, sh = 0, pred[2], nonz[2];
pana_bits(0);
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
if ((i = col % 14) == 0)
pred[0] = pred[1] = nonz[0] = nonz[1] = 0;
if (i % 3 == 2)
sh = 4 >> (3 - pana_bits(2));
if (nonz[i & 1])
{
if ((j = pana_bits(8)))
{
if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4)
pred[i & 1] &= ~((~0u) << sh);
pred[i & 1] += j << sh;
}
}
else if ((nonz[i & 1] = pana_bits(8)) || i > 11)
pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4);
if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width && row < height)
derror();
}
}
}
void CLASS olympus_load_raw()
{
ushort huff[4096];
int row, col, nbits, sign, low, high, i, c, w, n, nw;
int acarry[2][3], *carry, pred, diff;
huff[n = 0] = 0xc0c;
for (i = 12; i--;)
FORC(2048 >> i) huff[++n] = (i + 1) << 8 | i;
fseek(ifp, 7, SEEK_CUR);
getbits(-1);
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
memset(acarry, 0, sizeof acarry);
for (col = 0; col < raw_width; col++)
{
carry = acarry[col & 1];
i = 2 * (carry[2] < 3);
for (nbits = 2 + i; (ushort)carry[0] >> (nbits + i); nbits++)
;
low = (sign = getbits(3)) & 3;
sign = sign << 29 >> 31;
if ((high = getbithuff(12, huff)) == 12)
high = getbits(16 - nbits) >> 1;
carry[0] = (high << nbits) | getbits(nbits);
diff = (carry[0] ^ sign) + carry[1];
carry[1] = (diff * 3 + carry[1]) >> 5;
carry[2] = carry[0] > 16 ? 0 : carry[2] + 1;
if (col >= width)
continue;
if (row < 2 && col < 2)
pred = 0;
else if (row < 2)
pred = RAW(row, col - 2);
else if (col < 2)
pred = RAW(row - 2, col);
else
{
w = RAW(row, col - 2);
n = RAW(row - 2, col);
nw = RAW(row - 2, col - 2);
if ((w < nw && nw < n) || (n < nw && nw < w))
{
if (ABS(w - nw) > 32 || ABS(n - nw) > 32)
pred = w + n - nw;
else
pred = (w + n) >> 1;
}
else
pred = ABS(w - nw) > ABS(n - nw) ? w : n;
}
if ((RAW(row, col) = pred + ((diff << 2) | low)) >> 12)
derror();
}
}
}
void CLASS minolta_rd175_load_raw()
{
uchar pixel[768];
unsigned irow, box, row, col;
for (irow = 0; irow < 1481; irow++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread(pixel, 1, 768, ifp) < 768)
derror();
box = irow / 82;
row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box - 12) * 2);
switch (irow)
{
case 1477:
case 1479:
continue;
case 1476:
row = 984;
break;
case 1480:
row = 985;
break;
case 1478:
row = 985;
box = 1;
}
if ((box < 12) && (box & 1))
{
for (col = 0; col < 1533; col++, row ^= 1)
if (col != 1)
RAW(row, col) = (col + 1) & 2 ? pixel[col / 2 - 1] + pixel[col / 2 + 1] : pixel[col / 2] << 1;
RAW(row, 1) = pixel[1] << 1;
RAW(row, 1533) = pixel[765] << 1;
}
else
for (col = row & 1; col < 1534; col += 2)
RAW(row, col) = pixel[col / 2] << 1;
}
maximum = 0xff << 1;
}
void CLASS quicktake_100_load_raw()
{
uchar pixel[484][644];
static const short gstep[16] = {-89, -60, -44, -32, -22, -15, -8, -2, 2, 8, 15, 22, 32, 44, 60, 89};
static const short rstep[6][4] = {{-3, -1, 1, 3}, {-5, -1, 1, 5}, {-8, -2, 2, 8},
{-13, -3, 3, 13}, {-19, -4, 4, 19}, {-28, -6, 6, 28}};
static const short t_curve[256] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,
46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68,
69, 70, 71, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 88, 90, 92, 94, 97, 99,
101, 103, 105, 107, 110, 112, 114, 116, 118, 120, 123, 125, 127, 129, 131, 134, 136, 138, 140, 142, 144, 147,
149, 151, 153, 155, 158, 160, 162, 164, 166, 168, 171, 173, 175, 177, 179, 181, 184, 186, 188, 190, 192, 195,
197, 199, 201, 203, 205, 208, 210, 212, 214, 216, 218, 221, 223, 226, 230, 235, 239, 244, 248, 252, 257, 261,
265, 270, 274, 278, 283, 287, 291, 296, 300, 305, 309, 313, 318, 322, 326, 331, 335, 339, 344, 348, 352, 357,
361, 365, 370, 374, 379, 383, 387, 392, 396, 400, 405, 409, 413, 418, 422, 426, 431, 435, 440, 444, 448, 453,
457, 461, 466, 470, 474, 479, 483, 487, 492, 496, 500, 508, 519, 531, 542, 553, 564, 575, 587, 598, 609, 620,
631, 643, 654, 665, 676, 687, 698, 710, 721, 732, 743, 754, 766, 777, 788, 799, 810, 822, 833, 844, 855, 866,
878, 889, 900, 911, 922, 933, 945, 956, 967, 978, 989, 1001, 1012, 1023};
int rb, row, col, sharp, val = 0;
getbits(-1);
memset(pixel, 0x80, sizeof pixel);
for (row = 2; row < height + 2; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 2 + (row & 1); col < width + 2; col += 2)
{
val = ((pixel[row - 1][col - 1] + 2 * pixel[row - 1][col + 1] + pixel[row][col - 2]) >> 2) + gstep[getbits(4)];
pixel[row][col] = val = LIM(val, 0, 255);
if (col < 4)
pixel[row][col - 2] = pixel[row + 1][~row & 1] = val;
if (row == 2)
pixel[row - 1][col + 1] = pixel[row - 1][col + 3] = val;
}
pixel[row][col] = val;
}
for (rb = 0; rb < 2; rb++)
for (row = 2 + rb; row < height + 2; row += 2)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 3 - (row & 1); col < width + 2; col += 2)
{
if (row < 4 || col < 4)
sharp = 2;
else
{
val = ABS(pixel[row - 2][col] - pixel[row][col - 2]) + ABS(pixel[row - 2][col] - pixel[row - 2][col - 2]) +
ABS(pixel[row][col - 2] - pixel[row - 2][col - 2]);
sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5;
}
val = ((pixel[row - 2][col] + pixel[row][col - 2]) >> 1) + rstep[sharp][getbits(2)];
pixel[row][col] = val = LIM(val, 0, 255);
if (row < 4)
pixel[row - 2][col + 2] = val;
if (col < 4)
pixel[row + 2][col - 2] = val;
}
}
for (row = 2; row < height + 2; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 3 - (row & 1); col < width + 2; col += 2)
{
val = ((pixel[row][col - 1] + (pixel[row][col] << 2) + pixel[row][col + 1]) >> 1) - 0x100;
pixel[row][col] = LIM(val, 0, 255);
}
}
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col++)
RAW(row, col) = t_curve[pixel[row + 2][col + 2]];
}
maximum = 0x3ff;
}
#define radc_token(tree) ((signed char)getbithuff(8, huff[tree]))
#define FORYX \
for (y = 1; y < 3; y++) \
for (x = col + 1; x >= col; x--)
#define PREDICTOR \
(c ? (buf[c][y - 1][x] + buf[c][y][x + 1]) / 2 : (buf[c][y - 1][x + 1] + 2 * buf[c][y - 1][x] + buf[c][y][x + 1]) / 4)
#ifdef __GNUC__
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
#pragma GCC optimize("no-aggressive-loop-optimizations")
#endif
#endif
void CLASS kodak_radc_load_raw()
{
static const signed char src[] = {
1, 1, 2, 3, 3, 4, 4, 2, 5, 7, 6, 5, 7, 6, 7, 8, 1, 0, 2, 1, 3, 3, 4, 4, 5, 2, 6, 7, 7, 6,
8, 5, 8, 8, 2, 1, 2, 3, 3, 0, 3, 2, 3, 4, 4, 6, 5, 5, 6, 7, 6, 8, 2, 0, 2, 1, 2, 3, 3, 2,
4, 4, 5, 6, 6, 7, 7, 5, 7, 8, 2, 1, 2, 4, 3, 0, 3, 2, 3, 3, 4, 7, 5, 5, 6, 6, 6, 8, 2, 3,
3, 1, 3, 2, 3, 4, 3, 5, 3, 6, 4, 7, 5, 0, 5, 8, 2, 3, 2, 6, 3, 0, 3, 1, 4, 4, 4, 5, 4, 7,
5, 2, 5, 8, 2, 4, 2, 7, 3, 3, 3, 6, 4, 1, 4, 2, 4, 5, 5, 0, 5, 8, 2, 6, 3, 1, 3, 3, 3, 5,
3, 7, 3, 8, 4, 0, 5, 2, 5, 4, 2, 0, 2, 1, 3, 2, 3, 3, 4, 4, 4, 5, 5, 6, 5, 7, 4, 8, 1, 0,
2, 2, 2, -2, 1, -3, 1, 3, 2, -17, 2, -5, 2, 5, 2, 17, 2, -7, 2, 2, 2, 9, 2, 18, 2, -18, 2, -9, 2, -2,
2, 7, 2, -28, 2, 28, 3, -49, 3, -9, 3, 9, 4, 49, 5, -79, 5, 79, 2, -1, 2, 13, 2, 26, 3, 39, 4, -16, 5, 55,
6, -37, 6, 76, 2, -26, 2, -13, 2, 1, 3, -39, 4, 16, 5, -55, 6, -76, 6, 37};
ushort huff[19][256];
int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val;
short last[3] = {16, 16, 16}, mul[3], buf[3][3][386];
static const ushort pt[] = {0, 0, 1280, 1344, 2320, 3616, 3328, 8000, 4095, 16383, 65535, 16383};
for (i = 2; i < 12; i += 2)
for (c = pt[i - 2]; c <= pt[i]; c++)
curve[c] = (float)(c - pt[i - 2]) / (pt[i] - pt[i - 2]) * (pt[i + 1] - pt[i - 1]) + pt[i - 1] + 0.5;
for (s = i = 0; i < sizeof src; i += 2)
FORC(256 >> src[i])
((ushort *)huff)[s++] = src[i] << 8 | (uchar)src[i + 1];
s = kodak_cbpp == 243 ? 2 : 3;
FORC(256) huff[18][c] = (8 - s) << 8 | c >> s << s | 1 << (s - 1);
getbits(-1);
for (i = 0; i < sizeof(buf) / sizeof(short); i++)
((short *)buf)[i] = 2048;
for (row = 0; row < height; row += 4)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
FORC3 mul[c] = getbits(6);
FORC3
{
val = ((0x1000000 / last[c] + 0x7ff) >> 12) * mul[c];
s = val > 65564 ? 10 : 12;
x = ~((~0u) << (s - 1));
val <<= 12 - s;
for (i = 0; i < sizeof(buf[0]) / sizeof(short); i++)
((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s;
last[c] = mul[c];
for (r = 0; r <= !c; r++)
{
buf[c][1][width / 2] = buf[c][2][width / 2] = mul[c] << 7;
for (tree = 1, col = width / 2; col > 0;)
{
if ((tree = radc_token(tree)))
{
col -= 2;
if (tree == 8)
FORYX buf[c][y][x] = (uchar)radc_token(18) * mul[c];
else
FORYX buf[c][y][x] = radc_token(tree + 10) * 16 + PREDICTOR;
}
else
do
{
nreps = (col > 2) ? radc_token(9) + 1 : 1;
for (rep = 0; rep < 8 && rep < nreps && col > 0; rep++)
{
col -= 2;
FORYX buf[c][y][x] = PREDICTOR;
if (rep & 1)
{
step = radc_token(10) << 4;
FORYX buf[c][y][x] += step;
}
}
} while (nreps == 9);
}
for (y = 0; y < 2; y++)
for (x = 0; x < width / 2; x++)
{
val = (buf[c][y + 1][x] << 4) / mul[c];
if (val < 0)
val = 0;
if (c)
RAW(row + y * 2 + c - 1, x * 2 + 2 - c) = val;
else
RAW(row + r * 2 + y, x * 2 + y) = val;
}
memcpy(buf[c][0] + !c, buf[c][2], sizeof buf[c][0] - 2 * !c);
}
}
for (y = row; y < row + 4; y++)
for (x = 0; x < width; x++)
if ((x + y) & 1)
{
r = x ? x - 1 : x + 1;
s = x + 1 < width ? x + 1 : x - 1;
val = (RAW(y, x) - 2048) * 2 + (RAW(y, r) + RAW(y, s)) / 2;
if (val < 0)
val = 0;
RAW(y, x) = val;
}
}
for (i = 0; i < height * width; i++)
raw_image[i] = curve[raw_image[i]];
maximum = 0x3fff;
}
#undef FORYX
#undef PREDICTOR
#ifdef NO_JPEG
void CLASS kodak_jpeg_load_raw() {}
void CLASS lossy_dng_load_raw() {}
#else
#ifndef LIBRAW_LIBRARY_BUILD
METHODDEF(boolean)
fill_input_buffer(j_decompress_ptr cinfo)
{
static uchar jpeg_buffer[4096];
size_t nbytes;
nbytes = fread(jpeg_buffer, 1, 4096, ifp);
swab(jpeg_buffer, jpeg_buffer, nbytes);
cinfo->src->next_input_byte = jpeg_buffer;
cinfo->src->bytes_in_buffer = nbytes;
return TRUE;
}
void CLASS kodak_jpeg_load_raw()
{
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
JSAMPARRAY buf;
JSAMPLE(*pixel)[3];
int row, col;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, ifp);
cinfo.src->fill_input_buffer = fill_input_buffer;
jpeg_read_header(&cinfo, TRUE);
jpeg_start_decompress(&cinfo);
if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3))
{
fprintf(stderr, _("%s: incorrect JPEG dimensions\n"), ifname);
jpeg_destroy_decompress(&cinfo);
longjmp(failure, 3);
}
buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, width * 3, 1);
while (cinfo.output_scanline < cinfo.output_height)
{
row = cinfo.output_scanline * 2;
jpeg_read_scanlines(&cinfo, buf, 1);
pixel = (JSAMPLE(*)[3])buf[0];
for (col = 0; col < width; col += 2)
{
RAW(row + 0, col + 0) = pixel[col + 0][1] << 1;
RAW(row + 1, col + 1) = pixel[col + 1][1] << 1;
RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0];
RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2];
}
}
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
maximum = 0xff << 1;
}
#else
struct jpegErrorManager
{
struct jpeg_error_mgr pub;
};
static void jpegErrorExit(j_common_ptr cinfo)
{
jpegErrorManager *myerr = (jpegErrorManager *)cinfo->err;
throw LIBRAW_EXCEPTION_DECODE_JPEG;
}
// LibRaw's Kodak_jpeg_load_raw
void CLASS kodak_jpeg_load_raw()
{
if (data_size < 1)
throw LIBRAW_EXCEPTION_DECODE_JPEG;
int row, col;
jpegErrorManager jerr;
struct jpeg_decompress_struct cinfo;
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = jpegErrorExit;
unsigned char *jpg_buf = (unsigned char *)malloc(data_size);
merror(jpg_buf, "kodak_jpeg_load_raw");
unsigned char *pixel_buf = (unsigned char *)malloc(width * 3);
jpeg_create_decompress(&cinfo);
merror(pixel_buf, "kodak_jpeg_load_raw");
fread(jpg_buf, data_size, 1, ifp);
swab((char *)jpg_buf, (char *)jpg_buf, data_size);
try
{
jpeg_mem_src(&cinfo, jpg_buf, data_size);
int rc = jpeg_read_header(&cinfo, TRUE);
if (rc != 1)
throw LIBRAW_EXCEPTION_DECODE_JPEG;
jpeg_start_decompress(&cinfo);
if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3))
{
throw LIBRAW_EXCEPTION_DECODE_JPEG;
}
unsigned char *buf[1];
buf[0] = pixel_buf;
while (cinfo.output_scanline < cinfo.output_height)
{
checkCancel();
row = cinfo.output_scanline * 2;
jpeg_read_scanlines(&cinfo, buf, 1);
unsigned char(*pixel)[3] = (unsigned char(*)[3])buf[0];
for (col = 0; col < width; col += 2)
{
RAW(row + 0, col + 0) = pixel[col + 0][1] << 1;
RAW(row + 1, col + 1) = pixel[col + 1][1] << 1;
RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0];
RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2];
}
}
}
catch (...)
{
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
free(jpg_buf);
free(pixel_buf);
throw;
}
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
free(jpg_buf);
free(pixel_buf);
maximum = 0xff << 1;
}
#endif
#ifndef LIBRAW_LIBRARY_BUILD
void CLASS gamma_curve(double pwr, double ts, int mode, int imax);
#endif
void CLASS lossy_dng_load_raw()
{
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
JSAMPARRAY buf;
JSAMPLE(*pixel)[3];
unsigned sorder = order, ntags, opcode, deg, i, j, c;
unsigned save = data_offset - 4, trow = 0, tcol = 0, row, col;
ushort cur[3][256];
double coeff[9], tot;
if (meta_offset)
{
fseek(ifp, meta_offset, SEEK_SET);
order = 0x4d4d;
ntags = get4();
while (ntags--)
{
opcode = get4();
get4();
get4();
if (opcode != 8)
{
fseek(ifp, get4(), SEEK_CUR);
continue;
}
fseek(ifp, 20, SEEK_CUR);
if ((c = get4()) > 2)
break;
fseek(ifp, 12, SEEK_CUR);
if ((deg = get4()) > 8)
break;
for (i = 0; i <= deg && i < 9; i++)
coeff[i] = getreal(12);
for (i = 0; i < 256; i++)
{
for (tot = j = 0; j <= deg; j++)
tot += coeff[j] * pow(i / 255.0, (int)j);
cur[c][i] = tot * 0xffff;
}
}
order = sorder;
}
else
{
gamma_curve(1 / 2.4, 12.92, 1, 255);
FORC3 memcpy(cur[c], curve, sizeof cur[0]);
}
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
while (trow < raw_height)
{
fseek(ifp, save += 4, SEEK_SET);
if (tile_length < INT_MAX)
fseek(ifp, get4(), SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
if (libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1)
{
jpeg_destroy_decompress(&cinfo);
throw LIBRAW_EXCEPTION_DECODE_JPEG;
}
#else
jpeg_stdio_src(&cinfo, ifp);
#endif
jpeg_read_header(&cinfo, TRUE);
jpeg_start_decompress(&cinfo);
buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, cinfo.output_width * 3, 1);
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
jpeg_read_scanlines(&cinfo, buf, 1);
pixel = (JSAMPLE(*)[3])buf[0];
for (col = 0; col < cinfo.output_width && tcol + col < width; col++)
{
FORC3 image[row * width + tcol + col][c] = cur[c][pixel[col][c]];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
jpeg_destroy_decompress(&cinfo);
throw;
}
#endif
jpeg_abort_decompress(&cinfo);
if ((tcol += tile_width) >= raw_width)
trow += tile_length + (tcol = 0);
}
jpeg_destroy_decompress(&cinfo);
maximum = 0xffff;
}
#endif
void CLASS kodak_dc120_load_raw()
{
static const int mul[4] = {162, 192, 187, 92};
static const int add[4] = {0, 636, 424, 212};
uchar pixel[848];
int row, shift, col;
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread(pixel, 1, 848, ifp) < 848)
derror();
shift = row * mul[row & 3] + add[row & 3];
for (col = 0; col < width; col++)
RAW(row, col) = (ushort)pixel[(col + shift) % 848];
}
maximum = 0xff;
}
void CLASS eight_bit_load_raw()
{
uchar *pixel;
unsigned row, col;
pixel = (uchar *)calloc(raw_width, sizeof *pixel);
merror(pixel, "eight_bit_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread(pixel, 1, raw_width, ifp) < raw_width)
derror();
for (col = 0; col < raw_width; col++)
RAW(row, col) = curve[pixel[col]];
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
maximum = curve[0xff];
}
void CLASS kodak_c330_load_raw()
{
uchar *pixel;
int row, col, y, cb, cr, rgb[3], c;
pixel = (uchar *)calloc(raw_width, 2 * sizeof *pixel);
merror(pixel, "kodak_c330_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread(pixel, raw_width, 2, ifp) < 2)
derror();
if (load_flags && (row & 31) == 31)
fseek(ifp, raw_width * 32, SEEK_CUR);
for (col = 0; col < width; col++)
{
y = pixel[col * 2];
cb = pixel[(col * 2 & -4) | 1] - 128;
cr = pixel[(col * 2 & -4) | 3] - 128;
rgb[1] = y - ((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
maximum = curve[0xff];
}
void CLASS kodak_c603_load_raw()
{
uchar *pixel;
int row, col, y, cb, cr, rgb[3], c;
pixel = (uchar *)calloc(raw_width, 3 * sizeof *pixel);
merror(pixel, "kodak_c603_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (~row & 1)
if (fread(pixel, raw_width, 3, ifp) < 3)
derror();
for (col = 0; col < width; col++)
{
y = pixel[width * 2 * (row & 1) + col];
cb = pixel[width + (col & -2)] - 128;
cr = pixel[width + (col & -2) + 1] - 128;
rgb[1] = y - ((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
maximum = curve[0xff];
}
void CLASS kodak_262_load_raw()
{
static const uchar kodak_tree[2][26] = {
{0, 1, 5, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{0, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}};
ushort *huff[2];
uchar *pixel;
int *strip, ns, c, row, col, chess, pi = 0, pi1, pi2, pred, val;
FORC(2) huff[c] = make_decoder(kodak_tree[c]);
ns = (raw_height + 63) >> 5;
pixel = (uchar *)malloc(raw_width * 32 + ns * 4);
merror(pixel, "kodak_262_load_raw()");
strip = (int *)(pixel + raw_width * 32);
order = 0x4d4d;
FORC(ns) strip[c] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if ((row & 31) == 0)
{
fseek(ifp, strip[row >> 5], SEEK_SET);
getbits(-1);
pi = 0;
}
for (col = 0; col < raw_width; col++)
{
chess = (row + col) & 1;
pi1 = chess ? pi - 2 : pi - raw_width - 1;
pi2 = chess ? pi - 2 * raw_width : pi - raw_width + 1;
if (col <= chess)
pi1 = -1;
if (pi1 < 0)
pi1 = pi2;
if (pi2 < 0)
pi2 = pi1;
if (pi1 < 0 && col > 1)
pi1 = pi2 = pi - 2;
pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1;
pixel[pi] = val = pred + ljpeg_diff(huff[chess]);
if (val >> 8)
derror();
val = curve[pixel[pi++]];
RAW(row, col) = val;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(pixel);
throw;
}
#endif
free(pixel);
FORC(2) free(huff[c]);
}
int CLASS kodak_65000_decode(short *out, int bsize)
{
uchar c, blen[768];
ushort raw[6];
INT64 bitbuf = 0;
int save, bits = 0, i, j, len, diff;
save = ftell(ifp);
bsize = (bsize + 3) & -4;
for (i = 0; i < bsize; i += 2)
{
c = fgetc(ifp);
if ((blen[i] = c & 15) > 12 || (blen[i + 1] = c >> 4) > 12)
{
fseek(ifp, save, SEEK_SET);
for (i = 0; i < bsize; i += 8)
{
read_shorts(raw, 6);
out[i] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12;
out[i + 1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12;
for (j = 0; j < 6; j++)
out[i + 2 + j] = raw[j] & 0xfff;
}
return 1;
}
}
if ((bsize & 7) == 4)
{
bitbuf = fgetc(ifp) << 8;
bitbuf += fgetc(ifp);
bits = 16;
}
for (i = 0; i < bsize; i++)
{
len = blen[i];
if (bits < len)
{
for (j = 0; j < 32; j += 8)
bitbuf += (INT64)fgetc(ifp) << (bits + (j ^ 8));
bits += 32;
}
diff = bitbuf & (0xffff >> (16 - len));
bitbuf >>= len;
bits -= len;
if ((diff & (1 << (len - 1))) == 0)
diff -= (1 << len) - 1;
out[i] = diff;
}
return 0;
}
void CLASS kodak_65000_load_raw()
{
short buf[256];
int row, col, len, pred[2], ret, i;
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col += 256)
{
pred[0] = pred[1] = 0;
len = MIN(256, width - col);
ret = kodak_65000_decode(buf, len);
for (i = 0; i < len; i++)
if ((RAW(row, col + i) = curve[ret ? buf[i] : (pred[i & 1] += buf[i])]) >> 12)
derror();
}
}
}
void CLASS kodak_ycbcr_load_raw()
{
short buf[384], *bp;
int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3];
ushort *ip;
if (!image)
return;
unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17) ? load_flags : 10;
for (row = 0; row < height; row += 2)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col += 128)
{
len = MIN(128, width - col);
kodak_65000_decode(buf, len * 3);
y[0][1] = y[1][1] = cb = cr = 0;
for (bp = buf, i = 0; i < len; i += 2, bp += 2)
{
cb += bp[4];
cr += bp[5];
rgb[1] = -((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
for (j = 0; j < 2; j++)
for (k = 0; k < 2; k++)
{
if ((y[j][k] = y[j][k ^ 1] + *bp++) >> bits)
derror();
ip = image[(row + j) * width + col + i + k];
FORC3 ip[c] = curve[LIM(y[j][k] + rgb[c], 0, 0xfff)];
}
}
}
}
}
void CLASS kodak_rgb_load_raw()
{
short buf[768], *bp;
int row, col, len, c, i, rgb[3], ret;
ushort *ip = image[0];
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col += 256)
{
len = MIN(256, width - col);
ret = kodak_65000_decode(buf, len * 3);
memset(rgb, 0, sizeof rgb);
for (bp = buf, i = 0; i < len; i++, ip += 4)
#ifdef LIBRAW_LIBRARY_BUILD
if (load_flags == 12)
{
FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++);
}
else
#endif
FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror();
}
}
}
void CLASS kodak_thumb_load_raw()
{
int row, col;
colors = thumb_misc >> 5;
for (row = 0; row < height; row++)
for (col = 0; col < width; col++)
read_shorts(image[row * width + col], colors);
maximum = (1 << (thumb_misc & 31)) - 1;
}
void CLASS sony_decrypt(unsigned *data, int len, int start, int key)
{
#ifndef LIBRAW_NOTHREADS
#define pad tls->sony_decrypt.pad
#define p tls->sony_decrypt.p
#else
static unsigned pad[128], p;
#endif
if (start)
{
for (p = 0; p < 4; p++)
pad[p] = key = key * 48828125 + 1;
pad[3] = pad[3] << 1 | (pad[0] ^ pad[2]) >> 31;
for (p = 4; p < 127; p++)
pad[p] = (pad[p - 4] ^ pad[p - 2]) << 1 | (pad[p - 3] ^ pad[p - 1]) >> 31;
for (p = 0; p < 127; p++)
pad[p] = htonl(pad[p]);
}
while (len--)
{
*data++ ^= pad[p & 127] = pad[(p + 1) & 127] ^ pad[(p + 65) & 127];
p++;
}
#ifndef LIBRAW_NOTHREADS
#undef pad
#undef p
#endif
}
void CLASS sony_load_raw()
{
uchar head[40];
ushort *pixel;
unsigned i, key, row, col;
fseek(ifp, 200896, SEEK_SET);
fseek(ifp, (unsigned)fgetc(ifp) * 4 - 1, SEEK_CUR);
order = 0x4d4d;
key = get4();
fseek(ifp, 164600, SEEK_SET);
fread(head, 1, 40, ifp);
sony_decrypt((unsigned *)head, 10, 1, key);
for (i = 26; i-- > 22;)
key = key << 8 | head[i];
fseek(ifp, data_offset, SEEK_SET);
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
pixel = raw_image + row * raw_width;
if (fread(pixel, 2, raw_width, ifp) < raw_width)
derror();
sony_decrypt((unsigned *)pixel, raw_width / 2, !row, key);
for (col = 0; col < raw_width; col++)
if ((pixel[col] = ntohs(pixel[col])) >> 14)
derror();
}
maximum = 0x3ff0;
}
void CLASS sony_arw_load_raw()
{
ushort huff[32770];
static const ushort tab[18] = {0xf11, 0xf10, 0xe0f, 0xd0e, 0xc0d, 0xb0c, 0xa0b, 0x90a, 0x809,
0x708, 0x607, 0x506, 0x405, 0x304, 0x303, 0x300, 0x202, 0x201};
int i, c, n, col, row, sum = 0;
huff[0] = 15;
for (n = i = 0; i < 18; i++)
FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i];
getbits(-1);
for (col = raw_width; col--;)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (row = 0; row < raw_height + 1; row += 2)
{
if (row == raw_height)
row = 1;
if ((sum += ljpeg_diff(huff)) >> 12)
derror();
if (row < height)
RAW(row, col) = sum;
}
}
}
void CLASS sony_arw2_load_raw()
{
uchar *data, *dp;
ushort pix[16];
int row, col, val, max, min, imax, imin, sh, bit, i;
data = (uchar *)malloc(raw_width + 1);
merror(data, "sony_arw2_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try
{
#endif
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fread(data, 1, raw_width, ifp);
for (dp = data, col = 0; col < raw_width - 30; dp += 16)
{
max = 0x7ff & (val = sget4(dp));
min = 0x7ff & val >> 11;
imax = 0x0f & val >> 22;
imin = 0x0f & val >> 26;
for (sh = 0; sh < 4 && 0x80 << sh <= max - min; sh++)
;
#ifdef LIBRAW_LIBRARY_BUILD
/* flag checks if outside of loop */
if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set
|| (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE))
{
for (bit = 30, i = 0; i < 16; i++)
if (i == imax)
pix[i] = max;
else if (i == imin)
pix[i] = min;
else
{
pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min;
if (pix[i] > 0x7ff)
pix[i] = 0x7ff;
bit += 7;
}
}
else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY)
{
for (bit = 30, i = 0; i < 16; i++)
if (i == imax)
pix[i] = max;
else if (i == imin)
pix[i] = min;
else
pix[i] = 0;
}
else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY)
{
for (bit = 30, i = 0; i < 16; i++)
if (i == imax)
pix[i] = 0;
else if (i == imin)
pix[i] = 0;
else
{
pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min;
if (pix[i] > 0x7ff)
pix[i] = 0x7ff;
bit += 7;
}
}
else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE)
{
for (bit = 30, i = 0; i < 16; i++)
if (i == imax)
pix[i] = 0;
else if (i == imin)
pix[i] = 0;
else
{
pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh);
if (pix[i] > 0x7ff)
pix[i] = 0x7ff;
bit += 7;
}
}
#else
/* unaltered dcraw processing */
for (bit = 30, i = 0; i < 16; i++)
if (i == imax)
pix[i] = max;
else if (i == imin)
pix[i] = min;
else
{
pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min;
if (pix[i] > 0x7ff)
pix[i] = 0x7ff;
bit += 7;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE)
{
for (i = 0; i < 16; i++, col += 2)
{
unsigned slope = pix[i] < 1001 ? 2 : curve[pix[i] << 1] - curve[(pix[i] << 1) - 2];
unsigned step = 1 << sh;
RAW(row, col) = curve[pix[i] << 1] > black + imgdata.params.sony_arw2_posterization_thr
? LIM(((slope * step * 1000) / (curve[pix[i] << 1] - black)), 0, 10000)
: 0;
}
}
else
{
for (i = 0; i < 16; i++, col += 2)
RAW(row, col) = curve[pix[i] << 1];
}
#else
for (i = 0; i < 16; i++, col += 2)
RAW(row, col) = curve[pix[i] << 1] >> 2;
#endif
col -= col & 1 ? 1 : 31;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
free(data);
throw;
}
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE)
maximum = 10000;
#endif
free(data);
}
void CLASS samsung_load_raw()
{
int row, col, c, i, dir, op[4], len[4];
order = 0x4949;
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fseek(ifp, strip_offset + row * 4, SEEK_SET);
fseek(ifp, data_offset + get4(), SEEK_SET);
ph1_bits(-1);
FORC4 len[c] = row < 2 ? 7 : 4;
for (col = 0; col < raw_width; col += 16)
{
dir = ph1_bits(1);
FORC4 op[c] = ph1_bits(2);
FORC4 switch (op[c])
{
case 3:
len[c] = ph1_bits(4);
break;
case 2:
len[c]--;
break;
case 1:
len[c]++;
}
for (c = 0; c < 16; c += 2)
{
i = len[((c & 1) << 1) | (c >> 3)];
RAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) +
(dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128);
if (c == 14)
c = -1;
}
}
}
for (row = 0; row < raw_height - 1; row += 2)
for (col = 0; col < raw_width - 1; col += 2)
SWAP(RAW(row, col + 1), RAW(row + 1, col));
}
void CLASS samsung2_load_raw()
{
static const ushort tab[14] = {0x304, 0x307, 0x206, 0x205, 0x403, 0x600, 0x709,
0x80a, 0x90b, 0xa0c, 0xa0d, 0x501, 0x408, 0x402};
ushort huff[1026], vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2];
int i, c, n, row, col, diff;
huff[0] = 10;
for (n = i = 0; i < 14; i++)
FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i];
getbits(-1);
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < raw_width; col++)
{
diff = ljpeg_diff(huff);
if (col < 2)
hpred[col] = vpred[row & 1][col] += diff;
else
hpred[col & 1] += diff;
RAW(row, col) = hpred[col & 1];
if (hpred[col & 1] >> tiff_bps)
derror();
}
}
}
void CLASS samsung3_load_raw()
{
int opt, init, mag, pmode, row, tab, col, pred, diff, i, c;
ushort lent[3][2], len[4], *prow[2];
order = 0x4949;
fseek(ifp, 9, SEEK_CUR);
opt = fgetc(ifp);
init = (get2(), get2());
for (row = 0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fseek(ifp, (data_offset - ftell(ifp)) & 15, SEEK_CUR);
ph1_bits(-1);
mag = 0;
pmode = 7;
FORC(6)((ushort *)lent)[c] = row < 2 ? 7 : 4;
prow[row & 1] = &RAW(row - 1, 1 - ((row & 1) << 1)); // green
prow[~row & 1] = &RAW(row - 2, 0); // red and blue
for (tab = 0; tab + 15 < raw_width; tab += 16)
{
if (~opt & 4 && !(tab & 63))
{
i = ph1_bits(2);
mag = i < 3 ? mag - '2' + "204"[i] : ph1_bits(12);
}
if (opt & 2)
pmode = 7 - 4 * ph1_bits(1);
else if (!ph1_bits(1))
pmode = ph1_bits(3);
if (opt & 1 || !ph1_bits(1))
{
FORC4 len[c] = ph1_bits(2);
FORC4
{
i = ((row & 1) << 1 | (c & 1)) % 3;
len[c] = len[c] < 3 ? lent[i][0] - '1' + "120"[len[c]] : ph1_bits(4);
lent[i][0] = lent[i][1];
lent[i][1] = len[c];
}
}
FORC(16)
{
col = tab + (((c & 7) << 1) ^ (c >> 3) ^ (row & 1));
pred =
(pmode == 7 || row < 2)
? (tab ? RAW(row, tab - 2 + (col & 1)) : init)
: (prow[col & 1][col - '4' + "0224468"[pmode]] + prow[col & 1][col - '4' + "0244668"[pmode]] + 1) >> 1;
diff = ph1_bits(i = len[c >> 2]);
if (diff >> (i - 1))
diff -= 1 << i;
diff = diff * (mag * 2 + 1) + mag;
RAW(row, col) = pred + diff;
}
}
}
}
#define HOLE(row) ((holes >> (((row)-raw_height) & 7)) & 1)
/* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */
void CLASS smal_decode_segment(unsigned seg[2][2], int holes)
{
uchar hist[3][13] = {{7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0},
{7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0},
{3, 3, 0, 0, 63, 47, 31, 15, 0}};
int low, high = 0xff, carry = 0, nbits = 8;
int pix, s, count, bin, next, i, sym[3];
uchar diff, pred[] = {0, 0};
ushort data = 0, range = 0;
fseek(ifp, seg[0][1] + 1, SEEK_SET);
getbits(-1);
if (seg[1][0] > raw_width * raw_height)
seg[1][0] = raw_width * raw_height;
for (pix = seg[0][0]; pix < seg[1][0]; pix++)
{
for (s = 0; s < 3; s++)
{
data = data << nbits | getbits(nbits);
if (carry < 0)
carry = (nbits += carry + 1) < 1 ? nbits - 1 : 0;
while (--nbits >= 0)
if ((data >> nbits & 0xff) == 0xff)
break;
if (nbits > 0)
data = ((data & ((1 << (nbits - 1)) - 1)) << 1) |
((data + (((data & (1 << (nbits - 1)))) << 1)) & ((~0u) << nbits));
if (nbits >= 0)
{
data += getbits(1);
carry = nbits - 8;
}
count = ((((data - range + 1) & 0xffff) << 2) - 1) / (high >> 4);
for (bin = 0; hist[s][bin + 5] > count; bin++)
;
low = hist[s][bin + 5] * (high >> 4) >> 2;
if (bin)
high = hist[s][bin + 4] * (high >> 4) >> 2;
high -= low;
for (nbits = 0; high << nbits < 128; nbits++)
;
range = (range + low) << nbits;
high <<= nbits;
next = hist[s][1];
if (++hist[s][2] > hist[s][3])
{
next = (next + 1) & hist[s][0];
hist[s][3] = (hist[s][next + 4] - hist[s][next + 5]) >> 2;
hist[s][2] = 1;
}
if (hist[s][hist[s][1] + 4] - hist[s][hist[s][1] + 5] > 1)
{
if (bin < hist[s][1])
for (i = bin; i < hist[s][1]; i++)
hist[s][i + 5]--;
else if (next <= bin)
for (i = hist[s][1]; i < bin; i++)
hist[s][i + 5]++;
}
hist[s][1] = next;
sym[s] = bin;
}
diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3);
if (sym[0] & 4)
diff = diff ? -diff : 0x80;
if (ftell(ifp) + 12 >= seg[1][1])
diff = 0;
#ifdef LIBRAW_LIBRARY_BUILD
if (pix >= raw_width * raw_height)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
raw_image[pix] = pred[pix & 1] += diff;
if (!(pix & 1) && HOLE(pix / raw_width))
pix += 2;
}
maximum = 0xff;
}
void CLASS smal_v6_load_raw()
{
unsigned seg[2][2];
fseek(ifp, 16, SEEK_SET);
seg[0][0] = 0;
seg[0][1] = get2();
seg[1][0] = raw_width * raw_height;
seg[1][1] = INT_MAX;
smal_decode_segment(seg, 0);
}
int CLASS median4(int *p)
{
int min, max, sum, i;
min = max = sum = p[0];
for (i = 1; i < 4; i++)
{
sum += p[i];
if (min > p[i])
min = p[i];
if (max < p[i])
max = p[i];
}
return (sum - min - max) >> 1;
}
void CLASS fill_holes(int holes)
{
int row, col, val[4];
for (row = 2; row < height - 2; row++)
{
if (!HOLE(row))
continue;
for (col = 1; col < width - 1; col += 4)
{
val[0] = RAW(row - 1, col - 1);
val[1] = RAW(row - 1, col + 1);
val[2] = RAW(row + 1, col - 1);
val[3] = RAW(row + 1, col + 1);
RAW(row, col) = median4(val);
}
for (col = 2; col < width - 2; col += 4)
if (HOLE(row - 2) || HOLE(row + 2))
RAW(row, col) = (RAW(row, col - 2) + RAW(row, col + 2)) >> 1;
else
{
val[0] = RAW(row, col - 2);
val[1] = RAW(row, col + 2);
val[2] = RAW(row - 2, col);
val[3] = RAW(row + 2, col);
RAW(row, col) = median4(val);
}
}
}
void CLASS smal_v9_load_raw()
{
unsigned seg[256][2], offset, nseg, holes, i;
fseek(ifp, 67, SEEK_SET);
offset = get4();
nseg = (uchar)fgetc(ifp);
fseek(ifp, offset, SEEK_SET);
for (i = 0; i < nseg * 2; i++)
((unsigned *)seg)[i] = get4() + data_offset * (i & 1);
fseek(ifp, 78, SEEK_SET);
holes = fgetc(ifp);
fseek(ifp, 88, SEEK_SET);
seg[nseg][0] = raw_height * raw_width;
seg[nseg][1] = get4() + data_offset;
for (i = 0; i < nseg; i++)
smal_decode_segment(seg + i, holes);
if (holes)
fill_holes(holes);
}
void CLASS redcine_load_raw()
{
#ifndef NO_JASPER
int c, row, col;
jas_stream_t *in;
jas_image_t *jimg;
jas_matrix_t *jmat;
jas_seqent_t *data;
ushort *img, *pix;
jas_init();
#ifndef LIBRAW_LIBRARY_BUILD
in = jas_stream_fopen(ifname, "rb");
#else
in = (jas_stream_t *)ifp->make_jas_stream();
if (!in)
throw LIBRAW_EXCEPTION_DECODE_JPEG2000;
#endif
jas_stream_seek(in, data_offset + 20, SEEK_SET);
jimg = jas_image_decode(in, -1, 0);
#ifndef LIBRAW_LIBRARY_BUILD
if (!jimg)
longjmp(failure, 3);
#else
if (!jimg)
{
jas_stream_close(in);
throw LIBRAW_EXCEPTION_DECODE_JPEG2000;
}
#endif
jmat = jas_matrix_create(height / 2, width / 2);
merror(jmat, "redcine_load_raw()");
img = (ushort *)calloc((height + 2), (width + 2) * 2);
merror(img, "redcine_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
bool fastexitflag = false;
try
{
#endif
FORC4
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
jas_image_readcmpt(jimg, c, 0, 0, width / 2, height / 2, jmat);
data = jas_matrix_getref(jmat, 0, 0);
for (row = c >> 1; row < height; row += 2)
for (col = c & 1; col < width; col += 2)
img[(row + 1) * (width + 2) + col + 1] = data[(row / 2) * (width / 2) + col / 2];
}
for (col = 1; col <= width; col++)
{
img[col] = img[2 * (width + 2) + col];
img[(height + 1) * (width + 2) + col] = img[(height - 1) * (width + 2) + col];
}
for (row = 0; row < height + 2; row++)
{
img[row * (width + 2)] = img[row * (width + 2) + 2];
img[(row + 1) * (width + 2) - 1] = img[(row + 1) * (width + 2) - 3];
}
for (row = 1; row <= height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
pix = img + row * (width + 2) + (col = 1 + (FC(row, 1) & 1));
for (; col <= width; col += 2, pix += 2)
{
c = (((pix[0] - 0x800) << 3) + pix[-(width + 2)] + pix[width + 2] + pix[-1] + pix[1]) >> 2;
pix[0] = LIM(c, 0, 4095);
}
}
for (row = 0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = 0; col < width; col++)
RAW(row, col) = curve[img[(row + 1) * (width + 2) + col + 1]];
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
fastexitflag = true;
}
#endif
free(img);
jas_matrix_destroy(jmat);
jas_image_destroy(jimg);
jas_stream_close(in);
#ifdef LIBRAW_LIBRARY_BUILD
if (fastexitflag)
throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK;
#endif
#endif
}
void CLASS crop_masked_pixels()
{
int row, col;
unsigned
#ifndef LIBRAW_LIBRARY_BUILD
r,
raw_pitch = raw_width * 2, c, m, mblack[8], zero, val;
#else
c,
m, zero, val;
#define mblack imgdata.color.black_stat
#endif
#ifndef LIBRAW_LIBRARY_BUILD
if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c)
phase_one_correct();
if (fuji_width)
{
for (row = 0; row < raw_height - top_margin * 2; row++)
{
for (col = 0; col < fuji_width << !fuji_layout; col++)
{
if (fuji_layout)
{
r = fuji_width - 1 - col + (row >> 1);
c = col + ((row + 1) >> 1);
}
else
{
r = fuji_width - 1 + row - (col >> 1);
c = row + ((col + 1) >> 1);
}
if (r < height && c < width)
BAYER(r, c) = RAW(row + top_margin, col + left_margin);
}
}
}
else
{
for (row = 0; row < height; row++)
for (col = 0; col < width; col++)
BAYER2(row, col) = RAW(row + top_margin, col + left_margin);
}
#endif
if (mask[0][3] > 0)
goto mask_set;
if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw)
{
mask[0][1] = mask[1][1] += 2;
mask[0][3] -= 2;
goto sides;
}
if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw ||
(load_raw == &CLASS eight_bit_load_raw && strncmp(model, "DC2", 3)) || load_raw == &CLASS kodak_262_load_raw ||
(load_raw == &CLASS packed_load_raw && (load_flags & 32)))
{
sides:
mask[0][0] = mask[1][0] = top_margin;
mask[0][2] = mask[1][2] = top_margin + height;
mask[0][3] += left_margin;
mask[1][1] += left_margin + width;
mask[1][3] += raw_width;
}
if (load_raw == &CLASS nokia_load_raw)
{
mask[0][2] = top_margin;
mask[0][3] = width;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (load_raw == &CLASS broadcom_load_raw)
{
mask[0][2] = top_margin;
mask[0][3] = width;
}
#endif
mask_set:
memset(mblack, 0, sizeof mblack);
for (zero = m = 0; m < 8; m++)
for (row = MAX(mask[m][0], 0); row < MIN(mask[m][2], raw_height); row++)
for (col = MAX(mask[m][1], 0); col < MIN(mask[m][3], raw_width); col++)
{
c = FC(row - top_margin, col - left_margin);
mblack[c] += val = raw_image[(row)*raw_pitch / 2 + (col)];
mblack[4 + c]++;
zero += !val;
}
if (load_raw == &CLASS canon_600_load_raw && width < raw_width)
{
black = (mblack[0] + mblack[1] + mblack[2] + mblack[3]) / (mblack[4] + mblack[5] + mblack[6] + mblack[7]) - 4;
#ifndef LIBRAW_LIBRARY_BUILD
canon_600_correct();
#endif
}
else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7])
{
FORC4 cblack[c] = mblack[c] / mblack[4 + c];
black = cblack[4] = cblack[5] = cblack[6] = 0;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
#undef mblack
#endif
void CLASS remove_zeroes()
{
unsigned row, col, tot, n, r, c;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 0, 2);
#endif
for (row = 0; row < height; row++)
for (col = 0; col < width; col++)
if (BAYER(row, col) == 0)
{
tot = n = 0;
for (r = row - 2; r <= row + 2; r++)
for (c = col - 2; c <= col + 2; c++)
if (r < height && c < width && FC(r, c) == FC(row, col) && BAYER(r, c))
tot += (n++, BAYER(r, c));
if (n)
BAYER(row, col) = tot / n;
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 1, 2);
#endif
}
static const uchar xlat[2][256] = {
{0xc1, 0xbf, 0x6d, 0x0d, 0x59, 0xc5, 0x13, 0x9d, 0x83, 0x61, 0x6b, 0x4f, 0xc7, 0x7f, 0x3d, 0x3d, 0x53, 0x59, 0xe3,
0xc7, 0xe9, 0x2f, 0x95, 0xa7, 0x95, 0x1f, 0xdf, 0x7f, 0x2b, 0x29, 0xc7, 0x0d, 0xdf, 0x07, 0xef, 0x71, 0x89, 0x3d,
0x13, 0x3d, 0x3b, 0x13, 0xfb, 0x0d, 0x89, 0xc1, 0x65, 0x1f, 0xb3, 0x0d, 0x6b, 0x29, 0xe3, 0xfb, 0xef, 0xa3, 0x6b,
0x47, 0x7f, 0x95, 0x35, 0xa7, 0x47, 0x4f, 0xc7, 0xf1, 0x59, 0x95, 0x35, 0x11, 0x29, 0x61, 0xf1, 0x3d, 0xb3, 0x2b,
0x0d, 0x43, 0x89, 0xc1, 0x9d, 0x9d, 0x89, 0x65, 0xf1, 0xe9, 0xdf, 0xbf, 0x3d, 0x7f, 0x53, 0x97, 0xe5, 0xe9, 0x95,
0x17, 0x1d, 0x3d, 0x8b, 0xfb, 0xc7, 0xe3, 0x67, 0xa7, 0x07, 0xf1, 0x71, 0xa7, 0x53, 0xb5, 0x29, 0x89, 0xe5, 0x2b,
0xa7, 0x17, 0x29, 0xe9, 0x4f, 0xc5, 0x65, 0x6d, 0x6b, 0xef, 0x0d, 0x89, 0x49, 0x2f, 0xb3, 0x43, 0x53, 0x65, 0x1d,
0x49, 0xa3, 0x13, 0x89, 0x59, 0xef, 0x6b, 0xef, 0x65, 0x1d, 0x0b, 0x59, 0x13, 0xe3, 0x4f, 0x9d, 0xb3, 0x29, 0x43,
0x2b, 0x07, 0x1d, 0x95, 0x59, 0x59, 0x47, 0xfb, 0xe5, 0xe9, 0x61, 0x47, 0x2f, 0x35, 0x7f, 0x17, 0x7f, 0xef, 0x7f,
0x95, 0x95, 0x71, 0xd3, 0xa3, 0x0b, 0x71, 0xa3, 0xad, 0x0b, 0x3b, 0xb5, 0xfb, 0xa3, 0xbf, 0x4f, 0x83, 0x1d, 0xad,
0xe9, 0x2f, 0x71, 0x65, 0xa3, 0xe5, 0x07, 0x35, 0x3d, 0x0d, 0xb5, 0xe9, 0xe5, 0x47, 0x3b, 0x9d, 0xef, 0x35, 0xa3,
0xbf, 0xb3, 0xdf, 0x53, 0xd3, 0x97, 0x53, 0x49, 0x71, 0x07, 0x35, 0x61, 0x71, 0x2f, 0x43, 0x2f, 0x11, 0xdf, 0x17,
0x97, 0xfb, 0x95, 0x3b, 0x7f, 0x6b, 0xd3, 0x25, 0xbf, 0xad, 0xc7, 0xc5, 0xc5, 0xb5, 0x8b, 0xef, 0x2f, 0xd3, 0x07,
0x6b, 0x25, 0x49, 0x95, 0x25, 0x49, 0x6d, 0x71, 0xc7},
{0xa7, 0xbc, 0xc9, 0xad, 0x91, 0xdf, 0x85, 0xe5, 0xd4, 0x78, 0xd5, 0x17, 0x46, 0x7c, 0x29, 0x4c, 0x4d, 0x03, 0xe9,
0x25, 0x68, 0x11, 0x86, 0xb3, 0xbd, 0xf7, 0x6f, 0x61, 0x22, 0xa2, 0x26, 0x34, 0x2a, 0xbe, 0x1e, 0x46, 0x14, 0x68,
0x9d, 0x44, 0x18, 0xc2, 0x40, 0xf4, 0x7e, 0x5f, 0x1b, 0xad, 0x0b, 0x94, 0xb6, 0x67, 0xb4, 0x0b, 0xe1, 0xea, 0x95,
0x9c, 0x66, 0xdc, 0xe7, 0x5d, 0x6c, 0x05, 0xda, 0xd5, 0xdf, 0x7a, 0xef, 0xf6, 0xdb, 0x1f, 0x82, 0x4c, 0xc0, 0x68,
0x47, 0xa1, 0xbd, 0xee, 0x39, 0x50, 0x56, 0x4a, 0xdd, 0xdf, 0xa5, 0xf8, 0xc6, 0xda, 0xca, 0x90, 0xca, 0x01, 0x42,
0x9d, 0x8b, 0x0c, 0x73, 0x43, 0x75, 0x05, 0x94, 0xde, 0x24, 0xb3, 0x80, 0x34, 0xe5, 0x2c, 0xdc, 0x9b, 0x3f, 0xca,
0x33, 0x45, 0xd0, 0xdb, 0x5f, 0xf5, 0x52, 0xc3, 0x21, 0xda, 0xe2, 0x22, 0x72, 0x6b, 0x3e, 0xd0, 0x5b, 0xa8, 0x87,
0x8c, 0x06, 0x5d, 0x0f, 0xdd, 0x09, 0x19, 0x93, 0xd0, 0xb9, 0xfc, 0x8b, 0x0f, 0x84, 0x60, 0x33, 0x1c, 0x9b, 0x45,
0xf1, 0xf0, 0xa3, 0x94, 0x3a, 0x12, 0x77, 0x33, 0x4d, 0x44, 0x78, 0x28, 0x3c, 0x9e, 0xfd, 0x65, 0x57, 0x16, 0x94,
0x6b, 0xfb, 0x59, 0xd0, 0xc8, 0x22, 0x36, 0xdb, 0xd2, 0x63, 0x98, 0x43, 0xa1, 0x04, 0x87, 0x86, 0xf7, 0xa6, 0x26,
0xbb, 0xd6, 0x59, 0x4d, 0xbf, 0x6a, 0x2e, 0xaa, 0x2b, 0xef, 0xe6, 0x78, 0xb6, 0x4e, 0xe0, 0x2f, 0xdc, 0x7c, 0xbe,
0x57, 0x19, 0x32, 0x7e, 0x2a, 0xd0, 0xb8, 0xba, 0x29, 0x00, 0x3c, 0x52, 0x7d, 0xa8, 0x49, 0x3b, 0x2d, 0xeb, 0x25,
0x49, 0xfa, 0xa3, 0xaa, 0x39, 0xa7, 0xc5, 0xa7, 0x50, 0x11, 0x36, 0xfb, 0xc6, 0x67, 0x4a, 0xf5, 0xa5, 0x12, 0x65,
0x7e, 0xb0, 0xdf, 0xaf, 0x4e, 0xb3, 0x61, 0x7f, 0x2f}};
void CLASS gamma_curve(double pwr, double ts, int mode, int imax)
{
int i;
double g[6], bnd[2] = {0, 0}, r;
g[0] = pwr;
g[1] = ts;
g[2] = g[3] = g[4] = 0;
bnd[g[1] >= 1] = 1;
if (g[1] && (g[1] - 1) * (g[0] - 1) <= 0)
{
for (i = 0; i < 48; i++)
{
g[2] = (bnd[0] + bnd[1]) / 2;
if (g[0])
bnd[(pow(g[2] / g[1], -g[0]) - 1) / g[0] - 1 / g[2] > -1] = g[2];
else
bnd[g[2] / exp(1 - 1 / g[2]) < g[1]] = g[2];
}
g[3] = g[2] / g[1];
if (g[0])
g[4] = g[2] * (1 / g[0] - 1);
}
if (g[0])
g[5] = 1 / (g[1] * SQR(g[3]) / 2 - g[4] * (1 - g[3]) + (1 - pow(g[3], 1 + g[0])) * (1 + g[4]) / (1 + g[0])) - 1;
else
g[5] = 1 / (g[1] * SQR(g[3]) / 2 + 1 - g[2] - g[3] - g[2] * g[3] * (log(g[3]) - 1)) - 1;
if (!mode--)
{
memcpy(gamm, g, sizeof gamm);
return;
}
for (i = 0; i < 0x10000; i++)
{
curve[i] = 0xffff;
if ((r = (double)i / imax) < 1)
curve[i] = 0x10000 *
(mode ? (r < g[3] ? r * g[1] : (g[0] ? pow(r, g[0]) * (1 + g[4]) - g[4] : log(r) * g[2] + 1))
: (r < g[2] ? r / g[1] : (g[0] ? pow((r + g[4]) / (1 + g[4]), 1 / g[0]) : exp((r - 1) / g[2]))));
}
}
void CLASS pseudoinverse(double (*in)[3], double (*out)[3], int size)
{
double work[3][6], num;
int i, j, k;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 6; j++)
work[i][j] = j == i + 3;
for (j = 0; j < 3; j++)
for (k = 0; k < size; k++)
work[i][j] += in[k][i] * in[k][j];
}
for (i = 0; i < 3; i++)
{
num = work[i][i];
for (j = 0; j < 6; j++)
work[i][j] /= num;
for (k = 0; k < 3; k++)
{
if (k == i)
continue;
num = work[k][i];
for (j = 0; j < 6; j++)
work[k][j] -= work[i][j] * num;
}
}
for (i = 0; i < size; i++)
for (j = 0; j < 3; j++)
for (out[i][j] = k = 0; k < 3; k++)
out[i][j] += work[j][k + 3] * in[i][k];
}
void CLASS cam_xyz_coeff(float _rgb_cam[3][4], double cam_xyz[4][3])
{
double cam_rgb[4][3], inverse[4][3], num;
int i, j, k;
for (i = 0; i < colors; i++) /* Multiply out XYZ colorspace */
for (j = 0; j < 3; j++)
for (cam_rgb[i][j] = k = 0; k < 3; k++)
cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j];
for (i = 0; i < colors; i++)
{ /* Normalize cam_rgb so that */
for (num = j = 0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */
num += cam_rgb[i][j];
if (num > 0.00001)
{
for (j = 0; j < 3; j++)
cam_rgb[i][j] /= num;
pre_mul[i] = 1 / num;
}
else
{
for (j = 0; j < 3; j++)
cam_rgb[i][j] = 0.0;
pre_mul[i] = 1.0;
}
}
pseudoinverse(cam_rgb, inverse, colors);
for (i = 0; i < 3; i++)
for (j = 0; j < colors; j++)
_rgb_cam[i][j] = inverse[j][i];
}
#ifdef COLORCHECK
void CLASS colorcheck()
{
#define NSQ 24
// Coordinates of the GretagMacbeth ColorChecker squares
// width, height, 1st_column, 1st_row
int cut[NSQ][4]; // you must set these
// ColorChecker Chart under 6500-kelvin illumination
static const double gmb_xyY[NSQ][3] = {{0.400, 0.350, 10.1}, // Dark Skin
{0.377, 0.345, 35.8}, // Light Skin
{0.247, 0.251, 19.3}, // Blue Sky
{0.337, 0.422, 13.3}, // Foliage
{0.265, 0.240, 24.3}, // Blue Flower
{0.261, 0.343, 43.1}, // Bluish Green
{0.506, 0.407, 30.1}, // Orange
{0.211, 0.175, 12.0}, // Purplish Blue
{0.453, 0.306, 19.8}, // Moderate Red
{0.285, 0.202, 6.6}, // Purple
{0.380, 0.489, 44.3}, // Yellow Green
{0.473, 0.438, 43.1}, // Orange Yellow
{0.187, 0.129, 6.1}, // Blue
{0.305, 0.478, 23.4}, // Green
{0.539, 0.313, 12.0}, // Red
{0.448, 0.470, 59.1}, // Yellow
{0.364, 0.233, 19.8}, // Magenta
{0.196, 0.252, 19.8}, // Cyan
{0.310, 0.316, 90.0}, // White
{0.310, 0.316, 59.1}, // Neutral 8
{0.310, 0.316, 36.2}, // Neutral 6.5
{0.310, 0.316, 19.8}, // Neutral 5
{0.310, 0.316, 9.0}, // Neutral 3.5
{0.310, 0.316, 3.1}}; // Black
double gmb_cam[NSQ][4], gmb_xyz[NSQ][3];
double inverse[NSQ][3], cam_xyz[4][3], balance[4], num;
int c, i, j, k, sq, row, col, pass, count[4];
memset(gmb_cam, 0, sizeof gmb_cam);
for (sq = 0; sq < NSQ; sq++)
{
FORCC count[c] = 0;
for (row = cut[sq][3]; row < cut[sq][3] + cut[sq][1]; row++)
for (col = cut[sq][2]; col < cut[sq][2] + cut[sq][0]; col++)
{
c = FC(row, col);
if (c >= colors)
c -= 2;
gmb_cam[sq][c] += BAYER2(row, col);
BAYER2(row, col) = black + (BAYER2(row, col) - black) / 2;
count[c]++;
}
FORCC gmb_cam[sq][c] = gmb_cam[sq][c] / count[c] - black;
gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1];
gmb_xyz[sq][1] = gmb_xyY[sq][2];
gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1];
}
pseudoinverse(gmb_xyz, inverse, NSQ);
for (pass = 0; pass < 2; pass++)
{
for (raw_color = i = 0; i < colors; i++)
for (j = 0; j < 3; j++)
for (cam_xyz[i][j] = k = 0; k < NSQ; k++)
cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j];
cam_xyz_coeff(rgb_cam, cam_xyz);
FORCC balance[c] = pre_mul[c] * gmb_cam[20][c];
for (sq = 0; sq < NSQ; sq++)
FORCC gmb_cam[sq][c] *= balance[c];
}
if (verbose)
{
printf(" { \"%s %s\", %d,\n\t{", make, model, black);
num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]);
FORCC for (j = 0; j < 3; j++) printf("%c%d", (c | j) ? ',' : ' ', (int)(cam_xyz[c][j] * num + 0.5));
puts(" } },");
}
#undef NSQ
}
#endif
void CLASS hat_transform(float *temp, float *base, int st, int size, int sc)
{
int i;
for (i = 0; i < sc; i++)
temp[i] = 2 * base[st * i] + base[st * (sc - i)] + base[st * (i + sc)];
for (; i + sc < size; i++)
temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (i + sc)];
for (; i < size; i++)
temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (2 * size - 2 - (i + sc))];
}
#if !defined(LIBRAW_USE_OPENMP)
void CLASS wavelet_denoise()
{
float *fimg = 0, *temp, thold, mul[2], avg, diff;
int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2];
ushort *window[4];
static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044};
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Wavelet denoising...\n"));
#endif
while (maximum << scale < 0x10000)
scale++;
maximum <<= --scale;
black <<= scale;
FORC4 cblack[c] <<= scale;
if ((size = iheight * iwidth) < 0x15550000)
fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg);
merror(fimg, "wavelet_denoise()");
temp = fimg + size * 3;
if ((nc = colors) == 3 && filters)
nc++;
FORC(nc)
{ /* denoise R,G1,B,G3 individually */
for (i = 0; i < size; i++)
fimg[i] = 256 * sqrt((double)(image[i][c] << scale));
for (hpass = lev = 0; lev < 5; lev++)
{
lpass = size * ((lev & 1) + 1);
for (row = 0; row < iheight; row++)
{
hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev);
for (col = 0; col < iwidth; col++)
fimg[lpass + row * iwidth + col] = temp[col] * 0.25;
}
for (col = 0; col < iwidth; col++)
{
hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev);
for (row = 0; row < iheight; row++)
fimg[lpass + row * iwidth + col] = temp[row] * 0.25;
}
thold = threshold * noise[lev];
for (i = 0; i < size; i++)
{
fimg[hpass + i] -= fimg[lpass + i];
if (fimg[hpass + i] < -thold)
fimg[hpass + i] += thold;
else if (fimg[hpass + i] > thold)
fimg[hpass + i] -= thold;
else
fimg[hpass + i] = 0;
if (hpass)
fimg[i] += fimg[hpass + i];
}
hpass = lpass;
}
for (i = 0; i < size; i++)
image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000);
}
if (filters && colors == 3)
{ /* pull G1 and G3 closer together */
for (row = 0; row < 2; row++)
{
mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1];
blk[row] = cblack[FC(row, 0) | 1];
}
for (i = 0; i < 4; i++)
window[i] = (ushort *)fimg + width * i;
for (wlast = -1, row = 1; row < height - 1; row++)
{
while (wlast < row + 1)
{
for (wlast++, i = 0; i < 4; i++)
window[(i + 3) & 3] = window[i];
for (col = FC(wlast, 1) & 1; col < width; col += 2)
window[2][col] = BAYER(wlast, col);
}
thold = threshold / 512;
for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2)
{
avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) *
mul[row & 1] +
(window[1][col] + blk[row & 1]) * 0.5;
avg = avg < 0 ? 0 : sqrt(avg);
diff = sqrt((double)BAYER(row, col)) - avg;
if (diff < -thold)
diff += thold;
else if (diff > thold)
diff -= thold;
else
diff = 0;
BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5);
}
}
}
free(fimg);
}
#else /* LIBRAW_USE_OPENMP */
void CLASS wavelet_denoise()
{
float *fimg = 0, *temp, thold, mul[2], avg, diff;
int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2];
ushort *window[4];
static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044};
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Wavelet denoising...\n"));
#endif
while (maximum << scale < 0x10000)
scale++;
maximum <<= --scale;
black <<= scale;
FORC4 cblack[c] <<= scale;
if ((size = iheight * iwidth) < 0x15550000)
fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg);
merror(fimg, "wavelet_denoise()");
temp = fimg + size * 3;
if ((nc = colors) == 3 && filters)
nc++;
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp parallel default(shared) private(i, col, row, thold, lev, lpass, hpass, temp, c) firstprivate(scale, size)
#endif
{
temp = (float *)malloc((iheight + iwidth) * sizeof *fimg);
FORC(nc)
{ /* denoise R,G1,B,G3 individually */
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (i = 0; i < size; i++)
fimg[i] = 256 * sqrt((double)(image[i][c] << scale));
for (hpass = lev = 0; lev < 5; lev++)
{
lpass = size * ((lev & 1) + 1);
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (row = 0; row < iheight; row++)
{
hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev);
for (col = 0; col < iwidth; col++)
fimg[lpass + row * iwidth + col] = temp[col] * 0.25;
}
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (col = 0; col < iwidth; col++)
{
hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev);
for (row = 0; row < iheight; row++)
fimg[lpass + row * iwidth + col] = temp[row] * 0.25;
}
thold = threshold * noise[lev];
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (i = 0; i < size; i++)
{
fimg[hpass + i] -= fimg[lpass + i];
if (fimg[hpass + i] < -thold)
fimg[hpass + i] += thold;
else if (fimg[hpass + i] > thold)
fimg[hpass + i] -= thold;
else
fimg[hpass + i] = 0;
if (hpass)
fimg[i] += fimg[hpass + i];
}
hpass = lpass;
}
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (i = 0; i < size; i++)
image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000);
}
free(temp);
} /* end omp parallel */
/* the following loops are hard to parallize, no idea yes,
* problem is wlast which is carrying dependency
* second part should be easyer, but did not yet get it right.
*/
if (filters && colors == 3)
{ /* pull G1 and G3 closer together */
for (row = 0; row < 2; row++)
{
mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1];
blk[row] = cblack[FC(row, 0) | 1];
}
for (i = 0; i < 4; i++)
window[i] = (ushort *)fimg + width * i;
for (wlast = -1, row = 1; row < height - 1; row++)
{
while (wlast < row + 1)
{
for (wlast++, i = 0; i < 4; i++)
window[(i + 3) & 3] = window[i];
for (col = FC(wlast, 1) & 1; col < width; col += 2)
window[2][col] = BAYER(wlast, col);
}
thold = threshold / 512;
for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2)
{
avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) *
mul[row & 1] +
(window[1][col] + blk[row & 1]) * 0.5;
avg = avg < 0 ? 0 : sqrt(avg);
diff = sqrt((double)BAYER(row, col)) - avg;
if (diff < -thold)
diff += thold;
else if (diff > thold)
diff -= thold;
else
diff = 0;
BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5);
}
}
}
free(fimg);
}
#endif
// green equilibration
void CLASS green_matching()
{
int i, j;
double m1, m2, c1, c2;
int o1_1, o1_2, o1_3, o1_4;
int o2_1, o2_2, o2_3, o2_4;
ushort(*img)[4];
const int margin = 3;
int oj = 2, oi = 2;
float f;
const float thr = 0.01f;
if (half_size || shrink)
return;
if (FC(oj, oi) != 3)
oj++;
if (FC(oj, oi) != 3)
oi++;
if (FC(oj, oi) != 3)
oj--;
img = (ushort(*)[4])calloc(height * width, sizeof *image);
merror(img, "green_matching()");
memcpy(img, image, height * width * sizeof *image);
for (j = oj; j < height - margin; j += 2)
for (i = oi; i < width - margin; i += 2)
{
o1_1 = img[(j - 1) * width + i - 1][1];
o1_2 = img[(j - 1) * width + i + 1][1];
o1_3 = img[(j + 1) * width + i - 1][1];
o1_4 = img[(j + 1) * width + i + 1][1];
o2_1 = img[(j - 2) * width + i][3];
o2_2 = img[(j + 2) * width + i][3];
o2_3 = img[j * width + i - 2][3];
o2_4 = img[j * width + i + 2][3];
m1 = (o1_1 + o1_2 + o1_3 + o1_4) / 4.0;
m2 = (o2_1 + o2_2 + o2_3 + o2_4) / 4.0;
c1 = (abs(o1_1 - o1_2) + abs(o1_1 - o1_3) + abs(o1_1 - o1_4) + abs(o1_2 - o1_3) + abs(o1_3 - o1_4) +
abs(o1_2 - o1_4)) /
6.0;
c2 = (abs(o2_1 - o2_2) + abs(o2_1 - o2_3) + abs(o2_1 - o2_4) + abs(o2_2 - o2_3) + abs(o2_3 - o2_4) +
abs(o2_2 - o2_4)) /
6.0;
if ((img[j * width + i][3] < maximum * 0.95) && (c1 < maximum * thr) && (c2 < maximum * thr))
{
f = image[j * width + i][3] * m1 / m2;
image[j * width + i][3] = f > 0xffff ? 0xffff : f;
}
}
free(img);
}
void CLASS scale_colors()
{
unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8];
int val, dark, sat;
double dsum[8], dmin, dmax;
float scale_mul[4], fr, fc;
ushort *img = 0, *pix;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 0, 2);
#endif
if (user_mul[0])
memcpy(pre_mul, user_mul, sizeof pre_mul);
if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1))
{
memset(dsum, 0, sizeof dsum);
bottom = MIN(greybox[1] + greybox[3], height);
right = MIN(greybox[0] + greybox[2], width);
for (row = greybox[1]; row < bottom; row += 8)
for (col = greybox[0]; col < right; col += 8)
{
memset(sum, 0, sizeof sum);
for (y = row; y < row + 8 && y < bottom; y++)
for (x = col; x < col + 8 && x < right; x++)
FORC4
{
if (filters)
{
c = fcol(y, x);
val = BAYER2(y, x);
}
else
val = image[y * width + x][c];
if (val > maximum - 25)
goto skip_block;
if ((val -= cblack[c]) < 0)
val = 0;
sum[c] += val;
sum[c + 4]++;
if (filters)
break;
}
FORC(8) dsum[c] += sum[c];
skip_block:;
}
FORC4 if (dsum[c]) pre_mul[c] = dsum[c + 4] / dsum[c];
}
if (use_camera_wb && cam_mul[0] != -1)
{
memset(sum, 0, sizeof sum);
for (row = 0; row < 8; row++)
for (col = 0; col < 8; col++)
{
c = FC(row, col);
if ((val = white[row][col] - cblack[c]) > 0)
sum[c] += val;
sum[c + 4]++;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (load_raw == &LibRaw::nikon_load_sraw)
{
// Nikon sRAW: camera WB already applied:
pre_mul[0] = pre_mul[1] = pre_mul[2] = pre_mul[3] = 1.0;
}
else
#endif
if (sum[0] && sum[1] && sum[2] && sum[3])
FORC4 pre_mul[c] = (float)sum[c + 4] / sum[c];
else if (cam_mul[0] && cam_mul[2])
memcpy(pre_mul, cam_mul, sizeof pre_mul);
else
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB;
#endif
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("%s: Cannot use camera white balance.\n"), ifname);
#endif
}
}
#ifdef LIBRAW_LIBRARY_BUILD
// Nikon sRAW, daylight
if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f &&
cam_mul[1] > 0.001f && cam_mul[2] > 0.001f)
{
for (c = 0; c < 3; c++)
pre_mul[c] /= cam_mul[c];
}
#endif
if (pre_mul[1] == 0)
pre_mul[1] = 1;
if (pre_mul[3] == 0)
pre_mul[3] = colors < 4 ? pre_mul[1] : 1;
dark = black;
sat = maximum;
if (threshold)
wavelet_denoise();
maximum -= black;
for (dmin = DBL_MAX, dmax = c = 0; c < 4; c++)
{
if (dmin > pre_mul[c])
dmin = pre_mul[c];
if (dmax < pre_mul[c])
dmax = pre_mul[c];
}
if (!highlight)
dmax = dmin;
FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum;
#ifdef DCRAW_VERBOSE
if (verbose)
{
fprintf(stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat);
FORC4 fprintf(stderr, " %f", pre_mul[c]);
fputc('\n', stderr);
}
#endif
if (filters > 1000 && (cblack[4] + 1) / 2 == 1 && (cblack[5] + 1) / 2 == 1)
{
FORC4 cblack[FC(c / 2, c % 2)] += cblack[6 + c / 2 % cblack[4] * cblack[5] + c % 2 % cblack[5]];
cblack[4] = cblack[5] = 0;
}
size = iheight * iwidth;
#ifdef LIBRAW_LIBRARY_BUILD
scale_colors_loop(scale_mul);
#else
for (i = 0; i < size * 4; i++)
{
if (!(val = ((ushort *)image)[i]))
continue;
if (cblack[4] && cblack[5])
val -= cblack[6 + i / 4 / iwidth % cblack[4] * cblack[5] + i / 4 % iwidth % cblack[5]];
val -= cblack[i & 3];
val *= scale_mul[i & 3];
((ushort *)image)[i] = CLIP(val);
}
#endif
if ((aber[0] != 1 || aber[2] != 1) && colors == 3)
{
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Correcting chromatic aberration...\n"));
#endif
for (c = 0; c < 4; c += 2)
{
if (aber[c] == 1)
continue;
img = (ushort *)malloc(size * sizeof *img);
merror(img, "scale_colors()");
for (i = 0; i < size; i++)
img[i] = image[i][c];
for (row = 0; row < iheight; row++)
{
ur = fr = (row - iheight * 0.5) * aber[c] + iheight * 0.5;
if (ur > iheight - 2)
continue;
fr -= ur;
for (col = 0; col < iwidth; col++)
{
uc = fc = (col - iwidth * 0.5) * aber[c] + iwidth * 0.5;
if (uc > iwidth - 2)
continue;
fc -= uc;
pix = img + ur * iwidth + uc;
image[row * iwidth + col][c] =
(pix[0] * (1 - fc) + pix[1] * fc) * (1 - fr) + (pix[iwidth] * (1 - fc) + pix[iwidth + 1] * fc) * fr;
}
}
free(img);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 1, 2);
#endif
}
void CLASS pre_interpolate()
{
ushort(*img)[4];
int row, col, c;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 0, 2);
#endif
if (shrink)
{
if (half_size)
{
height = iheight;
width = iwidth;
if (filters == 9)
{
for (row = 0; row < 3; row++)
for (col = 1; col < 4; col++)
if (!(image[row * width + col][0] | image[row * width + col][2]))
goto break2;
break2:
for (; row < height; row += 3)
for (col = (col - 1) % 3 + 1; col < width - 1; col += 3)
{
img = image + row * width + col;
for (c = 0; c < 3; c += 2)
img[0][c] = (img[-1][c] + img[1][c]) >> 1;
}
}
}
else
{
img = (ushort(*)[4])calloc(height, width * sizeof *img);
merror(img, "pre_interpolate()");
for (row = 0; row < height; row++)
for (col = 0; col < width; col++)
{
c = fcol(row, col);
img[row * width + col][c] = image[(row >> 1) * iwidth + (col >> 1)][c];
}
free(image);
image = img;
shrink = 0;
}
}
if (filters > 1000 && colors == 3)
{
mix_green = four_color_rgb ^ half_size;
if (four_color_rgb | half_size)
colors++;
else
{
for (row = FC(1, 0) >> 1; row < height; row += 2)
for (col = FC(row, 1) & 1; col < width; col += 2)
image[row * width + col][1] = image[row * width + col][3];
filters &= ~((filters & 0x55555555) << 1);
}
}
if (half_size)
filters = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 1, 2);
#endif
}
void CLASS border_interpolate(int border)
{
unsigned row, col, y, x, f, c, sum[8];
for (row = 0; row < height; row++)
for (col = 0; col < width; col++)
{
if (col == border && row >= border && row < height - border)
col = width - border;
memset(sum, 0, sizeof sum);
for (y = row - 1; y != row + 2; y++)
for (x = col - 1; x != col + 2; x++)
if (y < height && x < width)
{
f = fcol(y, x);
sum[f] += image[y * width + x][f];
sum[f + 4]++;
}
f = fcol(row, col);
FORCC if (c != f && sum[c + 4]) image[row * width + col][c] = sum[c] / sum[c + 4];
}
}
void CLASS lin_interpolate_loop(int code[16][16][32], int size)
{
int row;
for (row = 1; row < height - 1; row++)
{
int col, *ip;
ushort *pix;
for (col = 1; col < width - 1; col++)
{
int i;
int sum[4];
pix = image[row * width + col];
ip = code[row % size][col % size];
memset(sum, 0, sizeof sum);
for (i = *ip++; i--; ip += 3)
sum[ip[2]] += pix[ip[0]] << ip[1];
for (i = colors; --i; ip += 2)
pix[ip[0]] = sum[ip[0]] * ip[1] >> 8;
}
}
}
void CLASS lin_interpolate()
{
int code[16][16][32], size = 16, *ip, sum[4];
int f, c, x, y, row, col, shift, color;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Bilinear interpolation...\n"));
#endif
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3);
#endif
if (filters == 9)
size = 6;
border_interpolate(1);
for (row = 0; row < size; row++)
for (col = 0; col < size; col++)
{
ip = code[row][col] + 1;
f = fcol(row, col);
memset(sum, 0, sizeof sum);
for (y = -1; y <= 1; y++)
for (x = -1; x <= 1; x++)
{
shift = (y == 0) + (x == 0);
color = fcol(row + y, col + x);
if (color == f)
continue;
*ip++ = (width * y + x) * 4 + color;
*ip++ = shift;
*ip++ = color;
sum[color] += 1 << shift;
}
code[row][col][0] = (ip - code[row][col]) / 3;
FORCC
if (c != f)
{
*ip++ = c;
*ip++ = sum[c] > 0 ? 256 / sum[c] : 0;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3);
#endif
lin_interpolate_loop(code, size);
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3);
#endif
}
/*
This algorithm is officially called:
"Interpolation using a Threshold-based variable number of gradients"
described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html
I've extended the basic idea to work with non-Bayer filter arrays.
Gradients are numbered clockwise from NW=0 to W=7.
*/
void CLASS vng_interpolate()
{
static const signed char *cp,
terms[] = {-2, -2, +0, -1, 0, 0x01, -2, -2, +0, +0, 1, 0x01, -2, -1, -1, +0, 0, 0x01, -2, -1, +0, -1, 0, 0x02,
-2, -1, +0, +0, 0, 0x03, -2, -1, +0, +1, 1, 0x01, -2, +0, +0, -1, 0, 0x06, -2, +0, +0, +0, 1, 0x02,
-2, +0, +0, +1, 0, 0x03, -2, +1, -1, +0, 0, 0x04, -2, +1, +0, -1, 1, 0x04, -2, +1, +0, +0, 0, 0x06,
-2, +1, +0, +1, 0, 0x02, -2, +2, +0, +0, 1, 0x04, -2, +2, +0, +1, 0, 0x04, -1, -2, -1, +0, 0, -128,
-1, -2, +0, -1, 0, 0x01, -1, -2, +1, -1, 0, 0x01, -1, -2, +1, +0, 1, 0x01, -1, -1, -1, +1, 0, -120,
-1, -1, +1, -2, 0, 0x40, -1, -1, +1, -1, 0, 0x22, -1, -1, +1, +0, 0, 0x33, -1, -1, +1, +1, 1, 0x11,
-1, +0, -1, +2, 0, 0x08, -1, +0, +0, -1, 0, 0x44, -1, +0, +0, +1, 0, 0x11, -1, +0, +1, -2, 1, 0x40,
-1, +0, +1, -1, 0, 0x66, -1, +0, +1, +0, 1, 0x22, -1, +0, +1, +1, 0, 0x33, -1, +0, +1, +2, 1, 0x10,
-1, +1, +1, -1, 1, 0x44, -1, +1, +1, +0, 0, 0x66, -1, +1, +1, +1, 0, 0x22, -1, +1, +1, +2, 0, 0x10,
-1, +2, +0, +1, 0, 0x04, -1, +2, +1, +0, 1, 0x04, -1, +2, +1, +1, 0, 0x04, +0, -2, +0, +0, 1, -128,
+0, -1, +0, +1, 1, -120, +0, -1, +1, -2, 0, 0x40, +0, -1, +1, +0, 0, 0x11, +0, -1, +2, -2, 0, 0x40,
+0, -1, +2, -1, 0, 0x20, +0, -1, +2, +0, 0, 0x30, +0, -1, +2, +1, 1, 0x10, +0, +0, +0, +2, 1, 0x08,
+0, +0, +2, -2, 1, 0x40, +0, +0, +2, -1, 0, 0x60, +0, +0, +2, +0, 1, 0x20, +0, +0, +2, +1, 0, 0x30,
+0, +0, +2, +2, 1, 0x10, +0, +1, +1, +0, 0, 0x44, +0, +1, +1, +2, 0, 0x10, +0, +1, +2, -1, 1, 0x40,
+0, +1, +2, +0, 0, 0x60, +0, +1, +2, +1, 0, 0x20, +0, +1, +2, +2, 0, 0x10, +1, -2, +1, +0, 0, -128,
+1, -1, +1, +1, 0, -120, +1, +0, +1, +2, 0, 0x08, +1, +0, +2, -1, 0, 0x40, +1, +0, +2, +1, 0, 0x10},
chood[] = {-1, -1, -1, 0, -1, +1, 0, +1, +1, +1, +1, 0, +1, -1, 0, -1};
ushort(*brow[5])[4], *pix;
int prow = 8, pcol = 2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4];
int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag;
int g, diff, thold, num, c;
lin_interpolate();
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("VNG interpolation...\n"));
#endif
if (filters == 1)
prow = pcol = 16;
if (filters == 9)
prow = pcol = 6;
ip = (int *)calloc(prow * pcol, 1280);
merror(ip, "vng_interpolate()");
for (row = 0; row < prow; row++) /* Precalculate for VNG */
for (col = 0; col < pcol; col++)
{
code[row][col] = ip;
for (cp = terms, t = 0; t < 64; t++)
{
y1 = *cp++;
x1 = *cp++;
y2 = *cp++;
x2 = *cp++;
weight = *cp++;
grads = *cp++;
color = fcol(row + y1, col + x1);
if (fcol(row + y2, col + x2) != color)
continue;
diag = (fcol(row, col + 1) == color && fcol(row + 1, col) == color) ? 2 : 1;
if (abs(y1 - y2) == diag && abs(x1 - x2) == diag)
continue;
*ip++ = (y1 * width + x1) * 4 + color;
*ip++ = (y2 * width + x2) * 4 + color;
*ip++ = weight;
for (g = 0; g < 8; g++)
if (grads & 1 << g)
*ip++ = g;
*ip++ = -1;
}
*ip++ = INT_MAX;
for (cp = chood, g = 0; g < 8; g++)
{
y = *cp++;
x = *cp++;
*ip++ = (y * width + x) * 4;
color = fcol(row, col);
if (fcol(row + y, col + x) != color && fcol(row + y * 2, col + x * 2) == color)
*ip++ = (y * width + x) * 8 + color;
else
*ip++ = 0;
}
}
brow[4] = (ushort(*)[4])calloc(width * 3, sizeof **brow);
merror(brow[4], "vng_interpolate()");
for (row = 0; row < 3; row++)
brow[row] = brow[4] + row * width;
for (row = 2; row < height - 2; row++)
{ /* Do VNG interpolation */
#ifdef LIBRAW_LIBRARY_BUILD
if (!((row - 2) % 256))
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, (row - 2) / 256 + 1, ((height - 3) / 256) + 1);
#endif
for (col = 2; col < width - 2; col++)
{
pix = image[row * width + col];
ip = code[row % prow][col % pcol];
memset(gval, 0, sizeof gval);
while ((g = ip[0]) != INT_MAX)
{ /* Calculate gradients */
diff = ABS(pix[g] - pix[ip[1]]) << ip[2];
gval[ip[3]] += diff;
ip += 5;
if ((g = ip[-1]) == -1)
continue;
gval[g] += diff;
while ((g = *ip++) != -1)
gval[g] += diff;
}
ip++;
gmin = gmax = gval[0]; /* Choose a threshold */
for (g = 1; g < 8; g++)
{
if (gmin > gval[g])
gmin = gval[g];
if (gmax < gval[g])
gmax = gval[g];
}
if (gmax == 0)
{
memcpy(brow[2][col], pix, sizeof *image);
continue;
}
thold = gmin + (gmax >> 1);
memset(sum, 0, sizeof sum);
color = fcol(row, col);
for (num = g = 0; g < 8; g++, ip += 2)
{ /* Average the neighbors */
if (gval[g] <= thold)
{
FORCC
if (c == color && ip[1])
sum[c] += (pix[c] + pix[ip[1]]) >> 1;
else
sum[c] += pix[ip[0] + c];
num++;
}
}
FORCC
{ /* Save to buffer */
t = pix[color];
if (c != color)
t += (sum[c] - sum[color]) / num;
brow[2][col][c] = CLIP(t);
}
}
if (row > 3) /* Write buffer to image */
memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image);
for (g = 0; g < 4; g++)
brow[(g - 1) & 3] = brow[g];
}
memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image);
memcpy(image[(row - 1) * width + 2], brow[1] + 2, (width - 4) * sizeof *image);
free(brow[4]);
free(code[0][0]);
}
/*
Patterned Pixel Grouping Interpolation by Alain Desbiolles
*/
void CLASS ppg_interpolate()
{
int dir[5] = {1, width, -1, -width, 1};
int row, col, diff[2], guess[2], c, d, i;
ushort(*pix)[4];
border_interpolate(3);
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("PPG interpolation...\n"));
#endif
/* Fill in the green layer with gradients and pattern recognition: */
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3);
#ifdef LIBRAW_USE_OPENMP
#pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static)
#endif
#endif
for (row = 3; row < height - 3; row++)
for (col = 3 + (FC(row, 3) & 1), c = FC(row, col); col < width - 3; col += 2)
{
pix = image + row * width + col;
for (i = 0; (d = dir[i]) > 0; i++)
{
guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2 * d][c] - pix[2 * d][c];
diff[i] = (ABS(pix[-2 * d][c] - pix[0][c]) + ABS(pix[2 * d][c] - pix[0][c]) + ABS(pix[-d][1] - pix[d][1])) * 3 +
(ABS(pix[3 * d][1] - pix[d][1]) + ABS(pix[-3 * d][1] - pix[-d][1])) * 2;
}
d = dir[i = diff[0] > diff[1]];
pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]);
}
/* Calculate red and blue for each green pixel: */
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3);
#ifdef LIBRAW_USE_OPENMP
#pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static)
#endif
#endif
for (row = 1; row < height - 1; row++)
for (col = 1 + (FC(row, 2) & 1), c = FC(row, col + 1); col < width - 1; col += 2)
{
pix = image + row * width + col;
for (i = 0; (d = dir[i]) > 0; c = 2 - c, i++)
pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1]) >> 1);
}
/* Calculate blue for red pixels and vice versa: */
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3);
#ifdef LIBRAW_USE_OPENMP
#pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static)
#endif
#endif
for (row = 1; row < height - 1; row++)
for (col = 1 + (FC(row, 1) & 1), c = 2 - FC(row, col); col < width - 1; col += 2)
{
pix = image + row * width + col;
for (i = 0; (d = dir[i] + dir[i + 1]) > 0; i++)
{
diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[d][1] - pix[0][1]);
guess[i] = pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1];
}
if (diff[0] != diff[1])
pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1);
else
pix[0][c] = CLIP((guess[0] + guess[1]) >> 2);
}
}
void CLASS cielab(ushort rgb[3], short lab[3])
{
int c, i, j, k;
float r, xyz[3];
#ifdef LIBRAW_NOTHREADS
static float cbrt[0x10000], xyz_cam[3][4];
#else
#define cbrt tls->ahd_data.cbrt
#define xyz_cam tls->ahd_data.xyz_cam
#endif
if (!rgb)
{
#ifndef LIBRAW_NOTHREADS
if (cbrt[0] < -1.0f)
#endif
for (i = 0; i < 0x10000; i++)
{
r = i / 65535.0;
cbrt[i] = r > 0.008856 ? pow(r, 1.f / 3.0f) : 7.787f * r + 16.f / 116.0f;
}
for (i = 0; i < 3; i++)
for (j = 0; j < colors; j++)
for (xyz_cam[i][j] = k = 0; k < 3; k++)
xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i];
return;
}
xyz[0] = xyz[1] = xyz[2] = 0.5;
FORCC
{
xyz[0] += xyz_cam[0][c] * rgb[c];
xyz[1] += xyz_cam[1][c] * rgb[c];
xyz[2] += xyz_cam[2][c] * rgb[c];
}
xyz[0] = cbrt[CLIP((int)xyz[0])];
xyz[1] = cbrt[CLIP((int)xyz[1])];
xyz[2] = cbrt[CLIP((int)xyz[2])];
lab[0] = 64 * (116 * xyz[1] - 16);
lab[1] = 64 * 500 * (xyz[0] - xyz[1]);
lab[2] = 64 * 200 * (xyz[1] - xyz[2]);
#ifndef LIBRAW_NOTHREADS
#undef cbrt
#undef xyz_cam
#endif
}
#define TS 512 /* Tile Size */
#define fcol(row, col) xtrans[(row + 6) % 6][(col + 6) % 6]
/*
Frank Markesteijn's algorithm for Fuji X-Trans sensors
*/
void CLASS xtrans_interpolate(int passes)
{
int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol;
#ifdef LIBRAW_LIBRARY_BUILD
int cstat[4]={0,0,0,0};
#endif
int val, ndir, pass, hm[8], avg[4], color[3][8];
static const short orth[12] = {1, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 1},
patt[2][16] = {{0, 1, 0, -1, 2, 0, -1, 0, 1, 1, 1, -1, 0, 0, 0, 0},
{0, 1, 0, -2, 1, 0, -2, 0, 1, 1, -2, -2, 1, -1, -1, 1}},
dir[4] = {1, TS, TS + 1, TS - 1};
short allhex[3][3][2][8], *hex;
ushort min, max, sgrow, sgcol;
ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4];
short(*lab)[TS][3], (*lix)[3];
float(*drv)[TS][TS], diff[6], tr;
char(*homo)[TS][TS], *buffer;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("%d-pass X-Trans interpolation...\n"), passes);
#endif
#ifdef LIBRAW_LIBRARY_BUILD
if(width < TS || height < TS)
throw LIBRAW_EXCEPTION_IO_CORRUPT; // too small image
/* Check against right pattern */
for (row = 0; row < 6; row++)
for (col = 0; col < 6; col++)
cstat[fcol(row,col)]++;
if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16
|| cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3])
throw LIBRAW_EXCEPTION_IO_CORRUPT;
// Init allhex table to unreasonable values
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
for(int k = 0; k < 2; k++)
for(int l = 0; l < 8; l++)
allhex[i][j][k][l]=32700;
#endif
cielab(0, 0);
ndir = 4 << (passes > 1);
buffer = (char *)malloc(TS * TS * (ndir * 11 + 6));
merror(buffer, "xtrans_interpolate()");
rgb = (ushort(*)[TS][TS][3])buffer;
lab = (short(*)[TS][3])(buffer + TS * TS * (ndir * 6));
drv = (float(*)[TS][TS])(buffer + TS * TS * (ndir * 6 + 6));
homo = (char(*)[TS][TS])(buffer + TS * TS * (ndir * 10 + 6));
int minv=0,maxv=0,minh=0,maxh=0;
/* Map a green hexagon around each non-green pixel and vice versa: */
for (row = 0; row < 3; row++)
for (col = 0; col < 3; col++)
for (ng = d = 0; d < 10; d += 2)
{
g = fcol(row, col) == 1;
if (fcol(row + orth[d], col + orth[d + 2]) == 1)
ng = 0;
else
ng++;
if (ng == 4)
{
sgrow = row;
sgcol = col;
}
if (ng == g + 1)
FORC(8)
{
v = orth[d] * patt[g][c * 2] + orth[d + 1] * patt[g][c * 2 + 1];
h = orth[d + 2] * patt[g][c * 2] + orth[d + 3] * patt[g][c * 2 + 1];
minv=MIN(v,minv);
maxv=MAX(v,maxv);
minh=MIN(v,minh);
maxh=MAX(v,maxh);
allhex[row][col][0][c ^ (g * 2 & d)] = h + v * width;
allhex[row][col][1][c ^ (g * 2 & d)] = h + v * TS;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
// Check allhex table initialization
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
for(int k = 0; k < 2; k++)
for(int l = 0; l < 8; l++)
if(allhex[i][j][k][l]>maxh+maxv*width+1 || allhex[i][j][k][l]<minh+minv*width-1)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
int retrycount = 0;
#endif
/* Set green1 and green3 to the minimum and maximum allowed values: */
for (row = 2; row < height - 2; row++)
for (min = ~(max = 0), col = 2; col < width - 2; col++)
{
if (fcol(row, col) == 1 && (min = ~(max = 0)))
continue;
pix = image + row * width + col;
hex = allhex[row % 3][col % 3][0];
if (!max)
FORC(6)
{
val = pix[hex[c]][1];
if (min > val)
min = val;
if (max < val)
max = val;
}
pix[0][1] = min;
pix[0][3] = max;
switch ((row - sgrow) % 3)
{
case 1:
if (row < height - 3)
{
row++;
col--;
}
break;
case 2:
if ((min = ~(max = 0)) && (col += 2) < width - 3 && row > 2)
{
row--;
#ifdef LIBRAW_LIBRARY_BUILD
if(retrycount++ > width*height)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
}
}
}
for (top = 3; top < height - 19; top += TS - 16)
for (left = 3; left < width - 19; left += TS - 16)
{
mrow = MIN(top + TS, height - 3);
mcol = MIN(left + TS, width - 3);
for (row = top; row < mrow; row++)
for (col = left; col < mcol; col++)
memcpy(rgb[0][row - top][col - left], image[row * width + col], 6);
FORC3 memcpy(rgb[c + 1], rgb[0], sizeof *rgb);
/* Interpolate green horizontally, vertically, and along both diagonals: */
for (row = top; row < mrow; row++)
for (col = left; col < mcol; col++)
{
if ((f = fcol(row, col)) == 1)
continue;
pix = image + row * width + col;
hex = allhex[row % 3][col % 3][0];
color[1][0] = 174 * (pix[hex[1]][1] + pix[hex[0]][1]) - 46 * (pix[2 * hex[1]][1] + pix[2 * hex[0]][1]);
color[1][1] = 223 * pix[hex[3]][1] + pix[hex[2]][1] * 33 + 92 * (pix[0][f] - pix[-hex[2]][f]);
FORC(2)
color[1][2 + c] = 164 * pix[hex[4 + c]][1] + 92 * pix[-2 * hex[4 + c]][1] +
33 * (2 * pix[0][f] - pix[3 * hex[4 + c]][f] - pix[-3 * hex[4 + c]][f]);
FORC4 rgb[c ^ !((row - sgrow) % 3)][row - top][col - left][1] = LIM(color[1][c] >> 8, pix[0][1], pix[0][3]);
}
for (pass = 0; pass < passes; pass++)
{
if (pass == 1)
memcpy(rgb += 4, buffer, 4 * sizeof *rgb);
/* Recalculate green from interpolated values of closer pixels: */
if (pass)
{
for (row = top + 2; row < mrow - 2; row++)
for (col = left + 2; col < mcol - 2; col++)
{
if ((f = fcol(row, col)) == 1)
continue;
pix = image + row * width + col;
hex = allhex[row % 3][col % 3][1];
for (d = 3; d < 6; d++)
{
rix = &rgb[(d - 2) ^ !((row - sgrow) % 3)][row - top][col - left];
val =
rix[-2 * hex[d]][1] + 2 * rix[hex[d]][1] - rix[-2 * hex[d]][f] - 2 * rix[hex[d]][f] + 3 * rix[0][f];
rix[0][1] = LIM(val / 3, pix[0][1], pix[0][3]);
}
}
}
/* Interpolate red and blue values for solitary green pixels: */
for (row = (top - sgrow + 4) / 3 * 3 + sgrow; row < mrow - 2; row += 3)
for (col = (left - sgcol + 4) / 3 * 3 + sgcol; col < mcol - 2; col += 3)
{
rix = &rgb[0][row - top][col - left];
h = fcol(row, col + 1);
memset(diff, 0, sizeof diff);
for (i = 1, d = 0; d < 6; d++, i ^= TS ^ 1, h ^= 2)
{
for (c = 0; c < 2; c++, h ^= 2)
{
g = 2 * rix[0][1] - rix[i << c][1] - rix[-i << c][1];
color[h][d] = g + rix[i << c][h] + rix[-i << c][h];
if (d > 1)
diff[d] += SQR(rix[i << c][1] - rix[-i << c][1] - rix[i << c][h] + rix[-i << c][h]) + SQR(g);
}
if (d > 1 && (d & 1))
if (diff[d - 1] < diff[d])
FORC(2) color[c * 2][d] = color[c * 2][d - 1];
if (d < 2 || (d & 1))
{
FORC(2) rix[0][c * 2] = CLIP(color[c * 2][d] / 2);
rix += TS * TS;
}
}
}
/* Interpolate red for blue pixels and vice versa: */
for (row = top + 3; row < mrow - 3; row++)
for (col = left + 3; col < mcol - 3; col++)
{
if ((f = 2 - fcol(row, col)) == 1)
continue;
rix = &rgb[0][row - top][col - left];
c = (row - sgrow) % 3 ? TS : 1;
h = 3 * (c ^ TS ^ 1);
for (d = 0; d < 4; d++, rix += TS * TS)
{
i = d > 1 || ((d ^ c) & 1) ||
((ABS(rix[0][1] - rix[c][1]) + ABS(rix[0][1] - rix[-c][1])) <
2 * (ABS(rix[0][1] - rix[h][1]) + ABS(rix[0][1] - rix[-h][1])))
? c
: h;
rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2 * rix[0][1] - rix[i][1] - rix[-i][1]) / 2);
}
}
/* Fill in red and blue for 2x2 blocks of green: */
for (row = top + 2; row < mrow - 2; row++)
if ((row - sgrow) % 3)
for (col = left + 2; col < mcol - 2; col++)
if ((col - sgcol) % 3)
{
rix = &rgb[0][row - top][col - left];
hex = allhex[row % 3][col % 3][1];
for (d = 0; d < ndir; d += 2, rix += TS * TS)
if (hex[d] + hex[d + 1])
{
g = 3 * rix[0][1] - 2 * rix[hex[d]][1] - rix[hex[d + 1]][1];
for (c = 0; c < 4; c += 2)
rix[0][c] = CLIP((g + 2 * rix[hex[d]][c] + rix[hex[d + 1]][c]) / 3);
}
else
{
g = 2 * rix[0][1] - rix[hex[d]][1] - rix[hex[d + 1]][1];
for (c = 0; c < 4; c += 2)
rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d + 1]][c]) / 2);
}
}
}
rgb = (ushort(*)[TS][TS][3])buffer;
mrow -= top;
mcol -= left;
/* Convert to CIELab and differentiate in all directions: */
for (d = 0; d < ndir; d++)
{
for (row = 2; row < mrow - 2; row++)
for (col = 2; col < mcol - 2; col++)
cielab(rgb[d][row][col], lab[row][col]);
for (f = dir[d & 3], row = 3; row < mrow - 3; row++)
for (col = 3; col < mcol - 3; col++)
{
lix = &lab[row][col];
g = 2 * lix[0][0] - lix[f][0] - lix[-f][0];
drv[d][row][col] = SQR(g) + SQR((2 * lix[0][1] - lix[f][1] - lix[-f][1] + g * 500 / 232)) +
SQR((2 * lix[0][2] - lix[f][2] - lix[-f][2] - g * 500 / 580));
}
}
/* Build homogeneity maps from the derivatives: */
memset(homo, 0, ndir * TS * TS);
for (row = 4; row < mrow - 4; row++)
for (col = 4; col < mcol - 4; col++)
{
for (tr = FLT_MAX, d = 0; d < ndir; d++)
if (tr > drv[d][row][col])
tr = drv[d][row][col];
tr *= 8;
for (d = 0; d < ndir; d++)
for (v = -1; v <= 1; v++)
for (h = -1; h <= 1; h++)
if (drv[d][row + v][col + h] <= tr)
homo[d][row][col]++;
}
/* Average the most homogenous pixels for the final result: */
if (height - top < TS + 4)
mrow = height - top + 2;
if (width - left < TS + 4)
mcol = width - left + 2;
for (row = MIN(top, 8); row < mrow - 8; row++)
for (col = MIN(left, 8); col < mcol - 8; col++)
{
for (d = 0; d < ndir; d++)
for (hm[d] = 0, v = -2; v <= 2; v++)
for (h = -2; h <= 2; h++)
hm[d] += homo[d][row + v][col + h];
for (d = 0; d < ndir - 4; d++)
if (hm[d] < hm[d + 4])
hm[d] = 0;
else if (hm[d] > hm[d + 4])
hm[d + 4] = 0;
for (max = hm[0], d = 1; d < ndir; d++)
if (max < hm[d])
max = hm[d];
max -= max >> 3;
memset(avg, 0, sizeof avg);
for (d = 0; d < ndir; d++)
if (hm[d] >= max)
{
FORC3 avg[c] += rgb[d][row][col][c];
avg[3]++;
}
FORC3 image[(row + top) * width + col + left][c] = avg[c] / avg[3];
}
}
free(buffer);
border_interpolate(8);
}
#undef fcol
/*
Adaptive Homogeneity-Directed interpolation is based on
the work of Keigo Hirakawa, Thomas Parks, and Paul Lee.
*/
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3])
{
int row, col;
int c, val;
ushort(*pix)[4];
const int rowlimit = MIN(top + TS, height - 2);
const int collimit = MIN(left + TS, width - 2);
for (row = top; row < rowlimit; row++)
{
col = left + (FC(row, left) & 1);
for (c = FC(row, col); col < collimit; col += 2)
{
pix = image + row * width + col;
val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2;
out_rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]);
val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2;
out_rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]);
}
}
}
void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3],
short (*out_lab)[TS][3])
{
unsigned row, col;
int c, val;
ushort(*pix)[4];
ushort(*rix)[3];
short(*lix)[3];
float xyz[3];
const unsigned num_pix_per_row = 4 * width;
const unsigned rowlimit = MIN(top + TS - 1, height - 3);
const unsigned collimit = MIN(left + TS - 1, width - 3);
ushort *pix_above;
ushort *pix_below;
int t1, t2;
for (row = top + 1; row < rowlimit; row++)
{
pix = image + row * width + left;
rix = &inout_rgb[row - top][0];
lix = &out_lab[row - top][0];
for (col = left + 1; col < collimit; col++)
{
pix++;
pix_above = &pix[0][0] - num_pix_per_row;
pix_below = &pix[0][0] + num_pix_per_row;
rix++;
lix++;
c = 2 - FC(row, col);
if (c == 1)
{
c = FC(row + 1, col);
t1 = 2 - c;
val = pix[0][1] + ((pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1]) >> 1);
rix[0][t1] = CLIP(val);
val = pix[0][1] + ((pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1]) >> 1);
}
else
{
t1 = -4 + c; /* -4+c: pixel of color c to the left */
t2 = 4 + c; /* 4+c: pixel of color c to the right */
val = rix[0][1] + ((pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS - 1][1] -
rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >>
2);
}
rix[0][c] = CLIP(val);
c = FC(row, col);
rix[0][c] = pix[0][c];
cielab(rix[0], lix[0]);
}
}
}
void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3],
short (*out_lab)[TS][TS][3])
{
int direction;
for (direction = 0; direction < 2; direction++)
{
ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]);
}
}
void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3],
char (*out_homogeneity_map)[TS][2])
{
int row, col;
int tr, tc;
int direction;
int i;
short(*lix)[3];
short(*lixs[2])[3];
short *adjacent_lix;
unsigned ldiff[2][4], abdiff[2][4], leps, abeps;
static const int dir[4] = {-1, 1, -TS, TS};
const int rowlimit = MIN(top + TS - 2, height - 4);
const int collimit = MIN(left + TS - 2, width - 4);
int homogeneity;
char(*homogeneity_map_p)[2];
memset(out_homogeneity_map, 0, 2 * TS * TS);
for (row = top + 2; row < rowlimit; row++)
{
tr = row - top;
homogeneity_map_p = &out_homogeneity_map[tr][1];
for (direction = 0; direction < 2; direction++)
{
lixs[direction] = &lab[direction][tr][1];
}
for (col = left + 2; col < collimit; col++)
{
tc = col - left;
homogeneity_map_p++;
for (direction = 0; direction < 2; direction++)
{
lix = ++lixs[direction];
for (i = 0; i < 4; i++)
{
adjacent_lix = lix[dir[i]];
ldiff[direction][i] = ABS(lix[0][0] - adjacent_lix[0]);
abdiff[direction][i] = SQR(lix[0][1] - adjacent_lix[1]) + SQR(lix[0][2] - adjacent_lix[2]);
}
}
leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3]));
abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3]));
for (direction = 0; direction < 2; direction++)
{
homogeneity = 0;
for (i = 0; i < 4; i++)
{
if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps)
{
homogeneity++;
}
}
homogeneity_map_p[0][direction] = homogeneity;
}
}
}
}
void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3],
char (*homogeneity_map)[TS][2])
{
int row, col;
int tr, tc;
int i, j;
int direction;
int hm[2];
int c;
const int rowlimit = MIN(top + TS - 3, height - 5);
const int collimit = MIN(left + TS - 3, width - 5);
ushort(*pix)[4];
ushort(*rix[2])[3];
for (row = top + 3; row < rowlimit; row++)
{
tr = row - top;
pix = &image[row * width + left + 2];
for (direction = 0; direction < 2; direction++)
{
rix[direction] = &rgb[direction][tr][2];
}
for (col = left + 3; col < collimit; col++)
{
tc = col - left;
pix++;
for (direction = 0; direction < 2; direction++)
{
rix[direction]++;
}
for (direction = 0; direction < 2; direction++)
{
hm[direction] = 0;
for (i = tr - 1; i <= tr + 1; i++)
{
for (j = tc - 1; j <= tc + 1; j++)
{
hm[direction] += homogeneity_map[i][j][direction];
}
}
}
if (hm[0] != hm[1])
{
memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort));
}
else
{
FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; }
}
}
}
}
void CLASS ahd_interpolate()
{
int i, j, k, top, left;
float xyz_cam[3][4], r;
char *buffer;
ushort(*rgb)[TS][TS][3];
short(*lab)[TS][TS][3];
char(*homo)[TS][2];
int terminate_flag = 0;
cielab(0, 0);
border_interpolate(5);
#ifdef LIBRAW_LIBRARY_BUILD
#ifdef LIBRAW_USE_OPENMP
#pragma omp parallel private(buffer, rgb, lab, homo, top, left, i, j, k) shared(xyz_cam, terminate_flag)
#endif
#endif
{
buffer = (char *)malloc(26 * TS * TS); /* 1664 kB */
merror(buffer, "ahd_interpolate()");
rgb = (ushort(*)[TS][TS][3])buffer;
lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS);
homo = (char(*)[TS][2])(buffer + 24 * TS * TS);
#ifdef LIBRAW_LIBRARY_BUILD
#ifdef LIBRAW_USE_OPENMP
#pragma omp for schedule(dynamic)
#endif
#endif
for (top = 2; top < height - 5; top += TS - 6)
{
#ifdef LIBRAW_LIBRARY_BUILD
#ifdef LIBRAW_USE_OPENMP
if (0 == omp_get_thread_num())
#endif
if (callbacks.progress_cb)
{
int rr =
(*callbacks.progress_cb)(callbacks.progresscb_data, LIBRAW_PROGRESS_INTERPOLATE, top - 2, height - 7);
if (rr)
terminate_flag = 1;
}
#endif
for (left = 2; !terminate_flag && (left < width - 5); left += TS - 6)
{
ahd_interpolate_green_h_and_v(top, left, rgb);
ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab);
ahd_interpolate_build_homogeneity_map(top, left, lab, homo);
ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo);
}
}
free(buffer);
}
#ifdef LIBRAW_LIBRARY_BUILD
if (terminate_flag)
throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK;
#endif
}
#else
void CLASS ahd_interpolate()
{
int i, j, top, left, row, col, tr, tc, c, d, val, hm[2];
static const int dir[4] = {-1, 1, -TS, TS};
unsigned ldiff[2][4], abdiff[2][4], leps, abeps;
ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4];
short(*lab)[TS][TS][3], (*lix)[3];
char(*homo)[TS][TS], *buffer;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("AHD interpolation...\n"));
#endif
cielab(0, 0);
border_interpolate(5);
buffer = (char *)malloc(26 * TS * TS);
merror(buffer, "ahd_interpolate()");
rgb = (ushort(*)[TS][TS][3])buffer;
lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS);
homo = (char(*)[TS][TS])(buffer + 24 * TS * TS);
for (top = 2; top < height - 5; top += TS - 6)
for (left = 2; left < width - 5; left += TS - 6)
{
/* Interpolate green horizontally and vertically: */
for (row = top; row < top + TS && row < height - 2; row++)
{
col = left + (FC(row, left) & 1);
for (c = FC(row, col); col < left + TS && col < width - 2; col += 2)
{
pix = image + row * width + col;
val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2;
rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]);
val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2;
rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]);
}
}
/* Interpolate red and blue, and convert to CIELab: */
for (d = 0; d < 2; d++)
for (row = top + 1; row < top + TS - 1 && row < height - 3; row++)
for (col = left + 1; col < left + TS - 1 && col < width - 3; col++)
{
pix = image + row * width + col;
rix = &rgb[d][row - top][col - left];
lix = &lab[d][row - top][col - left];
if ((c = 2 - FC(row, col)) == 1)
{
c = FC(row + 1, col);
val = pix[0][1] + ((pix[-1][2 - c] + pix[1][2 - c] - rix[-1][1] - rix[1][1]) >> 1);
rix[0][2 - c] = CLIP(val);
val = pix[0][1] + ((pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1]) >> 1);
}
else
val = rix[0][1] + ((pix[-width - 1][c] + pix[-width + 1][c] + pix[+width - 1][c] + pix[+width + 1][c] -
rix[-TS - 1][1] - rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >>
2);
rix[0][c] = CLIP(val);
c = FC(row, col);
rix[0][c] = pix[0][c];
cielab(rix[0], lix[0]);
}
/* Build homogeneity maps from the CIELab images: */
memset(homo, 0, 2 * TS * TS);
for (row = top + 2; row < top + TS - 2 && row < height - 4; row++)
{
tr = row - top;
for (col = left + 2; col < left + TS - 2 && col < width - 4; col++)
{
tc = col - left;
for (d = 0; d < 2; d++)
{
lix = &lab[d][tr][tc];
for (i = 0; i < 4; i++)
{
ldiff[d][i] = ABS(lix[0][0] - lix[dir[i]][0]);
abdiff[d][i] = SQR(lix[0][1] - lix[dir[i]][1]) + SQR(lix[0][2] - lix[dir[i]][2]);
}
}
leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3]));
abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3]));
for (d = 0; d < 2; d++)
for (i = 0; i < 4; i++)
if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps)
homo[d][tr][tc]++;
}
}
/* Combine the most homogenous pixels for the final result: */
for (row = top + 3; row < top + TS - 3 && row < height - 5; row++)
{
tr = row - top;
for (col = left + 3; col < left + TS - 3 && col < width - 5; col++)
{
tc = col - left;
for (d = 0; d < 2; d++)
for (hm[d] = 0, i = tr - 1; i <= tr + 1; i++)
for (j = tc - 1; j <= tc + 1; j++)
hm[d] += homo[d][i][j];
if (hm[0] != hm[1])
FORC3 image[row * width + col][c] = rgb[hm[1] > hm[0]][tr][tc][c];
else
FORC3 image[row * width + col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1;
}
}
}
free(buffer);
}
#endif
#undef TS
void CLASS median_filter()
{
ushort(*pix)[4];
int pass, c, i, j, k, med[9];
static const uchar opt[] = /* Optimal 9-element median search */
{1, 2, 4, 5, 7, 8, 0, 1, 3, 4, 6, 7, 1, 2, 4, 5, 7, 8, 0,
3, 5, 8, 4, 7, 3, 6, 1, 4, 2, 5, 4, 7, 4, 2, 6, 4, 4, 2};
for (pass = 1; pass <= med_passes; pass++)
{
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER, pass - 1, med_passes);
#endif
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Median filter pass %d...\n"), pass);
#endif
for (c = 0; c < 3; c += 2)
{
for (pix = image; pix < image + width * height; pix++)
pix[0][3] = pix[0][c];
for (pix = image + width; pix < image + width * (height - 1); pix++)
{
if ((pix - image + 1) % width < 2)
continue;
for (k = 0, i = -width; i <= width; i += width)
for (j = i - 1; j <= i + 1; j++)
med[k++] = pix[j][3] - pix[j][1];
for (i = 0; i < sizeof opt; i += 2)
if (med[opt[i]] > med[opt[i + 1]])
SWAP(med[opt[i]], med[opt[i + 1]]);
pix[0][c] = CLIP(med[4] + pix[0][1]);
}
}
}
}
void CLASS blend_highlights()
{
int clip = INT_MAX, row, col, c, i, j;
static const float trans[2][4][4] = {{{1, 1, 1}, {1.7320508, -1.7320508, 0}, {-1, -1, 2}},
{{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}};
static const float itrans[2][4][4] = {{{1, 0.8660254, -0.5}, {1, -0.8660254, -0.5}, {1, 0, 1}},
{{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}};
float cam[2][4], lab[2][4], sum[2], chratio;
if ((unsigned)(colors - 3) > 1)
return;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Blending highlights...\n"));
#endif
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 0, 2);
#endif
FORCC if (clip > (i = 65535 * pre_mul[c])) clip = i;
for (row = 0; row < height; row++)
for (col = 0; col < width; col++)
{
FORCC if (image[row * width + col][c] > clip) break;
if (c == colors)
continue;
FORCC
{
cam[0][c] = image[row * width + col][c];
cam[1][c] = MIN(cam[0][c], clip);
}
for (i = 0; i < 2; i++)
{
FORCC for (lab[i][c] = j = 0; j < colors; j++) lab[i][c] += trans[colors - 3][c][j] * cam[i][j];
for (sum[i] = 0, c = 1; c < colors; c++)
sum[i] += SQR(lab[i][c]);
}
chratio = sqrt(sum[1] / sum[0]);
for (c = 1; c < colors; c++)
lab[0][c] *= chratio;
FORCC for (cam[0][c] = j = 0; j < colors; j++) cam[0][c] += itrans[colors - 3][c][j] * lab[0][j];
FORCC image[row * width + col][c] = cam[0][c] / colors;
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 1, 2);
#endif
}
#define SCALE (4 >> shrink)
void CLASS recover_highlights()
{
float *map, sum, wgt, grow;
int hsat[4], count, spread, change, val, i;
unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x;
ushort *pixel;
static const signed char dir[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}};
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Rebuilding highlights...\n"));
#endif
grow = pow(2.0, 4 - highlight);
FORCC hsat[c] = 32000 * pre_mul[c];
for (kc = 0, c = 1; c < colors; c++)
if (pre_mul[kc] < pre_mul[c])
kc = c;
high = height / SCALE;
wide = width / SCALE;
map = (float *)calloc(high, wide * sizeof *map);
merror(map, "recover_highlights()");
FORCC if (c != kc)
{
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, c - 1, colors - 1);
#endif
memset(map, 0, high * wide * sizeof *map);
for (mrow = 0; mrow < high; mrow++)
for (mcol = 0; mcol < wide; mcol++)
{
sum = wgt = count = 0;
for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++)
for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++)
{
pixel = image[row * width + col];
if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000)
{
sum += pixel[c];
wgt += pixel[kc];
count++;
}
}
if (count == SCALE * SCALE)
map[mrow * wide + mcol] = sum / wgt;
}
for (spread = 32 / grow; spread--;)
{
for (mrow = 0; mrow < high; mrow++)
for (mcol = 0; mcol < wide; mcol++)
{
if (map[mrow * wide + mcol])
continue;
sum = count = 0;
for (d = 0; d < 8; d++)
{
y = mrow + dir[d][0];
x = mcol + dir[d][1];
if (y < high && x < wide && map[y * wide + x] > 0)
{
sum += (1 + (d & 1)) * map[y * wide + x];
count += 1 + (d & 1);
}
}
if (count > 3)
map[mrow * wide + mcol] = -(sum + grow) / (count + grow);
}
for (change = i = 0; i < high * wide; i++)
if (map[i] < 0)
{
map[i] = -map[i];
change = 1;
}
if (!change)
break;
}
for (i = 0; i < high * wide; i++)
if (map[i] == 0)
map[i] = 1;
for (mrow = 0; mrow < high; mrow++)
for (mcol = 0; mcol < wide; mcol++)
{
for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++)
for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++)
{
pixel = image[row * width + col];
if (pixel[c] / hsat[c] > 1)
{
val = pixel[kc] * map[mrow * wide + mcol];
if (pixel[c] < val)
pixel[c] = CLIP(val);
}
}
}
}
free(map);
}
#undef SCALE
void CLASS tiff_get(unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save)
{
*tag = get2();
*type = get2();
*len = get4();
*save = ftell(ifp) + 4;
if (*len * ("11124811248484"[*type < 14 ? *type : 0] - '0') > 4)
fseek(ifp, get4() + base, SEEK_SET);
}
void CLASS parse_thumb_note(int base, unsigned toff, unsigned tlen)
{
unsigned entries, tag, type, len, save;
entries = get2();
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
if (tag == toff)
thumb_offset = get4() + base;
if (tag == tlen)
thumb_length = get4();
fseek(ifp, save, SEEK_SET);
}
}
static float powf_lim(float a, float b, float limup) { return (b > limup || b < -limup) ? 0.f : powf(a, b); }
static float powf64(float a, float b) { return powf_lim(a, b, 64.f); }
#ifdef LIBRAW_LIBRARY_BUILD
static float my_roundf(float x)
{
float t;
if (x >= 0.0)
{
t = ceilf(x);
if (t - x > 0.5)
t -= 1.0;
return t;
}
else
{
t = ceilf(-x);
if (t + x > 0.5)
t -= 1.0;
return -t;
}
}
static float _CanonConvertAperture(ushort in)
{
if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff))
return 0.0f;
return powf64(2.0, in / 64.0);
}
static float _CanonConvertEV(short in)
{
short EV, Sign, Frac;
float Frac_f;
EV = in;
if (EV < 0)
{
EV = -EV;
Sign = -1;
}
else
{
Sign = 1;
}
Frac = EV & 0x1f;
EV -= Frac; // remove fraction
if (Frac == 0x0c)
{ // convert 1/3 and 2/3 codes
Frac_f = 32.0f / 3.0f;
}
else if (Frac == 0x14)
{
Frac_f = 64.0f / 3.0f;
}
else
Frac_f = (float)Frac;
return ((float)Sign * ((float)EV + Frac_f)) / 32.0f;
}
void CLASS setCanonBodyFeatures(unsigned id)
{
imgdata.lens.makernotes.CamID = id;
if ((id == 0x80000001) || // 1D
(id == 0x80000174) || // 1D2
(id == 0x80000232) || // 1D2N
(id == 0x80000169) || // 1D3
(id == 0x80000281) // 1D4
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
}
else if ((id == 0x80000167) || // 1Ds
(id == 0x80000188) || // 1Ds2
(id == 0x80000215) || // 1Ds3
(id == 0x80000269) || // 1DX
(id == 0x80000328) || // 1DX2
(id == 0x80000324) || // 1DC
(id == 0x80000213) || // 5D
(id == 0x80000218) || // 5D2
(id == 0x80000285) || // 5D3
(id == 0x80000349) || // 5D4
(id == 0x80000382) || // 5DS
(id == 0x80000401) || // 5DS R
(id == 0x80000302) // 6D
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
}
else if ((id == 0x80000331) || // M
(id == 0x80000355) || // M2
(id == 0x80000374) || // M3
(id == 0x80000384) || // M10
(id == 0x80000394) || // M5
(id == 0x80000407) // M6
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M;
}
else if ((id == 0x01140000) || // D30
(id == 0x01668000) || // D60
(id > 0x80000000))
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
return;
}
void CLASS processCanonCameraInfo(unsigned id, uchar *CameraInfo, unsigned maxlen)
{
ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0,
iCanonFocalType = 0;
CameraInfo[0] = 0;
CameraInfo[1] = 0;
switch (id)
{
case 0x80000001: // 1D
case 0x80000167: // 1DS
iCanonCurFocal = 10;
iCanonLensID = 13;
iCanonMinFocal = 14;
iCanonMaxFocal = 16;
if (!imgdata.lens.makernotes.CurFocal)
imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal);
if (!imgdata.lens.makernotes.MinFocal)
imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal);
if (!imgdata.lens.makernotes.MaxFocal)
imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal);
break;
case 0x80000174: // 1DMkII
case 0x80000188: // 1DsMkII
iCanonCurFocal = 9;
iCanonLensID = 12;
iCanonMinFocal = 17;
iCanonMaxFocal = 19;
iCanonFocalType = 45;
break;
case 0x80000232: // 1DMkII N
iCanonCurFocal = 9;
iCanonLensID = 12;
iCanonMinFocal = 17;
iCanonMaxFocal = 19;
break;
case 0x80000169: // 1DMkIII
case 0x80000215: // 1DsMkIII
iCanonCurFocal = 29;
iCanonLensID = 273;
iCanonMinFocal = 275;
iCanonMaxFocal = 277;
break;
case 0x80000281: // 1DMkIV
iCanonCurFocal = 30;
iCanonLensID = 335;
iCanonMinFocal = 337;
iCanonMaxFocal = 339;
break;
case 0x80000269: // 1D X
iCanonCurFocal = 35;
iCanonLensID = 423;
iCanonMinFocal = 425;
iCanonMaxFocal = 427;
break;
case 0x80000213: // 5D
iCanonCurFocal = 40;
if (!sget2Rev(CameraInfo + 12))
iCanonLensID = 151;
else
iCanonLensID = 12;
iCanonMinFocal = 147;
iCanonMaxFocal = 149;
break;
case 0x80000218: // 5DMkII
iCanonCurFocal = 30;
iCanonLensID = 230;
iCanonMinFocal = 232;
iCanonMaxFocal = 234;
break;
case 0x80000285: // 5DMkIII
iCanonCurFocal = 35;
iCanonLensID = 339;
iCanonMinFocal = 341;
iCanonMaxFocal = 343;
break;
case 0x80000302: // 6D
iCanonCurFocal = 35;
iCanonLensID = 353;
iCanonMinFocal = 355;
iCanonMaxFocal = 357;
break;
case 0x80000250: // 7D
iCanonCurFocal = 30;
iCanonLensID = 274;
iCanonMinFocal = 276;
iCanonMaxFocal = 278;
break;
case 0x80000190: // 40D
iCanonCurFocal = 29;
iCanonLensID = 214;
iCanonMinFocal = 216;
iCanonMaxFocal = 218;
iCanonLens = 2347;
break;
case 0x80000261: // 50D
iCanonCurFocal = 30;
iCanonLensID = 234;
iCanonMinFocal = 236;
iCanonMaxFocal = 238;
break;
case 0x80000287: // 60D
iCanonCurFocal = 30;
iCanonLensID = 232;
iCanonMinFocal = 234;
iCanonMaxFocal = 236;
break;
case 0x80000325: // 70D
iCanonCurFocal = 35;
iCanonLensID = 358;
iCanonMinFocal = 360;
iCanonMaxFocal = 362;
break;
case 0x80000176: // 450D
iCanonCurFocal = 29;
iCanonLensID = 222;
iCanonLens = 2355;
break;
case 0x80000252: // 500D
iCanonCurFocal = 30;
iCanonLensID = 246;
iCanonMinFocal = 248;
iCanonMaxFocal = 250;
break;
case 0x80000270: // 550D
iCanonCurFocal = 30;
iCanonLensID = 255;
iCanonMinFocal = 257;
iCanonMaxFocal = 259;
break;
case 0x80000286: // 600D
case 0x80000288: // 1100D
iCanonCurFocal = 30;
iCanonLensID = 234;
iCanonMinFocal = 236;
iCanonMaxFocal = 238;
break;
case 0x80000301: // 650D
case 0x80000326: // 700D
iCanonCurFocal = 35;
iCanonLensID = 295;
iCanonMinFocal = 297;
iCanonMaxFocal = 299;
break;
case 0x80000254: // 1000D
iCanonCurFocal = 29;
iCanonLensID = 226;
iCanonMinFocal = 228;
iCanonMaxFocal = 230;
iCanonLens = 2359;
break;
}
if (iCanonFocalType)
{
if (iCanonFocalType >= maxlen)
return; // broken;
imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType];
if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1'
imgdata.lens.makernotes.FocalType = 1;
}
if (!imgdata.lens.makernotes.CurFocal)
{
if (iCanonCurFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal);
}
if (!imgdata.lens.makernotes.LensID)
{
if (iCanonLensID >= maxlen)
return; // broken;
imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID);
}
if (!imgdata.lens.makernotes.MinFocal)
{
if (iCanonMinFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal);
}
if (!imgdata.lens.makernotes.MaxFocal)
{
if (iCanonMaxFocal >= maxlen)
return; // broken;
imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal);
}
if (!imgdata.lens.makernotes.Lens[0] && iCanonLens)
{
if (iCanonLens + 64 >= maxlen)
return; // broken;
if (CameraInfo[iCanonLens] < 65) // non-Canon lens
{
memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else
{
memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
imgdata.lens.makernotes.Lens[2] = 32;
memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62);
}
}
return;
}
void CLASS Canon_CameraSettings()
{
fseek(ifp, 10, SEEK_CUR);
imgdata.shootinginfo.DriveMode = get2();
get2();
imgdata.shootinginfo.FocusMode = get2();
fseek(ifp, 18, SEEK_CUR);
imgdata.shootinginfo.MeteringMode = get2();
get2();
imgdata.shootinginfo.AFPoint = get2();
imgdata.shootinginfo.ExposureMode = get2();
get2();
imgdata.lens.makernotes.LensID = get2();
imgdata.lens.makernotes.MaxFocal = get2();
imgdata.lens.makernotes.MinFocal = get2();
imgdata.lens.makernotes.CanonFocalUnits = get2();
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
{
imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2());
imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2());
fseek(ifp, 12, SEEK_CUR);
imgdata.shootinginfo.ImageStabilization = get2();
}
void CLASS Canon_WBpresets(int skip1, int skip2)
{
int c;
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2();
if (skip1)
fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2();
if (skip2)
fseek(ifp, skip2, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2();
return;
}
void CLASS Canon_WBCTpresets(short WBCTversion)
{
if (WBCTversion == 0)
for (int i = 0; i < 15; i++) // tint, as shot R, as shot B, CСT
{
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if (WBCTversion == 1)
for (int i = 0; i < 15; i++) // as shot R, as shot B, tint, CСT
{
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f);
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3
(unique_id == 0x80000384) || // M10
(unique_id == 0x80000394) || // M5
(unique_id == 0x80000407) || // M6
(unique_id == 0x03970000) || // G7 X Mark II
(unique_id == 0x04100000))) // G9 X Mark II
for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT
{
fseek(ifp, 2, SEEK_CUR);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f, get2());
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f, get2());
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X
for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT
{
fseek(ifp, 2, SEEK_CUR);
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f;
imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f;
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
return;
}
void CLASS processNikonLensData(uchar *LensData, unsigned len)
{
ushort i;
if (!(imgdata.lens.nikon.NikonLensType & 0x01))
{
imgdata.lens.makernotes.LensFeatures_pre[0] = 'A';
imgdata.lens.makernotes.LensFeatures_pre[1] = 'F';
}
else
{
imgdata.lens.makernotes.LensFeatures_pre[0] = 'M';
imgdata.lens.makernotes.LensFeatures_pre[1] = 'F';
}
if (imgdata.lens.nikon.NikonLensType & 0x02)
{
if (imgdata.lens.nikon.NikonLensType & 0x04)
imgdata.lens.makernotes.LensFeatures_suf[0] = 'G';
else
imgdata.lens.makernotes.LensFeatures_suf[0] = 'D';
imgdata.lens.makernotes.LensFeatures_suf[1] = ' ';
}
if (imgdata.lens.nikon.NikonLensType & 0x08)
{
imgdata.lens.makernotes.LensFeatures_suf[2] = 'V';
imgdata.lens.makernotes.LensFeatures_suf[3] = 'R';
}
if (imgdata.lens.nikon.NikonLensType & 0x10)
{
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX;
imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH;
}
else
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F;
if (imgdata.lens.nikon.NikonLensType & 0x20)
{
strcpy(imgdata.lens.makernotes.Adapter, "FT-1");
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH;
}
imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf;
if (len < 20)
{
switch (len)
{
case 9:
i = 2;
break;
case 15:
i = 7;
break;
case 16:
i = 8;
break;
}
imgdata.lens.nikon.NikonLensIDNumber = LensData[i];
imgdata.lens.nikon.NikonLensFStops = LensData[i + 1];
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f)
{
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2])
imgdata.lens.makernotes.MinFocal = 5.0f * powf64(2.0f, (float)LensData[i + 2] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3])
imgdata.lens.makernotes.MaxFocal = 5.0f * powf64(2.0f, (float)LensData[i + 3] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4])
imgdata.lens.makernotes.MaxAp4MinFocal = powf64(2.0f, (float)LensData[i + 4] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5])
imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(2.0f, (float)LensData[i + 5] / 24.0f);
}
imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6];
if (i != 2)
{
if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f))
imgdata.lens.makernotes.CurFocal = 5.0f * powf64(2.0f, (float)LensData[i - 1] / 24.0f);
if (LensData[i + 7])
imgdata.lens.nikon.NikonEffectiveMaxAp = powf64(2.0f, (float)LensData[i + 7] / 24.0f);
}
imgdata.lens.makernotes.LensID =
(unsigned long long)LensData[i] << 56 | (unsigned long long)LensData[i + 1] << 48 |
(unsigned long long)LensData[i + 2] << 40 | (unsigned long long)LensData[i + 3] << 32 |
(unsigned long long)LensData[i + 4] << 24 | (unsigned long long)LensData[i + 5] << 16 |
(unsigned long long)LensData[i + 6] << 8 | (unsigned long long)imgdata.lens.nikon.NikonLensType;
}
else if ((len == 459) || (len == 590))
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64);
}
else if (len == 509)
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64);
}
else if (len == 879)
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64);
}
return;
}
void CLASS setOlympusBodyFeatures(unsigned long long id)
{
imgdata.lens.makernotes.CamID = id;
if ((id == 0x4434303430ULL) || // E-1
(id == 0x4434303431ULL) || // E-300
((id & 0x00ffff0000ULL) == 0x0030300000ULL))
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT;
if ((id == 0x4434303430ULL) || // E-1
(id == 0x4434303431ULL) || // E-330
((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520
(id == 0x5330303233ULL) || // E-620
(id == 0x5330303239ULL) || // E-450
(id == 0x5330303330ULL) || // E-600
(id == 0x5330303333ULL)) // E-5
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT;
}
}
else
{
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
return;
}
void CLASS parseCanonMakernotes(unsigned tag, unsigned type, unsigned len)
{
if (tag == 0x0001)
Canon_CameraSettings();
else if (tag == 0x0002) // focal length
{
imgdata.lens.makernotes.FocalType = get2();
imgdata.lens.makernotes.CurFocal = get2();
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
{
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
}
else if (tag == 0x0004) // shot info
{
short tempAp;
fseek(ifp, 30, SEEK_CUR);
imgdata.other.FlashEC = _CanonConvertEV((signed short)get2());
fseek(ifp, 8 - 32, SEEK_CUR);
if ((tempAp = get2()) != 0x7fff)
imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp);
if (imgdata.lens.makernotes.CurAp < 0.7f)
{
fseek(ifp, 32, SEEK_CUR);
imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2());
}
if (!aperture)
aperture = imgdata.lens.makernotes.CurAp;
}
else if (tag == 0x0095 && // lens model tag
!imgdata.lens.makernotes.Lens[0])
{
fread(imgdata.lens.makernotes.Lens, 2, 1, ifp);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens
fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp);
else
{
char efs[2];
imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0];
imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1];
fread(efs, 2, 1, ifp);
if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77))
{ // "EF-S, TS-E, MP-E, EF-M" lenses
imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0];
imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1];
imgdata.lens.makernotes.Lens[4] = 32;
if (efs[1] == 83)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
}
else if (efs[1] == 77)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M;
}
}
else
{ // "EF" lenses
imgdata.lens.makernotes.Lens[2] = 32;
imgdata.lens.makernotes.Lens[3] = efs[0];
imgdata.lens.makernotes.Lens[4] = efs[1];
}
fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp);
}
}
else if (tag == 0x00a9)
{
long int save1 = ftell(ifp);
int c;
fseek(ifp, (0x1 << 1), SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
Canon_WBpresets(0, 0);
fseek(ifp, save1, SEEK_SET);
}
else if (tag == 0x00e0) // sensor info
{
imgdata.makernotes.canon.SensorWidth = (get2(), get2());
imgdata.makernotes.canon.SensorHeight = get2();
imgdata.makernotes.canon.SensorLeftBorder = (get2(), get2(), get2());
imgdata.makernotes.canon.SensorTopBorder = get2();
imgdata.makernotes.canon.SensorRightBorder = get2();
imgdata.makernotes.canon.SensorBottomBorder = get2();
imgdata.makernotes.canon.BlackMaskLeftBorder = get2();
imgdata.makernotes.canon.BlackMaskTopBorder = get2();
imgdata.makernotes.canon.BlackMaskRightBorder = get2();
imgdata.makernotes.canon.BlackMaskBottomBorder = get2();
}
else if (tag == 0x4001 && len > 500)
{
int c;
long int save1 = ftell(ifp);
switch (len)
{
case 582:
imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D
{
fseek(ifp, save1 + (0x1e << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x41 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x46 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x23 << 1), SEEK_SET);
Canon_WBpresets(2, 2);
fseek(ifp, save1 + (0x4b << 1), SEEK_SET);
Canon_WBCTpresets(1); // ABCT
}
break;
case 653:
imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2
{
fseek(ifp, save1 + (0x18 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x90 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x95 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x9a << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x27 << 1), SEEK_SET);
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xa4 << 1), SEEK_SET);
Canon_WBCTpresets(1); // ABCT
}
break;
case 796:
imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek(ifp, save1 + (0x44 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x49 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x71 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x76 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x7b << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x80 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x4e << 1), SEEK_SET);
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0x85 << 1), SEEK_SET);
Canon_WBCTpresets(0); // BCAT
fseek(ifp, save1 + (0x0c4 << 1), SEEK_SET); // offset 196 short
int bls = 0;
FORC4
bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
break;
// 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII
// 7D / 40D / 50D / 60D / 450D / 500D
// 550D / 1000D / 1100D
case 674:
case 692:
case 702:
case 1227:
case 1250:
case 1251:
case 1337:
case 1338:
case 1346:
imgdata.makernotes.canon.CanonColorDataVer = 4;
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek(ifp, save1 + (0x44 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x49 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x53 << 1), SEEK_SET);
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xa8 << 1), SEEK_SET);
Canon_WBCTpresets(0); // BCAT
fseek(ifp, save1 + (0x0e7 << 1), SEEK_SET); // offset 231 short
int bls = 0;
FORC4
bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5))
{
fseek(ifp, save1 + (0x2b9 << 1), SEEK_SET); // offset 697 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) ||
(imgdata.makernotes.canon.CanonColorDataSubVer == 7))
{
fseek(ifp, save1 + (0x2d0 << 1), SEEK_SET); // offset 720 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9)
{
fseek(ifp, save1 + (0x2d4 << 1), SEEK_SET); // offset 724 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
break;
case 5120:
imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, G7 X, G9 X, EOS M3, EOS M5, EOS M6
{
if ((unique_id == 0x03970000) || // G7 X Mark II
(unique_id == 0x04100000) || // G9 X Mark II
(unique_id == 0x80000394) || // EOS M5
(unique_id == 0x80000407)) // EOS M6
{
fseek(ifp, save1 + (0x4f << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
Canon_WBpresets(8, 24);
fseek(ifp, 168, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2();
fseek(ifp, 24, SEEK_CUR);
Canon_WBCTpresets(2); // BCADT
fseek(ifp, 6, SEEK_CUR);
}
else
{
fseek(ifp, save1 + (0x4c << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
get2();
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
get2();
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2();
get2();
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xba << 1), SEEK_SET);
Canon_WBCTpresets(2); // BCADT
fseek(ifp, save1 + (0x108 << 1), SEEK_SET); // offset 264 short
}
int bls = 0;
FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
break;
case 1273:
case 1275:
imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek(ifp, save1 + (0x44 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x49 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x67 << 1), SEEK_SET);
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xbc << 1), SEEK_SET);
Canon_WBCTpresets(0); // BCAT
fseek(ifp, save1 + (0x0fb << 1), SEEK_SET); // offset 251 short
int bls = 0;
FORC4
bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
fseek(ifp, save1 + (0x1e4 << 1), SEEK_SET); // offset 484 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
break;
// 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D
case 1312:
case 1313:
case 1316:
case 1506:
imgdata.makernotes.canon.CanonColorDataVer = 7;
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek(ifp, save1 + (0x44 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x49 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x80 << 1), SEEK_SET);
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0xd5 << 1), SEEK_SET);
Canon_WBCTpresets(0); // BCAT
fseek(ifp, save1 + (0x114 << 1), SEEK_SET); // offset 276 shorts
int bls = 0;
FORC4
bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
if (imgdata.makernotes.canon.CanonColorDataSubVer == 10)
{
fseek(ifp, save1 + (0x1fd << 1), SEEK_SET); // offset 509 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11)
{
fseek(ifp, save1 + (0x2dd << 1), SEEK_SET); // offset 733 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
break;
// 5DS / 5DS R / 80D / 1300D / 5D4 / 800D / 77D / 6D II / 200D
case 1560:
case 1592:
case 1353:
case 1602:
imgdata.makernotes.canon.CanonColorDataVer = 8;
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek(ifp, save1 + (0x44 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x49 << 1), SEEK_SET);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2();
fseek(ifp, save1 + (0x85 << 1), SEEK_SET);
Canon_WBpresets(2, 12);
fseek(ifp, save1 + (0x107 << 1), SEEK_SET);
Canon_WBCTpresets(0); // BCAT
fseek(ifp, save1 + (0x146 << 1), SEEK_SET); // offset 326 shorts
int bls = 0;
FORC4
bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2());
imgdata.makernotes.canon.AverageBlackLevel = bls / 4;
}
if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D
{
fseek(ifp, save1 + (0x231 << 1), SEEK_SET);
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
else
{
fseek(ifp, save1 + (0x30f << 1), SEEK_SET); // offset 783 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
break;
}
fseek(ifp, save1, SEEK_SET);
}
}
void CLASS setPentaxBodyFeatures(unsigned id)
{
imgdata.lens.makernotes.CamID = id;
switch (id)
{
case 0x12994:
case 0x12aa2:
case 0x12b1a:
case 0x12b60:
case 0x12b62:
case 0x12b7e:
case 0x12b80:
case 0x12b9c:
case 0x12b9d:
case 0x12ba2:
case 0x12c1e:
case 0x12c20:
case 0x12cd2:
case 0x12cd4:
case 0x12cfa:
case 0x12d72:
case 0x12d73:
case 0x12db8:
case 0x12dfe:
case 0x12e6c:
case 0x12e76:
case 0x12ef8:
case 0x12f52:
case 0x12f70:
case 0x12f71:
case 0x12fb6:
case 0x12fc0:
case 0x12fca:
case 0x1301a:
case 0x13024:
case 0x1309c:
case 0x13222:
case 0x1322c:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
break;
case 0x13092:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
break;
case 0x12e08:
case 0x13010:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF;
break;
case 0x12ee4:
case 0x12f66:
case 0x12f7a:
case 0x1302e:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q;
break;
default:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
return;
}
void CLASS PentaxISO(ushort c)
{
int code[] = {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, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261,
262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278};
double value[] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640,
800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000,
12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000,
204800, 258000, 325000, 409600, 516000, 650000, 819200, 50, 100, 200, 400, 800,
1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100,
1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200};
#define numel (sizeof(code) / sizeof(code[0]))
int i;
for (i = 0; i < numel; i++)
{
if (code[i] == c)
{
iso_speed = value[i];
return;
}
}
if (i == numel)
iso_speed = 65535.0f;
}
#undef numel
void CLASS PentaxLensInfo(unsigned id, unsigned len) // tag 0x0207
{
ushort iLensData = 0;
uchar *table_buf;
table_buf = (uchar *)malloc(MAX(len, 128));
fread(table_buf, len, 1, ifp);
if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D
(id == 0x12b9d) || // K110D
(id == 0x12ba2)) && // K100D Super
((!table_buf[20] || (table_buf[20] == 0xff)))))
{
iLensData = 3;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1];
}
else
switch (len)
{
case 90: // LensInfo3
iLensData = 13;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4];
break;
case 91: // LensInfo4
iLensData = 12;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4];
break;
case 80: // LensInfo5
case 128:
iLensData = 15;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) << 8) + table_buf[5];
break;
default:
if (id >= 0x12b9c) // LensInfo2
{
iLensData = 4;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) << 8) + table_buf[3];
}
}
if (iLensData)
{
if (table_buf[iLensData + 9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f))
imgdata.lens.makernotes.CurFocal =
10 * (table_buf[iLensData + 9] >> 2) * powf64(4, (table_buf[iLensData + 9] & 0x03) - 2);
if (table_buf[iLensData + 10] & 0xf0)
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 10] & 0xf0) >> 4) / 4.0f);
if (table_buf[iLensData + 10] & 0x0f)
imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 10] & 0x0f) + 10) / 4.0f);
if (iLensData != 12)
{
switch (table_buf[iLensData] & 0x06)
{
case 0:
imgdata.lens.makernotes.MinAp4MinFocal = 22.0f;
break;
case 2:
imgdata.lens.makernotes.MinAp4MinFocal = 32.0f;
break;
case 4:
imgdata.lens.makernotes.MinAp4MinFocal = 45.0f;
break;
case 6:
imgdata.lens.makernotes.MinAp4MinFocal = 16.0f;
break;
}
if (table_buf[iLensData] & 0x70)
imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f;
imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData + 3] & 0xf8);
imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData + 3] & 0x07);
if ((table_buf[iLensData + 14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f))
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 14] & 0x7f) - 1) / 32.0f);
}
else if ((id != 0x12e76) && // K-5
(table_buf[iLensData + 15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f))
{
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 15] & 0x7f) - 1) / 32.0f);
}
}
free(table_buf);
return;
}
void CLASS setPhaseOneFeatures(unsigned id)
{
ushort i;
static const struct
{
ushort id;
char t_model[32];
} p1_unique[] = {
// Phase One section:
{1, "Hasselblad V"},
{10, "PhaseOne/Mamiya"},
{12, "Contax 645"},
{16, "Hasselblad V"},
{17, "Hasselblad V"},
{18, "Contax 645"},
{19, "PhaseOne/Mamiya"},
{20, "Hasselblad V"},
{21, "Contax 645"},
{22, "PhaseOne/Mamiya"},
{23, "Hasselblad V"},
{24, "Hasselblad H"},
{25, "PhaseOne/Mamiya"},
{32, "Contax 645"},
{34, "Hasselblad V"},
{35, "Hasselblad V"},
{36, "Hasselblad H"},
{37, "Contax 645"},
{38, "PhaseOne/Mamiya"},
{39, "Hasselblad V"},
{40, "Hasselblad H"},
{41, "Contax 645"},
{42, "PhaseOne/Mamiya"},
{44, "Hasselblad V"},
{45, "Hasselblad H"},
{46, "Contax 645"},
{47, "PhaseOne/Mamiya"},
{48, "Hasselblad V"},
{49, "Hasselblad H"},
{50, "Contax 645"},
{51, "PhaseOne/Mamiya"},
{52, "Hasselblad V"},
{53, "Hasselblad H"},
{54, "Contax 645"},
{55, "PhaseOne/Mamiya"},
{67, "Hasselblad V"},
{68, "Hasselblad H"},
{69, "Contax 645"},
{70, "PhaseOne/Mamiya"},
{71, "Hasselblad V"},
{72, "Hasselblad H"},
{73, "Contax 645"},
{74, "PhaseOne/Mamiya"},
{76, "Hasselblad V"},
{77, "Hasselblad H"},
{78, "Contax 645"},
{79, "PhaseOne/Mamiya"},
{80, "Hasselblad V"},
{81, "Hasselblad H"},
{82, "Contax 645"},
{83, "PhaseOne/Mamiya"},
{84, "Hasselblad V"},
{85, "Hasselblad H"},
{86, "Contax 645"},
{87, "PhaseOne/Mamiya"},
{99, "Hasselblad V"},
{100, "Hasselblad H"},
{101, "Contax 645"},
{102, "PhaseOne/Mamiya"},
{103, "Hasselblad V"},
{104, "Hasselblad H"},
{105, "PhaseOne/Mamiya"},
{106, "Contax 645"},
{112, "Hasselblad V"},
{113, "Hasselblad H"},
{114, "Contax 645"},
{115, "PhaseOne/Mamiya"},
{131, "Hasselblad V"},
{132, "Hasselblad H"},
{133, "Contax 645"},
{134, "PhaseOne/Mamiya"},
{135, "Hasselblad V"},
{136, "Hasselblad H"},
{137, "Contax 645"},
{138, "PhaseOne/Mamiya"},
{140, "Hasselblad V"},
{141, "Hasselblad H"},
{142, "Contax 645"},
{143, "PhaseOne/Mamiya"},
{148, "Hasselblad V"},
{149, "Hasselblad H"},
{150, "Contax 645"},
{151, "PhaseOne/Mamiya"},
{160, "A-250"},
{161, "A-260"},
{162, "A-280"},
{167, "Hasselblad V"},
{168, "Hasselblad H"},
{169, "Contax 645"},
{170, "PhaseOne/Mamiya"},
{172, "Hasselblad V"},
{173, "Hasselblad H"},
{174, "Contax 645"},
{175, "PhaseOne/Mamiya"},
{176, "Hasselblad V"},
{177, "Hasselblad H"},
{178, "Contax 645"},
{179, "PhaseOne/Mamiya"},
{180, "Hasselblad V"},
{181, "Hasselblad H"},
{182, "Contax 645"},
{183, "PhaseOne/Mamiya"},
{208, "Hasselblad V"},
{211, "PhaseOne/Mamiya"},
{448, "Phase One 645AF"},
{457, "Phase One 645DF"},
{471, "Phase One 645DF+"},
{704, "Phase One iXA"},
{705, "Phase One iXA - R"},
{706, "Phase One iXU 150"},
{707, "Phase One iXU 150 - NIR"},
{708, "Phase One iXU 180"},
{721, "Phase One iXR"},
// Leaf section:
{333, "Mamiya"},
{329, "Universal"},
{330, "Hasselblad H1/H2"},
{332, "Contax"},
{336, "AFi"},
{327, "Mamiya"},
{324, "Universal"},
{325, "Hasselblad H1/H2"},
{326, "Contax"},
{335, "AFi"},
{340, "Mamiya"},
{337, "Universal"},
{338, "Hasselblad H1/H2"},
{339, "Contax"},
{323, "Mamiya"},
{320, "Universal"},
{322, "Hasselblad H1/H2"},
{321, "Contax"},
{334, "AFi"},
{369, "Universal"},
{370, "Mamiya"},
{371, "Hasselblad H1/H2"},
{372, "Contax"},
{373, "Afi"},
};
imgdata.lens.makernotes.CamID = id;
if (id && !imgdata.lens.makernotes.body[0])
{
for (i = 0; i < sizeof p1_unique / sizeof *p1_unique; i++)
if (id == p1_unique[i].id)
{
strcpy(imgdata.lens.makernotes.body, p1_unique[i].t_model);
}
}
return;
}
void CLASS parseFujiMakernotes(unsigned tag, unsigned type)
{
switch (tag)
{
case 0x1002:
imgdata.makernotes.fuji.WB_Preset = get2();
break;
case 0x1011:
imgdata.other.FlashEC = getreal(type);
break;
case 0x1020:
imgdata.makernotes.fuji.Macro = get2();
break;
case 0x1021:
imgdata.makernotes.fuji.FocusMode = get2();
break;
case 0x1022:
imgdata.makernotes.fuji.AFMode = get2();
break;
case 0x1023:
imgdata.makernotes.fuji.FocusPixel[0] = get2();
imgdata.makernotes.fuji.FocusPixel[1] = get2();
break;
case 0x1034:
imgdata.makernotes.fuji.ExrMode = get2();
break;
case 0x1050:
imgdata.makernotes.fuji.ShutterType = get2();
break;
case 0x1400:
imgdata.makernotes.fuji.FujiDynamicRange = get2();
break;
case 0x1401:
imgdata.makernotes.fuji.FujiFilmMode = get2();
break;
case 0x1402:
imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2();
break;
case 0x1403:
imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2();
break;
case 0x140b:
imgdata.makernotes.fuji.FujiAutoDynamicRange = get2();
break;
case 0x1404:
imgdata.lens.makernotes.MinFocal = getreal(type);
break;
case 0x1405:
imgdata.lens.makernotes.MaxFocal = getreal(type);
break;
case 0x1406:
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
break;
case 0x1407:
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
break;
case 0x1422:
imgdata.makernotes.fuji.ImageStabilization[0] = get2();
imgdata.makernotes.fuji.ImageStabilization[1] = get2();
imgdata.makernotes.fuji.ImageStabilization[2] = get2();
imgdata.shootinginfo.ImageStabilization =
(imgdata.makernotes.fuji.ImageStabilization[0] << 9) + imgdata.makernotes.fuji.ImageStabilization[1];
break;
case 0x1431:
imgdata.makernotes.fuji.Rating = get4();
break;
case 0x3820:
imgdata.makernotes.fuji.FrameRate = get2();
break;
case 0x3821:
imgdata.makernotes.fuji.FrameWidth = get2();
break;
case 0x3822:
imgdata.makernotes.fuji.FrameHeight = get2();
break;
}
return;
}
void CLASS setSonyBodyFeatures(unsigned id)
{
imgdata.lens.makernotes.CamID = id;
if ( // FF cameras
(id == 257) || // a900
(id == 269) || // a850
(id == 340) || // ILCE-7M2
(id == 318) || // ILCE-7S
(id == 350) || // ILCE-7SM2
(id == 311) || // ILCE-7R
(id == 347) || // ILCE-7RM2
(id == 306) || // ILCE-7
(id == 298) || // DSC-RX1
(id == 299) || // NEX-VG900
(id == 310) || // DSC-RX1R
(id == 344) || // DSC-RX1RM2
(id == 354) || // ILCA-99M2
(id == 358) || // ILCE-9
(id == 294) // SLT-99, Hasselblad HV
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
}
else if ((id == 297) || // DSC-RX100
(id == 308) || // DSC-RX100M2
(id == 309) || // DSC-RX10
(id == 317) || // DSC-RX100M3
(id == 341) || // DSC-RX100M4
(id == 342) || // DSC-RX10M2
(id == 355) || // DSC-RX10M3
(id == 356) // DSC-RX100M5
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH;
}
else if (id != 002) // DSC-R1
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
}
if ( // E-mount cameras, ILCE series
(id == 302) || (id == 306) || (id == 311) || (id == 312) || (id == 313) || (id == 318) || (id == 339) ||
(id == 340) || (id == 346) || (id == 347) || (id == 350) || (id == 360) || (id == 358))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCE;
}
else if ( // E-mount cameras, NEX series
(id == 278) || (id == 279) || (id == 284) || (id == 288) || (id == 289) || (id == 290) || (id == 293) ||
(id == 295) || (id == 296) || (id == 299) || (id == 300) || (id == 305) || (id == 307))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_NEX;
}
else if ( // A-mount cameras, DSLR series
(id == 256) || (id == 257) || (id == 258) || (id == 259) || (id == 260) || (id == 261) || (id == 262) ||
(id == 263) || (id == 264) || (id == 265) || (id == 266) || (id == 269) || (id == 270) || (id == 273) ||
(id == 274) || (id == 275) || (id == 282) || (id == 283))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSLR;
}
else if ( // A-mount cameras, SLT series
(id == 280) || (id == 281) || (id == 285) || (id == 286) || (id == 287) || (id == 291) || (id == 292) ||
(id == 294) || (id == 303))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_SLT;
}
else if ( // A-mount cameras, ILCA series
(id == 319) || (id == 353) || (id == 354))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCA;
}
else if ( // DSC
(id == 002) || // DSC-R1
(id == 297) || // DSC-RX100
(id == 298) || // DSC-RX1
(id == 308) || // DSC-RX100M2
(id == 309) || // DSC-RX10
(id == 310) || // DSC-RX1R
(id == 344) || // DSC-RX1RM2
(id == 317) || // DSC-RX100M3
(id == 341) || // DSC-RX100M4
(id == 342) || // DSC-RX10M2
(id == 355) || // DSC-RX10M3
(id == 356) // DSC-RX100M5
)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC;
}
return;
}
void CLASS parseSonyLensType2(uchar a, uchar b)
{
ushort lid2;
lid2 = (((ushort)a) << 8) | ((ushort)b);
if (!lid2)
return;
if (lid2 < 0x100)
{
if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00))
{
imgdata.lens.makernotes.AdapterID = lid2;
switch (lid2)
{
case 1:
case 2:
case 3:
case 6:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
break;
case 44:
case 78:
case 239:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
break;
}
}
}
else
imgdata.lens.makernotes.LensID = lid2;
if ((lid2 >= 50481) && (lid2 < 50500))
{
strcpy(imgdata.lens.makernotes.Adapter, "MC-11");
imgdata.lens.makernotes.AdapterID = 0x4900;
}
return;
}
#define strnXcat(buf, string) strncat(buf, string, LIM(sizeof(buf) - strbuflen(buf) - 1, 0, sizeof(buf)))
void CLASS parseSonyLensFeatures(uchar a, uchar b)
{
ushort features;
features = (((ushort)a) << 8) | ((ushort)b);
if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) ||
(imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features)
return;
imgdata.lens.makernotes.LensFeatures_pre[0] = 0;
imgdata.lens.makernotes.LensFeatures_suf[0] = 0;
if ((features & 0x0200) && (features & 0x0100))
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E");
else if (features & 0x0200)
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE");
else if (features & 0x0100)
strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT");
if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount)
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
if ((features & 0x0200) && (features & 0x0100))
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
}
else if (features & 0x0200)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
}
else if (features & 0x0100)
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
}
}
if (features & 0x4000)
strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ");
if (features & 0x0008)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G");
else if (features & 0x0004)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA");
if ((features & 0x0020) && (features & 0x0040))
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro");
else if (features & 0x0020)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF");
else if (features & 0x0040)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex");
else if (features & 0x0080)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye");
if (features & 0x0001)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM");
else if (features & 0x0002)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM");
if (features & 0x8000)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS");
if (features & 0x2000)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE");
if (features & 0x0800)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II");
if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ')
memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf + 1,
strbuflen(imgdata.lens.makernotes.LensFeatures_suf) - 1);
return;
}
#undef strnXcat
void CLASS process_Sony_0x940c(uchar *buf)
{
ushort lid2;
if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) &&
(imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F))
{
switch (SonySubstitution[buf[0x0008]])
{
case 1:
case 5:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
break;
case 4:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
break;
}
}
lid2 = (((ushort)SonySubstitution[buf[0x000a]]) << 8) | ((ushort)SonySubstitution[buf[0x0009]]);
if ((lid2 > 0) && (lid2 < 32784))
parseSonyLensType2(SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids
SonySubstitution[buf[0x0009]]);
return;
}
void CLASS process_Sony_0x9050(uchar *buf, unsigned id)
{
ushort lid;
if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) &&
(imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens))
{
if (buf[0])
imgdata.lens.makernotes.MaxAp4CurFocal =
my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f;
if (buf[1])
imgdata.lens.makernotes.MinAp4CurFocal =
my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f;
}
if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)
{
if (buf[0x3d] | buf[0x3c])
{
lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]];
imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid / 256.0f - 16.0f) / 2.0f);
}
if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) &&
(imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F))
imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]];
if (buf[0x106])
imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]];
}
if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)
{
parseSonyLensType2(SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids
SonySubstitution[buf[0x0107]]);
}
if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) &&
(buf[0x010a] | buf[0x0109]))
{
imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids
SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]];
if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900))
{
imgdata.lens.makernotes.AdapterID = 0x4900;
imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F;
strcpy(imgdata.lens.makernotes.Adapter, "MC-11");
}
else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) &&
(imgdata.lens.makernotes.LensID != 0xFF00))
{
imgdata.lens.makernotes.AdapterID = 0xEF00;
imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
}
}
if ((id >= 286) && (id <= 293))
// "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E",
// "SLT-A37", "SLT-A57", "NEX-F3", "Lunar"
parseSonyLensFeatures(SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]);
else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)
parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]);
if ((id == 347) || (id == 350) || (id == 357))
{
unsigned long long b88 = SonySubstitution[buf[0x88]];
unsigned long long b89 = SonySubstitution[buf[0x89]];
unsigned long long b8a = SonySubstitution[buf[0x8a]];
unsigned long long b8b = SonySubstitution[buf[0x8b]];
unsigned long long b8c = SonySubstitution[buf[0x8c]];
unsigned long long b8d = SonySubstitution[buf[0x8d]];
sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx",
(b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d);
}
else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (id > 279) && (id != 282) && (id != 283))
{
unsigned long long bf0 = SonySubstitution[buf[0xf0]];
unsigned long long bf1 = SonySubstitution[buf[0xf1]];
unsigned long long bf2 = SonySubstitution[buf[0xf2]];
unsigned long long bf3 = SonySubstitution[buf[0xf3]];
unsigned long long bf4 = SonySubstitution[buf[0xf4]];
sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx",
(bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4);
}
else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290))
{
unsigned b7c = SonySubstitution[buf[0x7c]];
unsigned b7d = SonySubstitution[buf[0x7d]];
unsigned b7e = SonySubstitution[buf[0x7e]];
unsigned b7f = SonySubstitution[buf[0x7f]];
sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f);
}
return;
}
void CLASS parseSonyMakernotes(unsigned tag, unsigned type, unsigned len, unsigned dng_writer, uchar *&table_buf_0x9050,
ushort &table_buf_0x9050_present, uchar *&table_buf_0x940c,
ushort &table_buf_0x940c_present)
{
ushort lid;
uchar *table_buf;
if (tag == 0xb001) // Sony ModelID
{
unique_id = get2();
setSonyBodyFeatures(unique_id);
if (table_buf_0x9050_present)
{
process_Sony_0x9050(table_buf_0x9050, unique_id);
free(table_buf_0x9050);
table_buf_0x9050_present = 0;
}
if (table_buf_0x940c_present)
{
if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)
{
process_Sony_0x940c(table_buf_0x940c);
}
free(table_buf_0x940c);
table_buf_0x940c_present = 0;
}
}
else if ((tag == 0x0010) && // CameraInfo
strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) &&
((len == 368) || // a700
(len == 5478) || // a850, a900
(len == 5506) || // a200, a300, a350
(len == 6118) || // a230, a290, a330, a380, a390
// a450, a500, a550, a560, a580
// a33, a35, a55
// NEX3, NEX5, NEX5C, NEXC3, VG10E
(len == 15360)))
{
table_buf = (uchar *)malloc(len);
fread(table_buf, len, 1, ifp);
if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) &&
memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8))
{
switch (len)
{
case 368:
case 5478:
// a700, a850, a900: CameraInfo
if ((!dng_writer) ||
(saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7])))
{
if (table_buf[0] | table_buf[3])
imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]);
if (table_buf[2] | table_buf[5])
imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]);
if (table_buf[4])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f;
if (table_buf[4])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f;
parseSonyLensFeatures(table_buf[1], table_buf[6]);
}
break;
default:
// CameraInfo2 & 3
if ((!dng_writer) ||
(saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])))
{
if (table_buf[1] | table_buf[2])
imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]);
if (table_buf[3] | table_buf[4])
imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]);
if (table_buf[5])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f;
if (table_buf[6])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f;
parseSonyLensFeatures(table_buf[0], table_buf[7]);
}
}
}
free(table_buf);
}
else if ((!dng_writer) && (tag == 0x0020) && // WBInfoA100, needs 0xb028 processing
!strncasecmp(model, "DSLR-A100", 9))
{
fseek(ifp, 0x49dc, SEEK_CUR);
stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp);
}
else if (tag == 0x0104)
{
imgdata.other.FlashEC = getreal(type);
}
else if (tag == 0x0105) // Teleconverter
{
imgdata.lens.makernotes.TeleconverterID = get2();
}
else if (tag == 0x0114 && len < 256000) // CameraSettings
{
table_buf = (uchar *)malloc(len);
fread(table_buf, len, 1, ifp);
switch (len)
{
case 280:
case 364:
case 332:
// CameraSettings and CameraSettings2 are big endian
if (table_buf[2] | table_buf[3])
{
lid = (((ushort)table_buf[2]) << 8) | ((ushort)table_buf[3]);
imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid / 8.0f - 1.0f) / 2.0f);
}
break;
case 1536:
case 2048:
// CameraSettings3 are little endian
parseSonyLensType2(table_buf[1016], table_buf[1015]);
if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF)
{
switch (table_buf[153])
{
case 16:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
break;
case 17:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
break;
}
}
break;
}
free(table_buf);
}
else if (tag == 0x9050 && len < 256000) // little endian
{
table_buf_0x9050 = (uchar *)malloc(len);
table_buf_0x9050_present = 1;
fread(table_buf_0x9050, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID);
free(table_buf_0x9050);
table_buf_0x9050_present = 0;
}
}
else if (tag == 0x940c && len < 256000)
{
table_buf_0x940c = (uchar *)malloc(len);
table_buf_0x940c_present = 1;
fread(table_buf_0x940c, len, 1, ifp);
if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E))
{
process_Sony_0x940c(table_buf_0x940c);
free(table_buf_0x940c);
table_buf_0x940c_present = 0;
}
}
else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1))
{
imgdata.lens.makernotes.LensID = get4();
if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900))
{
imgdata.lens.makernotes.AdapterID = 0x4900;
imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F;
strcpy(imgdata.lens.makernotes.Adapter, "MC-11");
}
else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) &&
(imgdata.lens.makernotes.LensID != 0xFF00))
{
imgdata.lens.makernotes.AdapterID = 0xEF00;
imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
}
if (tag == 0x010c)
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;
}
else if (tag == 0xb02a && len < 256000) // Sony LensSpec
{
table_buf = (uchar *)malloc(len);
fread(table_buf, len, 1, ifp);
if ((!dng_writer) ||
(saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])))
{
if (table_buf[1] | table_buf[2])
imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]);
if (table_buf[3] | table_buf[4])
imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]);
if (table_buf[5])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f;
if (table_buf[6])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f;
parseSonyLensFeatures(table_buf[0], table_buf[7]);
}
free(table_buf);
}
}
void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer)
{
unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c;
unsigned i;
uchar NikonKey, ci, cj, ck;
unsigned serial = 0;
unsigned custom_serial = 0;
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
unsigned NikonFlashInfoVersion = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_present = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_present = 0;
short morder, sorder = order;
char buf[10];
INT64 fsize = ifp->size();
fread(buf, 1, 10, ifp);
if (!strcmp(buf, "Nikon"))
{
base = ftell(ifp);
order = get2();
if (get2() != 42)
goto quit;
offset = get4();
fseek(ifp, offset - 8, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") ||
(!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG)))
{
base = ftell(ifp) - 10;
fseek(ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O')
get2();
}
else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic"))
{
goto nf;
}
else if (!strncmp(buf, "FUJIFILM", 8))
{
base = ftell(ifp) - 10;
nf:
order = 0x4949;
fseek(ifp, 2, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON"))
fseek(ifp, -2, SEEK_CUR);
else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC"))
fseek(ifp, -4, SEEK_CUR);
else
{
fseek(ifp, -10, SEEK_CUR);
if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)))
base = ftell(ifp);
}
entries = get2();
if (entries > 1000)
return;
morder = order;
while (entries--)
{
order = morder;
tiff_get(base, &tag, &type, &len, &save);
INT64 pos = ifp->tell();
if (len > 8 && pos + len > 2 * fsize)
continue;
tag |= uptag << 16;
if (len > 100 * 1024 * 1024)
goto next; // 100Mb tag? No!
if (!strncmp(make, "Canon", 5))
{
if (tag == 0x000d && len < 256000) // camera info
{
CanonCameraInfo = (uchar *)malloc(len);
fread(CanonCameraInfo, len, 1, ifp);
lenCanonCameraInfo = len;
}
else if (tag == 0x10) // Canon ModelID
{
unique_id = get4();
if (unique_id == 0x03740000) // EOS M3
unique_id = 0x80000374;
else if (unique_id == 0x03840000) // EOS M10
unique_id = 0x80000384;
else if (unique_id == 0x03940000) // EOS M5
unique_id = 0x80000394;
else if (unique_id == 0x04070000) // EOS M6
unique_id = 0x80000407;
setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo)
{
processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo);
free(CanonCameraInfo);
CanonCameraInfo = 0;
lenCanonCameraInfo = 0;
}
}
else
parseCanonMakernotes(tag, type, len);
}
else if (!strncmp(make, "FUJI", 4))
parseFujiMakernotes(tag, type);
else if (!strncasecmp(make, "LEICA", 5))
{
if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9))
{
int ind = tag == 0x035e ? 0 : 1;
for (int j = 0; j < 3; j++)
FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type);
imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX;
}
if ((tag == 0x0303) && (type != 4))
{
stmread(imgdata.lens.makernotes.Lens, len, ifp);
}
if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5)))
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote(base, 0x3400);
}
}
else if (!strncmp(make, "NIKON", 5))
{
if (tag == 0x1d) // serial number
while ((c = fgetc(ifp)) && c != EOF)
{
if ((!custom_serial) && (!isdigit(c)))
{
if ((strbuflen(model) == 3) && (!strcmp(model, "D50")))
{
custom_serial = 34;
}
else
{
custom_serial = 96;
}
}
serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10);
}
else if (tag == 0x000a)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
else if (tag == 0x0082) // lens attachment
{
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c);
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
}
}
else if (tag == 0x0093)
{
imgdata.makernotes.nikon.NEFCompression = i = get2();
if ((i == 7) || (i == 9))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0097)
{
for (i = 0; i < 4; i++)
ver97 = ver97 * 10 + fgetc(ifp) - '0';
if (ver97 == 601) // Coolpix A
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100:
lenNikonLensData = 9;
break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203:
lenNikonLensData = 15;
break;
case 204:
lenNikonLensData = 16;
break;
case 400:
lenNikonLensData = 459;
break;
case 401:
lenNikonLensData = 590;
break;
case 402:
lenNikonLensData = 509;
break;
case 403:
lenNikonLensData = 879;
break;
}
if (lenNikonLensData)
{
table_buf = (uchar *)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
free(table_buf);
lenNikonLensData = 0;
}
}
}
else if (tag == 0xa7) // shutter count
{
NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
if (custom_serial)
{
ci = xlat[0][custom_serial];
}
else
{
ci = xlat[0][serial & 0xff];
}
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
free(table_buf);
}
}
else if (tag == 0x00a8) // contains flash data
{
for (i = 0; i < 4; i++)
{
NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0';
}
}
else if (tag == 37 && (!iso_speed || iso_speed == 65535))
{
unsigned char cc;
fread(&cc, 1, 1, ifp);
iso_speed = (int)(100.0 * powf64(2.0, (double)(cc) / 12.0 - 5.0));
break;
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
int SubDirOffsetValid = strncmp(model, "E-300", 5) && strncmp(model, "E-330", 5) && strncmp(model, "E-400", 5) &&
strncmp(model, "E-500", 5) && strncmp(model, "E-1", 3);
if ((tag == 0x2010) || (tag == 0x2020))
{
fseek(ifp, save - 4, SEEK_SET);
fseek(ifp, base + get4(), SEEK_SET);
parse_makernote_0xc634(base, tag, dng_writer);
}
if (!SubDirOffsetValid && ((len > 4) || (((type == 3) || (type == 8)) && (len > 2)) ||
(((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9)))
goto skip_Oly_broken_tags;
switch (tag)
{
case 0x0207:
case 0x20100100:
{
uchar sOlyID[8];
unsigned long long OlyID;
fread(sOlyID, MIN(len, 7), 1, ifp);
sOlyID[7] = 0;
OlyID = sOlyID[0];
i = 1;
while (i < 7 && sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type) / 2);
break;
case 0x20100102:
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
break;
case 0x20100201:
imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp) << 16 |
(unsigned long long)(fgetc(ifp), fgetc(ifp)) << 8 |
(unsigned long long)fgetc(ifp);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT;
if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) &&
(imgdata.lens.makernotes.LensID & 0x10))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT;
}
break;
case 0x20100202:
if ((!imgdata.lens.LensSerial[0]))
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0x20100203:
stmread(imgdata.lens.makernotes.Lens, len, ifp);
break;
case 0x20100205:
imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100207:
imgdata.lens.makernotes.MinFocal = (float)get2();
break;
case 0x20100208:
imgdata.lens.makernotes.MaxFocal = (float)get2();
if (imgdata.lens.makernotes.MaxFocal > 1000.0f)
imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal;
break;
case 0x2010020a:
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100301:
imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8;
fgetc(ifp);
imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp);
break;
case 0x20100303:
stmread(imgdata.lens.makernotes.Teleconverter, len, ifp);
break;
case 0x20100403:
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
break;
case 0x20200401:
imgdata.other.FlashEC = getreal(type);
break;
}
skip_Oly_broken_tags:;
}
else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG)))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
}
else if (tag == 0x0013)
{
imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f;
}
else if (tag == 0x0014)
{
PentaxISO(get2());
}
else if (tag == 0x001d)
{
imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f;
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x004d)
{
if (type == 9)
imgdata.other.FlashEC = getreal(type) / 256.0f;
else
imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f;
}
else if (tag == 0x007e)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = (long)(-1) * get4();
}
else if (tag == 0x0207)
{
if (len < 65535) // Safety belt
PentaxLensInfo(imgdata.lens.makernotes.CamID, len);
}
else if ((tag >= 0x020d) && (tag <= 0x0214))
{
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0221)
{
int nWB = get2();
if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0]))
for (int i = 0; i < nWB; i++)
{
imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2();
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = get2();
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000;
imgdata.color.WBCT_Coeffs[i][3] = get2();
}
}
else if (tag == 0x0215)
{
fseek(ifp, 16, SEEK_CUR);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4());
}
else if (tag == 0x0229)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x022d)
{
int wb_ind;
getc(ifp);
for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++)
{
wb_ind = getc(ifp);
if (wb_ind < nPentax_wb_list2)
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2();
}
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo[20];
fseek(ifp, 12, SEEK_CUR);
stread(imgdata.lens.makernotes.Lens, 30, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
stread(LensInfo, 20, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))
{
if (tag == 0x0002)
{
if (get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
imgdata.lens.makernotes.CamID = unique_id = get4();
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa005)
{
stmread(imgdata.lens.InternalLensSerial, len, ifp);
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2))))
{
parseSonyMakernotes(tag, type, len, AdobeDNG, table_buf_0x9050, table_buf_0x9050_present, table_buf_0x940c,
table_buf_0x940c_present);
}
next:
fseek(ifp, save, SEEK_SET);
}
quit:
order = sorder;
}
#else
void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */}
#endif
void CLASS parse_makernote(int base, int uptag)
{
unsigned offset = 0, entries, tag, type, len, save, c;
unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0};
uchar buf97[324], ci, cj, ck;
short morder, sorder = order;
char buf[10];
unsigned SamsungKey[11];
uchar NikonKey;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned custom_serial = 0;
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
unsigned NikonFlashInfoVersion = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_present = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_present = 0;
INT64 fsize = ifp->size();
#endif
/*
The MakerNote might have its own TIFF header (possibly with
its own byte-order!), or it might just be a table.
*/
if (!strncmp(make, "Nokia", 5))
return;
fread(buf, 1, 10, ifp);
if (!strncmp(buf, "KDK", 3) || /* these aren't TIFF tables */
!strncmp(buf, "VER", 3) || !strncmp(buf, "IIII", 4) || !strncmp(buf, "MMMM", 4))
return;
if (!strncmp(buf, "KC", 2) || /* Konica KD-400Z, KD-510Z */
!strncmp(buf, "MLY", 3))
{ /* Minolta DiMAGE G series */
order = 0x4d4d;
while ((i = ftell(ifp)) < data_offset && i < 16384)
{
wb[0] = wb[2];
wb[2] = wb[1];
wb[1] = wb[3];
wb[3] = get2();
if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640)
FORC4 cam_mul[c] = wb[c];
}
goto quit;
}
if (!strcmp(buf, "Nikon"))
{
base = ftell(ifp);
order = get2();
if (get2() != 42)
goto quit;
offset = get4();
fseek(ifp, offset - 8, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX "))
{
base = ftell(ifp) - 10;
fseek(ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O')
get2();
}
else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic"))
{
goto nf;
}
else if (!strncmp(buf, "FUJIFILM", 8))
{
base = ftell(ifp) - 10;
nf:
order = 0x4949;
fseek(ifp, 2, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON"))
fseek(ifp, -2, SEEK_CUR);
else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC"))
fseek(ifp, -4, SEEK_CUR);
else
{
fseek(ifp, -10, SEEK_CUR);
if (!strncmp(make, "SAMSUNG", 7))
base = ftell(ifp);
}
// adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400
if (!strncasecmp(make, "LEICA", 5))
{
if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7))
{
base = ftell(ifp) - 8;
}
else if (!strncasecmp(model, "LEICA M (Typ 240)", 17))
{
base = 0;
}
else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) ||
!strncasecmp(model, "Leica M Monochrom", 11))
{
if (!uptag)
{
base = ftell(ifp) - 10;
fseek(ifp, 8, SEEK_CUR);
}
else if (uptag == 0x3400)
{
fseek(ifp, 10, SEEK_CUR);
base += 10;
}
}
else if (!strncasecmp(model, "LEICA T", 7))
{
base = ftell(ifp) - 8;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T;
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (!strncasecmp(model, "LEICA SL", 8))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
}
#endif
}
entries = get2();
if (entries > 1000)
return;
morder = order;
while (entries--)
{
order = morder;
tiff_get(base, &tag, &type, &len, &save);
tag |= uptag << 16;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 _pos = ftell(ifp);
if (len > 8 && _pos + len > 2 * fsize)
continue;
if (!strncmp(make, "Canon", 5))
{
if (tag == 0x000d && len < 256000) // camera info
{
CanonCameraInfo = (uchar *)malloc(len);
fread(CanonCameraInfo, len, 1, ifp);
lenCanonCameraInfo = len;
}
else if (tag == 0x10) // Canon ModelID
{
unique_id = get4();
if (unique_id == 0x03740000) // EOS M3
unique_id = 0x80000374;
else if (unique_id == 0x03840000) // EOS M10
unique_id = 0x80000384;
else if (unique_id == 0x03940000) // EOS M5
unique_id = 0x80000394;
else if (unique_id == 0x04070000) // EOS M6
unique_id = 0x80000407;
setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo)
{
processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo);
free(CanonCameraInfo);
CanonCameraInfo = 0;
lenCanonCameraInfo = 0;
}
}
else
parseCanonMakernotes(tag, type, len);
}
else if (!strncmp(make, "FUJI", 4))
{
if (tag == 0x0010)
{
char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)];
char *words[4];
char yy[2], mm[3], dd[3], ystr[16], ynum[16];
int year, nwords, ynum_len;
unsigned c;
stmread(FujiSerial, len, ifp);
nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial));
for (int i = 0; i < nwords; i++)
{
mm[2] = dd[2] = 0;
if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18)
if (i == 0)
strncpy(imgdata.shootinginfo.InternalBodySerial, words[0],
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
else
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
snprintf(tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
else
{
strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2);
strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2);
strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2);
year = (yy[0] - '0') * 10 + (yy[1] - '0');
if (year < 70)
year += 2000;
else
year += 1900;
ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18;
strncpy(ynum, words[i], ynum_len);
ynum[ynum_len] = 0;
for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, "%2x", &c); j += 2)
ystr[j / 2] = c;
ystr[ynum_len / 2 + 1] = 0;
strcpy(model2, ystr);
if (i == 0)
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
if (nwords == 1)
snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s",
words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr,
year, mm, dd);
else
snprintf(tbuf, sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd,
words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
else
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm,
dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12);
strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial) - 1);
}
}
}
}
else
parseFujiMakernotes(tag, type);
}
else if (!strncasecmp(model, "Hasselblad X1D", 14) || !strncasecmp(model, "Hasselblad H6D", 14))
{
if (tag == 0x0045)
{
imgdata.makernotes.hasselblad.BaseISO = get4();
}
else if (tag == 0x0046)
{
imgdata.makernotes.hasselblad.Gain = getreal(type);
}
}
else if (!strncasecmp(make, "LEICA", 5))
{
if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9))
{
int ind = tag == 0x035e ? 0 : 1;
for (int j = 0; j < 3; j++)
FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type);
imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX;
}
if ((tag == 0x0303) && (type != 4))
{
stmread(imgdata.lens.makernotes.Lens, len, ifp);
}
if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5)))
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote(base, 0x3400);
}
}
else if (!strncmp(make, "NIKON", 5))
{
if (tag == 0x000a)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
else if (tag == 0x0012)
{
char a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
imgdata.other.FlashEC = (float)(a * b) / (float)c;
}
else if (tag == 0x0082) // lens attachment
{
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c);
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f;
}
}
else if (tag == 0x0093) // Nikon compression
{
imgdata.makernotes.nikon.NEFCompression = i = get2();
if ((i == 7) || (i == 9))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100:
lenNikonLensData = 9;
break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203:
lenNikonLensData = 15;
break;
case 204:
lenNikonLensData = 16;
break;
case 400:
lenNikonLensData = 459;
break;
case 401:
lenNikonLensData = 590;
break;
case 402:
lenNikonLensData = 509;
break;
case 403:
lenNikonLensData = 879;
break;
}
if (lenNikonLensData > 0)
{
table_buf = (uchar *)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
free(table_buf);
lenNikonLensData = 0;
}
}
}
else if (tag == 0x00a0)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x00a8) // contains flash data
{
for (i = 0; i < 4; i++)
{
NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0';
}
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
switch (tag)
{
case 0x0404:
case 0x101a:
case 0x20100101:
if (!imgdata.shootinginfo.BodySerial[0])
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0x20100102:
if (!imgdata.shootinginfo.InternalBodySerial[0])
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
break;
case 0x0207:
case 0x20100100:
{
uchar sOlyID[8];
unsigned long long OlyID;
fread(sOlyID, MIN(len, 7), 1, ifp);
sOlyID[7] = 0;
OlyID = sOlyID[0];
i = 1;
while (i < 7 && sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type) / 2);
break;
case 0x20401112:
imgdata.makernotes.olympus.OlympusCropID = get2();
break;
case 0x20401113:
FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2();
break;
case 0x20100201:
{
unsigned long long oly_lensid[3];
oly_lensid[0] = fgetc(ifp);
fgetc(ifp);
oly_lensid[1] = fgetc(ifp);
oly_lensid[2] = fgetc(ifp);
imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2];
}
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT;
if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) &&
(imgdata.lens.makernotes.LensID & 0x10))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT;
}
break;
case 0x20100202:
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0x20100203:
stmread(imgdata.lens.makernotes.Lens, len, ifp);
break;
case 0x20100205:
imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100207:
imgdata.lens.makernotes.MinFocal = (float)get2();
break;
case 0x20100208:
imgdata.lens.makernotes.MaxFocal = (float)get2();
if (imgdata.lens.makernotes.MaxFocal > 1000.0f)
imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal;
break;
case 0x2010020a:
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100301:
imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8;
fgetc(ifp);
imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp);
break;
case 0x20100303:
stmread(imgdata.lens.makernotes.Teleconverter, len, ifp);
break;
case 0x20100403:
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
break;
}
}
else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
char buffer[17];
int count = 0;
fread(buffer, 16, 1, ifp);
buffer[16] = 0;
for (int i = 0; i < 16; i++)
{
// sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]);
if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i])))
count++;
}
if (count == 16)
{
sprintf(imgdata.shootinginfo.BodySerial, "%8s", buffer + 8);
buffer[8] = 0;
sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer);
}
else
{
sprintf(imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10],
buffer[11]);
}
}
else if ((tag == 0x1001) && (type == 3))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
imgdata.lens.makernotes.FocalType = 1;
}
else if ((tag == 0x100b) && (type == 10))
{
imgdata.other.FlashEC = getreal(type);
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
}
else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6))
{
if ((tag == 0x0005) && !strncmp(model, "GXR", 3))
{
char buffer[9];
buffer[8] = 0;
fread(buffer, 8, 1, ifp);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer);
}
else if ((tag == 0x100b) && (type == 10))
{
imgdata.other.FlashEC = getreal(type);
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
else if ((tag == 0x2001) && !strncmp(model, "GXR", 3))
{
short ntags, cur_tag;
fseek(ifp, 20, SEEK_CUR);
ntags = get2();
cur_tag = get2();
while (cur_tag != 0x002c)
{
fseek(ifp, 10, SEEK_CUR);
cur_tag = get2();
}
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, get4() + 20, SEEK_SET);
stread(imgdata.shootinginfo.BodySerial, 12, ifp);
get2();
imgdata.lens.makernotes.LensID = getc(ifp) - '0';
switch (imgdata.lens.makernotes.LensID)
{
case 1:
case 2:
case 3:
case 5:
case 6:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule;
break;
case 8:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
break;
default:
imgdata.lens.makernotes.LensID = -1;
}
fseek(ifp, 17, SEEK_CUR);
stread(imgdata.lens.LensSerial, 12, ifp);
}
}
else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && dng_version)) &&
strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
}
else if (tag == 0x0013)
{
imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f;
}
else if (tag == 0x0014)
{
PentaxISO(get2());
}
else if (tag == 0x001d)
{
imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f;
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x004d)
{
if (type == 9)
imgdata.other.FlashEC = getreal(type) / 256.0f;
else
imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f;
}
else if (tag == 0x007e)
{
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = (long)(-1) * get4();
}
else if (tag == 0x0207)
{
if (len < 65535) // Safety belt
PentaxLensInfo(imgdata.lens.makernotes.CamID, len);
}
else if ((tag >= 0x020d) && (tag <= 0x0214))
{
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0221)
{
int nWB = get2();
if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0]))
for (int i = 0; i < nWB; i++)
{
imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2();
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = get2();
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000;
imgdata.color.WBCT_Coeffs[i][3] = get2();
}
}
else if (tag == 0x0215)
{
fseek(ifp, 16, SEEK_CUR);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4());
}
else if (tag == 0x0229)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x022d)
{
int wb_ind;
getc(ifp);
for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++)
{
wb_ind = getc(ifp);
if (wb_ind < nPentax_wb_list2)
FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2();
}
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo[20];
fseek(ifp, 2, SEEK_CUR);
stread(imgdata.lens.makernotes.Lens, 30, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
stread(LensInfo, 20, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7))
{
if (tag == 0x0002)
{
if (get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
unique_id = imgdata.lens.makernotes.CamID = get4();
}
else if (tag == 0xa002)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa005)
{
stmread(imgdata.lens.InternalLensSerial, len, ifp);
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2))))
{
parseSonyMakernotes(tag, type, len, nonDNG, table_buf_0x9050, table_buf_0x9050_present, table_buf_0x940c,
table_buf_0x940c_present);
}
fseek(ifp, _pos, SEEK_SET);
#endif
if (tag == 2 && strstr(make, "NIKON") && !iso_speed)
iso_speed = (get2(), get2());
if (tag == 37 && strstr(make, "NIKON") && (!iso_speed || iso_speed == 65535))
{
unsigned char cc;
fread(&cc, 1, 1, ifp);
iso_speed = int(100.0 * powf64(2.0f, float(cc) / 12.0 - 5.0));
}
if (tag == 4 && len > 26 && len < 35)
{
if ((i = (get4(), get2())) != 0x7fff && (!iso_speed || iso_speed == 65535))
iso_speed = 50 * powf64(2.0, i / 32.0 - 4);
#ifdef LIBRAW_LIBRARY_BUILD
get4();
#else
if ((i = (get2(), get2())) != 0x7fff && !aperture)
aperture = powf64(2.0, i / 64.0);
#endif
if ((i = get2()) != 0xffff && !shutter)
shutter = powf64(2.0, (short)i / -32.0);
wbi = (get2(), get2());
shot_order = (get2(), get2());
}
if ((tag == 4 || tag == 0x114) && !strncmp(make, "KONICA", 6))
{
fseek(ifp, tag == 4 ? 140 : 160, SEEK_CUR);
switch (get2())
{
case 72:
flip = 0;
break;
case 76:
flip = 6;
break;
case 82:
flip = 5;
break;
}
}
if (tag == 7 && type == 2 && len > 20)
fgets(model2, 64, ifp);
if (tag == 8 && type == 4)
shot_order = get4();
if (tag == 9 && !strncmp(make, "Canon", 5))
fread(artist, 64, 1, ifp);
if (tag == 0xc && len == 4)
FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type);
if (tag == 0xd && type == 7 && get2() == 0xaaaa)
{
#if 0 /* Canon rotation data is handled by EXIF.Orientation */
for (c = i = 2; (ushort)c != 0xbbbb && i < len; i++)
c = c << 8 | fgetc(ifp);
while ((i += 4) < len - 5)
if (get4() == 257 && (i = len) && (c = (get4(), fgetc(ifp))) < 3)
flip = "065"[c] - '0';
#endif
}
#ifndef LIBRAW_LIBRARY_BUILD
if (tag == 0x10 && type == 4)
unique_id = get4();
#endif
#ifdef LIBRAW_LIBRARY_BUILD
INT64 _pos2 = ftell(ifp);
if (!strncasecmp(make, "Olympus", 7))
{
short nWB, tWB;
if ((tag == 0x20300108) || (tag == 0x20310109))
imgdata.makernotes.olympus.ColorSpace = get2();
if ((tag == 0x20400101) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5)))
{
int i;
for (i = 0; i < 64; i++)
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] =
imgdata.color.WB_Coeffs[i][3] = 0x100;
for (i = 64; i < 256; i++)
imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100;
}
if ((tag >= 0x20400101) && (tag <= 0x20400111))
{
nWB = tag - 0x20400101;
tWB = Oly_wb_list2[nWB << 1];
ushort CT = Oly_wb_list2[(nWB << 1) | 1];
int wb[4];
wb[0] = get2();
wb[2] = get2();
if (tWB != 0x100)
{
imgdata.color.WB_Coeffs[tWB][0] = wb[0];
imgdata.color.WB_Coeffs[tWB][2] = wb[2];
}
if (CT)
{
imgdata.color.WBCT_Coeffs[nWB - 1][0] = CT;
imgdata.color.WBCT_Coeffs[nWB - 1][1] = wb[0];
imgdata.color.WBCT_Coeffs[nWB - 1][3] = wb[2];
}
if (len == 4)
{
wb[1] = get2();
wb[3] = get2();
if (tWB != 0x100)
{
imgdata.color.WB_Coeffs[tWB][1] = wb[1];
imgdata.color.WB_Coeffs[tWB][3] = wb[3];
}
if (CT)
{
imgdata.color.WBCT_Coeffs[nWB - 1][2] = wb[1];
imgdata.color.WBCT_Coeffs[nWB - 1][4] = wb[3];
}
}
}
if ((tag >= 0x20400112) && (tag <= 0x2040011e))
{
nWB = tag - 0x20400112;
int wbG = get2();
tWB = Oly_wb_list2[nWB << 1];
if (nWB)
imgdata.color.WBCT_Coeffs[nWB - 1][2] = imgdata.color.WBCT_Coeffs[nWB - 1][4] = wbG;
if (tWB != 0x100)
imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = wbG;
}
if (tag == 0x20400121)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2();
if (len == 4)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2();
}
}
if (tag == 0x2040011f)
{
int wbG = get2();
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0])
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = wbG;
FORC4 if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][0])
imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][3] =
wbG;
}
if ((tag == 0x30000110) && strcmp(software, "v757-71"))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][2] = get2();
if (len == 2)
{
for (int i = 0; i < 256; i++)
imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100;
}
}
if ((((tag >= 0x30000120) && (tag <= 0x30000124)) || ((tag >= 0x30000130) && (tag <= 0x30000133))) &&
strcmp(software, "v757-71"))
{
int wb_ind;
if (tag <= 0x30000124)
wb_ind = tag - 0x30000120;
else
wb_ind = tag - 0x30000130 + 5;
imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][0] = get2();
imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][2] = get2();
}
if ((tag == 0x20400805) && (len == 2))
{
imgdata.makernotes.olympus.OlympusSensorCalibration[0] = getreal(type);
imgdata.makernotes.olympus.OlympusSensorCalibration[1] = getreal(type);
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0];
}
if (tag == 0x20200401)
{
imgdata.other.FlashEC = getreal(type);
}
}
fseek(ifp, _pos2, SEEK_SET);
#endif
if (tag == 0x11 && is_raw && !strncmp(make, "NIKON", 5))
{
fseek(ifp, get4() + base, SEEK_SET);
parse_tiff_ifd(base);
}
if (tag == 0x14 && type == 7)
{
if (len == 2560)
{
fseek(ifp, 1248, SEEK_CUR);
goto get2_256;
}
fread(buf, 1, 10, ifp);
if (!strncmp(buf, "NRW ", 4))
{
fseek(ifp, strcmp(buf + 4, "0100") ? 46 : 1546, SEEK_CUR);
cam_mul[0] = get4() << 2;
cam_mul[1] = get4() + get4();
cam_mul[2] = get4() << 2;
}
}
if (tag == 0x15 && type == 2 && is_raw)
fread(model, 64, 1, ifp);
if (strstr(make, "PENTAX"))
{
if (tag == 0x1b)
tag = 0x1018;
if (tag == 0x1c)
tag = 0x1017;
}
if (tag == 0x1d)
{
while ((c = fgetc(ifp)) && c != EOF)
#ifdef LIBRAW_LIBRARY_BUILD
{
if ((!custom_serial) && (!isdigit(c)))
{
if ((strbuflen(model) == 3) && (!strcmp(model, "D50")))
{
custom_serial = 34;
}
else
{
custom_serial = 96;
}
}
#endif
serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10);
#ifdef LIBRAW_LIBRARY_BUILD
}
if (!imgdata.shootinginfo.BodySerial[0])
sprintf(imgdata.shootinginfo.BodySerial, "%d", serial);
#endif
}
if (tag == 0x29 && type == 1)
{ // Canon PowerShot G9
c = wbi < 18 ? "012347800000005896"[wbi] - '0' : 0;
fseek(ifp, 8 + c * 32, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4();
}
#ifndef LIBRAW_LIBRARY_BUILD
if (tag == 0x3d && type == 3 && len == 4)
FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps);
#endif
if (tag == 0x81 && type == 4)
{
data_offset = get4();
fseek(ifp, data_offset + 41, SEEK_SET);
raw_height = get2() * 2;
raw_width = get2();
filters = 0x61616161;
}
if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1))
{
thumb_offset = ftell(ifp);
thumb_length = len;
}
if (tag == 0x88 && type == 4 && (thumb_offset = get4()))
thumb_offset += base;
if (tag == 0x89 && type == 4)
thumb_length = get4();
if (tag == 0x8c || tag == 0x96)
meta_offset = ftell(ifp);
if (tag == 0x97)
{
for (i = 0; i < 4; i++)
ver97 = ver97 * 10 + fgetc(ifp) - '0';
switch (ver97)
{
case 100:
fseek(ifp, 68, SEEK_CUR);
FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2();
break;
case 102:
fseek(ifp, 6, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
break;
case 103:
fseek(ifp, 16, SEEK_CUR);
FORC4 cam_mul[c] = get2();
}
if (ver97 >= 200)
{
if (ver97 != 205)
fseek(ifp, 280, SEEK_CUR);
fread(buf97, 324, 1, ifp);
}
}
if ((tag == 0xa1) && (type == 7) && strncasecmp(make, "Samsung", 7))
{
order = 0x4949;
fseek(ifp, 140, SEEK_CUR);
FORC3 cam_mul[c] = get4();
}
if (tag == 0xa4 && type == 3)
{
fseek(ifp, wbi * 48, SEEK_CUR);
FORC3 cam_mul[c] = get2();
}
if (tag == 0xa7)
{ // shutter count
NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);
if ((unsigned)(ver97 - 200) < 17)
{
ci = xlat[0][serial & 0xff];
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < 324; i++)
buf97[i] ^= (cj += ci * ck++);
i = "66666>666;6A;:;55"[ver97 - 200] - '0';
FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2);
}
#ifdef LIBRAW_LIBRARY_BUILD
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
if (custom_serial)
{
ci = xlat[0][custom_serial];
}
else
{
ci = xlat[0][serial & 0xff];
}
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
free(table_buf);
}
if (ver97 == 601) // Coolpix A
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
#endif
}
if (tag == 0xb001 && type == 3) // Sony ModelID
{
unique_id = get2();
}
if (tag == 0x200 && len == 3)
shot_order = (get4(), get4());
if (tag == 0x200 && len == 4) // Pentax black level
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x201 && len == 4) // Pentax As Shot WB
FORC4 cam_mul[c ^ (c >> 1)] = get2();
if (tag == 0x220 && type == 7)
meta_offset = ftell(ifp);
if (tag == 0x401 && type == 4 && len == 4)
FORC4 cblack[c ^ c >> 1] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
// not corrected for file bitcount, to be patched in open_datastream
if (tag == 0x03d && strstr(make, "NIKON") && len == 4)
{
FORC4 cblack[c ^ c >> 1] = get2();
i = cblack[3];
FORC3 if (i > cblack[c]) i = cblack[c];
FORC4 cblack[c] -= i;
black += i;
}
#endif
if (tag == 0xe01)
{ /* Nikon Capture Note */
#ifdef LIBRAW_LIBRARY_BUILD
int loopc = 0;
#endif
order = 0x4949;
fseek(ifp, 22, SEEK_CUR);
for (offset = 22; offset + 22 < len; offset += 22 + i)
{
#ifdef LIBRAW_LIBRARY_BUILD
if (loopc++ > 1024)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
tag = get4();
fseek(ifp, 14, SEEK_CUR);
i = get4() - 4;
if (tag == 0x76a43207)
flip = get2();
else
fseek(ifp, i, SEEK_CUR);
}
}
if (tag == 0xe80 && len == 256 && type == 7)
{
fseek(ifp, 48, SEEK_CUR);
cam_mul[0] = get2() * 508 * 1.078 / 0x10000;
cam_mul[2] = get2() * 382 * 1.173 / 0x10000;
}
if (tag == 0xf00 && type == 7)
{
if (len == 614)
fseek(ifp, 176, SEEK_CUR);
else if (len == 734 || len == 1502)
fseek(ifp, 148, SEEK_CUR);
else
goto next;
goto get2_256;
}
if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, "v757-71"))
for (i = 0; i < 3; i++)
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!imgdata.makernotes.olympus.ColorSpace)
{
FORC3 cmatrix[i][c] = ((short)get2()) / 256.0;
}
else
{
FORC3 imgdata.color.ccm[i][c] = ((short)get2()) / 256.0;
}
#else
FORC3 cmatrix[i][c] = ((short)get2()) / 256.0;
#endif
}
if ((tag == 0x1012 || tag == 0x20400600) && len == 4)
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x1017 || tag == 0x20400100)
cam_mul[0] = get2() / 256.0;
if (tag == 0x1018 || tag == 0x20400100)
cam_mul[2] = get2() / 256.0;
if (tag == 0x2011 && len == 2)
{
get2_256:
order = 0x4d4d;
cam_mul[0] = get2() / 256.0;
cam_mul[2] = get2() / 256.0;
}
if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13))
fseek(ifp, get4() + base, SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
if (tag == 0x2010)
{
INT64 _pos3 = ftell(ifp);
parse_makernote(base, 0x2010);
fseek(ifp, _pos3, SEEK_SET);
}
if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031)) && ((type == 7) || (type == 13)) &&
!strncasecmp(make, "Olympus", 7))
{
INT64 _pos3 = ftell(ifp);
parse_makernote(base, tag);
fseek(ifp, _pos3, SEEK_SET);
}
// IB end
#endif
if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, "OLYMP", 5))
parse_thumb_note(base, 257, 258);
if (tag == 0x2040)
parse_makernote(base, 0x2040);
if (tag == 0xb028)
{
fseek(ifp, get4() + base, SEEK_SET);
parse_thumb_note(base, 136, 137);
}
if (tag == 0x4001 && len > 500 && len < 100000)
{
i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126;
fseek(ifp, i, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
for (i += 18; i <= len; i += 10)
{
get2();
FORC4 sraw_mul[c ^ (c >> 1)] = get2();
if (sraw_mul[1] == 1170)
break;
}
}
if (!strncasecmp(make, "Samsung", 7))
{
if (tag == 0xa020) // get the full Samsung encryption key
for (i = 0; i < 11; i++)
SamsungKey[i] = get4();
if (tag == 0xa021) // get and decode Samsung cam_mul array
FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c];
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 0xa022)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4;
}
}
if (tag == 0xa023)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4;
}
}
if (tag == 0xa024)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4;
}
}
/*
if (tag == 0xa025) {
i = get4();
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = i - SamsungKey[0]; printf ("Samsung 0xa025 %d\n", i); }
*/
if (tag == 0xa030 && len == 9)
for (i = 0; i < 3; i++)
FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0;
#endif
if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix
for (i = 0; i < 3; i++)
FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0;
if (tag == 0xa028)
FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c];
}
else
{
// Somebody else use 0xa021 and 0xa028?
if (tag == 0xa021)
FORC4 cam_mul[c ^ (c >> 1)] = get4();
if (tag == 0xa028)
FORC4 cam_mul[c ^ (c >> 1)] -= get4();
}
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) &&
(imgdata.makernotes.canon.multishot[1] = get4()))
{
if (len >= 4)
{
imgdata.makernotes.canon.multishot[2] = get4();
imgdata.makernotes.canon.multishot[3] = get4();
}
FORC4 cam_mul[c] = 1024;
}
#else
if (tag == 0x4021 && get4() && get4())
FORC4 cam_mul[c] = 1024;
#endif
next:
fseek(ifp, save, SEEK_SET);
}
quit:
order = sorder;
}
/*
Since the TIFF DateTime string has no timezone information,
assume that the camera's clock was set to Universal Time.
*/
void CLASS get_timestamp(int reversed)
{
struct tm t;
char str[20];
int i;
str[19] = 0;
if (reversed)
for (i = 19; i--;)
str[i] = fgetc(ifp);
else
fread(str, 19, 1, ifp);
memset(&t, 0, sizeof t);
if (sscanf(str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6)
return;
t.tm_year -= 1900;
t.tm_mon -= 1;
t.tm_isdst = -1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
}
void CLASS parse_exif(int base)
{
unsigned kodak, entries, tag, type, len, save, c;
double expo, ape;
kodak = !strncmp(make, "EASTMAN", 7) && tiff_nifds < 3;
entries = get2();
if (!strncmp(make, "Hasselblad", 10) && (tiff_nifds > 3) && (entries > 512))
return;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 fsize = ifp->size();
#endif
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
#ifdef LIBRAW_LIBRARY_BUILD
INT64 savepos = ftell(ifp);
if (len > 8 && savepos + len > fsize * 2)
continue;
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp);
fseek(ifp, savepos, SEEK_SET);
}
#endif
switch (tag)
{
#ifdef LIBRAW_LIBRARY_BUILD
case 0xa405: // FocalLengthIn35mmFormat
imgdata.lens.FocalLengthIn35mmFormat = get2();
break;
case 0xa431: // BodySerialNumber
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa435: // LensSerialNumber
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
imgdata.lens.dng.MinFocal = getreal(type);
imgdata.lens.dng.MaxFocal = getreal(type);
imgdata.lens.dng.MaxAp4MinFocal = getreal(type);
imgdata.lens.dng.MaxAp4MaxFocal = getreal(type);
break;
case 0xa433: // LensMake
stmread(imgdata.lens.LensMake, len, ifp);
break;
case 0xa434: // LensModel
stmread(imgdata.lens.Lens, len, ifp);
if (!strncmp(imgdata.lens.Lens, "----", 4))
imgdata.lens.Lens[0] = 0;
break;
case 0x9205:
imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f));
break;
#endif
case 33434:
tiff_ifd[tiff_nifds - 1].t_shutter = shutter = getreal(type);
break;
case 33437:
aperture = getreal(type);
break; // 0x829d FNumber
case 34855:
iso_speed = get2();
break;
case 34865:
if (iso_speed == 0xffff && !strncasecmp(make, "FUJI", 4))
iso_speed = getreal(type);
break;
case 34866:
if (iso_speed == 0xffff && (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "CANON", 5)))
iso_speed = getreal(type);
break;
case 36867:
case 36868:
get_timestamp(0);
break;
case 37377:
if ((expo = -getreal(type)) < 128 && shutter == 0.)
tiff_ifd[tiff_nifds - 1].t_shutter = shutter = powf64(2.0, expo);
break;
case 37378: // 0x9202 ApertureValue
if ((fabs(ape = getreal(type)) < 256.0) && (!aperture))
aperture = powf64(2.0, ape / 2);
break;
case 37385:
flash_used = getreal(type);
break;
case 37386:
focal_len = getreal(type);
break;
case 37500: // tag 0x927c
#ifdef LIBRAW_LIBRARY_BUILD
if (((make[0] == '\0') && (!strncmp(model, "ov5647", 6))) ||
((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_OV5647", 9))) ||
((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_imx219", 9))))
{
char mn_text[512];
char *pos;
char ccms[512];
ushort l;
float num;
fgets(mn_text, len, ifp);
pos = strstr(mn_text, "gain_r=");
if (pos)
cam_mul[0] = atof(pos + 7);
pos = strstr(mn_text, "gain_b=");
if (pos)
cam_mul[2] = atof(pos + 7);
if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f))
cam_mul[1] = cam_mul[3] = 1.0f;
else
cam_mul[0] = cam_mul[2] = 0.0f;
pos = strstr(mn_text, "ccm=") + 4;
l = strstr(pos, " ") - pos;
memcpy(ccms, pos, l);
ccms[l] = '\0';
pos = strtok(ccms, ",");
for (l = 0; l < 4; l++)
{
num = 0.0;
for (c = 0; c < 3; c++)
{
imgdata.color.ccm[l][c] = (float)atoi(pos);
num += imgdata.color.ccm[l][c];
pos = strtok(NULL, ",");
}
if (num > 0.01)
FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;
}
}
else
#endif
parse_makernote(base, 0);
break;
case 40962:
if (kodak)
raw_width = get4();
break;
case 40963:
if (kodak)
raw_height = get4();
break;
case 41730:
if (get4() == 0x20002)
for (exif_cfa = c = 0; c < 8; c += 2)
exif_cfa |= fgetc(ifp) * 0x01010101 << c;
}
fseek(ifp, save, SEEK_SET);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS parse_gps_libraw(int base)
{
unsigned entries, tag, type, len, save, c;
entries = get2();
if (entries > 200)
return;
if (entries > 0)
imgdata.other.parsed_gps.gpsparsed = 1;
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
if (len > 1024)
continue; // no GPS tags are 1k or larger
switch (tag)
{
case 1:
imgdata.other.parsed_gps.latref = getc(ifp);
break;
case 3:
imgdata.other.parsed_gps.longref = getc(ifp);
break;
case 5:
imgdata.other.parsed_gps.altref = getc(ifp);
break;
case 2:
if (len == 3)
FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type);
break;
case 4:
if (len == 3)
FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type);
break;
case 7:
if (len == 3)
FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type);
break;
case 6:
imgdata.other.parsed_gps.altitude = getreal(type);
break;
case 9:
imgdata.other.parsed_gps.gpsstatus = getc(ifp);
break;
}
fseek(ifp, save, SEEK_SET);
}
}
#endif
void CLASS parse_gps(int base)
{
unsigned entries, tag, type, len, save, c;
entries = get2();
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
if (len > 1024)
continue; // no GPS tags are 1k or larger
switch (tag)
{
case 1:
case 3:
case 5:
gpsdata[29 + tag / 2] = getc(ifp);
break;
case 2:
case 4:
case 7:
FORC(6) gpsdata[tag / 3 * 6 + c] = get4();
break;
case 6:
FORC(2) gpsdata[18 + c] = get4();
break;
case 18:
case 29:
fgets((char *)(gpsdata + 14 + tag / 3), MIN(len, 12), ifp);
}
fseek(ifp, save, SEEK_SET);
}
}
void CLASS romm_coeff(float romm_cam[3][3])
{
static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */
{{2.034193, -0.727420, -0.306766}, {-0.228811, 1.231729, -0.002922}, {-0.008565, -0.153273, 1.161839}};
int i, j, k;
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
for (cmatrix[i][j] = k = 0; k < 3; k++)
cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j];
}
void CLASS parse_mos(int offset)
{
char data[40];
int skip, from, i, c, neut[4], planes = 0, frot = 0;
static const char *mod[] = {"",
"DCB2",
"Volare",
"Cantare",
"CMost",
"Valeo 6",
"Valeo 11",
"Valeo 22",
"Valeo 11p",
"Valeo 17",
"",
"Aptus 17",
"Aptus 22",
"Aptus 75",
"Aptus 65",
"Aptus 54S",
"Aptus 65S",
"Aptus 75S",
"AFi 5",
"AFi 6",
"AFi 7",
"AFi-II 7",
"Aptus-II 7",
"",
"Aptus-II 6",
"",
"",
"Aptus-II 10",
"Aptus-II 5",
"",
"",
"",
"",
"Aptus-II 10R",
"Aptus-II 8",
"",
"Aptus-II 12",
"",
"AFi-II 12"};
float romm_cam[3][3];
fseek(ifp, offset, SEEK_SET);
while (1)
{
if (get4() != 0x504b5453)
break;
get4();
fread(data, 1, 40, ifp);
skip = get4();
from = ftell(ifp);
// IB start
#ifdef LIBRAW_LIBRARY_BUILD
if (!strcmp(data, "CameraObj_camera_type"))
{
stmread(imgdata.lens.makernotes.body, skip, ifp);
}
if (!strcmp(data, "back_serial_number"))
{
char buffer[sizeof(imgdata.shootinginfo.BodySerial)];
char *words[4];
int nwords;
stmread(buffer, skip, ifp);
nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.BodySerial));
strcpy(imgdata.shootinginfo.BodySerial, words[0]);
}
if (!strcmp(data, "CaptProf_serial_number"))
{
char buffer[sizeof(imgdata.shootinginfo.InternalBodySerial)];
char *words[4];
int nwords;
stmread(buffer, skip, ifp);
nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial));
strcpy(imgdata.shootinginfo.InternalBodySerial, words[0]);
}
#endif
// IB end
if (!strcmp(data, "JPEG_preview_data"))
{
thumb_offset = from;
thumb_length = skip;
}
if (!strcmp(data, "icc_camera_profile"))
{
profile_offset = from;
profile_length = skip;
}
if (!strcmp(data, "ShootObj_back_type"))
{
fscanf(ifp, "%d", &i);
if ((unsigned)i < sizeof mod / sizeof(*mod))
strcpy(model, mod[i]);
}
if (!strcmp(data, "icc_camera_to_tone_matrix"))
{
for (i = 0; i < 9; i++)
((float *)romm_cam)[i] = int_to_float(get4());
romm_coeff(romm_cam);
}
if (!strcmp(data, "CaptProf_color_matrix"))
{
for (i = 0; i < 9; i++)
fscanf(ifp, "%f", (float *)romm_cam + i);
romm_coeff(romm_cam);
}
if (!strcmp(data, "CaptProf_number_of_planes"))
fscanf(ifp, "%d", &planes);
if (!strcmp(data, "CaptProf_raw_data_rotation"))
fscanf(ifp, "%d", &flip);
if (!strcmp(data, "CaptProf_mosaic_pattern"))
FORC4
{
fscanf(ifp, "%d", &i);
if (i == 1)
frot = c ^ (c >> 1);
}
if (!strcmp(data, "ImgProf_rotation_angle"))
{
fscanf(ifp, "%d", &i);
flip = i - flip;
}
if (!strcmp(data, "NeutObj_neutrals") && !cam_mul[0])
{
FORC4 fscanf(ifp, "%d", neut + c);
FORC3 cam_mul[c] = (float)neut[0] / neut[c + 1];
}
if (!strcmp(data, "Rows_data"))
load_flags = get4();
parse_mos(from);
fseek(ifp, skip + from, SEEK_SET);
}
if (planes)
filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip / 90 + frot) & 3];
}
void CLASS linear_table(unsigned len)
{
int i;
if (len > 0x10000)
len = 0x10000;
read_shorts(curve, len);
for (i = len; i < 0x10000; i++)
curve[i] = curve[i - 1];
maximum = curve[len < 0x1000 ? 0xfff : len - 1];
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS Kodak_WB_0x08tags(int wb, unsigned type)
{
float mul[3] = {1, 1, 1}, num, mul2;
int c;
FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num;
imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1];
mul2 = mul[1] * mul[1];
imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0];
imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2];
return;
}
/* Thanks to Alexey Danilchenko for wb as-shot parsing code */
void CLASS parse_kodak_ifd(int base)
{
unsigned entries, tag, type, len, save;
int i, c, wbi = -2;
float mul[3] = {1, 1, 1}, num;
static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042};
// int a_blck = 0;
entries = get2();
if (entries > 1024)
return;
INT64 fsize = ifp->size();
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
INT64 savepos = ftell(ifp);
if (len > 8 && len + savepos > 2 * fsize)
continue;
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag | 0x20000, type, len, order, ifp);
fseek(ifp, savepos, SEEK_SET);
}
if (tag == 1011)
imgdata.other.FlashEC = getreal(type);
if (tag == 1020)
wbi = getint(type);
if (tag == 1021 && len == 72)
{ /* WB set in software */
fseek(ifp, 40, SEEK_CUR);
FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f, get2());
wbi = -2;
}
if ((tag == 0x03ef) && (!strcmp(model, "EOS D2000C")))
black = get2();
if ((tag == 0x03f0) && (!strcmp(model, "EOS D2000C")))
{
if (black) // already set by tag 0x03ef
black = (black + get2()) / 2;
else
black = get2();
}
INT64 _pos2 = ftell(ifp);
if (tag == 0x0848)
Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type);
if (tag == 0x0849)
Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type);
if (tag == 0x084a)
Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type);
if (tag == 0x084b)
Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type);
if (tag == 0x084c)
Kodak_WB_0x08tags(LIBRAW_WBI_Custom, type);
if (tag == 0x084d)
Kodak_WB_0x08tags(LIBRAW_WBI_Auto, type);
if (tag == 0x0e93)
imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = get2();
if (tag == 0x09ce)
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
if (tag == 0xfa00)
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if (tag == 0xfa27)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1];
}
if (tag == 0xfa28)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1];
}
if (tag == 0xfa29)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1];
}
if (tag == 0xfa2a)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1];
}
fseek(ifp, _pos2, SEEK_SET);
if (tag == 2120 + wbi || (wbi < 0 && tag == 2125)) /* use Auto WB if illuminant index is not set */
{
FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num;
FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */
}
if (tag == 2317)
linear_table(len);
if (tag == 0x903)
iso_speed = getreal(type);
// if (tag == 6020) iso_speed = getint(type);
if (tag == 64013)
wbi = fgetc(ifp);
if ((unsigned)wbi < 7 && tag == wbtag[wbi])
FORC3 cam_mul[c] = get4();
if (tag == 64019)
width = getint(type);
if (tag == 64020)
height = (getint(type) + 1) & -2;
fseek(ifp, save, SEEK_SET);
}
}
#else
void CLASS parse_kodak_ifd(int base)
{
unsigned entries, tag, type, len, save;
int i, c, wbi = -2, wbtemp = 6500;
float mul[3] = {1, 1, 1}, num;
static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042};
entries = get2();
if (entries > 1024)
return;
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
if (tag == 1020)
wbi = getint(type);
if (tag == 1021 && len == 72)
{ /* WB set in software */
fseek(ifp, 40, SEEK_CUR);
FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, get2());
wbi = -2;
}
if (tag == 2118)
wbtemp = getint(type);
if (tag == 2120 + wbi && wbi >= 0)
FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, getreal(type));
if (tag == 2130 + wbi)
FORC3 mul[c] = getreal(type);
if (tag == 2140 + wbi && wbi >= 0)
FORC3
{
for (num = i = 0; i < 4; i++)
num += getreal(type) * pow(wbtemp / 100.0, i);
cam_mul[c] = 2048 / fMAX(1.0, (num * mul[c]));
}
if (tag == 2317)
linear_table(len);
if (tag == 6020)
iso_speed = getint(type);
if (tag == 64013)
wbi = fgetc(ifp);
if ((unsigned)wbi < 7 && tag == wbtag[wbi])
FORC3 cam_mul[c] = get4();
if (tag == 64019)
width = getint(type);
if (tag == 64020)
height = (getint(type) + 1) & -2;
fseek(ifp, save, SEEK_SET);
}
}
#endif
int CLASS parse_tiff_ifd(int base)
{
unsigned entries, tag, type, len, plen = 16, save;
int ifd, use_cm = 0, cfa, i, j, c, ima_len = 0;
char *cbuf, *cp;
uchar cfa_pat[16], cfa_pc[] = {0, 1, 2, 3}, tab[256];
double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num;
double ab[] = {1, 1, 1, 1}, asn[] = {0, 0, 0, 0}, xyz[] = {1, 1, 1};
unsigned sony_curve[] = {0, 0, 0, 0, 0, 4095};
unsigned *buf, sony_offset = 0, sony_length = 0, sony_key = 0;
struct jhead jh;
int pana_raw = 0;
#ifndef LIBRAW_LIBRARY_BUILD
FILE *sfp;
#endif
if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0])
return 1;
ifd = tiff_nifds++;
for (j = 0; j < 4; j++)
for (i = 0; i < 4; i++)
cc[j][i] = i == j;
entries = get2();
if (entries > 512)
return 1;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 fsize = ifp->size();
#endif
while (entries--)
{
tiff_get(base, &tag, &type, &len, &save);
#ifdef LIBRAW_LIBRARY_BUILD
INT64 savepos = ftell(ifp);
if (len > 8 && len + savepos > fsize * 2)
continue; // skip tag pointing out of 2xfile
if (callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data, tag | (pana_raw ? 0x30000 : 0), type, len, order, ifp);
fseek(ifp, savepos, SEEK_SET);
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncasecmp(make, "SONY", 4) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "HV", 2))))
{
switch (tag)
{
case 0x7300: // SR2 black level
for (int i = 0; i < 4 && i < len; i++)
cblack[i] = get2();
break;
case 0x7302:
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = get2();
break;
case 0x7312:
{
int i, lc[4];
FORC4 lc[c] = get2();
i = (lc[1] == 1024 && lc[2] == 1024) << 1;
SWAP(lc[i], lc[i + 1]);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c] = lc[c];
}
break;
case 0x7480:
case 0x7820:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1];
break;
case 0x7481:
case 0x7821:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1];
break;
case 0x7482:
case 0x7822:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1];
break;
case 0x7483:
case 0x7823:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1];
break;
case 0x7484:
case 0x7824:
imgdata.color.WBCT_Coeffs[0][0] = 4500;
FORC3 imgdata.color.WBCT_Coeffs[0][c + 1] = get2();
imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2];
break;
case 0x7486:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1];
break;
case 0x7825:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1];
break;
case 0x7826:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1];
break;
case 0x7827:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1];
break;
case 0x7828:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1];
break;
case 0x7829:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1];
break;
case 0x782a:
imgdata.color.WBCT_Coeffs[1][0] = 8500;
FORC3 imgdata.color.WBCT_Coeffs[1][c + 1] = get2();
imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2];
break;
case 0x782b:
imgdata.color.WBCT_Coeffs[2][0] = 6000;
FORC3 imgdata.color.WBCT_Coeffs[2][c + 1] = get2();
imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2];
break;
case 0x782c:
imgdata.color.WBCT_Coeffs[3][0] = 3200;
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c + 1] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1];
break;
case 0x782d:
imgdata.color.WBCT_Coeffs[4][0] = 2500;
FORC3 imgdata.color.WBCT_Coeffs[4][c + 1] = get2();
imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2];
break;
case 0x787f:
FORC3 imgdata.color.linear_max[c] = get2();
imgdata.color.linear_max[3] = imgdata.color.linear_max[1];
break;
}
}
#endif
switch (tag)
{
case 1:
if (len == 4)
pana_raw = get4();
break;
case 5:
width = get2();
break;
case 6:
height = get2();
break;
case 7:
width += get2();
break;
case 9:
if ((i = get2()))
filters = i;
#ifdef LIBRAW_LIBRARY_BUILD
if (pana_raw && len == 1 && type == 3)
pana_black[3] += i;
#endif
break;
case 8:
case 10:
#ifdef LIBRAW_LIBRARY_BUILD
if (pana_raw && len == 1 && type == 3)
pana_black[3] += get2();
#endif
break;
case 14:
case 15:
case 16:
#ifdef LIBRAW_LIBRARY_BUILD
if (pana_raw)
{
imgdata.color.linear_max[tag - 14] = get2();
if (tag == 15)
imgdata.color.linear_max[3] = imgdata.color.linear_max[1];
}
#endif
break;
case 17:
case 18:
if (type == 3 && len == 1)
cam_mul[(tag - 17) * 2] = get2() / 256.0;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 19:
if (pana_raw)
{
ushort nWB, cnt, tWB;
nWB = get2();
if (nWB > 0x100)
break;
for (cnt = 0; cnt < nWB; cnt++)
{
tWB = get2();
if (tWB < 0x100)
{
imgdata.color.WB_Coeffs[tWB][0] = get2();
imgdata.color.WB_Coeffs[tWB][2] = get2();
imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100;
}
else
get4();
}
}
break;
#endif
case 23:
if (type == 3)
iso_speed = get2();
break;
case 28:
case 29:
case 30:
#ifdef LIBRAW_LIBRARY_BUILD
if (pana_raw && len == 1 && type == 3)
{
pana_black[tag - 28] = get2();
}
else
#endif
{
cblack[tag - 28] = get2();
cblack[3] = cblack[1];
}
break;
case 36:
case 37:
case 38:
cam_mul[tag - 36] = get2();
break;
case 39:
#ifdef LIBRAW_LIBRARY_BUILD
if (pana_raw)
{
ushort nWB, cnt, tWB;
nWB = get2();
if (nWB > 0x100)
break;
for (cnt = 0; cnt < nWB; cnt++)
{
tWB = get2();
if (tWB < 0x100)
{
imgdata.color.WB_Coeffs[tWB][0] = get2();
imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2();
imgdata.color.WB_Coeffs[tWB][2] = get2();
}
else
fseek(ifp, 6, SEEK_CUR);
}
}
break;
#endif
if (len < 50 || cam_mul[0])
break;
fseek(ifp, 12, SEEK_CUR);
FORC3 cam_mul[c] = get2();
break;
case 46:
if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8)
break;
thumb_offset = ftell(ifp) - 2;
thumb_length = len;
break;
case 61440: /* Fuji HS10 table */
fseek(ifp, get4() + base, SEEK_SET);
parse_tiff_ifd(base);
break;
case 2:
case 256:
case 61441: /* ImageWidth */
tiff_ifd[ifd].t_width = getint(type);
break;
case 3:
case 257:
case 61442: /* ImageHeight */
tiff_ifd[ifd].t_height = getint(type);
break;
case 258: /* BitsPerSample */
case 61443:
tiff_ifd[ifd].samples = len & 7;
tiff_ifd[ifd].bps = getint(type);
if (tiff_bps < tiff_ifd[ifd].bps)
tiff_bps = tiff_ifd[ifd].bps;
break;
case 61446:
raw_height = 0;
if (tiff_ifd[ifd].bps > 12)
break;
load_raw = &CLASS packed_load_raw;
load_flags = get4() ? 24 : 80;
break;
case 259: /* Compression */
tiff_ifd[ifd].comp = getint(type);
break;
case 262: /* PhotometricInterpretation */
tiff_ifd[ifd].phint = get2();
break;
case 270: /* ImageDescription */
fread(desc, 512, 1, ifp);
break;
case 271: /* Make */
fgets(make, 64, ifp);
break;
case 272: /* Model */
fgets(model, 64, ifp);
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 278:
tiff_ifd[ifd].rows_per_strip = getint(type);
break;
#endif
case 280: /* Panasonic RW2 offset */
if (type != 4)
break;
load_raw = &CLASS panasonic_load_raw;
load_flags = 0x2008;
case 273: /* StripOffset */
#ifdef LIBRAW_LIBRARY_BUILD
if (len > 1 && len < 16384)
{
off_t sav = ftell(ifp);
tiff_ifd[ifd].strip_offsets = (int *)calloc(len, sizeof(int));
tiff_ifd[ifd].strip_offsets_count = len;
for (int i = 0; i < len; i++)
tiff_ifd[ifd].strip_offsets[i] = get4() + base;
fseek(ifp, sav, SEEK_SET); // restore position
}
/* fallback */
#endif
case 513: /* JpegIFOffset */
case 61447:
tiff_ifd[ifd].offset = get4() + base;
if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0)
{
fseek(ifp, tiff_ifd[ifd].offset, SEEK_SET);
if (ljpeg_start(&jh, 1))
{
tiff_ifd[ifd].comp = 6;
tiff_ifd[ifd].t_width = jh.wide;
tiff_ifd[ifd].t_height = jh.high;
tiff_ifd[ifd].bps = jh.bits;
tiff_ifd[ifd].samples = jh.clrs;
if (!(jh.sraw || (jh.clrs & 1)))
tiff_ifd[ifd].t_width *= jh.clrs;
if ((tiff_ifd[ifd].t_width > 4 * tiff_ifd[ifd].t_height) & ~jh.clrs)
{
tiff_ifd[ifd].t_width /= 2;
tiff_ifd[ifd].t_height *= 2;
}
i = order;
parse_tiff(tiff_ifd[ifd].offset + 12);
order = i;
}
}
break;
case 274: /* Orientation */
tiff_ifd[ifd].t_flip = "50132467"[get2() & 7] - '0';
break;
case 277: /* SamplesPerPixel */
tiff_ifd[ifd].samples = getint(type) & 7;
break;
case 279: /* StripByteCounts */
#ifdef LIBRAW_LIBRARY_BUILD
if (len > 1 && len < 16384)
{
off_t sav = ftell(ifp);
tiff_ifd[ifd].strip_byte_counts = (int *)calloc(len, sizeof(int));
tiff_ifd[ifd].strip_byte_counts_count = len;
for (int i = 0; i < len; i++)
tiff_ifd[ifd].strip_byte_counts[i] = get4();
fseek(ifp, sav, SEEK_SET); // restore position
}
/* fallback */
#endif
case 514:
case 61448:
tiff_ifd[ifd].bytes = get4();
break;
case 61454: // FujiFilm "As Shot"
FORC3 cam_mul[(4 - c) % 3] = getint(type);
break;
case 305:
case 11: /* Software */
fgets(software, 64, ifp);
if (!strncmp(software, "Adobe", 5) || !strncmp(software, "dcraw", 5) || !strncmp(software, "UFRaw", 5) ||
!strncmp(software, "Bibble", 6) || !strcmp(software, "Digital Photo Professional"))
is_raw = 0;
break;
case 306: /* DateTime */
get_timestamp(0);
break;
case 315: /* Artist */
fread(artist, 64, 1, ifp);
break;
case 317:
tiff_ifd[ifd].predictor = getint(type);
break;
case 322: /* TileWidth */
tiff_ifd[ifd].t_tile_width = getint(type);
break;
case 323: /* TileLength */
tiff_ifd[ifd].t_tile_length = getint(type);
break;
case 324: /* TileOffsets */
tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4();
if (len == 1)
tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0;
if (len == 4)
{
load_raw = &CLASS sinar_4shot_load_raw;
is_raw = 5;
}
break;
case 325:
tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp) : get4();
break;
case 330: /* SubIFDs */
if (!strcmp(model, "DSLR-A100") && tiff_ifd[ifd].t_width == 3872)
{
load_raw = &CLASS sony_arw_load_raw;
data_offset = get4() + base;
ifd++;
#ifdef LIBRAW_LIBRARY_BUILD
if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0])
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
break;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(make, "Hasselblad", 10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag)
{
fseek(ifp, ftell(ifp) + 4, SEEK_SET);
fseek(ifp, get4() + base, SEEK_SET);
parse_tiff_ifd(base);
break;
}
#endif
if (len > 1000)
len = 1000; /* 1000 SubIFDs is enough */
while (len--)
{
i = ftell(ifp);
fseek(ifp, get4() + base, SEEK_SET);
if (parse_tiff_ifd(base))
break;
fseek(ifp, i + 4, SEEK_SET);
}
break;
case 339:
tiff_ifd[ifd].sample_format = getint(type);
break;
case 400:
strcpy(make, "Sarnoff");
maximum = 0xfff;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 700:
if ((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000)
{
xmpdata = (char *)malloc(xmplen = len + 1);
fread(xmpdata, len, 1, ifp);
xmpdata[len] = 0;
}
break;
#endif
case 28688:
FORC4 sony_curve[c + 1] = get2() >> 2 & 0xfff;
for (i = 0; i < 5; i++)
for (j = sony_curve[i] + 1; j <= sony_curve[i + 1]; j++)
curve[j] = curve[j - 1] + (1 << i);
break;
case 29184:
sony_offset = get4();
break;
case 29185:
sony_length = get4();
break;
case 29217:
sony_key = get4();
break;
case 29264:
parse_minolta(ftell(ifp));
raw_width = 0;
break;
case 29443:
FORC4 cam_mul[c ^ (c < 2)] = get2();
break;
case 29459:
FORC4 cam_mul[c] = get2();
i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1;
SWAP(cam_mul[i], cam_mul[i + 1])
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800
for (i = 0; i < 3; i++)
{
float num = 0.0;
for (c = 0; c < 3; c++)
{
imgdata.color.ccm[i][c] = (float)((short)get2());
num += imgdata.color.ccm[i][c];
}
if (num > 0.01)
FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num;
}
break;
#endif
case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4
FORC4 cblack[c ^ c >> 1] = get2();
i = cblack[3];
FORC3 if (i > cblack[c]) i = cblack[c];
FORC4 cblack[c] -= i;
black = i;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("...Sony black: %u cblack: %u %u %u %u\n"), black, cblack[0], cblack[1], cblack[2],
cblack[3]);
#endif
break;
case 33405: /* Model2 */
fgets(model2, 64, ifp);
break;
case 33421: /* CFARepeatPatternDim */
if (get2() == 6 && get2() == 6)
filters = 9;
break;
case 33422: /* CFAPattern */
if (filters == 9)
{
FORC(36)((char *)xtrans)[c] = fgetc(ifp) & 3;
break;
}
case 64777: /* Kodak P-series */
if (len == 36)
{
filters = 9;
colors = 3;
FORC(36) xtrans[0][c] = fgetc(ifp) & 3;
}
else if (len > 0)
{
if ((plen = len) > 16)
plen = 16;
fread(cfa_pat, 1, plen, ifp);
for (colors = cfa = i = 0; i < plen && colors < 4; i++)
{
colors += !(cfa & (1 << cfa_pat[i]));
cfa |= 1 << cfa_pat[i];
}
if (cfa == 070)
memcpy(cfa_pc, "\003\004\005", 3); /* CMY */
if (cfa == 072)
memcpy(cfa_pc, "\005\003\004\001", 4); /* GMCY */
goto guess_cfa_pc;
}
break;
case 33424:
case 65024:
fseek(ifp, get4() + base, SEEK_SET);
parse_kodak_ifd(base);
break;
case 33434: /* ExposureTime */
tiff_ifd[ifd].t_shutter = shutter = getreal(type);
break;
case 33437: /* FNumber */
aperture = getreal(type);
break;
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
case 0xa405: // FocalLengthIn35mmFormat
imgdata.lens.FocalLengthIn35mmFormat = get2();
break;
case 0xa431: // BodySerialNumber
case 0xc62f:
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa435: // LensSerialNumber
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa433: // LensMake
stmread(imgdata.lens.LensMake, len, ifp);
break;
case 0xa434: // LensModel
stmread(imgdata.lens.Lens, len, ifp);
if (!strncmp(imgdata.lens.Lens, "----", 4))
imgdata.lens.Lens[0] = 0;
break;
case 0x9205:
imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f));
break;
// IB end
#endif
case 34306: /* Leaf white balance */
FORC4 cam_mul[c ^ 1] = 4096.0 / get2();
break;
case 34307: /* Leaf CatchLight color matrix */
fread(software, 1, 7, ifp);
if (strncmp(software, "MATRIX", 6))
break;
colors = 4;
for (raw_color = i = 0; i < 3; i++)
{
FORC4 fscanf(ifp, "%f", &rgb_cam[i][c ^ 1]);
if (!use_camera_wb)
continue;
num = 0;
FORC4 num += rgb_cam[i][c];
FORC4 rgb_cam[i][c] /= MAX(1, num);
}
break;
case 34310: /* Leaf metadata */
parse_mos(ftell(ifp));
case 34303:
strcpy(make, "Leaf");
break;
case 34665: /* EXIF tag */
fseek(ifp, get4() + base, SEEK_SET);
parse_exif(base);
break;
case 34853: /* GPSInfo tag */
{
unsigned pos;
fseek(ifp, pos = (get4() + base), SEEK_SET);
parse_gps(base);
#ifdef LIBRAW_LIBRARY_BUILD
fseek(ifp, pos, SEEK_SET);
parse_gps_libraw(base);
#endif
}
break;
case 34675: /* InterColorProfile */
case 50831: /* AsShotICCProfile */
profile_offset = ftell(ifp);
profile_length = len;
break;
case 37122: /* CompressedBitsPerPixel */
kodak_cbpp = get4();
break;
case 37386: /* FocalLength */
focal_len = getreal(type);
break;
case 37393: /* ImageNumber */
shot_order = getint(type);
break;
case 37400: /* old Kodak KDC tag */
for (raw_color = i = 0; i < 3; i++)
{
getreal(type);
FORC3 rgb_cam[i][c] = getreal(type);
}
break;
case 40976:
strip_offset = get4();
switch (tiff_ifd[ifd].comp)
{
case 32770:
load_raw = &CLASS samsung_load_raw;
break;
case 32772:
load_raw = &CLASS samsung2_load_raw;
break;
case 32773:
load_raw = &CLASS samsung3_load_raw;
break;
}
break;
case 46275: /* Imacon tags */
strcpy(make, "Imacon");
data_offset = ftell(ifp);
ima_len = len;
break;
case 46279:
if (!ima_len)
break;
fseek(ifp, 38, SEEK_CUR);
case 46274:
fseek(ifp, 40, SEEK_CUR);
raw_width = get4();
raw_height = get4();
left_margin = get4() & 7;
width = raw_width - left_margin - (get4() & 7);
top_margin = get4() & 7;
height = raw_height - top_margin - (get4() & 7);
if (raw_width == 7262 && ima_len == 234317952)
{
height = 5412;
width = 7216;
left_margin = 7;
filters = 0;
}
else if (raw_width == 7262)
{
height = 5444;
width = 7244;
left_margin = 7;
}
fseek(ifp, 52, SEEK_CUR);
FORC3 cam_mul[c] = getreal(11);
fseek(ifp, 114, SEEK_CUR);
flip = (get2() >> 7) * 90;
if (width * height * 6 == ima_len)
{
if (flip % 180 == 90)
SWAP(width, height);
raw_width = width;
raw_height = height;
left_margin = top_margin = filters = flip = 0;
}
sprintf(model, "Ixpress %d-Mp", height * width / 1000000);
load_raw = &CLASS imacon_full_load_raw;
if (filters)
{
if (left_margin & 1)
filters = 0x61616161;
load_raw = &CLASS unpacked_load_raw;
}
maximum = 0xffff;
break;
case 50454: /* Sinar tag */
case 50455:
if (len < 1 || len > 2560000 || !(cbuf = (char *)malloc(len)))
break;
#ifndef LIBRAW_LIBRARY_BUILD
fread(cbuf, 1, len, ifp);
#else
if (fread(cbuf, 1, len, ifp) != len)
throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle
#endif
cbuf[len - 1] = 0;
for (cp = cbuf - 1; cp && cp < cbuf + len; cp = strchr(cp, '\n'))
if (!strncmp(++cp, "Neutral ", 8))
sscanf(cp + 8, "%f %f %f", cam_mul, cam_mul + 1, cam_mul + 2);
free(cbuf);
break;
case 50458:
if (!make[0])
strcpy(make, "Hasselblad");
break;
case 50459: /* Hasselblad tag */
#ifdef LIBRAW_LIBRARY_BUILD
libraw_internal_data.unpacker_data.hasselblad_parser_flag = 1;
#endif
i = order;
j = ftell(ifp);
c = tiff_nifds;
order = get2();
fseek(ifp, j + (get2(), get4()), SEEK_SET);
parse_tiff_ifd(j);
maximum = 0xffff;
tiff_nifds = c;
order = i;
break;
case 50706: /* DNGVersion */
FORC4 dng_version = (dng_version << 8) + fgetc(ifp);
if (!make[0])
strcpy(make, "DNG");
is_raw = 1;
break;
case 50708: /* UniqueCameraModel */
#ifdef LIBRAW_LIBRARY_BUILD
stmread(imgdata.color.UniqueCameraModel, len, ifp);
imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel) - 1] = 0;
#endif
if (model[0])
break;
#ifndef LIBRAW_LIBRARY_BUILD
fgets(make, 64, ifp);
#else
strncpy(make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel)));
#endif
if ((cp = strchr(make, ' ')))
{
strcpy(model, cp + 1);
*cp = 0;
}
break;
case 50710: /* CFAPlaneColor */
if (filters == 9)
break;
if (len > 4)
len = 4;
colors = len;
fread(cfa_pc, 1, colors, ifp);
guess_cfa_pc:
FORCC tab[cfa_pc[c]] = c;
cdesc[c] = 0;
for (i = 16; i--;)
filters = filters << 2 | tab[cfa_pat[i % plen]];
filters -= !filters;
break;
case 50711: /* CFALayout */
if (get2() == 2)
fuji_width = 1;
break;
case 291:
case 50712: /* LinearizationTable */
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_LINTABLE;
tiff_ifd[ifd].lineartable_offset = ftell(ifp);
tiff_ifd[ifd].lineartable_len = len;
#endif
linear_table(len);
break;
case 50713: /* BlackLevelRepeatDim */
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK;
tiff_ifd[ifd].dng_levels.dng_cblack[4] =
#endif
cblack[4] = get2();
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.dng_cblack[5] =
#endif
cblack[5] = get2();
if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof(cblack[0]) - 6))
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.dng_cblack[4] = tiff_ifd[ifd].dng_levels.dng_cblack[5] =
#endif
cblack[4] = cblack[5] = 1;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 0xf00d:
if (strcmp(model, "X-A3") && strcmp(model, "X-A10"))
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][(4 - c) % 3] = getint(type);
imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1];
}
break;
case 0xf00c:
if (strcmp(model, "X-A3") && strcmp(model, "X-A10"))
{
unsigned fwb[4];
FORC4 fwb[c] = get4();
if (fwb[3] < 0x100)
{
imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1];
imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0];
imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2];
if ((fwb[3] == 17) && (libraw_internal_data.unpacker_data.lenRAFData > 3) &&
(libraw_internal_data.unpacker_data.lenRAFData < 10240000))
{
INT64 f_save = ftell(ifp);
ushort *rafdata = (ushort *)malloc(sizeof(ushort) * libraw_internal_data.unpacker_data.lenRAFData);
fseek(ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET);
fread(rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp);
fseek(ifp, f_save, SEEK_SET);
int fj, found = 0;
for (int fi = 0; fi < (libraw_internal_data.unpacker_data.lenRAFData - 3); fi++)
{
if ((fwb[0] == rafdata[fi]) && (fwb[1] == rafdata[fi + 1]) && (fwb[2] == rafdata[fi + 2]))
{
if (rafdata[fi - 15] != fwb[0])
continue;
for (int wb_ind = 0, ofst = fi - 15; wb_ind < nFuji_wb_list1; wb_ind++, ofst += 3)
{
imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][1] =
imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][3] = rafdata[ofst];
imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][0] = rafdata[ofst + 1];
imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][2] = rafdata[ofst + 2];
}
fi += 0x60;
for (fj = fi; fj < (fi + 15); fj += 3)
if (rafdata[fj] != rafdata[fi])
{
found = 1;
break;
}
if (found)
{
fj = fj - 93;
for (int iCCT = 0; iCCT < 31; iCCT++)
{
imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT];
imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT * 3 + 1 + fj];
imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT * 3 + fj];
imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT * 3 + 2 + fj];
}
}
free(rafdata);
break;
}
}
}
}
FORC4 fwb[c] = get4();
if (fwb[3] < 0x100)
{
imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1];
imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0];
imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2];
}
}
break;
#endif
#ifdef LIBRAW_LIBRARY_BUILD
case 50709:
stmread(imgdata.color.LocalizedCameraModel, len, ifp);
break;
#endif
case 61450:
cblack[4] = cblack[5] = MIN(sqrt((double)len), 64);
case 50714: /* BlackLevel */
#ifdef LIBRAW_LIBRARY_BUILD
if (tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black
{
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK;
for (i = 0; i < colors && i < 4 && i < len; i++)
tiff_ifd[ifd].dng_levels.dng_cblack[i] = cblack[i] = getreal(type) + 0.5;
tiff_ifd[ifd].dng_levels.dng_black = black = 0;
}
else
#endif
if ((cblack[4] * cblack[5] < 2) && len == 1)
{
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK;
tiff_ifd[ifd].dng_levels.dng_black =
#endif
black = getreal(type);
}
else if (cblack[4] * cblack[5] <= len)
{
FORC(cblack[4] * cblack[5])
cblack[6 + c] = getreal(type);
black = 0;
FORC4
cblack[c] = 0;
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 50714)
{
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK;
FORC(cblack[4] * cblack[5])
tiff_ifd[ifd].dng_levels.dng_cblack[6 + c] = cblack[6 + c];
tiff_ifd[ifd].dng_levels.dng_black = 0;
FORC4
tiff_ifd[ifd].dng_levels.dng_cblack[c] = 0;
}
#endif
}
break;
case 50715: /* BlackLevelDeltaH */
case 50716: /* BlackLevelDeltaV */
for (num = i = 0; i < len && i < 65536; i++)
num += getreal(type);
black += num / len + 0.5;
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.dng_black += num / len + 0.5;
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK;
#endif
break;
case 50717: /* WhiteLevel */
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_WHITE;
tiff_ifd[ifd].dng_levels.dng_whitelevel[0] =
#endif
maximum = getint(type);
#ifdef LIBRAW_LIBRARY_BUILD
if (tiff_ifd[ifd].samples > 1) // Linear DNG case
for (i = 1; i < colors && i < 4 && i < len; i++)
tiff_ifd[ifd].dng_levels.dng_whitelevel[i] = getint(type);
#endif
break;
case 50718: /* DefaultScale */
pixel_aspect = getreal(type);
pixel_aspect /= getreal(type);
if (pixel_aspect > 0.995 && pixel_aspect < 1.005)
pixel_aspect = 1.0;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 50719: /* DefaultCropOrigin */
if (len == 2)
{
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPORIGIN;
tiff_ifd[ifd].dng_levels.default_crop[0] = getreal(type);
tiff_ifd[ifd].dng_levels.default_crop[1] = getreal(type);
}
break;
case 50720: /* DefaultCropSize */
if (len == 2)
{
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPSIZE;
tiff_ifd[ifd].dng_levels.default_crop[2] = getreal(type);
tiff_ifd[ifd].dng_levels.default_crop[3] = getreal(type);
}
break;
#endif
#ifdef LIBRAW_LIBRARY_BUILD
case 50778:
tiff_ifd[ifd].dng_color[0].illuminant = get2();
tiff_ifd[ifd].dng_color[0].parsedfields |= LIBRAW_DNGFM_ILLUMINANT;
break;
case 50779:
tiff_ifd[ifd].dng_color[1].illuminant = get2();
tiff_ifd[ifd].dng_color[1].parsedfields |= LIBRAW_DNGFM_ILLUMINANT;
break;
#endif
case 50721: /* ColorMatrix1 */
case 50722: /* ColorMatrix2 */
#ifdef LIBRAW_LIBRARY_BUILD
i = tag == 50721 ? 0 : 1;
tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_COLORMATRIX;
#endif
FORCC for (j = 0; j < 3; j++)
{
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_color[i].colormatrix[c][j] =
#endif
cm[c][j] = getreal(type);
}
use_cm = 1;
break;
case 0xc714: /* ForwardMatrix1 */
case 0xc715: /* ForwardMatrix2 */
#ifdef LIBRAW_LIBRARY_BUILD
i = tag == 0xc714 ? 0 : 1;
tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX;
#endif
for (j = 0; j < 3; j++)
FORCC
{
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_color[i].forwardmatrix[j][c] =
#endif
fm[j][c] = getreal(type);
}
break;
case 50723: /* CameraCalibration1 */
case 50724: /* CameraCalibration2 */
#ifdef LIBRAW_LIBRARY_BUILD
j = tag == 50723 ? 0 : 1;
tiff_ifd[ifd].dng_color[j].parsedfields |= LIBRAW_DNGFM_CALIBRATION;
#endif
for (i = 0; i < colors; i++)
FORCC
{
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_color[j].calibration[i][c] =
#endif
cc[i][c] = getreal(type);
}
break;
case 50727: /* AnalogBalance */
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_ANALOGBALANCE;
#endif
FORCC
{
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.analogbalance[c] =
#endif
ab[c] = getreal(type);
}
break;
case 50728: /* AsShotNeutral */
FORCC asn[c] = getreal(type);
break;
case 50729: /* AsShotWhiteXY */
xyz[0] = getreal(type);
xyz[1] = getreal(type);
xyz[2] = 1 - xyz[0] - xyz[1];
FORC3 xyz[c] /= d65_white[c];
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 50730: /* DNG: Baseline Exposure */
baseline_exposure = getreal(type);
break;
#endif
// IB start
case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */
#ifdef LIBRAW_LIBRARY_BUILD
{
char mbuf[64];
unsigned short makernote_found = 0;
INT64 curr_pos, start_pos = ftell(ifp);
unsigned MakN_order, m_sorder = order;
unsigned MakN_length;
unsigned pos_in_original_raw;
fread(mbuf, 1, 6, ifp);
if (!strcmp(mbuf, "Adobe"))
{
order = 0x4d4d; // Adobe header is always in "MM" / big endian
curr_pos = start_pos + 6;
while (curr_pos + 8 - start_pos <= len)
{
fread(mbuf, 1, 4, ifp);
curr_pos += 8;
if (!strncmp(mbuf, "MakN", 4))
{
makernote_found = 1;
MakN_length = get4();
MakN_order = get2();
pos_in_original_raw = get4();
order = MakN_order;
parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG);
break;
}
}
}
else
{
fread(mbuf + 6, 1, 2, ifp);
if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG"))
{
makernote_found = 1;
fseek(ifp, start_pos, SEEK_SET);
parse_makernote_0xc634(base, 0, CameraDNG);
}
}
fseek(ifp, start_pos, SEEK_SET);
order = m_sorder;
}
// IB end
#endif
if (dng_version)
break;
parse_minolta(j = get4() + base);
fseek(ifp, j, SEEK_SET);
parse_tiff_ifd(base);
break;
case 50752:
read_shorts(cr2_slice, 3);
break;
case 50829: /* ActiveArea */
top_margin = getint(type);
left_margin = getint(type);
height = getint(type) - top_margin;
width = getint(type) - left_margin;
break;
case 50830: /* MaskedAreas */
for (i = 0; i < len && i < 32; i++)
((int *)mask)[i] = getint(type);
black = 0;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 50970: /* PreviewColorSpace */
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_PREVIEWCS;
tiff_ifd[ifd].dng_levels.preview_colorspace = getint(type);
break;
#endif
case 51009: /* OpcodeList2 */
#ifdef LIBRAW_LIBRARY_BUILD
tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_OPCODE2;
tiff_ifd[ifd].opcode2_offset =
#endif
meta_offset = ftell(ifp);
break;
case 64772: /* Kodak P-series */
if (len < 13)
break;
fseek(ifp, 16, SEEK_CUR);
data_offset = get4();
fseek(ifp, 28, SEEK_CUR);
data_offset += get4();
load_raw = &CLASS packed_load_raw;
break;
case 65026:
if (type == 2)
fgets(model2, 64, ifp);
}
fseek(ifp, save, SEEK_SET);
}
if (sony_length && sony_length < 10240000 && (buf = (unsigned *)malloc(sony_length)))
{
fseek(ifp, sony_offset, SEEK_SET);
fread(buf, sony_length, 1, ifp);
sony_decrypt(buf, sony_length / 4, 1, sony_key);
#ifndef LIBRAW_LIBRARY_BUILD
sfp = ifp;
if ((ifp = tmpfile()))
{
fwrite(buf, sony_length, 1, ifp);
fseek(ifp, 0, SEEK_SET);
parse_tiff_ifd(-sony_offset);
fclose(ifp);
}
ifp = sfp;
#else
if (!ifp->tempbuffer_open(buf, sony_length))
{
parse_tiff_ifd(-sony_offset);
ifp->tempbuffer_close();
}
#endif
free(buf);
}
for (i = 0; i < colors; i++)
FORCC cc[i][c] *= ab[i];
if (use_cm)
{
FORCC for (i = 0; i < 3; i++) for (cam_xyz[c][i] = j = 0; j < colors; j++) cam_xyz[c][i] +=
cc[c][j] * cm[j][i] * xyz[i];
cam_xyz_coeff(cmatrix, cam_xyz);
}
if (asn[0])
{
cam_mul[3] = 0;
FORCC cam_mul[c] = 1 / asn[c];
}
if (!use_cm)
FORCC pre_mul[c] /= cc[c][c];
return 0;
}
int CLASS parse_tiff(int base)
{
int doff;
fseek(ifp, base, SEEK_SET);
order = get2();
if (order != 0x4949 && order != 0x4d4d)
return 0;
get2();
while ((doff = get4()))
{
fseek(ifp, doff + base, SEEK_SET);
if (parse_tiff_ifd(base))
break;
}
return 1;
}
void CLASS apply_tiff()
{
int max_samp = 0, ties = 0, raw = -1, thm = -1, i;
unsigned long long ns, os;
struct jhead jh;
thumb_misc = 16;
if (thumb_offset)
{
fseek(ifp, thumb_offset, SEEK_SET);
if (ljpeg_start(&jh, 1))
{
if ((unsigned)jh.bits < 17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000)
{
thumb_misc = jh.bits;
thumb_width = jh.wide;
thumb_height = jh.high;
}
}
}
for (i = tiff_nifds; i--;)
{
if (tiff_ifd[i].t_shutter)
shutter = tiff_ifd[i].t_shutter;
tiff_ifd[i].t_shutter = shutter;
}
for (i = 0; i < tiff_nifds; i++)
{
if (max_samp < tiff_ifd[i].samples)
max_samp = tiff_ifd[i].samples;
if (max_samp > 3)
max_samp = 3;
os = raw_width * raw_height;
ns = tiff_ifd[i].t_width * tiff_ifd[i].t_height;
if (tiff_bps)
{
os *= tiff_bps;
ns *= tiff_ifd[i].bps;
}
if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) &&
unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 &&
(unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++)))
{
raw_width = tiff_ifd[i].t_width;
raw_height = tiff_ifd[i].t_height;
tiff_bps = tiff_ifd[i].bps;
tiff_compress = tiff_ifd[i].comp;
data_offset = tiff_ifd[i].offset;
#ifdef LIBRAW_LIBRARY_BUILD
data_size = tiff_ifd[i].bytes;
#endif
tiff_flip = tiff_ifd[i].t_flip;
tiff_samples = tiff_ifd[i].samples;
tile_width = tiff_ifd[i].t_tile_width;
tile_length = tiff_ifd[i].t_tile_length;
shutter = tiff_ifd[i].t_shutter;
raw = i;
}
}
if (is_raw == 1 && ties)
is_raw = ties;
if (!tile_width)
tile_width = INT_MAX;
if (!tile_length)
tile_length = INT_MAX;
for (i = tiff_nifds; i--;)
if (tiff_ifd[i].t_flip)
tiff_flip = tiff_ifd[i].t_flip;
if (raw >= 0 && !load_raw)
switch (tiff_compress)
{
case 32767:
if (tiff_ifd[raw].bytes == raw_width * raw_height)
{
tiff_bps = 12;
load_raw = &CLASS sony_arw2_load_raw;
break;
}
if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2)
{
tiff_bps = 14;
load_raw = &CLASS unpacked_load_raw;
break;
}
if (tiff_ifd[raw].bytes * 8 != raw_width * raw_height * tiff_bps)
{
raw_height += 8;
load_raw = &CLASS sony_arw_load_raw;
break;
}
load_flags = 79;
case 32769:
load_flags++;
case 32770:
case 32773:
goto slr;
case 0:
case 1:
#ifdef LIBRAW_LIBRARY_BUILD
// Sony 14-bit uncompressed
if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2)
{
tiff_bps = 14;
load_raw = &CLASS unpacked_load_raw;
break;
}
if (!strncasecmp(make, "Nikon", 5) && !strncmp(software, "Nikon Scan", 10))
{
load_raw = &CLASS nikon_coolscan_load_raw;
raw_color = 1;
filters = 0;
break;
}
#endif
if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 2 == raw_width * raw_height * 3)
load_flags = 24;
if (tiff_ifd[raw].bytes * 5 == raw_width * raw_height * 8)
{
load_flags = 81;
tiff_bps = 12;
}
slr:
switch (tiff_bps)
{
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 12:
if (tiff_ifd[raw].phint == 2)
load_flags = 6;
load_raw = &CLASS packed_load_raw;
break;
case 14:
load_flags = 0;
case 16:
load_raw = &CLASS unpacked_load_raw;
if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 7 > raw_width * raw_height)
load_raw = &CLASS olympus_load_raw;
}
break;
case 6:
case 7:
case 99:
load_raw = &CLASS lossless_jpeg_load_raw;
break;
case 262:
load_raw = &CLASS kodak_262_load_raw;
break;
case 34713:
if ((raw_width + 9) / 10 * 16 * raw_height == tiff_ifd[raw].bytes)
{
load_raw = &CLASS packed_load_raw;
load_flags = 1;
}
else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2)
{
load_raw = &CLASS packed_load_raw;
if (model[0] == 'N')
load_flags = 80;
}
else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes)
{
load_raw = &CLASS nikon_yuv_load_raw;
gamma_curve(1 / 2.4, 12.92, 1, 4095);
memset(cblack, 0, sizeof cblack);
filters = 0;
}
else if (raw_width * raw_height * 2 == tiff_ifd[raw].bytes)
{
load_raw = &CLASS unpacked_load_raw;
load_flags = 4;
order = 0x4d4d;
}
else
#ifdef LIBRAW_LIBRARY_BUILD
if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2)
{
load_raw = &CLASS packed_load_raw;
load_flags = 80;
}
else if (tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count &&
tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count)
{
int fit = 1;
for (int i = 0; i < tiff_ifd[raw].strip_byte_counts_count - 1; i++) // all but last
if (tiff_ifd[raw].strip_byte_counts[i] * 2 != tiff_ifd[raw].rows_per_strip * raw_width * 3)
{
fit = 0;
break;
}
if (fit)
load_raw = &CLASS nikon_load_striped_packed_raw;
else
load_raw = &CLASS nikon_load_raw; // fallback
}
else
#endif
load_raw = &CLASS nikon_load_raw;
break;
case 65535:
load_raw = &CLASS pentax_load_raw;
break;
case 65000:
switch (tiff_ifd[raw].phint)
{
case 2:
load_raw = &CLASS kodak_rgb_load_raw;
filters = 0;
break;
case 6:
load_raw = &CLASS kodak_ycbcr_load_raw;
filters = 0;
break;
case 32803:
load_raw = &CLASS kodak_65000_load_raw;
}
case 32867:
case 34892:
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 8:
break;
#endif
default:
is_raw = 0;
}
if (!dng_version)
if (((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) ||
(tiff_bps == 8 && strncmp(make, "Phase", 5) && strncmp(make, "Leaf", 4) && !strcasestr(make, "Kodak") &&
!strstr(model2, "DEBUG RAW"))) &&
strncmp(software, "Nikon Scan", 10))
is_raw = 0;
for (i = 0; i < tiff_nifds; i++)
if (i != raw &&
(tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */
&& tiff_ifd[i].bps > 0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 &&
unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 &&
tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps) + 1) >
thumb_width * thumb_height / (SQR(thumb_misc) + 1) &&
tiff_ifd[i].comp != 34892)
{
thumb_width = tiff_ifd[i].t_width;
thumb_height = tiff_ifd[i].t_height;
thumb_offset = tiff_ifd[i].offset;
thumb_length = tiff_ifd[i].bytes;
thumb_misc = tiff_ifd[i].bps;
thm = i;
}
if (thm >= 0)
{
thumb_misc |= tiff_ifd[thm].samples << 5;
switch (tiff_ifd[thm].comp)
{
case 0:
write_thumb = &CLASS layer_thumb;
break;
case 1:
if (tiff_ifd[thm].bps <= 8)
write_thumb = &CLASS ppm_thumb;
else if (!strncmp(make, "Imacon", 6))
write_thumb = &CLASS ppm16_thumb;
else
thumb_load_raw = &CLASS kodak_thumb_load_raw;
break;
case 65000:
thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw;
}
}
}
void CLASS parse_minolta(int base)
{
int save, tag, len, offset, high = 0, wide = 0, i, c;
short sorder = order;
fseek(ifp, base, SEEK_SET);
if (fgetc(ifp) || fgetc(ifp) - 'M' || fgetc(ifp) - 'R')
return;
order = fgetc(ifp) * 0x101;
offset = base + get4() + 8;
while ((save = ftell(ifp)) < offset)
{
for (tag = i = 0; i < 4; i++)
tag = tag << 8 | fgetc(ifp);
len = get4();
switch (tag)
{
case 0x505244: /* PRD */
fseek(ifp, 8, SEEK_CUR);
high = get2();
wide = get2();
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 0x524946: /* RIF */
if (!strncasecmp(model, "DSLR-A100", 9))
{
fseek(ifp, 8, SEEK_CUR);
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2();
get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100;
}
break;
#endif
case 0x574247: /* WBG */
get4();
i = strcmp(model, "DiMAGE A200") ? 0 : 3;
FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2();
break;
case 0x545457: /* TTW */
parse_tiff(ftell(ifp));
data_offset = offset;
}
fseek(ifp, save + len + 8, SEEK_SET);
}
raw_height = high;
raw_width = wide;
order = sorder;
}
/*
Many cameras have a "debug mode" that writes JPEG and raw
at the same time. The raw file has no header, so try to
to open the matching JPEG file and read its metadata.
*/
void CLASS parse_external_jpeg()
{
const char *file, *ext;
char *jname, *jfile, *jext;
#ifndef LIBRAW_LIBRARY_BUILD
FILE *save = ifp;
#else
#if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310)
if (ifp->wfname())
{
std::wstring rawfile(ifp->wfname());
rawfile.replace(rawfile.length() - 3, 3, L"JPG");
if (!ifp->subfile_open(rawfile.c_str()))
{
parse_tiff(12);
thumb_offset = 0;
is_raw = 1;
ifp->subfile_close();
}
else
imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA;
return;
}
#endif
if (!ifp->fname())
{
imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA;
return;
}
#endif
ext = strrchr(ifname, '.');
file = strrchr(ifname, '/');
if (!file)
file = strrchr(ifname, '\\');
#ifndef LIBRAW_LIBRARY_BUILD
if (!file)
file = ifname - 1;
#else
if (!file)
file = (char *)ifname - 1;
#endif
file++;
if (!ext || strlen(ext) != 4 || ext - file != 8)
return;
jname = (char *)malloc(strlen(ifname) + 1);
merror(jname, "parse_external_jpeg()");
strcpy(jname, ifname);
jfile = file - ifname + jname;
jext = ext - ifname + jname;
if (strcasecmp(ext, ".jpg"))
{
strcpy(jext, isupper(ext[1]) ? ".JPG" : ".jpg");
if (isdigit(*file))
{
memcpy(jfile, file + 4, 4);
memcpy(jfile + 4, file, 4);
}
}
else
while (isdigit(*--jext))
{
if (*jext != '9')
{
(*jext)++;
break;
}
*jext = '0';
}
#ifndef LIBRAW_LIBRARY_BUILD
if (strcmp(jname, ifname))
{
if ((ifp = fopen(jname, "rb")))
{
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Reading metadata from %s ...\n"), jname);
#endif
parse_tiff(12);
thumb_offset = 0;
is_raw = 1;
fclose(ifp);
}
}
#else
if (strcmp(jname, ifname))
{
if (!ifp->subfile_open(jname))
{
parse_tiff(12);
thumb_offset = 0;
is_raw = 1;
ifp->subfile_close();
}
else
imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA;
}
#endif
if (!timestamp)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA;
#endif
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("Failed to read metadata from %s\n"), jname);
#endif
}
free(jname);
#ifndef LIBRAW_LIBRARY_BUILD
ifp = save;
#endif
}
/*
CIFF block 0x1030 contains an 8x8 white sample.
Load this into white[][] for use in scale_colors().
*/
void CLASS ciff_block_1030()
{
static const ushort key[] = {0x410, 0x45f3};
int i, bpp, row, col, vbits = 0;
unsigned long bitbuf = 0;
if ((get2(), get4()) != 0x80008 || !get4())
return;
bpp = get2();
if (bpp != 10 && bpp != 12)
return;
for (i = row = 0; row < 8; row++)
for (col = 0; col < 8; col++)
{
if (vbits < bpp)
{
bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]);
vbits += 16;
}
white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp);
}
}
/*
Parse a CIFF file, better known as Canon CRW format.
*/
void CLASS parse_ciff(int offset, int length, int depth)
{
int tboff, nrecs, c, type, len, save, wbi = -1;
ushort key[] = {0x410, 0x45f3};
fseek(ifp, offset + length - 4, SEEK_SET);
tboff = get4() + offset;
fseek(ifp, tboff, SEEK_SET);
nrecs = get2();
if ((nrecs | depth) > 127)
return;
while (nrecs--)
{
type = get2();
len = get4();
save = ftell(ifp) + 4;
fseek(ifp, offset + get4(), SEEK_SET);
if ((((type >> 8) + 8) | 8) == 0x38)
{
parse_ciff(ftell(ifp), len, depth + 1); /* Parse a sub-table */
}
#ifdef LIBRAW_LIBRARY_BUILD
if (type == 0x3004)
parse_ciff(ftell(ifp), len, depth + 1);
#endif
if (type == 0x0810)
fread(artist, 64, 1, ifp);
if (type == 0x080a)
{
fread(make, 64, 1, ifp);
fseek(ifp, strbuflen(make) - 63, SEEK_CUR);
fread(model, 64, 1, ifp);
}
if (type == 0x1810)
{
width = get4();
height = get4();
pixel_aspect = int_to_float(get4());
flip = get4();
}
if (type == 0x1835) /* Get the decoder table */
tiff_compress = get4();
if (type == 0x2007)
{
thumb_offset = ftell(ifp);
thumb_length = len;
}
if (type == 0x1818)
{
shutter = powf64(2.0f, -int_to_float((get4(), get4())));
aperture = powf64(2.0f, int_to_float(get4()) / 2);
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CurAp = aperture;
#endif
}
if (type == 0x102a)
{
// iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50;
iso_speed = powf64(2.0f, ((get2(), get2()) + get2()) / 32.0f - 5.0f) * 100.0f;
#ifdef LIBRAW_LIBRARY_BUILD
aperture = _CanonConvertAperture((get2(), get2()));
imgdata.lens.makernotes.CurAp = aperture;
#else
aperture = powf64(2.0, (get2(), (short)get2()) / 64.0);
#endif
shutter = powf64(2.0, -((short)get2()) / 32.0);
wbi = (get2(), get2());
if (wbi > 17)
wbi = 0;
fseek(ifp, 32, SEEK_CUR);
if (shutter > 1e6)
shutter = get2() / 10.0;
}
if (type == 0x102c)
{
if (get2() > 512)
{ /* Pro90, G1 */
fseek(ifp, 118, SEEK_CUR);
FORC4 cam_mul[c ^ 2] = get2();
}
else
{ /* G2, S30, S40 */
fseek(ifp, 98, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2();
}
}
#ifdef LIBRAW_LIBRARY_BUILD
if (type == 0x10a9)
{
INT64 o = ftell(ifp);
fseek(ifp, (0x1 << 1), SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2();
Canon_WBpresets(0, 0);
fseek(ifp, o, SEEK_SET);
}
if (type == 0x102d)
{
INT64 o = ftell(ifp);
Canon_CameraSettings();
fseek(ifp, o, SEEK_SET);
}
if (type == 0x580b)
{
if (strcmp(model, "Canon EOS D30"))
sprintf(imgdata.shootinginfo.BodySerial, "%d", len);
else
sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len >> 16, len & 0xffff);
}
#endif
if (type == 0x0032)
{
if (len == 768)
{ /* EOS D30 */
fseek(ifp, 72, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2();
if (!wbi)
cam_mul[0] = -1; /* use my auto white balance */
}
else if (!cam_mul[0])
{
if (get2() == key[0]) /* Pro1, G6, S60, S70 */
c = (strstr(model, "Pro1") ? "012346000000000000" : "01345:000000006008")[LIM(0, wbi, 17)] - '0' + 2;
else
{ /* G3, G5, S45, S50 */
c = "023457000000006000"[LIM(0, wbi, 17)] - '0';
key[0] = key[1] = 0;
}
fseek(ifp, 78 + c * 8, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1];
if (!wbi)
cam_mul[0] = -1;
}
}
if (type == 0x10a9)
{ /* D60, 10D, 300D, and clones */
if (len > 66)
wbi = "0134567028"[LIM(0, wbi, 9)] - '0';
fseek(ifp, 2 + wbi * 8, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
}
if (type == 0x1030 && wbi >= 0 && (0x18040 >> wbi & 1))
ciff_block_1030(); /* all that don't have 0x10a9 */
if (type == 0x1031)
{
raw_width = (get2(), get2());
raw_height = get2();
}
if (type == 0x501c)
{
iso_speed = len & 0xffff;
}
if (type == 0x5029)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CurFocal = len >> 16;
imgdata.lens.makernotes.FocalType = len & 0xffff;
if (imgdata.lens.makernotes.FocalType == 2)
{
imgdata.lens.makernotes.CanonFocalUnits = 32;
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
focal_len = imgdata.lens.makernotes.CurFocal;
#else
focal_len = len >> 16;
if ((len & 0xffff) == 2)
focal_len /= 32;
#endif
}
if (type == 0x5813)
flash_used = int_to_float(len);
if (type == 0x5814)
canon_ev = int_to_float(len);
if (type == 0x5817)
shot_order = len;
if (type == 0x5834)
{
unique_id = len;
#ifdef LIBRAW_LIBRARY_BUILD
setCanonBodyFeatures(unique_id);
#endif
}
if (type == 0x580e)
timestamp = len;
if (type == 0x180e)
timestamp = get4();
#ifdef LOCALTIME
if ((type | 0x4000) == 0x580e)
timestamp = mktime(gmtime(×tamp));
#endif
fseek(ifp, save, SEEK_SET);
}
}
void CLASS parse_rollei()
{
char line[128], *val;
struct tm t;
fseek(ifp, 0, SEEK_SET);
memset(&t, 0, sizeof t);
do
{
fgets(line, 128, ifp);
if ((val = strchr(line, '=')))
*val++ = 0;
else
val = line + strbuflen(line);
if (!strcmp(line, "DAT"))
sscanf(val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year);
if (!strcmp(line, "TIM"))
sscanf(val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec);
if (!strcmp(line, "HDR"))
thumb_offset = atoi(val);
if (!strcmp(line, "X "))
raw_width = atoi(val);
if (!strcmp(line, "Y "))
raw_height = atoi(val);
if (!strcmp(line, "TX "))
thumb_width = atoi(val);
if (!strcmp(line, "TY "))
thumb_height = atoi(val);
} while (strncmp(line, "EOHD", 4));
data_offset = thumb_offset + thumb_width * thumb_height * 2;
t.tm_year -= 1900;
t.tm_mon -= 1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
strcpy(make, "Rollei");
strcpy(model, "d530flex");
write_thumb = &CLASS rollei_thumb;
}
void CLASS parse_sinar_ia()
{
int entries, off;
char str[8], *cp;
order = 0x4949;
fseek(ifp, 4, SEEK_SET);
entries = get4();
fseek(ifp, get4(), SEEK_SET);
while (entries--)
{
off = get4();
get4();
fread(str, 8, 1, ifp);
if (!strcmp(str, "META"))
meta_offset = off;
if (!strcmp(str, "THUMB"))
thumb_offset = off;
if (!strcmp(str, "RAW0"))
data_offset = off;
}
fseek(ifp, meta_offset + 20, SEEK_SET);
fread(make, 64, 1, ifp);
make[63] = 0;
if ((cp = strchr(make, ' ')))
{
strcpy(model, cp + 1);
*cp = 0;
}
raw_width = get2();
raw_height = get2();
load_raw = &CLASS unpacked_load_raw;
thumb_width = (get4(), get2());
thumb_height = get2();
write_thumb = &CLASS ppm_thumb;
maximum = 0x3fff;
}
void CLASS parse_phase_one(int base)
{
unsigned entries, tag, type, len, data, save, i, c;
float romm_cam[3][3];
char *cp;
memset(&ph1, 0, sizeof ph1);
fseek(ifp, base, SEEK_SET);
order = get4() & 0xffff;
if (get4() >> 8 != 0x526177)
return; /* "Raw" */
fseek(ifp, get4() + base, SEEK_SET);
entries = get4();
get4();
while (entries--)
{
tag = get4();
type = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek(ifp, base + data, SEEK_SET);
switch (tag)
{
#ifdef LIBRAW_LIBRARY_BUILD
case 0x0102:
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49))
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41;
}
else
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41;
}
setPhaseOneFeatures(unique_id);
break;
case 0x0401:
if (type == 4)
imgdata.lens.makernotes.CurAp = powf64(2.0f, (int_to_float(data) / 2.0f));
else
imgdata.lens.makernotes.CurAp = powf64(2.0f, (getreal(type) / 2.0f));
break;
case 0x0403:
if (type == 4)
imgdata.lens.makernotes.CurFocal = int_to_float(data);
else
imgdata.lens.makernotes.CurFocal = getreal(type);
break;
case 0x0410:
stmread(imgdata.lens.makernotes.body, len, ifp);
break;
case 0x0412:
stmread(imgdata.lens.makernotes.Lens, len, ifp);
break;
case 0x0414:
if (type == 4)
{
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (int_to_float(data) / 2.0f));
}
else
{
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f));
}
break;
case 0x0415:
if (type == 4)
{
imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (int_to_float(data) / 2.0f));
}
else
{
imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f));
}
break;
case 0x0416:
if (type == 4)
{
imgdata.lens.makernotes.MinFocal = int_to_float(data);
}
else
{
imgdata.lens.makernotes.MinFocal = getreal(type);
}
if (imgdata.lens.makernotes.MinFocal > 1000.0f)
{
imgdata.lens.makernotes.MinFocal = 0.0f;
}
break;
case 0x0417:
if (type == 4)
{
imgdata.lens.makernotes.MaxFocal = int_to_float(data);
}
else
{
imgdata.lens.makernotes.MaxFocal = getreal(type);
}
break;
#endif
case 0x100:
flip = "0653"[data & 3] - '0';
break;
case 0x106:
for (i = 0; i < 9; i++)
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.P1_color[0].romm_cam[i] =
#endif
((float *)romm_cam)[i] = getreal(11);
romm_coeff(romm_cam);
break;
case 0x107:
FORC3 cam_mul[c] = getreal(11);
break;
case 0x108:
raw_width = data;
break;
case 0x109:
raw_height = data;
break;
case 0x10a:
left_margin = data;
break;
case 0x10b:
top_margin = data;
break;
case 0x10c:
width = data;
break;
case 0x10d:
height = data;
break;
case 0x10e:
ph1.format = data;
break;
case 0x10f:
data_offset = data + base;
break;
case 0x110:
meta_offset = data + base;
meta_length = len;
break;
case 0x112:
ph1.key_off = save - 4;
break;
case 0x210:
ph1.tag_210 = int_to_float(data);
break;
case 0x21a:
ph1.tag_21a = data;
break;
case 0x21c:
strip_offset = data + base;
break;
case 0x21d:
ph1.t_black = data;
break;
case 0x222:
ph1.split_col = data;
break;
case 0x223:
ph1.black_col = data + base;
break;
case 0x224:
ph1.split_row = data;
break;
case 0x225:
ph1.black_row = data + base;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 0x226:
for (i = 0; i < 9; i++)
imgdata.color.P1_color[1].romm_cam[i] = getreal(11);
break;
#endif
case 0x301:
model[63] = 0;
fread(model, 1, 63, ifp);
if ((cp = strstr(model, " camera")))
*cp = 0;
}
fseek(ifp, save, SEEK_SET);
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0])
{
fseek(ifp, meta_offset, SEEK_SET);
order = get2();
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, meta_offset + get4(), SEEK_SET);
entries = get4();
get4();
while (entries--)
{
tag = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek(ifp, meta_offset + data, SEEK_SET);
if (tag == 0x0407)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49))
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41;
}
else
{
unique_id =
(((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41;
}
setPhaseOneFeatures(unique_id);
}
fseek(ifp, save, SEEK_SET);
}
}
#endif
load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c;
maximum = 0xffff;
strcpy(make, "Phase One");
if (model[0])
return;
switch (raw_height)
{
case 2060:
strcpy(model, "LightPhase");
break;
case 2682:
strcpy(model, "H 10");
break;
case 4128:
strcpy(model, "H 20");
break;
case 5488:
strcpy(model, "H 25");
break;
}
}
void CLASS parse_fuji(int offset)
{
unsigned entries, tag, len, save, c;
fseek(ifp, offset, SEEK_SET);
entries = get4();
if (entries > 255)
return;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED;
#endif
while (entries--)
{
tag = get2();
len = get2();
save = ftell(ifp);
if (tag == 0x100)
{
raw_height = get2();
raw_width = get2();
}
else if (tag == 0x121)
{
height = get2();
if ((width = get2()) == 4284)
width += 3;
}
else if (tag == 0x130)
{
fuji_layout = fgetc(ifp) >> 7;
fuji_width = !(fgetc(ifp) & 8);
}
else if (tag == 0x131)
{
filters = 9;
FORC(36) xtrans_abs[0][35 - c] = fgetc(ifp) & 3;
}
else if (tag == 0x2ff0)
{
FORC4 cam_mul[c ^ 1] = get2();
// IB start
#ifdef LIBRAW_LIBRARY_BUILD
}
else if (tag == 0x9650)
{
short a = (short)get2();
float b = fMAX(1.0f, get2());
imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b;
}
else if (tag == 0x2f00)
{
int nWBs = get4();
nWBs = MIN(nWBs, 6);
for (int wb_ind = 0; wb_ind < nWBs; wb_ind++)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + wb_ind][c ^ 1] = get2();
fseek(ifp, 8, SEEK_CUR);
}
}
else if (tag == 0x2000)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ 1] = get2();
}
else if (tag == 0x2100)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][c ^ 1] = get2();
}
else if (tag == 0x2200)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ 1] = get2();
}
else if (tag == 0x2300)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2();
}
else if (tag == 0x2301)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2();
}
else if (tag == 0x2302)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2();
}
else if (tag == 0x2310)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2();
}
else if (tag == 0x2400)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2();
}
else if (tag == 0x2410)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ 1] = get2();
#endif
// IB end
}
else if (tag == 0xc000)
/* 0xc000 tag versions, second ushort; valid if the first ushort is 0
X100F 0x0259
X100T 0x0153
X-E2 0x014f 0x024f depends on firmware
X-A1 0x014e
XQ2 0x0150
XQ1 0x0150
X100S 0x0149 0x0249 depends on firmware
X30 0x0152
X20 0x0146
X-T10 0x0154
X-T2 0x0258
X-M1 0x014d
X-E2s 0x0355
X-A2 0x014e
X-T20 0x025b
GFX 50S 0x025a
X-T1 0x0151 0x0251 0x0351 depends on firmware
X70 0x0155
X-Pro2 0x0255
*/
{
c = order;
order = 0x4949;
if ((tag = get4()) > 10000)
tag = get4();
if (tag > 10000)
tag = get4();
width = tag;
height = get4();
#ifdef LIBRAW_LIBRARY_BUILD
if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10"))
{
int wb[4];
int nWB, tWB, pWB;
int iCCT = 0;
int cnt;
fseek(ifp, save + 0x200, SEEK_SET);
for (int wb_ind = 0; wb_ind < 42; wb_ind++)
{
nWB = get4();
tWB = get4();
wb[0] = get4() << 1;
wb[1] = get4();
wb[3] = get4();
wb[2] = get4() << 1;
if (tWB && (iCCT < 255))
{
imgdata.color.WBCT_Coeffs[iCCT][0] = tWB;
for (cnt = 0; cnt < 4; cnt++)
imgdata.color.WBCT_Coeffs[iCCT][cnt + 1] = wb[cnt];
iCCT++;
}
if (nWB != 70)
{
for (pWB = 1; pWB < nFuji_wb_list2; pWB += 2)
{
if (Fuji_wb_list2[pWB] == nWB)
{
for (cnt = 0; cnt < 4; cnt++)
imgdata.color.WB_Coeffs[Fuji_wb_list2[pWB - 1]][cnt] = wb[cnt];
break;
}
}
}
}
}
else
{
libraw_internal_data.unpacker_data.posRAFData = save;
libraw_internal_data.unpacker_data.lenRAFData = (len >> 1);
}
#endif
order = c;
}
fseek(ifp, save + len, SEEK_SET);
}
height <<= fuji_layout;
width >>= fuji_layout;
}
int CLASS parse_jpeg(int offset)
{
int len, save, hlen, mark;
fseek(ifp, offset, SEEK_SET);
if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8)
return 0;
while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda)
{
order = 0x4d4d;
len = get2() - 2;
save = ftell(ifp);
if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9)
{
fgetc(ifp);
raw_height = get2();
raw_width = get2();
}
order = get2();
hlen = get4();
if (get4() == 0x48454150
#ifdef LIBRAW_LIBRARY_BUILD
&& (save + hlen) >= 0 && (save + hlen) <= ifp->size()
#endif
) /* "HEAP" */
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
#endif
parse_ciff(save + hlen, len - hlen, 0);
}
if (parse_tiff(save + 6))
apply_tiff();
fseek(ifp, save + len, SEEK_SET);
}
return 1;
}
void CLASS parse_riff()
{
unsigned i, size, end;
char tag[4], date[64], month[64];
static const char mon[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
struct tm t;
order = 0x4949;
fread(tag, 4, 1, ifp);
size = get4();
end = ftell(ifp) + size;
if (!memcmp(tag, "RIFF", 4) || !memcmp(tag, "LIST", 4))
{
int maxloop = 1000;
get4();
while (ftell(ifp) + 7 < end && !feof(ifp) && maxloop--)
parse_riff();
}
else if (!memcmp(tag, "nctg", 4))
{
while (ftell(ifp) + 7 < end)
{
i = get2();
size = get2();
if ((i + 1) >> 1 == 10 && size == 20)
get_timestamp(0);
else
fseek(ifp, size, SEEK_CUR);
}
}
else if (!memcmp(tag, "IDIT", 4) && size < 64)
{
fread(date, 64, 1, ifp);
date[size] = 0;
memset(&t, 0, sizeof t);
if (sscanf(date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6)
{
for (i = 0; i < 12 && strcasecmp(mon[i], month); i++)
;
t.tm_mon = i;
t.tm_year -= 1900;
if (mktime(&t) > 0)
timestamp = mktime(&t);
}
}
else
fseek(ifp, size, SEEK_CUR);
}
void CLASS parse_qt(int end)
{
unsigned save, size;
char tag[4];
order = 0x4d4d;
while (ftell(ifp) + 7 < end)
{
save = ftell(ifp);
if ((size = get4()) < 8)
return;
fread(tag, 4, 1, ifp);
if (!memcmp(tag, "moov", 4) || !memcmp(tag, "udta", 4) || !memcmp(tag, "CNTH", 4))
parse_qt(save + size);
if (!memcmp(tag, "CNDA", 4))
parse_jpeg(ftell(ifp));
fseek(ifp, save + size, SEEK_SET);
}
}
void CLASS parse_smal(int offset, int fsize)
{
int ver;
fseek(ifp, offset + 2, SEEK_SET);
order = 0x4949;
ver = fgetc(ifp);
if (ver == 6)
fseek(ifp, 5, SEEK_CUR);
if (get4() != fsize)
return;
if (ver > 6)
data_offset = get4();
raw_height = height = get2();
raw_width = width = get2();
strcpy(make, "SMaL");
sprintf(model, "v%d %dx%d", ver, width, height);
if (ver == 6)
load_raw = &CLASS smal_v6_load_raw;
if (ver == 9)
load_raw = &CLASS smal_v9_load_raw;
}
void CLASS parse_cine()
{
unsigned off_head, off_setup, off_image, i;
order = 0x4949;
fseek(ifp, 4, SEEK_SET);
is_raw = get2() == 2;
fseek(ifp, 14, SEEK_CUR);
is_raw *= get4();
off_head = get4();
off_setup = get4();
off_image = get4();
timestamp = get4();
if ((i = get4()))
timestamp = i;
fseek(ifp, off_head + 4, SEEK_SET);
raw_width = get4();
raw_height = get4();
switch (get2(), get2())
{
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 16:
load_raw = &CLASS unpacked_load_raw;
}
fseek(ifp, off_setup + 792, SEEK_SET);
strcpy(make, "CINE");
sprintf(model, "%d", get4());
fseek(ifp, 12, SEEK_CUR);
switch ((i = get4()) & 0xffffff)
{
case 3:
filters = 0x94949494;
break;
case 4:
filters = 0x49494949;
break;
default:
is_raw = 0;
}
fseek(ifp, 72, SEEK_CUR);
switch ((get4() + 3600) % 360)
{
case 270:
flip = 4;
break;
case 180:
flip = 1;
break;
case 90:
flip = 7;
break;
case 0:
flip = 2;
}
cam_mul[0] = getreal(11);
cam_mul[2] = getreal(11);
maximum = ~((~0u) << get4());
fseek(ifp, 668, SEEK_CUR);
shutter = get4() / 1000000000.0;
fseek(ifp, off_image, SEEK_SET);
if (shot_select < is_raw)
fseek(ifp, shot_select * 8, SEEK_CUR);
data_offset = (INT64)get4() + 8;
data_offset += (INT64)get4() << 32;
}
void CLASS parse_redcine()
{
unsigned i, len, rdvo;
order = 0x4d4d;
is_raw = 0;
fseek(ifp, 52, SEEK_SET);
width = get4();
height = get4();
fseek(ifp, 0, SEEK_END);
fseek(ifp, -(i = ftello(ifp) & 511), SEEK_CUR);
if (get4() != i || get4() != 0x52454f42)
{
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("%s: Tail is missing, parsing from head...\n"), ifname);
#endif
fseek(ifp, 0, SEEK_SET);
while ((len = get4()) != EOF)
{
if (get4() == 0x52454456)
if (is_raw++ == shot_select)
data_offset = ftello(ifp) - 8;
fseek(ifp, len - 8, SEEK_CUR);
}
}
else
{
rdvo = get4();
fseek(ifp, 12, SEEK_CUR);
is_raw = get4();
fseeko(ifp, rdvo + 8 + shot_select * 4, SEEK_SET);
data_offset = get4();
}
}
/*
All matrices are from Adobe DNG Converter unless otherwise noted.
*/
void CLASS adobe_coeff(const char *t_make, const char *t_model
#ifdef LIBRAW_LIBRARY_BUILD
,
int internal_only
#endif
)
{
// clang-format off
static const struct
{
const char *prefix;
int t_black, t_maximum, trans[12];
} table[] = {
{ "AgfaPhoto DC-833m", 0, 0, /* DJC */
{ 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } },
{ "Apple QuickTake", 0, 0, /* DJC */
{ 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } },
{"Broadcom RPi IMX219", 66, 0x3ff,
{ 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */
{ "Broadcom RPi OV5647", 16, 0x3ff,
{ 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */
{ "Canon EOS D2000", 0, 0,
{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
{ "Canon EOS D6000", 0, 0,
{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
{ "Canon EOS D30", 0, 0, /* updated */
{ 9900,-2771,-1324,-7072,14229,3140,-2790,3344,8861 } },
{ "Canon EOS D60", 0, 0xfa0, /* updated */
{ 6211,-1358,-896,-8557,15766,3012,-3001,3507,8567 } },
{ "Canon EOS 5DS", 0, 0x3c96,
{ 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } },
{ "Canon EOS 5D Mark IV", 0, 0,
{ 6446,-366,-864,-4436,12204,2513,-952,2496,6348 } },
{ "Canon EOS 5D Mark III", 0, 0x3c80,
{ 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } },
{ "Canon EOS 5D Mark II", 0, 0x3cf0,
{ 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } },
{ "Canon EOS 5D", 0, 0xe6c,
{ 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } },
{ "Canon EOS 6D Mark II", 0, 0x38de, /* updated */
{ 6875,-970,-932,-4691,12459,2501,-874,1953,5809 } },
{ "Canon EOS 6D", 0, 0x3c82, /* skipped update */
{ 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } },
{ "Canon EOS 77D", 0, 0,
{ 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } },
{ "Canon EOS 7D Mark II", 0, 0x3510,
{ 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } },
{ "Canon EOS 7D", 0, 0x3510,
{ 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } },
{ "Canon EOS 800D", 0, 0,
{ 6970,-512,-968,-4425,12161,2553,-739,1982,5601 } },
{ "Canon EOS 80D", 0, 0,
{ 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } },
{ "Canon EOS 10D", 0, 0xfa0, /* updated */
{ 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } },
{ "Canon EOS 200D", 0, 0,
{ 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } },
{ "Canon EOS 20Da", 0, 0,
{ 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } },
{ "Canon EOS 20D", 0, 0xfff,
{ 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } },
{ "Canon EOS 30D", 0, 0,
{ 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } },
{ "Canon EOS 40D", 0, 0x3f60,
{ 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } },
{ "Canon EOS 50D", 0, 0x3d93,
{ 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } },
{ "Canon EOS 60Da", 0, 0x2ff7, /* added */
{ 17492,-7240,-2023,-1791,10323,1701,-186,1329,5406 } },
{ "Canon EOS 60D", 0, 0x2ff7,
{ 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } },
{ "Canon EOS 70D", 0, 0x3bc7,
{ 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } },
{ "Canon EOS 100D", 0, 0x350f,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 300D", 0, 0xfa0, /* updated */
{ 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } },
{ "Canon EOS 350D", 0, 0xfff,
{ 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } },
{ "Canon EOS 400D", 0, 0xe8e,
{ 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } },
{ "Canon EOS 450D", 0, 0x390d,
{ 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } },
{ "Canon EOS 500D", 0, 0x3479,
{ 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } },
{ "Canon EOS 550D", 0, 0x3dd7,
{ 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } },
{ "Canon EOS 600D", 0, 0x3510,
{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
{ "Canon EOS 650D", 0, 0x354d,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 750D", 0, 0x3c00,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS 760D", 0, 0x3c00,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS 700D", 0, 0x3c00,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 1000D", 0, 0xe43,
{ 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } },
{ "Canon EOS 1100D", 0, 0x3510,
{ 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } },
{ "Canon EOS 1200D", 0, 0x37c2,
{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
{ "Canon EOS 1300D", 0, 0x37c2,
{ 6939,-1016,-866,-4428,12473,2177,-1175,2178,6162 } },
{ "Canon EOS M6", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M5", 0, 0,
{ 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } },
{ "Canon EOS M3", 0, 0,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS M2", 0, 0, /* added */
{ 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } },
{ "Canon EOS M10", 0, 0,
{ 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } },
{ "Canon EOS M", 0, 0,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS-1Ds Mark III", 0, 0x3bb0,
{ 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } },
{ "Canon EOS-1Ds Mark II", 0, 0xe80,
{ 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } },
{ "Canon EOS-1D Mark IV", 0, 0x3bb0,
{ 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } },
{ "Canon EOS-1D Mark III", 0, 0x3bb0,
{ 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } },
{ "Canon EOS-1D Mark II N", 0, 0xe80,
{ 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } },
{ "Canon EOS-1D Mark II", 0, 0xe80,
{ 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } },
{ "Canon EOS-1DS", 0, 0xe20, /* updated */
{ 3925,4060,-1739,-8973,16552,2545,-3287,3945,8243 } },
{ "Canon EOS-1D C", 0, 0x3c4e,
{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
{ "Canon EOS-1D X Mark II", 0, 0x3c4e, /* updated */
{ 7596,-978,-967,-4808,12571,2503,-1398,2567,5752 } },
{ "Canon EOS-1D X", 0, 0x3c4e,
{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
{ "Canon EOS-1D", 0, 0xe20,
{ 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } },
{ "Canon EOS C500", 853, 0, /* DJC */
{ 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } },
{"Canon PowerShot 600", 0, 0, /* added */
{ -3822,10019,1311,4085,-157,3386,-5341,10829,4812,-1969,10969,1126 } },
{ "Canon PowerShot A530", 0, 0,
{ 0 } }, /* don't want the A5 matrix */
{ "Canon PowerShot A50", 0, 0,
{ -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } },
{ "Canon PowerShot A5", 0, 0,
{ -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } },
{ "Canon PowerShot G10", 0, 0,
{ 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } },
{ "Canon PowerShot G11", 0, 0,
{ 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } },
{ "Canon PowerShot G12", 0, 0,
{ 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } },
{ "Canon PowerShot G15", 0, 0,
{ 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } },
{ "Canon PowerShot G16", 0, 0, /* updated */
{ 8020,-2687,-682,-3704,11879,2052,-965,1921,5556 } },
{ "Canon PowerShot G1 X Mark II", 0, 0,
{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
{ "Canon PowerShot G1 X", 0, 0,
{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
{ "Canon PowerShot G1", 0, 0, /* updated */
{ -5686,10300,2223,4725,-1157,4383,-6128,10783,6163,-2688,12093,604 } },
{ "Canon PowerShot G2", 0, 0, /* updated */
{ 9194,-2787,-1059,-8098,15657,2608,-2610,3064,7867 } },
{ "Canon PowerShot G3 X", 0, 0,
{ 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } },
{ "Canon PowerShot G3", 0, 0, /* updated */
{ 9326,-2882,-1084,-7940,15447,2677,-2620,3090,7740 } },
{ "Canon PowerShot G5 X",0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G5", 0, 0, /* updated */
{ 9869,-2972,-942,-7314,15098,2369,-1898,2536,7282 } },
{ "Canon PowerShot G6", 0, 0,
{ 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } },
{ "Canon PowerShot G7 X Mark II", 0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G7 X", 0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G9 X Mark II", 0, 0,
{ 10056,-4131,-944,-2576,11143,1625,-238,1294,5179 } },
{ "Canon PowerShot G9 X",0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G9", 0, 0,
{ 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } },
{ "Canon PowerShot Pro1", 0, 0,
{ 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } },
{ "Canon PowerShot Pro70", 34, 0, /* updated */
{ -5106,10695,1576,3820,53,4566,-6497,10736,6701,-3336,11887,1394 } },
{ "Canon PowerShot Pro90", 0, 0, /* updated */
{ -5912,10768,2288,4612,-989,4333,-6153,10897,5944,-2907,12288,624 } },
{ "Canon PowerShot S30", 0, 0, /* updated */
{ 10744,-3813,-1142,-7962,15966,2075,-2492,2805,7744 } },
{ "Canon PowerShot S40", 0, 0, /* updated */
{ 8606,-2573,-949,-8237,15489,2974,-2649,3076,9100 } },
{ "Canon PowerShot S45", 0, 0, /* updated */
{ 8251,-2410,-964,-8047,15430,2823,-2380,2824,8119 } },
{ "Canon PowerShot S50", 0, 0, /* updated */
{ 8979,-2658,-871,-7721,15500,2357,-1773,2366,6634 } },
{ "Canon PowerShot S60", 0, 0,
{ 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } },
{ "Canon PowerShot S70", 0, 0,
{ 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } },
{ "Canon PowerShot S90", 0, 0,
{ 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } },
{ "Canon PowerShot S95", 0, 0,
{ 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } },
{ "Canon PowerShot S120", 0, 0,
{ 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } },
{ "Canon PowerShot S110", 0, 0,
{ 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } },
{ "Canon PowerShot S100", 0, 0,
{ 7968,-2565,-636,-2873,10697,2513,180,667,4211 } },
{ "Canon PowerShot SX1 IS", 0, 0,
{ 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } },
{ "Canon PowerShot SX50 HS", 0, 0,
{ 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } },
{ "Canon PowerShot SX60 HS", 0, 0,
{ 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } },
{ "Canon PowerShot A3300", 0, 0, /* DJC */
{ 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } },
{ "Canon PowerShot A470", 0, 0, /* DJC */
{ 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } },
{ "Canon PowerShot A610", 0, 0, /* DJC */
{ 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } },
{ "Canon PowerShot A620", 0, 0, /* DJC */
{ 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } },
{ "Canon PowerShot A630", 0, 0, /* DJC */
{ 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } },
{ "Canon PowerShot A640", 0, 0, /* DJC */
{ 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } },
{ "Canon PowerShot A650", 0, 0, /* DJC */
{ 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } },
{ "Canon PowerShot A720", 0, 0, /* DJC */
{ 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } },
{ "Canon PowerShot D10", 127, 0, /* DJC */
{ 14052,-5229,-1156,-1325,9420,2252,-498,1957,4116 } },
{ "Canon PowerShot S3 IS", 0, 0, /* DJC */
{ 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } },
{ "Canon PowerShot SX110 IS", 0, 0, /* DJC */
{ 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } },
{ "Canon PowerShot SX220", 0, 0, /* DJC */
{ 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } },
{ "Canon IXUS 160", 0, 0, /* DJC */
{ 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } },
{ "Casio EX-F1", 0, 0, /* added */
{ 9084,-2016,-848,-6711,14351,2570,-1059,1725,6135 } },
{ "Casio EX-FH100", 0, 0, /* added */
{ 12771,-4179,-1558,-2149,10938,1375,-453,1751,4494 } },
{ "Casio EX-S20", 0, 0, /* DJC */
{ 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } },
{ "Casio EX-Z750", 0, 0, /* DJC */
{ 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } },
{ "Casio EX-Z10", 128, 0xfff, /* DJC */
{ 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } },
{ "CINE 650", 0, 0,
{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
{ "CINE 660", 0, 0,
{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
{ "CINE", 0, 0,
{ 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } },
{ "Contax N Digital", 0, 0xf1e,
{ 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } },
{ "DXO ONE", 0, 0,
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Epson R-D1", 0, 0,
{ 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } },
{ "Fujifilm E550", 0, 0, /* updated */
{ 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } },
{ "Fujifilm E900", 0, 0,
{ 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } },
{ "Fujifilm F5", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F6", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F77", 0, 0xfe9,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F7", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm F810", 0, 0, /* added */
{ 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } },
{ "Fujifilm F8", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm S100FS", 514, 0,
{ 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } },
{ "Fujifilm S1", 0, 0,
{ 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } },
{ "Fujifilm S20Pro", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm S20", 512, 0x3fff,
{ 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } },
{ "Fujifilm S2Pro", 128, 0, /* updated */
{ 12741,-4916,-1420,-8510,16791,1715,-1767,2302,7771 } },
{ "Fujifilm S3Pro", 0, 0,
{ 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } },
{ "Fujifilm S5Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm S5000", 0, 0,
{ 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } },
{ "Fujifilm S5100", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5500", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5200", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S5600", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S6", 0, 0,
{ 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } },
{ "Fujifilm S7000", 0, 0,
{ 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } },
{ "Fujifilm S9000", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9500", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9100", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm S9600", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm SL1000", 0, 0,
{ 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } },
{ "Fujifilm IS-1", 0, 0,
{ 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } },
{ "Fujifilm IS Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm HS10 HS11", 0, 0xf68,
{ 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } },
{ "Fujifilm HS2", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS3", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS50EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm F900EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm X100S", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100F", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X100T", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100", 0, 0,
{ 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } },
{ "Fujifilm X10", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X20", 0, 0,
{ 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } },
{ "Fujifilm X30", 0, 0,
{ 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } },
{ "Fujifilm X70", 0, 0,
{ 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } },
{ "Fujifilm X-Pro1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-Pro2", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-A10", 0, 0,
{ 11540,-4999,-991,-2949,10963,2278,-382,1049,5605} },
{ "Fujifilm X-A1", 0, 0,
{ 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } },
{ "Fujifilm X-A2", 0, 0,
{ 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } },
{ "Fujifilm X-A3", 0, 0,
{ 12407,-5222,-1086,-2971,11116,2120,-294,1029,5284 } },
{ "Fujifilm X-E1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-E2S", 0, 0,
{ 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } },
{ "Fujifilm X-E2", 0, 0,
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm XF1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-M1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-S1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-T20", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-T2", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-T10", 0, 0, /* updated */
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-T1", 0, 0,
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm XQ1", 0, 0,
{ 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } },
{ "Fujifilm XQ2", 0, 0,
{ 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } },
{ "Fujifilm GFX 50S", 0, 0,
{ 11756,-4754,-874,-3056,11045,2305,-381,1457,6006 } },
{ "GITUP GIT2P", 4160, 0,
{ 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "GITUP GIT2", 3200, 0,
{ 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "Hasselblad HV", 0, 0, /* added */
{ 6344,-1612,-461,-4862,12476,2680,-864,1785,6898 } },
{ "Hasselblad Lunar", 0, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Hasselblad Lusso", 0, 0, /* added */
{ 4912,-540,-201,-6129,13513,2906,-1563,2151,7182 } },
{ "Hasselblad Stellar", -800, 0,
{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
{ "Hasselblad 500 mech.", 0, 0, /* added */
{ 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } },
{ "Hasselblad CFV", 0, 0,
{ 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } },
{ "Hasselblad H-16MP", 0, 0, /* LibRaw */
{ 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } },
{ "Hasselblad H-22MP", 0, 0, /* LibRaw */
{ 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } },
{ "Hasselblad H-31MP",0, 0, /* LibRaw */
{ 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } },
{ "Hasselblad 39-Coated", 0, 0, /* added */
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H-39MP",0, 0,
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H2D-39", 0, 0, /* added */
{ 3894,-110,287,-4672,12610,2295,-2092,4100,6196 } },
{ "Hasselblad H3D-50", 0, 0,
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H3D", 0, 0, /* added */
{ 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } },
{ "Hasselblad H4D-40",0, 0, /* LibRaw */
{ 6325,-860,-957,-6559,15945,266,167,770,5936 } },
{ "Hasselblad H4D-50",0, 0, /* LibRaw */
{ 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } },
{ "Hasselblad H4D-60",0, 0,
{ 9662,-684,-279,-4903,12293,2950,-344,1669,6024 } },
{ "Hasselblad H5D-50c",0, 0,
{ 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } },
{ "Hasselblad H5D-50",0, 0,
{ 5656,-659,-346,-3923,12306,1791,-1602,3509,5442 } },
{ "Hasselblad H6D-100c",0, 0,
{ 5110,-1357,-308,-5573,12835,3077,-1279,2025,7010 } },
{ "Hasselblad X1D",0, 0,
{ 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } },
{ "HTC One A9", 64, 1023, /* this is CM1 transposed */
{ 101, -20, -2, -11, 145, 41, -24, 1, 56 } },
{ "Imacon Ixpress", 0, 0, /* DJC */
{ 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } },
{ "Kodak NC2000", 0, 0,
{ 13891,-6055,-803,-465,9919,642,2121,82,1291 } },
{ "Kodak DCS315C", -8, 0,
{ 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } },
{ "Kodak DCS330C", -8, 0,
{ 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } },
{ "Kodak DCS420", 0, 0,
{ 10868,-1852,-644,-1537,11083,484,2343,628,2216 } },
{ "Kodak DCS460", 0, 0,
{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
{ "Kodak EOSDCS1", 0, 0,
{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
{ "Kodak EOSDCS3B", 0, 0,
{ 9898,-2700,-940,-2478,12219,206,1985,634,1031 } },
{ "Kodak DCS520C", -178, 0,
{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
{ "Kodak DCS560C", -177, 0,
{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
{ "Kodak DCS620C", -177, 0,
{ 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } },
{ "Kodak DCS620X", -176, 0,
{ 13095,-6231,154,12221,-21,-2137,895,4602,2258 } },
{ "Kodak DCS660C", -173, 0,
{ 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } },
{ "Kodak DCS720X", 0, 0,
{ 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } },
{ "Kodak DCS760C", 0, 0,
{ 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } },
{ "Kodak DCS Pro SLR", 0, 0,
{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
{ "Kodak DCS Pro 14nx", 0, 0,
{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
{ "Kodak DCS Pro 14", 0, 0,
{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
{ "Photo Control Camerz ZDS 14", 0, 0,
{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
{ "Kodak ProBack645", 0, 0,
{ 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } },
{ "Kodak ProBack", 0, 0,
{ 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } },
{ "Kodak P712", 0, 0,
{ 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } },
{ "Kodak P850", 0, 0xf7c,
{ 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } },
{ "Kodak P880", 0, 0xfff,
{ 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } },
{ "Kodak EasyShare Z980", 0, 0,
{ 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } },
{ "Kodak EasyShare Z981", 0, 0,
{ 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } },
{ "Kodak EasyShare Z990", 0, 0xfed,
{ 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } },
{ "Kodak EASYSHARE Z1015", 0, 0xef1,
{ 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } },
{ "Leaf C-Most", 0, 0, /* updated */
{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
{ "Leaf Valeo 6", 0, 0,
{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
{ "Leaf Aptus 54S", 0, 0,
{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
{ "Leaf Aptus-II 8", 0, 0, /* added */
{ 7361,1257,-163,-6929,14061,3176,-1839,3454,5603 } },
{ "Leaf AFi-II 7", 0, 0, /* added */
{ 7691,-108,-339,-6185,13627,2833,-2046,3899,5952 } },
{ "Leaf Aptus-II 5", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Aptus 65", 0, 0,
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf AFi 65S", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Aptus 75", 0, 0,
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf AFi 75S", 0, 0, /* added */
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Credo 40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Leaf Credo 50", 0, 0,
{ 3984,0,0,0,10000,0,0,0,7666 } },
{ "Leaf Credo 60", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Leaf Credo 80", 0, 0,
{ 6294,686,-712,-5435, 13417,2211,-1006,2435,5042 } },
{ "Leaf", 0, 0,
{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
{ "Leica M10", 0, 0, /* added */
{ 9090,-3342,-740,-4006,13456,493,-569,2266,6871 } },
{ "Leica M9", 0, 0, /* added */
{ 6687,-1751,-291,-3556,11373,2492,-548,2204,7146 } },
{ "Leica M8", 0, 0, /* added */
{ 7675,-2196,-305,-5860,14119,1856,-2425,4006,6578 } },
{ "Leica M (Typ 240)", 0, 0, /* added */
{ 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } },
{ "Leica M (Typ 262)", 0, 0,
{ 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } },
{ "Leica SL (Typ 601)", 0, 0,
{ 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} },
{ "Leica S2", 0, 0, /* added */
{ 5627,-721,-447,-4423,12456,2192,-1048,2948,7379 } },
{"Leica S-E (Typ 006)", 0, 0, /* added */
{ 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } },
{"Leica S (Typ 006)", 0, 0, /* added */
{ 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } },
{ "Leica S (Typ 007)", 0, 0,
{ 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } },
{ "Leica Q (Typ 116)", 0, 0, /* updated */
{ 10068,-4043,-1068,-5319,14268,1044,-765,1701,6522 } },
{ "Leica T (Typ 701)", 0, 0, /* added */
{ 6295 ,-1679 ,-475 ,-5586 ,13046 ,2837 ,-1410 ,1889 ,7075 } },
{ "Leica X2", 0, 0, /* added */
{ 8336,-2853,-699,-4425,11989,2760,-954,1625,6396 } },
{ "Leica X1", 0, 0, /* added */
{ 9055,-2611,-666,-4906,12652,2519,-555,1384,7417 } },
{ "Leica X", 0, 0, /* X(113), X-U(113), XV, X Vario(107) */ /* updated */
{ 9062,-3198,-828,-4065,11772,2603,-761,1468,6458 } },
{ "Mamiya M31", 0, 0, /* added */
{ 4516 ,-244 ,-36 ,-7020 ,14976 ,2174 ,-3206 ,4670 ,7087 } },
{ "Mamiya M22", 0, 0, /* added */
{ 2905 ,732 ,-237 ,-8135 ,16626 ,1476 ,-3038 ,4253 ,7517 } },
{ "Mamiya M18", 0, 0, /* added */
{ 6516 ,-2050 ,-507 ,-8217 ,16703 ,1479 ,-3492 ,4741 ,8489 } },
{ "Mamiya ZD", 0, 0,
{ 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } },
{ "Micron 2010", 110, 0, /* DJC */
{ 16695,-3761,-2151,155,9682,163,3433,951,4904 } },
{ "Minolta DiMAGE 5", 0, 0xf7d, /* updated */
{ 9117,-3063,-973,-7949,15763,2306,-2752,3136,8093 } },
{ "Minolta DiMAGE 7Hi", 0, 0xf7d, /* updated */
{ 11555,-4064,-1256,-7903,15633,2409,-2811,3320,7358 } },
{ "Minolta DiMAGE 7i", 0, 0xf7d, /* added */
{ 11050,-3791,-1199,-7875,15585,2434,-2797,3359,7560 } },
{ "Minolta DiMAGE 7", 0, 0xf7d, /* updated */
{ 9258,-2879,-1008,-8076,15847,2351,-2806,3280,7821 } },
{ "Minolta DiMAGE A1", 0, 0xf8b, /* updated */
{ 9274,-2548,-1167,-8220,16324,1943,-2273,2721,8340 } },
{ "Minolta DiMAGE A200", 0, 0,
{ 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } },
{ "Minolta DiMAGE A2", 0, 0xf8f,
{ 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } },
{ "Minolta DiMAGE Z2", 0, 0, /* DJC */
{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
{ "Minolta DYNAX 5", 0, 0xffb,
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta Maxxum 5D", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta ALPHA-5 DIGITAL", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta ALPHA SWEET DIGITAL", 0, 0xffb, /* added */
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta DYNAX 7", 0, 0xffb,
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Minolta Maxxum 7D", 0, 0xffb, /* added */
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Minolta ALPHA-7 DIGITAL", 0, 0xffb, /* added */
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Motorola PIXL", 0, 0, /* DJC */
{ 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } },
{ "Nikon D100", 0, 0,
{ 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } },
{ "Nikon D1H", 0, 0, /* updated */
{ 7659,-2238,-935,-8942,16969,2004,-2701,3051,8690 } },
{ "Nikon D1X", 0, 0,
{ 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } },
{ "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */
{ 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } },
{ "Nikon D200", 0, 0xfbc,
{ 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } },
{ "Nikon D2H", 0, 0,
{ 5733,-911,-629,-7967,15987,2055,-3050,4013,7048 } },
{ "Nikon D2X", 0, 0, /* updated */
{ 10231,-2768,-1254,-8302,15900,2551,-797,681,7148 } },
{ "Nikon D3000", 0, 0,
{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
{ "Nikon D3100", 0, 0,
{ 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } },
{ "Nikon D3200", 0, 0xfb9,
{ 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } },
{ "Nikon D3300", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D3400", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D300", 0, 0,
{ 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } },
{ "Nikon D3X", 0, 0,
{ 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } },
{ "Nikon D3S", 0, 0,
{ 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } },
{ "Nikon D3", 0, 0,
{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
{ "Nikon D40X", 0, 0,
{ 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } },
{ "Nikon D40", 0, 0,
{ 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } },
{ "Nikon D4S", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon D4", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon Df", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon D5000", 0, 0xf00,
{ 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } },
{ "Nikon D5100", 0, 0x3de6,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon D5200", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D5300", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D5500", 0, 0,
{ 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } },
{ "Nikon D5600", 0, 0,
{ 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } },
{ "Nikon D500", 0, 0,
{ 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } },
{ "Nikon D50", 0, 0,
{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
{ "Nikon D5", 0, 0,
{ 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } },
{ "Nikon D600", 0, 0x3e07,
{ 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } },
{ "Nikon D610",0, 0, /* updated */
{ 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } },
{ "Nikon D60", 0, 0,
{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
{ "Nikon D7000", 0, 0,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon D7100", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D7200", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D7500", 0, 0,
{ 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } },
{ "Nikon D750", -600, 0,
{ 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } },
{ "Nikon D700", 0, 0,
{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
{ "Nikon D70", 0, 0,
{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
{ "Nikon D810A", 0, 0,
{ 11973,-5685,-888,-1965,10326,1901,-115,1123,7169 } },
{ "Nikon D810", 0, 0,
{ 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } },
{ "Nikon D800", 0, 0,
{ 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } },
{ "Nikon D80", 0, 0,
{ 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } },
{ "Nikon D90", 0, 0xf00,
{ 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } },
{ "Nikon E700", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E800", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E950", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E995", 0, 0, /* copied from E5000 */
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E2100", 0, 0, /* copied from Z2, new white balance */
{ 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } },
{ "Nikon E2500", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E3200", 0, 0, /* DJC */
{ 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } },
{ "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */
{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
{ "Nikon E4500", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E5000", 0, 0, /* updated */
{ -6678,12805,2248,5725,-499,3375,-5903,10713,6034,-270,9976,134 } },
{ "Nikon E5400", 0, 0, /* updated */
{ 9349,-2988,-1001,-7918,15766,2266,-2097,2680,6839 } },
{ "Nikon E5700", 0, 0, /* updated */
{ -6475,12496,2428,5409,-16,3180,-5965,10912,5866,-177,9918,248 } },
{ "Nikon E8400", 0, 0,
{ 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } },
{ "Nikon E8700", 0, 0,
{ 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "Nikon E8800", 0, 0,
{ 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } },
{ "Nikon COOLPIX A", 0, 0,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon COOLPIX B700", 0, 0,
{ 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } },
{ "Nikon COOLPIX P330", -200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P340", -200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX Kalon", 0, 0, /* added */
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX Deneb", 0, 0, /* added */
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P6000", 0, 0,
{ 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } },
{ "Nikon COOLPIX P7000", 0, 0,
{ 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } },
{ "Nikon COOLPIX P7100", 0, 0,
{ 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } },
{ "Nikon COOLPIX P7700", -3200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P7800", -3200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon 1 V3", -200, 0,
{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
{ "Nikon 1 J4", 0, 0,
{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
{ "Nikon 1 J5", 0, 0,
{ 7520,-2518,-645,-3844,12102,1945,-913,2249,6835 } },
{ "Nikon 1 S2", -200, 0,
{ 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } },
{ "Nikon 1 V2", 0, 0,
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 J3", 0, 0, /* updated */
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 AW1", 0, 0,
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */
{ 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } },
{ "Olympus AIR-A01", 0, 0xfe1,
{ 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } },
{ "Olympus C5050", 0, 0, /* updated */
{ 10633,-3234,-1285,-7460,15570,1967,-1917,2510,6299 } },
{ "Olympus C5060", 0, 0,
{ 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } },
{ "Olympus C7070", 0, 0,
{ 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } },
{ "Olympus C70", 0, 0,
{ 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } },
{ "Olympus C80", 0, 0,
{ 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } },
{ "Olympus E-10", 0, 0xffc, /* updated */
{ 12970,-4703,-1433,-7466,15843,1644,-2191,2451,6668 } },
{ "Olympus E-1", 0, 0,
{ 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } },
{ "Olympus E-20", 0, 0xffc, /* updated */
{ 13414,-4950,-1517,-7166,15293,1960,-2325,2664,7212 } },
{ "Olympus E-300", 0, 0,
{ 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } },
{ "Olympus E-330", 0, 0,
{ 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } },
{ "Olympus E-30", 0, 0xfbc,
{ 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } },
{ "Olympus E-3", 0, 0xf99,
{ 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } },
{ "Olympus E-400", 0, 0,
{ 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } },
{ "Olympus E-410", 0, 0xf6a,
{ 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } },
{ "Olympus E-420", 0, 0xfd7,
{ 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } },
{ "Olympus E-450", 0, 0xfd2,
{ 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } },
{ "Olympus E-500", 0, 0,
{ 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } },
{ "Olympus E-510", 0, 0xf6a,
{ 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } },
{ "Olympus E-520", 0, 0xfd2,
{ 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } },
{ "Olympus E-5", 0, 0xeec,
{ 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } },
{ "Olympus E-600", 0, 0xfaf,
{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
{ "Olympus E-620", 0, 0xfaf,
{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
{ "Olympus E-P1", 0, 0xffd,
{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
{ "Olympus E-P2", 0, 0xffd,
{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
{ "Olympus E-P3", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-P5", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL1s", 0, 0,
{ 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } },
{ "Olympus E-PL1", 0, 0,
{ 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } },
{ "Olympus E-PL2", 0, 0xcf3,
{ 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } },
{ "Olympus E-PL3", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-PL5", 0, 0xfcb,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL6", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL7", 0, 0,
{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
{ "Olympus E-PL8", 0, 0,
{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
{ "Olympus E-PM1", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-PM2", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-M10", 0, 0, /* Same for E-M10MarkII */
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-M1MarkII", 0, 0,
{ 9383,-3170,-763,-2457,10702,2020,-384,1236,5552 } },
{ "Olympus E-M1", 0, 0,
{ 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } },
{ "Olympus E-M5MarkII", 0, 0,
{ 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } },
{ "Olympus E-M5", 0, 0xfe1,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus PEN-F",0, 0,
{ 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } },
{ "Olympus SP350", 0, 0,
{ 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } },
{ "Olympus SP3", 0, 0,
{ 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } },
{ "Olympus SP500UZ", 0, 0xfff,
{ 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } },
{ "Olympus SP510UZ", 0, 0xffe,
{ 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } },
{ "Olympus SP550UZ", 0, 0xffe,
{ 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } },
{ "Olympus SP560UZ", 0, 0xff9,
{ 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } },
{ "Olympus SP565UZ", 0, 0, /* added */
{ 11856,-4469,-1159,-4814,12368,2756,-993,1779,5589 } },
{ "Olympus SP570UZ", 0, 0,
{ 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } },
{ "Olympus SH-2", 0, 0,
{ 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } },
{ "Olympus SH-3", 0, 0, /* Alias of SH-2 */
{ 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } },
{ "Olympus STYLUS1",0, 0, /* updated */
{ 8360,-2420,-880,-3928,12353,1739,-1381,2416,5173 } },
{ "Olympus TG-4", 0, 0,
{ 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } },
{ "Olympus TG-5", 0, 0,
{ 10899,-3833,-1082,-2112,10736,1575,-267,1452,5269 } },
{ "Olympus XZ-10", 0, 0,
{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
{ "Olympus XZ-1", 0, 0,
{ 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } },
{ "Olympus XZ-2", 0, 0,
{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
{ "OmniVision", 16, 0x3ff,
{ 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */
{ "Pentax *ist DL2", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Pentax *ist DL", 0, 0,
{ 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } },
{ "Pentax *ist DS2", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Pentax *ist DS", 0, 0,
{ 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } },
{ "Pentax *ist D", 0, 0,
{ 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } },
{ "Pentax GR", 0, 0, /* added */
{ 5329,-1459,-390,-5407,12930,2768,-1119,1772,6046 } },
{ "Pentax K-01", 0, 0, /* added */
{ 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } },
{ "Pentax K10D", 0, 0, /* updated */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Pentax K1", 0, 0,
{ 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } },
{ "Pentax K20D", 0, 0,
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Pentax K200D", 0, 0,
{ 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } },
{ "Pentax K2000", 0, 0, /* updated */
{ 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } },
{ "Pentax K-m", 0, 0, /* updated */
{ 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } },
{ "Pentax KP", 0, 0,
{ 7825,-2160,-1403,-4841,13555,1349,-1559,2449,5814 } },
{ "Pentax K-x", 0, 0,
{ 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } },
{ "Pentax K-r", 0, 0,
{ 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } },
{ "Pentax K-1", 0, 0, /* updated */
{ 8596,-2981,-639,-4202,12046,2431,-685,1424,6122 } },
{ "Pentax K-30", 0, 0, /* updated */
{ 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } },
{ "Pentax K-3 II", 0, 0, /* updated */
{ 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } },
{ "Pentax K-3", 0, 0,
{ 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } },
{ "Pentax K-5 II", 0, 0,
{ 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } },
{ "Pentax K-500", 0, 0, /* added */
{ 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } },
{ "Pentax K-50", 0, 0, /* added */
{ 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } },
{ "Pentax K-5", 0, 0,
{ 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } },
{ "Pentax K-70", 0, 0,
{ 8766,-3149,-747,-3976,11943,2292,-517,1259,5552 } },
{ "Pentax K-7", 0, 0,
{ 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } },
{ "Pentax KP", 0, 0, /* temp */
{ 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } },
{ "Pentax K-S1", 0, 0,
{ 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } },
{ "Pentax K-S2", 0, 0,
{ 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } },
{ "Pentax Q-S1", 0, 0,
{ 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } },
{ "Pentax Q7", 0, 0, /* added */
{ 10901,-3938,-1025,-2743,11210,1738,-823,1805,5344 } },
{ "Pentax Q10", 0, 0, /* updated */
{ 11562,-4183,-1172,-2357,10919,1641,-582,1726,5112 } },
{ "Pentax Q", 0, 0, /* added */
{ 11731,-4169,-1267,-2015,10727,1473,-217,1492,4870 } },
{ "Pentax MX-1", 0, 0, /* updated */
{ 9296,-3146,-888,-2860,11287,1783,-618,1698,5151 } },
{ "Pentax 645D", 0, 0x3e00,
{ 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } },
{ "Pentax 645Z", 0, 0, /* updated */
{ 9519,-3591,-664,-4074,11725,2671,-624,1501,6653 } },
{ "Panasonic DMC-CM10", -15, 0,
{ 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } },
{ "Panasonic DMC-CM1", -15, 0,
{ 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } },
{ "Panasonic DC-FZ82", -15, 0, /* markets: FZ80 FZ82 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DC-FZ80", -15, 0, /* markets: FZ80 FZ82 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DMC-FZ8", 0, 0xf7f,
{ 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } },
{ "Panasonic DMC-FZ18", 0, 0,
{ 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } },
{ "Panasonic DMC-FZ28", -15, 0xf96,
{ 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } },
{ "Panasonic DMC-FZ300", -15, 0xfff,
{ 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } },
{ "Panasonic DMC-FZ330", -15, 0xfff,
{ 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } },
{ "Panasonic DMC-FZ30", 0, 0xf94,
{ 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } },
{ "Panasonic DMC-FZ3", -15, 0,
{ 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } },
{ "Panasonic DMC-FZ4", -15, 0, /* 40,42,45 */
{ 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } },
{ "Panasonic DMC-FZ50", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Panasonic DMC-FZ7", -15, 0,
{ 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } },
{ "Leica V-LUX1", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Leica V-LUX 1", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Panasonic DMC-L10", -15, 0xf96,
{ 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } },
{ "Panasonic DMC-L1", 0, 0xf7f,
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Leica DIGILUX3", 0, 0xf7f, /* added */
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Leica DIGILUX 3", 0, 0xf7f,
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Panasonic DMC-LC1", 0, 0,
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Leica DIGILUX2", 0, 0, /* added */
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Leica DIGILUX 2", 0, 0,
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Panasonic DMC-LX100", -15, 0,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Leica D-LUX (Typ 109)", -15, 0,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Panasonic DMC-LF1", -15, 0,
{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
{ "Leica C (Typ 112)", -15, 0,
{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
{ "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-LX1", 0, 0xf7f,
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Leica D-Lux (Typ 109)", 0, 0xf7f,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Leica D-LUX2", 0, 0xf7f,
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Leica D-LUX 2", 0, 0xf7f, /* added */
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Panasonic DMC-LX2", 0, 0,
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Leica D-LUX3", 0, 0,
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Leica D-LUX 3", 0, 0, /* added */
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Panasonic DMC-LX3", -15, 0,
{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
{ "Leica D-LUX 4", -15, 0,
{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
{ "Panasonic DMC-LX5", -15, 0,
{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
{ "Leica D-LUX 5", -15, 0,
{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
{ "Panasonic DMC-LX7", -15, 0,
{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
{ "Leica D-LUX 6", -15, 0,
{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
{ "Panasonic DMC-FZ1000", -15, 0,
{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
{ "Leica V-LUX (Typ 114)", 15, 0,
{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
{ "Panasonic DMC-FZ100", -15, 0xfff,
{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
{ "Leica V-LUX 2", -15, 0xfff,
{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
{ "Panasonic DMC-FZ150", -15, 0xfff,
{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
{ "Leica V-LUX 3", -15, 0xfff,
{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
{ "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000, DMC-FZ2500 ,FZH1 */
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZ2500", -15, 0,
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZH1", -15, 0,
{ 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } },
{ "Panasonic DMC-FZ200", -15, 0xfff,
{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
{ "Leica V-LUX 4", -15, 0xfff,
{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
{ "Panasonic DMC-FX150", -15, 0xfff,
{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
{ "Panasonic DMC-FX180", -15, 0xfff, /* added */
{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
{ "Panasonic DMC-G10", 0, 0,
{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
{ "Panasonic DMC-G1", -15, 0xf94,
{ 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } },
{ "Panasonic DMC-G2", -15, 0xf3c,
{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
{ "Panasonic DMC-G3", -15, 0xfff,
{ 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } },
{ "Panasonic DMC-G5", -15, 0xfff,
{ 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } },
{ "Panasonic DMC-G6", -15, 0xfff,
{ 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } },
{ "Panasonic DMC-G7", -15, 0xfff,
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-GF1", -15, 0xf92,
{ 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } },
{ "Panasonic DMC-GF2", -15, 0xfff,
{ 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } },
{ "Panasonic DMC-GF3", -15, 0xfff,
{ 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } },
{ "Panasonic DMC-GF5", -15, 0xfff,
{ 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } },
{ "Panasonic DMC-GF6", -15, 0,
{ 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } },
{ "Panasonic DMC-GF7", -15, 0,
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-GF8", -15, 0,
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-GH1", -15, 0xf92,
{ 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } },
{ "Panasonic DMC-GH2", -15, 0xf95,
{ 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } },
{ "Panasonic DMC-GH3", -15, 0,
{ 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } },
{ "Panasonic DMC-GH4", -15, 0,
{ 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } },
{ "Panasonic AG-GH4", -15, 0, /* added */
{ 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } },
{ "Panasonic DC-GH5", -15, 0,
{ 7641,-2336,-605,-3218,11299,2187,-485,1338,5121 } },
{ "Yuneec CGO4", -15, 0,
{ 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } },
{ "Panasonic DMC-GM1", -15, 0,
{ 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } },
{ "Panasonic DMC-GM5", -15, 0,
{ 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } },
{ "Panasonic DMC-GX1", -15, 0,
{ 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } },
{ "Panasonic DC-GX850", -15, 0, /* markets: GX850 GX800 GF9 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DC-GX800", -15, 0, /* markets: GX850 GX800 GF9 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DC-GF9", -15, 0, /* markets: GX850 GX800 GF9 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */
{ 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } },
{ "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */
{ 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } },
{ "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */
{ 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } },
{ "Panasonic DMC-GX7", -15,0,
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-GX8", -15,0,
{ 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } },
{ "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */
{ 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } },
{ "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ82 TZ85 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DC-TZ90", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */
{ 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } },
{ "Panasonic DC-TZ91", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */
{ 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } },
{ "Panasonic DC-TZ92", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */
{ 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } },
{ "Panasonic DC-T93", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */
{ 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } },
{ "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */
{ 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } },
{ "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */
{ 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } },
{ "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */
{ 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } },
{ "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DC-ZS70", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */
{ 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } },
{ "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Phase One H 20", 0, 0, /* DJC */
{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
{ "Phase One H20", 0, 0, /* DJC */
{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
{ "Phase One H 25", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One H25", 0, 0, /* added */
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One IQ280", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ260", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ250",0, 0,
// { 4396,-153,-249,-5267,12249,2657,-1397,2323,6014 } }, /* keep for now */
{ 3984,0,0,0,10000,0,0,0,7666 } },
{ "Phase One IQ180", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ160", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ150", 0, 0, /* added */
{ 3984,0,0,0,10000,0,0,0,7666 } },
{ "Phase One IQ140", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P65", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P 65", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P45", 0, 0, /* added */
{ 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } },
{ "Phase One P 45", 0, 0, /* added */
{ 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } },
{ "Phase One P40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P 40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P30", 0, 0, /* added */
{ 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } },
{ "Phase One P 30", 0, 0, /* added */
{ 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } },
{ "Phase One P25", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P 25", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P21", 0, 0, /* added */
{ 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } },
{ "Phase One P 21", 0, 0, /* added */
{ 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } },
{ "Phase One P20", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P20", 0, 0, /* added */
{ 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } },
{ "Phase One P 2", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One P2", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One IQ3 100MP", 0, 0, /* added */
{ 2423,0,0,0,9901,0,0,0,7989 } },
{ "Phase One IQ3 80MP", 0, 0, /* added */
{ 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } },
{ "Phase One IQ3 60MP", 0, 0, /* added */
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One IQ3 50MP", 0, 0, /* added */
{ 3984,0,0,0,10000,0,0,0,7666 } },
{ "Photron BC2-HD", 0, 0, /* DJC */
{ 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } },
{ "Polaroid x530", 0, 0,
{ 13458,-2556,-510,-5444,15081,205,0,0,12120 } },
{ "Red One", 704, 0xffff, /* DJC */
{ 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } },
{ "Ricoh S10 24-72mm F2.5-4.4 VC", 0, 0, /* added */
{ 10531,-4043,-878,-2038,10270,2052,-107,895,4577 } },
{ "Ricoh GR A12 50mm F2.5 MACRO", 0, 0, /* added */
{ 8849,-2560,-689,-5092,12831,2520,-507,1280,7104 } },
{ "Ricoh GR DIGITAL 3", 0, 0, /* added */
{ 8170,-2496,-655,-5147,13056,2312,-1367,1859,5265 } },
{ "Ricoh GR DIGITAL 4", 0, 0, /* added */
{ 8771,-3151,-837,-3097,11015,2389,-703,1343,4924 } },
{ "Ricoh GR II", 0, 0,
{ 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } },
{ "Ricoh GR", 0, 0,
{ 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } },
{ "Ricoh GX200", 0, 0, /* added */
{ 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } },
{ "Ricoh RICOH GX200", 0, 0, /* added */
{ 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } },
{ "Ricoh GXR MOUNT A12", 0, 0, /* added */
{ 7834,-2182,-739,-5453,13409,2241,-952,2005,6620 } },
{ "Ricoh GXR A16", 0, 0, /* added */
{ 7837,-2538,-730,-4370,12184,2461,-868,1648,5830 } },
{ "Ricoh GXR A12", 0, 0, /* added */
{ 10228,-3159,-933,-5304,13158,2371,-943,1873,6685 } },
{ "Samsung EK-GN100", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-GN110", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-GN120", 0, 0, /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EK-KN120", 0, 0, /* added */ /* Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EX1", 0, 0x3e00,
{ 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } },
{ "Samsung EX2F", 0, 0x7ff,
{ 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } },
{ "Samsung Galaxy S7 Edge", 0, 0, /* added */
{ 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } },
{ "Samsung Galaxy S7", 0, 0, /* added */
{ 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } },
{ "Samsung Galaxy NX", 0, 0, /* added */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX U", 0, 0, /* added */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX mini", 0, 0,
{ 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } },
{ "Samsung NX3300", 0, 0,
{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
{ "Samsung NX3000", 0, 0,
{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
{ "Samsung NX30", 0, 0, /* used for NX30/NX300/NX300M */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX2000", 0, 0,
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX2", 0, 0xfff, /* used for NX20/NX200/NX210 */
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX1000", 0, 0,
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX1100", 0, 0,
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX11", 0, 0,
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX10", 0, 0, /* used for NX10/NX100 */
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX500", 0, 0,
{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
{ "Samsung NX5", 0, 0,
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX1", 0, 0,
{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
{ "Samsung NXF1", 0, 0, /* added */
{ 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } },
{ "Samsung WB2000", 0, 0xfff,
{ 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } },
{ "Samsung GX10", 0, 0, /* added */ /* Pentax K10D */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Samsung GX-10", 0, 0, /* added */ /* Pentax K10D */
{ 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } },
{ "Samsung GX-1", 0, 0, /* used for GX-1L/GX-1S */
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Samsung GX20", 0, 0, /* copied from Pentax K20D */
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Samsung GX-20", 0, 0, /* added */ /* copied from Pentax K20D */
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Samsung S85", 0, 0, /* DJC */
{ 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } },
// Foveon: LibRaw color data
{ "Sigma dp0 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp1 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp2 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp3 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma sd Quattro H", 256, 0,
{ 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */
{ "Sigma sd Quattro", 2047, 0,
{ 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */
{ "Sigma SD9", 15, 4095, /* updated */
{ 13564,-2537,-751,-5465,15154,194,-67,116,10425 } },
{ "Sigma SD10", 15, 16383, /* updated */
{ 6787,-1682,575,-3091,8357,160,217,-369,12314 } },
{ "Sigma SD14", 15, 16383, /* updated */
{ 13589,-2509,-739,-5440,15104,193,-61,105,10554 } },
{ "Sigma SD15", 15, 4095, /* updated */
{ 13556,-2537,-730,-5462,15144,195,-61,106,10577 } },
// Merills + SD1
{ "Sigma SD1", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP1 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP2 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP3 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
// Sigma DP (non-Merill Versions)
{ "Sigma DP1X", 0, 4095, /* updated */
{ 13704,-2452,-857,-5413,15073,186,-89,151,9820 } },
{ "Sigma DP1", 0, 4095, /* updated */
{ 12774,-2591,-394,-5333,14676,207,15,-21,12127 } },
{ "Sigma DP", 0, 4095, /* LibRaw */
// { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } },
{ 13100,-3638,-847,6855,2369,580,2723,3218,3251 } },
{ "Sinar", 0, 0, /* DJC */
{ 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } },
{ "Sony DSC-F828", 0, 0,
{ 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } },
{ "Sony DSC-R1", 0, 0,
{ 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } },
{ "Sony DSC-V3", 0, 0,
{ 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } },
{"Sony DSC-RX100M5", -800, 0,
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Sony DSC-RX100M", -800, 0, /* used for M2/M3/M4 */
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Sony DSC-RX100", 0, 0,
{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
{ "Sony DSC-RX10",0, 0, /* same for M2/M3 */
{ 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } },
{ "Sony DSC-RX1RM2", 0, 0,
{ 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } },
{ "Sony DSC-RX1R", 0, 0, /* updated */
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
{ "Sony DSC-RX1", 0, 0,
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
{ "Sony DSLR-A100", 0, 0xfeb,
{ 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } },
{ "Sony DSLR-A290", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A2", 0, 0,
{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
{ "Sony DSLR-A300", 0, 0,
{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
{ "Sony DSLR-A330", 0, 0,
{ 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } },
{ "Sony DSLR-A350", 0, 0xffc,
{ 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } },
{ "Sony DSLR-A380", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A390", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A450", 0, 0xfeb,
{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
{ "Sony DSLR-A580", 0, 0xfeb,
{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
{ "Sony DSLR-A500", 0, 0xfeb,
{ 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } },
{ "Sony DSLR-A5", 0, 0xfeb,
{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
{ "Sony DSLR-A700", 0, 0,
{ 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } },
{ "Sony DSLR-A850", 0, 0,
{ 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } },
{ "Sony DSLR-A900", 0, 0,
{ 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } },
{ "Sony ILCA-68", 0, 0,
{ 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } },
{ "Sony ILCA-77M2", 0, 0,
{ 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } },
{ "Sony ILCA-99M2", 0, 0,
{ 6660,-1918,-471,-4613,12398,2485,-649,1433,6447 } },
{ "Sony ILCE-9", 0, 0,
{ 6389,-1703,-378,-4562,12265,2587,-670,1489,6550 } },
{ "Sony ILCE-7M2", 0, 0,
{ 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } },
{ "Sony ILCE-7SM2", 0, 0,
{ 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } },
{ "Sony ILCE-7S", 0, 0,
{ 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } },
{ "Sony ILCE-7RM2", 0, 0,
{ 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } },
{ "Sony ILCE-7R", 0, 0,
{ 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } },
{ "Sony ILCE-7", 0, 0,
{ 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } },
{ "Sony ILCE-6300", 0, 0,
{ 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } },
{ "Sony ILCE-6500", 0, 0,
{ 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } },
{ "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony MODEL-NAME", 0, 0, /* added */
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Sony NEX-5N", 0, 0,
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony NEX-5R", 0, 0,
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-5T", 0, 0,
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-3N", 0, 0,
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-3", 0, 0,
{ 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } },
{ "Sony NEX-5", 0, 0,
{ 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } },
{ "Sony NEX-6", 0, 0,
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-7", 0, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Sony NEX-VG30", 0, 0, /* added */
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-VG900", 0, 0, /* added */
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
{ "Sony NEX", 0, 0, /* NEX-C3, NEX-F3, NEX-VG20 */
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony SLT-A33", 0, 0,
{ 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } },
{ "Sony SLT-A35", 0, 0,
{ 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } },
{ "Sony SLT-A37", 0, 0,
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony SLT-A55", 0, 0,
{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
{ "Sony SLT-A57", 0, 0,
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony SLT-A58", 0, 0,
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony SLT-A65", 0, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Sony SLT-A77", 0, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Sony SLT-A99", 0, 0,
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
};
// clang-format on
double cam_xyz[4][3];
char name[130];
int i, j;
if (colors > 4 || colors < 1)
return;
int bl4 = (cblack[0] + cblack[1] + cblack[2] + cblack[3]) / 4, bl64 = 0;
if (cblack[4] * cblack[5] > 0)
{
for (unsigned c = 0; c < 4096 && c < cblack[4] * cblack[5]; c++)
bl64 += cblack[c + 6];
bl64 /= cblack[4] * cblack[5];
}
int rblack = black + bl4 + bl64;
sprintf(name, "%s %s", t_make, t_model);
for (i = 0; i < sizeof table / sizeof *table; i++)
if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix)))
{
if (!dng_version)
{
if (table[i].t_black > 0)
{
black = (ushort)table[i].t_black;
memset(cblack, 0, sizeof(cblack));
}
else if (table[i].t_black < 0 && rblack == 0)
{
black = (ushort)(-table[i].t_black);
memset(cblack, 0, sizeof(cblack));
}
if (table[i].t_maximum)
maximum = (ushort)table[i].t_maximum;
}
if (table[i].trans[0])
{
for (raw_color = j = 0; j < 12; j++)
#ifdef LIBRAW_LIBRARY_BUILD
if (internal_only)
imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0;
else
imgdata.color.cam_xyz[0][j] =
#endif
((double *)cam_xyz)[j] = table[i].trans[j] / 10000.0;
#ifdef LIBRAW_LIBRARY_BUILD
if (!internal_only)
#endif
cam_xyz_coeff(rgb_cam, cam_xyz);
}
break;
}
}
void CLASS simple_coeff(int index)
{
static const float table[][12] = {/* index 0 -- all Foveon cameras */
{1.4032, -0.2231, -0.1016, -0.5263, 1.4816, 0.017, -0.0112, 0.0183, 0.9113},
/* index 1 -- Kodak DC20 and DC25 */
{2.25, 0.75, -1.75, -0.25, -0.25, 0.75, 0.75, -0.25, -0.25, -1.75, 0.75, 2.25},
/* index 2 -- Logitech Fotoman Pixtura */
{1.893, -0.418, -0.476, -0.495, 1.773, -0.278, -1.017, -0.655, 2.672},
/* index 3 -- Nikon E880, E900, and E990 */
{-1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680,
-1.204965, 1.082304, 2.941367, -1.818705}};
int i, c;
for (raw_color = i = 0; i < 3; i++)
FORCC rgb_cam[i][c] = table[index][i * colors + c];
}
short CLASS guess_byte_order(int words)
{
uchar test[4][2];
int t = 2, msb;
double diff, sum[2] = {0, 0};
fread(test[0], 2, 2, ifp);
for (words -= 2; words--;)
{
fread(test[t], 2, 1, ifp);
for (msb = 0; msb < 2; msb++)
{
diff = (test[t ^ 2][msb] << 8 | test[t ^ 2][!msb]) - (test[t][msb] << 8 | test[t][!msb]);
sum[msb] += diff * diff;
}
t = (t + 1) & 3;
}
return sum[0] < sum[1] ? 0x4d4d : 0x4949;
}
float CLASS find_green(int bps, int bite, int off0, int off1)
{
UINT64 bitbuf = 0;
int vbits, col, i, c;
ushort img[2][2064];
double sum[] = {0, 0};
FORC(2)
{
fseek(ifp, c ? off1 : off0, SEEK_SET);
for (vbits = col = 0; col < width; col++)
{
for (vbits -= bps; vbits < 0; vbits += bite)
{
bitbuf <<= bite;
for (i = 0; i < bite; i += 8)
bitbuf |= (unsigned)(fgetc(ifp) << i);
}
img[c][col] = bitbuf << (64 - bps - vbits) >> (64 - bps);
}
}
FORC(width - 1)
{
sum[c & 1] += ABS(img[0][c] - img[1][c + 1]);
sum[~c & 1] += ABS(img[1][c] - img[0][c + 1]);
}
return 100 * log(sum[0] / sum[1]);
}
#ifdef LIBRAW_LIBRARY_BUILD
static void remove_trailing_spaces(char *string, size_t len)
{
if (len < 1)
return; // not needed, b/c sizeof of make/model is 64
string[len - 1] = 0;
if (len < 3)
return; // also not needed
len = strnlen(string, len - 1);
for (int i = len - 1; i >= 0; i--)
{
if (isspace(string[i]))
string[i] = 0;
else
break;
}
}
void CLASS initdata()
{
tiff_flip = flip = filters = UINT_MAX; /* unknown */
raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
maximum = height = width = top_margin = left_margin = 0;
cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
iso_speed = shutter = aperture = focal_len = unique_id = 0;
tiff_nifds = 0;
memset(tiff_ifd, 0, sizeof tiff_ifd);
for (int i = 0; i < LIBRAW_IFD_MAXCOUNT; i++)
{
tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff;
for (int c = 0; c < 4; c++)
tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f;
}
for (int i = 0; i < 0x10000; i++)
curve[i] = i;
memset(gpsdata, 0, sizeof gpsdata);
memset(cblack, 0, sizeof cblack);
memset(white, 0, sizeof white);
memset(mask, 0, sizeof mask);
thumb_offset = thumb_length = thumb_width = thumb_height = 0;
load_raw = thumb_load_raw = 0;
write_thumb = &CLASS jpeg_thumb;
data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0;
kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
timestamp = shot_order = tiff_samples = black = is_foveon = 0;
mix_green = profile_length = data_error = zero_is_bad = 0;
pixel_aspect = is_raw = raw_color = 1;
tile_width = tile_length = 0;
}
#endif
/*
Identify which camera created this file, and set global variables
accordingly.
*/
void CLASS identify()
{
static const short pana[][6] = {
{3130, 1743, 4, 0, -6, 0}, {3130, 2055, 4, 0, -6, 0}, {3130, 2319, 4, 0, -6, 0},
{3170, 2103, 18, 0, -42, 20}, {3170, 2367, 18, 13, -42, -21}, {3177, 2367, 0, 0, -1, 0},
{3304, 2458, 0, 0, -1, 0}, {3330, 2463, 9, 0, -5, 0}, {3330, 2479, 9, 0, -17, 4},
{3370, 1899, 15, 0, -44, 20}, {3370, 2235, 15, 0, -44, 20}, {3370, 2511, 15, 10, -44, -21},
{3690, 2751, 3, 0, -8, -3}, {3710, 2751, 0, 0, -3, 0}, {3724, 2450, 0, 0, 0, -2},
{3770, 2487, 17, 0, -44, 19}, {3770, 2799, 17, 15, -44, -19}, {3880, 2170, 6, 0, -6, 0},
{4060, 3018, 0, 0, 0, -2}, {4290, 2391, 3, 0, -8, -1}, {4330, 2439, 17, 15, -44, -19},
{4508, 2962, 0, 0, -3, -4}, {4508, 3330, 0, 0, -3, -6},
};
static const ushort canon[][11] = {
{1944, 1416, 0, 0, 48, 0},
{2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25},
{2224, 1456, 48, 6, 0, 2},
{2376, 1728, 12, 6, 52, 2},
{2672, 1968, 12, 6, 44, 2},
{3152, 2068, 64, 12, 0, 0, 16},
{3160, 2344, 44, 12, 4, 4},
{3344, 2484, 4, 6, 52, 6},
{3516, 2328, 42, 14, 0, 0},
{3596, 2360, 74, 12, 0, 0},
{3744, 2784, 52, 12, 8, 12},
{3944, 2622, 30, 18, 6, 2},
{3948, 2622, 42, 18, 0, 2},
{3984, 2622, 76, 20, 0, 2, 14},
{4104, 3048, 48, 12, 24, 12},
{4116, 2178, 4, 2, 0, 0},
{4152, 2772, 192, 12, 0, 0},
{4160, 3124, 104, 11, 8, 65},
{4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49},
{4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49},
{4312, 2876, 22, 18, 0, 2},
{4352, 2874, 62, 18, 0, 0},
{4476, 2954, 90, 34, 0, 0},
{4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49},
{4480, 3366, 80, 50, 0, 0},
{4496, 3366, 80, 50, 12, 0},
{4768, 3516, 96, 16, 0, 0, 0, 16},
{4832, 3204, 62, 26, 0, 0},
{4832, 3228, 62, 51, 0, 0},
{5108, 3349, 98, 13, 0, 0},
{5120, 3318, 142, 45, 62, 0},
{5280, 3528, 72, 52, 0, 0}, /* EOS M */
{5344, 3516, 142, 51, 0, 0},
{5344, 3584, 126, 100, 0, 2},
{5360, 3516, 158, 51, 0, 0},
{5568, 3708, 72, 38, 0, 0},
{5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49},
{5712, 3774, 62, 20, 10, 2},
{5792, 3804, 158, 51, 0, 0},
{5920, 3950, 122, 80, 2, 0},
{6096, 4056, 72, 34, 0, 0}, /* EOS M3 */
{6288, 4056, 266, 36, 0, 0}, /* EOS 80D */
{6384, 4224, 120, 44, 0, 0}, /* 6D II */
{6880, 4544, 136, 42, 0, 0}, /* EOS 5D4 */
{8896, 5920, 160, 64, 0, 0},
};
static const struct
{
ushort id;
char t_model[20];
} unique[] =
{
{0x001, "EOS-1D"},
{0x167, "EOS-1DS"},
{0x168, "EOS 10D"},
{0x169, "EOS-1D Mark III"},
{0x170, "EOS 300D"},
{0x174, "EOS-1D Mark II"},
{0x175, "EOS 20D"},
{0x176, "EOS 450D"},
{0x188, "EOS-1Ds Mark II"},
{0x189, "EOS 350D"},
{0x190, "EOS 40D"},
{0x213, "EOS 5D"},
{0x215, "EOS-1Ds Mark III"},
{0x218, "EOS 5D Mark II"},
{0x232, "EOS-1D Mark II N"},
{0x234, "EOS 30D"},
{0x236, "EOS 400D"},
{0x250, "EOS 7D"},
{0x252, "EOS 500D"},
{0x254, "EOS 1000D"},
{0x261, "EOS 50D"},
{0x269, "EOS-1D X"},
{0x270, "EOS 550D"},
{0x281, "EOS-1D Mark IV"},
{0x285, "EOS 5D Mark III"},
{0x286, "EOS 600D"},
{0x287, "EOS 60D"},
{0x288, "EOS 1100D"},
{0x289, "EOS 7D Mark II"},
{0x301, "EOS 650D"},
{0x302, "EOS 6D"},
{0x324, "EOS-1D C"},
{0x325, "EOS 70D"},
{0x326, "EOS 700D"},
{0x327, "EOS 1200D"},
{0x328, "EOS-1D X Mark II"},
{0x331, "EOS M"},
{0x335, "EOS M2"},
{0x374, "EOS M3"}, /* temp */
{0x384, "EOS M10"}, /* temp */
{0x394, "EOS M5"}, /* temp */
{0x346, "EOS 100D"},
{0x347, "EOS 760D"},
{0x349, "EOS 5D Mark IV"},
{0x350, "EOS 80D"},
{0x382, "EOS 5DS"},
{0x393, "EOS 750D"},
{0x401, "EOS 5DS R"},
{0x404, "EOS 1300D"},
{0x405, "EOS 800D"},
{0x406, "EOS 6D Mark II"},
{0x407, "EOS M6"},
{0x408, "EOS 77D"},
{0x417, "EOS 200D"},
},
sonique[] = {
{0x002, "DSC-R1"}, {0x100, "DSLR-A100"}, {0x101, "DSLR-A900"}, {0x102, "DSLR-A700"},
{0x103, "DSLR-A200"}, {0x104, "DSLR-A350"}, {0x105, "DSLR-A300"}, {0x106, "DSLR-A900"},
{0x107, "DSLR-A380"}, {0x108, "DSLR-A330"}, {0x109, "DSLR-A230"}, {0x10a, "DSLR-A290"},
{0x10d, "DSLR-A850"}, {0x10e, "DSLR-A850"}, {0x111, "DSLR-A550"}, {0x112, "DSLR-A500"},
{0x113, "DSLR-A450"}, {0x116, "NEX-5"}, {0x117, "NEX-3"}, {0x118, "SLT-A33"},
{0x119, "SLT-A55V"}, {0x11a, "DSLR-A560"}, {0x11b, "DSLR-A580"}, {0x11c, "NEX-C3"},
{0x11d, "SLT-A35"}, {0x11e, "SLT-A65V"}, {0x11f, "SLT-A77V"}, {0x120, "NEX-5N"},
{0x121, "NEX-7"}, {0x122, "NEX-VG20E"}, {0x123, "SLT-A37"}, {0x124, "SLT-A57"},
{0x125, "NEX-F3"}, {0x126, "SLT-A99V"}, {0x127, "NEX-6"}, {0x128, "NEX-5R"},
{0x129, "DSC-RX100"}, {0x12a, "DSC-RX1"}, {0x12b, "NEX-VG900"}, {0x12c, "NEX-VG30E"},
{0x12e, "ILCE-3000"}, {0x12f, "SLT-A58"}, {0x131, "NEX-3N"}, {0x132, "ILCE-7"},
{0x133, "NEX-5T"}, {0x134, "DSC-RX100M2"}, {0x135, "DSC-RX10"}, {0x136, "DSC-RX1R"},
{0x137, "ILCE-7R"}, {0x138, "ILCE-6000"}, {0x139, "ILCE-5000"}, {0x13d, "DSC-RX100M3"},
{0x13e, "ILCE-7S"}, {0x13f, "ILCA-77M2"}, {0x153, "ILCE-5100"}, {0x154, "ILCE-7M2"},
{0x155, "DSC-RX100M4"}, {0x156, "DSC-RX10M2"}, {0x158, "DSC-RX1RM2"}, {0x15a, "ILCE-QX1"},
{0x15b, "ILCE-7RM2"}, {0x15e, "ILCE-7SM2"}, {0x161, "ILCA-68"}, {0x162, "ILCA-99M2"},
{0x163, "DSC-RX10M3"}, {0x164, "DSC-RX100M5"}, {0x165, "ILCE-6300"}, {0x166, "ILCE-9"},
{0x168, "ILCE-6500"},
};
#ifdef LIBRAW_LIBRARY_BUILD
static const libraw_custom_camera_t const_table[]
#else
static const struct
{
unsigned fsize;
ushort rw, rh;
uchar lm, tm, rm, bm, lf, cf, max, flags;
char t_make[10], t_model[20];
ushort offset;
} table[]
#endif
= {
{786432, 1024, 768, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-080C"},
{1447680, 1392, 1040, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-145C"},
{1920000, 1600, 1200, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-201C"},
{5067304, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C"},
{5067316, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C", 12},
{10134608, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C"},
{10134620, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C", 12},
{16157136, 3272, 2469, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-810C"},
{15980544, 3264, 2448, 0, 0, 0, 0, 8, 0x61, 0, 1, "AgfaPhoto", "DC-833m"},
{9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Alcatel", "5035D"},
{31850496, 4608, 3456, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 4:3"},
{23887872, 4608, 2592, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 16:9"},
{32257024, 4624, 3488, 8, 2, 16, 2, 0, 0x94, 0, 0, "GITUP", "GIT2P 4:3"},
// Android Raw dumps id start
// File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb
{1540857, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "Samsung", "S3"},
{2658304, 1212, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontMipi"},
{2842624, 1296, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontQCOM"},
{2969600, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wMipi"},
{3170304, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wQCOM"},
{3763584, 1584, 1184, 0, 0, 0, 0, 96, 0x61, 0, 0, "I_Mobile", "I_StyleQ6"},
{5107712, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel1"},
{5382640, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel2"},
{5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{5364240, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"},
{6299648, 2592, 1944, 0, 0, 0, 0, 1, 0x16, 0, 0, "OmniVisi", "OV5648"},
{6721536, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "OmniVisi", "OV56482"},
{6746112, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "OneSV"},
{9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "5mp"},
{9830400, 2560, 1920, 0, 0, 0, 0, 96, 0x61, 0, 0, "NGM", "ForwardArt"},
{10186752, 3264, 2448, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX219-mipi 8mp"},
{10223360, 2608, 1944, 0, 0, 0, 0, 96, 0x16, 0, 0, "Sony", "IMX"},
{10782464, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "MyTouch4GSlide"},
{10788864, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "Xperia", "L"},
{15967488, 3264, 2446, 0, 0, 0, 0, 96, 0x16, 0, 0, "OmniVison", "OV8850"},
{16224256, 4208, 3082, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3MipiL"},
{16424960, 4208, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "IMX135", "MipiL"},
{17326080, 4164, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3LQCom"},
{17522688, 4212, 3120, 0, 0, 0, 0, 0, 0x16, 0, 0, "Sony", "IMX135-QCOM"},
{19906560, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7mipi"},
{19976192, 5312, 2988, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G4"},
{20389888, 4632, 3480, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "RedmiNote3Pro"},
{20500480, 4656, 3496, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX298-mipi 16mp"},
{21233664, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7qcom"},
{26023936, 4192, 3104, 0, 0, 0, 0, 96, 0x94, 0, 0, "THL", "5000"},
{26257920, 4208, 3120, 0, 0, 0, 0, 96, 0x94, 0, 0, "Sony", "IMX214"},
{26357760, 4224, 3120, 0, 0, 0, 0, 96, 0x61, 0, 0, "OV", "13860"},
{41312256, 5248, 3936, 0, 0, 0, 0, 96, 0x61, 0, 0, "Meizu", "MX4"},
{42923008, 5344, 4016, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "IMX230"},
// Android Raw dumps id end
{20137344, 3664, 2748, 0, 0, 0, 0, 0x40, 0x49, 0, 0, "Aptina", "MT9J003", 0xffff},
{2868726, 1384, 1036, 0, 0, 0, 0, 64, 0x49, 0, 8, "Baumer", "TXG14", 1078},
{5298000, 2400, 1766, 12, 12, 44, 2, 40, 0x94, 0, 2, "Canon", "PowerShot SD300"},
{6553440, 2664, 1968, 4, 4, 44, 4, 40, 0x94, 0, 2, "Canon", "PowerShot A460"},
{6573120, 2672, 1968, 12, 8, 44, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A610"},
{6653280, 2672, 1992, 10, 6, 42, 2, 40, 0x94, 0, 2, "Canon", "PowerShot A530"},
{7710960, 2888, 2136, 44, 8, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot S3 IS"},
{9219600, 3152, 2340, 36, 12, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A620"},
{9243240, 3152, 2346, 12, 7, 44, 13, 40, 0x49, 0, 2, "Canon", "PowerShot A470"},
{10341600, 3336, 2480, 6, 5, 32, 3, 40, 0x94, 0, 2, "Canon", "PowerShot A720 IS"},
{10383120, 3344, 2484, 12, 6, 44, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A630"},
{12945240, 3736, 2772, 12, 6, 52, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A640"},
{15636240, 4104, 3048, 48, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot A650"},
{15467760, 3720, 2772, 6, 12, 30, 0, 40, 0x94, 0, 2, "Canon", "PowerShot SX110 IS"},
{15534576, 3728, 2778, 12, 9, 44, 9, 40, 0x94, 0, 2, "Canon", "PowerShot SX120 IS"},
{18653760, 4080, 3048, 24, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot SX20 IS"},
{18763488, 4104, 3048, 10, 22, 82, 22, 8, 0x49, 0, 0, "Canon", "PowerShot D10"},
{19131120, 4168, 3060, 92, 16, 4, 1, 40, 0x94, 0, 2, "Canon", "PowerShot SX220 HS"},
{21936096, 4464, 3276, 25, 10, 73, 12, 40, 0x16, 0, 2, "Canon", "PowerShot SX30 IS"},
{24724224, 4704, 3504, 8, 16, 56, 8, 40, 0x49, 0, 2, "Canon", "PowerShot A3300 IS"},
{30858240, 5248, 3920, 8, 16, 56, 16, 40, 0x94, 0, 2, "Canon", "IXUS 160"},
{1976352, 1632, 1211, 0, 2, 0, 1, 0, 0x94, 0, 1, "Casio", "QV-2000UX"},
{3217760, 2080, 1547, 0, 0, 10, 1, 0, 0x94, 0, 1, "Casio", "QV-3*00EX"},
{6218368, 2585, 1924, 0, 0, 9, 0, 0, 0x94, 0, 1, "Casio", "QV-5700"},
{7816704, 2867, 2181, 0, 0, 34, 36, 0, 0x16, 0, 1, "Casio", "EX-Z60"},
{2937856, 1621, 1208, 0, 0, 1, 0, 0, 0x94, 7, 13, "Casio", "EX-S20"},
{4948608, 2090, 1578, 0, 0, 32, 34, 0, 0x94, 7, 1, "Casio", "EX-S100"},
{6054400, 2346, 1720, 2, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "QV-R41"},
{7426656, 2568, 1928, 0, 0, 0, 0, 0, 0x94, 0, 1, "Casio", "EX-P505"},
{7530816, 2602, 1929, 0, 0, 22, 0, 0, 0x94, 7, 1, "Casio", "QV-R51"},
{7542528, 2602, 1932, 0, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "EX-Z50"},
{7562048, 2602, 1937, 0, 0, 25, 0, 0, 0x16, 7, 1, "Casio", "EX-Z500"},
{7753344, 2602, 1986, 0, 0, 32, 26, 0, 0x94, 7, 1, "Casio", "EX-Z55"},
{9313536, 2858, 2172, 0, 0, 14, 30, 0, 0x94, 7, 1, "Casio", "EX-P600"},
{10834368, 3114, 2319, 0, 0, 27, 0, 0, 0x94, 0, 1, "Casio", "EX-Z750"},
{10843712, 3114, 2321, 0, 0, 25, 0, 0, 0x94, 0, 1, "Casio", "EX-Z75"},
{10979200, 3114, 2350, 0, 0, 32, 32, 0, 0x94, 7, 1, "Casio", "EX-P700"},
{12310144, 3285, 2498, 0, 0, 6, 30, 0, 0x94, 0, 1, "Casio", "EX-Z850"},
{12489984, 3328, 2502, 0, 0, 47, 35, 0, 0x94, 0, 1, "Casio", "EX-Z8"},
{15499264, 3754, 2752, 0, 0, 82, 0, 0, 0x94, 0, 1, "Casio", "EX-Z1050"},
{18702336, 4096, 3044, 0, 0, 24, 0, 80, 0x94, 7, 1, "Casio", "EX-ZR100"},
{7684000, 2260, 1700, 0, 0, 0, 0, 13, 0x94, 0, 1, "Casio", "QV-4000"},
{787456, 1024, 769, 0, 1, 0, 0, 0, 0x49, 0, 0, "Creative", "PC-CAM 600"},
{28829184, 4384, 3288, 0, 0, 0, 0, 36, 0x61, 0, 0, "DJI"},
{15151104, 4608, 3288, 0, 0, 0, 0, 0, 0x94, 0, 0, "Matrix"},
{3840000, 1600, 1200, 0, 0, 0, 0, 65, 0x49, 0, 0, "Foculus", "531C"},
{307200, 640, 480, 0, 0, 0, 0, 0, 0x94, 0, 0, "Generic"},
{62464, 256, 244, 1, 1, 6, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"},
{124928, 512, 244, 1, 1, 10, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"},
{1652736, 1536, 1076, 0, 52, 0, 0, 0, 0x61, 0, 0, "Kodak", "DCS200"},
{4159302, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330"},
{4162462, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330", 3160},
{2247168, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"},
{3370752, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"},
{6163328, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603"},
{6166488, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603", 3160},
{460800, 640, 480, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"},
{9116448, 2848, 2134, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"},
{12241200, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP"},
{12272756, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP", 31556},
{18000000, 4000, 3000, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "12MP"},
{614400, 640, 480, 0, 3, 0, 0, 64, 0x94, 0, 0, "Kodak", "KAI-0340"},
{15360000, 3200, 2400, 0, 0, 0, 0, 96, 0x16, 0, 0, "Lenovo", "A820"},
{3884928, 1608, 1207, 0, 0, 0, 0, 96, 0x16, 0, 0, "Micron", "2010", 3212},
{1138688, 1534, 986, 0, 0, 0, 0, 0, 0x61, 0, 0, "Minolta", "RD175", 513},
{1581060, 1305, 969, 0, 0, 18, 6, 6, 0x1e, 4, 1, "Nikon", "E900"},
{2465792, 1638, 1204, 0, 0, 22, 1, 6, 0x4b, 5, 1, "Nikon", "E950"},
{2940928, 1616, 1213, 0, 0, 0, 7, 30, 0x94, 0, 1, "Nikon", "E2100"},
{4771840, 2064, 1541, 0, 0, 0, 1, 6, 0xe1, 0, 1, "Nikon", "E990"},
{4775936, 2064, 1542, 0, 0, 0, 0, 30, 0x94, 0, 1, "Nikon", "E3700"},
{5865472, 2288, 1709, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E4500"},
{5869568, 2288, 1710, 0, 0, 0, 0, 6, 0x16, 0, 1, "Nikon", "E4300"},
{7438336, 2576, 1925, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E5000"},
{8998912, 2832, 2118, 0, 0, 0, 0, 30, 0x94, 7, 1, "Nikon", "COOLPIX S6"},
{5939200, 2304, 1718, 0, 0, 0, 0, 30, 0x16, 0, 0, "Olympus", "C770UZ"},
{3178560, 2064, 1540, 0, 0, 0, 0, 0, 0x94, 0, 1, "Pentax", "Optio S"},
{4841984, 2090, 1544, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S"},
{6114240, 2346, 1737, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S4"},
{10702848, 3072, 2322, 0, 0, 0, 21, 30, 0x94, 0, 1, "Pentax", "Optio 750Z"},
{4147200, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD"},
{4151666, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD", 8},
{13248000, 2208, 3000, 0, 0, 0, 0, 13, 0x61, 0, 0, "Pixelink", "A782"},
{6291456, 2048, 1536, 0, 0, 0, 0, 96, 0x61, 0, 0, "RoverShot", "3320AF"},
{311696, 644, 484, 0, 0, 0, 0, 0, 0x16, 0, 8, "ST Micro", "STV680 VGA"},
{16098048, 3288, 2448, 0, 0, 24, 0, 9, 0x94, 0, 1, "Samsung", "S85"},
{16215552, 3312, 2448, 0, 0, 48, 0, 9, 0x94, 0, 1, "Samsung", "S85"},
{20487168, 3648, 2808, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"},
{24000000, 4000, 3000, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"},
{12582980, 3072, 2048, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{33292868, 4080, 4080, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{44390468, 4080, 5440, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68},
{1409024, 1376, 1024, 0, 0, 1, 0, 0, 0x49, 0, 0, "Sony", "XCD-SX910CR"},
{2818048, 1376, 1024, 0, 0, 1, 0, 97, 0x49, 0, 0, "Sony", "XCD-SX910CR"},
};
#ifdef LIBRAW_LIBRARY_BUILD
libraw_custom_camera_t table[64 + sizeof(const_table) / sizeof(const_table[0])];
#endif
static const char *corp[] = {"AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta",
"Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus",
"Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony"};
#ifdef LIBRAW_LIBRARY_BUILD
char head[64], *cp;
#else
char head[32], *cp;
#endif
int hlen, flen, fsize, zero_fsize = 1, i, c;
struct jhead jh;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned camera_count = parse_custom_cameras(64, table, imgdata.params.custom_camera_strings);
for (int q = 0; q < sizeof(const_table) / sizeof(const_table[0]); q++)
memmove(&table[q + camera_count], &const_table[q], sizeof(const_table[0]));
camera_count += sizeof(const_table) / sizeof(const_table[0]);
#endif
tiff_flip = flip = filters = UINT_MAX; /* unknown */
raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
maximum = height = width = top_margin = left_margin = 0;
cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
iso_speed = shutter = aperture = focal_len = unique_id = 0;
tiff_nifds = 0;
memset(tiff_ifd, 0, sizeof tiff_ifd);
#ifdef LIBRAW_LIBRARY_BUILD
for (i = 0; i < LIBRAW_IFD_MAXCOUNT; i++)
{
tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff;
for (int c = 0; c < 4; c++)
tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f;
}
#endif
memset(gpsdata, 0, sizeof gpsdata);
memset(cblack, 0, sizeof cblack);
memset(white, 0, sizeof white);
memset(mask, 0, sizeof mask);
thumb_offset = thumb_length = thumb_width = thumb_height = 0;
load_raw = thumb_load_raw = 0;
write_thumb = &CLASS jpeg_thumb;
data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0;
kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
timestamp = shot_order = tiff_samples = black = is_foveon = 0;
mix_green = profile_length = data_error = zero_is_bad = 0;
pixel_aspect = is_raw = raw_color = 1;
tile_width = tile_length = 0;
for (i = 0; i < 4; i++)
{
cam_mul[i] = i == 1;
pre_mul[i] = i < 3;
FORC3 cmatrix[c][i] = 0;
FORC3 rgb_cam[c][i] = c == i;
}
colors = 3;
for (i = 0; i < 0x10000; i++)
curve[i] = i;
order = get2();
hlen = get4();
fseek(ifp, 0, SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
fread(head, 1, 64, ifp);
libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0;
#else
fread(head, 1, 32, ifp);
#endif
fseek(ifp, 0, SEEK_END);
flen = fsize = ftell(ifp);
if ((cp = (char *)memmem(head, 32, (char *)"MMMM", 4)) || (cp = (char *)memmem(head, 32, (char *)"IIII", 4)))
{
parse_phase_one(cp - head);
if (cp - head && parse_tiff(0))
apply_tiff();
}
else if (order == 0x4949 || order == 0x4d4d)
{
if (!memcmp(head + 6, "HEAPCCDR", 8))
{
data_offset = hlen;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
#endif
parse_ciff(hlen, flen - hlen, 0);
load_raw = &CLASS canon_load_raw;
}
else if (parse_tiff(0))
apply_tiff();
}
else if (!memcmp(head, "\xff\xd8\xff\xe1", 4) && !memcmp(head + 6, "Exif", 4))
{
fseek(ifp, 4, SEEK_SET);
data_offset = 4 + get2();
fseek(ifp, data_offset, SEEK_SET);
if (fgetc(ifp) != 0xff)
parse_tiff(12);
thumb_offset = 0;
}
else if (!memcmp(head + 25, "ARECOYK", 7))
{
strcpy(make, "Contax");
strcpy(model, "N Digital");
fseek(ifp, 33, SEEK_SET);
get_timestamp(1);
fseek(ifp, 52, SEEK_SET);
switch (get4())
{
case 7:
iso_speed = 25;
break;
case 8:
iso_speed = 32;
break;
case 9:
iso_speed = 40;
break;
case 10:
iso_speed = 50;
break;
case 11:
iso_speed = 64;
break;
case 12:
iso_speed = 80;
break;
case 13:
iso_speed = 100;
break;
case 14:
iso_speed = 125;
break;
case 15:
iso_speed = 160;
break;
case 16:
iso_speed = 200;
break;
case 17:
iso_speed = 250;
break;
case 18:
iso_speed = 320;
break;
case 19:
iso_speed = 400;
break;
}
shutter = powf64(2.0f, (((float)get4()) / 8.0f)) / 16000.0f;
FORC4 cam_mul[c ^ (c >> 1)] = get4();
fseek(ifp, 88, SEEK_SET);
aperture = powf64(2.0f, ((float)get4()) / 16.0f);
fseek(ifp, 112, SEEK_SET);
focal_len = get4();
#ifdef LIBRAW_LIBRARY_BUILD
fseek(ifp, 104, SEEK_SET);
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, ((float)get4()) / 16.0f);
fseek(ifp, 124, SEEK_SET);
stmread(imgdata.lens.makernotes.Lens, 32, ifp);
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N;
#endif
}
else if (!strcmp(head, "PXN"))
{
strcpy(make, "Logitech");
strcpy(model, "Fotoman Pixtura");
}
else if (!strcmp(head, "qktk"))
{
strcpy(make, "Apple");
strcpy(model, "QuickTake 100");
load_raw = &CLASS quicktake_100_load_raw;
}
else if (!strcmp(head, "qktn"))
{
strcpy(make, "Apple");
strcpy(model, "QuickTake 150");
load_raw = &CLASS kodak_radc_load_raw;
}
else if (!memcmp(head, "FUJIFILM", 8))
{
#ifdef LIBRAW_LIBRARY_BUILD
strcpy(model, head + 0x1c);
memcpy(model2, head + 0x3c, 4);
model2[4] = 0;
#endif
fseek(ifp, 84, SEEK_SET);
thumb_offset = get4();
thumb_length = get4();
fseek(ifp, 92, SEEK_SET);
parse_fuji(get4());
if (thumb_offset > 120)
{
fseek(ifp, 120, SEEK_SET);
is_raw += (i = get4()) ? 1 : 0;
if (is_raw == 2 && shot_select)
parse_fuji(i);
}
load_raw = &CLASS unpacked_load_raw;
fseek(ifp, 100 + 28 * (shot_select > 0), SEEK_SET);
parse_tiff(data_offset = get4());
parse_tiff(thumb_offset + 12);
apply_tiff();
}
else if (!memcmp(head, "RIFF", 4))
{
fseek(ifp, 0, SEEK_SET);
parse_riff();
}
else if (!memcmp(head + 4, "ftypqt ", 9))
{
fseek(ifp, 0, SEEK_SET);
parse_qt(fsize);
is_raw = 0;
}
else if (!memcmp(head, "\0\001\0\001\0@", 6))
{
fseek(ifp, 6, SEEK_SET);
fread(make, 1, 8, ifp);
fread(model, 1, 8, ifp);
fread(model2, 1, 16, ifp);
data_offset = get2();
get2();
raw_width = get2();
raw_height = get2();
load_raw = &CLASS nokia_load_raw;
filters = 0x61616161;
}
else if (!memcmp(head, "NOKIARAW", 8))
{
strcpy(make, "NOKIA");
order = 0x4949;
fseek(ifp, 300, SEEK_SET);
data_offset = get4();
i = get4();
width = get2();
height = get2();
switch (tiff_bps = i * 8 / (width * height))
{
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 10:
load_raw = &CLASS nokia_load_raw;
}
raw_height = height + (top_margin = i / (width * tiff_bps / 8) - height);
mask[0][3] = 1;
filters = 0x61616161;
}
else if (!memcmp(head, "ARRI", 4))
{
order = 0x4949;
fseek(ifp, 20, SEEK_SET);
width = get4();
height = get4();
strcpy(make, "ARRI");
fseek(ifp, 668, SEEK_SET);
fread(model, 1, 64, ifp);
data_offset = 4096;
load_raw = &CLASS packed_load_raw;
load_flags = 88;
filters = 0x61616161;
}
else if (!memcmp(head, "XPDS", 4))
{
order = 0x4949;
fseek(ifp, 0x800, SEEK_SET);
fread(make, 1, 41, ifp);
raw_height = get2();
raw_width = get2();
fseek(ifp, 56, SEEK_CUR);
fread(model, 1, 30, ifp);
data_offset = 0x10000;
load_raw = &CLASS canon_rmf_load_raw;
gamma_curve(0, 12.25, 1, 1023);
}
else if (!memcmp(head + 4, "RED1", 4))
{
strcpy(make, "Red");
strcpy(model, "One");
parse_redcine();
load_raw = &CLASS redcine_load_raw;
gamma_curve(1 / 2.4, 12.92, 1, 4095);
filters = 0x49494949;
}
else if (!memcmp(head, "DSC-Image", 9))
parse_rollei();
else if (!memcmp(head, "PWAD", 4))
parse_sinar_ia();
else if (!memcmp(head, "\0MRM", 4))
parse_minolta(0);
else if (!memcmp(head, "FOVb", 4))
{
#ifdef LIBRAW_LIBRARY_BUILD
#ifdef LIBRAW_DEMOSAIC_PACK_GPL2
if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F))
parse_foveon();
else
#endif
parse_x3f();
#else
#ifdef LIBRAW_DEMOSAIC_PACK_GPL2
parse_foveon();
#endif
#endif
}
else if (!memcmp(head, "CI", 2))
parse_cine();
if (make[0] == 0)
#ifdef LIBRAW_LIBRARY_BUILD
for (zero_fsize = i = 0; i < camera_count; i++)
#else
for (zero_fsize = i = 0; i < sizeof table / sizeof *table; i++)
#endif
if (fsize == table[i].fsize)
{
strcpy(make, table[i].t_make);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(make, "Canon", 5))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
#endif
strcpy(model, table[i].t_model);
flip = table[i].flags >> 2;
zero_is_bad = table[i].flags & 2;
if (table[i].flags & 1)
parse_external_jpeg();
data_offset = table[i].offset == 0xffff ? 0 : table[i].offset;
raw_width = table[i].rw;
raw_height = table[i].rh;
left_margin = table[i].lm;
top_margin = table[i].tm;
width = raw_width - left_margin - table[i].rm;
height = raw_height - top_margin - table[i].bm;
filters = 0x1010101 * table[i].cf;
colors = 4 - !((filters & filters >> 1) & 0x5555);
load_flags = table[i].lf;
switch (tiff_bps = (fsize - data_offset) * 8 / (raw_width * raw_height))
{
case 6:
load_raw = &CLASS minolta_rd175_load_raw;
break;
case 8:
load_raw = &CLASS eight_bit_load_raw;
break;
case 10:
if ((fsize - data_offset) / raw_height * 3 >= raw_width * 4)
{
load_raw = &CLASS android_loose_load_raw;
break;
}
else if (load_flags & 1)
{
load_raw = &CLASS android_tight_load_raw;
break;
}
case 12:
load_flags |= 128;
load_raw = &CLASS packed_load_raw;
break;
case 16:
order = 0x4949 | 0x404 * (load_flags & 1);
tiff_bps -= load_flags >> 4;
tiff_bps -= load_flags = load_flags >> 1 & 7;
load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw;
}
maximum = (1 << tiff_bps) - (1 << table[i].max);
}
if (zero_fsize)
fsize = 0;
if (make[0] == 0)
parse_smal(0, flen);
if (make[0] == 0)
{
parse_jpeg(0);
fseek(ifp, 0, SEEK_END);
int sz = ftell(ifp);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(model, "RP_imx219", 9) && sz >= 0x9cb600 && !fseek(ifp, -0x9cb600, SEEK_END) &&
fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4))
{
strcpy(make, "Broadcom");
strcpy(model, "RPi IMX219");
if (raw_height > raw_width)
flip = 5;
data_offset = ftell(ifp) + 0x8000 - 0x20;
parse_broadcom();
black = 66;
maximum = 0x3ff;
load_raw = &CLASS broadcom_load_raw;
thumb_offset = 0;
thumb_length = sz - 0x9cb600 - 1;
}
else if (!(strncmp(model, "ov5647", 6) && strncmp(model, "RP_OV5647", 9)) && sz >= 0x61b800 &&
!fseek(ifp, -0x61b800, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4))
{
strcpy(make, "Broadcom");
if (!strncmp(model, "ov5647", 6))
strcpy(model, "RPi OV5647 v.1");
else
strcpy(model, "RPi OV5647 v.2");
if (raw_height > raw_width)
flip = 5;
data_offset = ftell(ifp) + 0x8000 - 0x20;
parse_broadcom();
black = 16;
maximum = 0x3ff;
load_raw = &CLASS broadcom_load_raw;
thumb_offset = 0;
thumb_length = sz - 0x61b800 - 1;
#else
if (!(strncmp(model, "ov", 2) && strncmp(model, "RP_OV", 5)) && sz >= 6404096 && !fseek(ifp, -6404096, SEEK_END) &&
fread(head, 1, 32, ifp) && !strcmp(head, "BRCMn"))
{
strcpy(make, "OmniVision");
data_offset = ftell(ifp) + 0x8000 - 32;
width = raw_width;
raw_width = 2611;
load_raw = &CLASS nokia_load_raw;
filters = 0x16161616;
#endif
}
else
is_raw = 0;
}
#ifdef LIBRAW_LIBRARY_BUILD
// make sure strings are terminated
desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0;
#endif
for (i = 0; i < sizeof corp / sizeof *corp; i++)
if (strcasestr(make, corp[i])) /* Simplify company names */
strcpy(make, corp[i]);
if ((!strncmp(make, "Kodak", 5) || !strncmp(make, "Leica", 5)) &&
((cp = strcasestr(model, " DIGITAL CAMERA")) || (cp = strstr(model, "FILE VERSION"))))
*cp = 0;
if (!strncasecmp(model, "PENTAX", 6))
strcpy(make, "Pentax");
#ifdef LIBRAW_LIBRARY_BUILD
remove_trailing_spaces(make, sizeof(make));
remove_trailing_spaces(model, sizeof(model));
#else
cp = make + strlen(make); /* Remove trailing spaces */
while (*--cp == ' ')
*cp = 0;
cp = model + strlen(model);
while (*--cp == ' ')
*cp = 0;
#endif
i = strbuflen(make); /* Remove make from model */
if (!strncasecmp(model, make, i) && model[i++] == ' ')
memmove(model, model + i, 64 - i);
if (!strncmp(model, "FinePix ", 8))
strcpy(model, model + 8);
if (!strncmp(model, "Digital Camera ", 15))
strcpy(model, model + 15);
desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0;
if (!is_raw)
goto notraw;
if (!height)
height = raw_height;
if (!width)
width = raw_width;
if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */
{
height = 2616;
width = 3896;
}
if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */
{
height = 3124;
width = 4688;
filters = 0x16161616;
}
if (width == 4352 && (!strcmp(model, "K-r") || !strcmp(model, "K-x")))
{
width = 4309;
filters = 0x16161616;
}
if (width >= 4960 && !strncmp(model, "K-5", 3))
{
left_margin = 10;
width = 4950;
filters = 0x16161616;
}
if (width == 6080 && !strcmp(model, "K-70"))
{
height = 4016;
top_margin = 32;
width = 6020;
left_margin = 60;
}
if (width == 4736 && !strcmp(model, "K-7"))
{
height = 3122;
width = 4684;
filters = 0x16161616;
top_margin = 2;
}
if (width == 6080 && !strcmp(model, "K-3 II")) /* moved back */
{
left_margin = 4;
width = 6040;
}
if (width == 6112 && !strcmp(model, "KP"))
{
/* From DNG, maybe too strict */
left_margin = 54;
top_margin = 28;
width = 6028;
height = raw_height - top_margin;
}
if (width == 6080 && !strcmp(model, "K-3"))
{
left_margin = 4;
width = 6040;
}
if (width == 7424 && !strcmp(model, "645D"))
{
height = 5502;
width = 7328;
filters = 0x61616161;
top_margin = 29;
left_margin = 48;
}
if (height == 3014 && width == 4096) /* Ricoh GX200 */
width = 4014;
if (dng_version)
{
if (filters == UINT_MAX)
filters = 0;
if (filters)
is_raw *= tiff_samples;
else
colors = tiff_samples;
switch (tiff_compress)
{
case 0: /* Compression not set, assuming uncompressed */
case 1:
load_raw = &CLASS packed_dng_load_raw;
break;
case 7:
load_raw = &CLASS lossless_dng_load_raw;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 8:
load_raw = &CLASS deflate_dng_load_raw;
break;
#endif
case 34892:
load_raw = &CLASS lossy_dng_load_raw;
break;
default:
load_raw = 0;
}
if (!strncmp(make, "Canon", 5) && unique_id)
{
for (i = 0; i < sizeof unique / sizeof *unique; i++)
if (unique_id == 0x80000000 + unique[i].id)
{
strcpy(model, unique[i].t_model);
break;
}
}
if (!strncasecmp(make, "Sony", 4) && unique_id)
{
for (i = 0; i < sizeof sonique / sizeof *sonique; i++)
if (unique_id == sonique[i].id)
{
strcpy(model, sonique[i].t_model);
break;
}
}
goto dng_skip;
}
if (!strncmp(make, "Canon", 5) && !fsize && tiff_bps != 15)
{
if (!load_raw)
load_raw = &CLASS lossless_jpeg_load_raw;
for (i = 0; i < sizeof canon / sizeof *canon; i++)
if (raw_width == canon[i][0] && raw_height == canon[i][1])
{
width = raw_width - (left_margin = canon[i][2]);
height = raw_height - (top_margin = canon[i][3]);
width -= canon[i][4];
height -= canon[i][5];
mask[0][1] = canon[i][6];
mask[0][3] = -canon[i][7];
mask[1][1] = canon[i][8];
mask[1][3] = -canon[i][9];
if (canon[i][10])
filters = canon[i][10] * 0x01010101;
}
if ((unique_id | 0x20000) == 0x2720000)
{
left_margin = 8;
top_margin = 16;
}
}
if (!strncmp(make, "Canon", 5) && unique_id)
{
for (i = 0; i < sizeof unique / sizeof *unique; i++)
if (unique_id == 0x80000000 + unique[i].id)
{
adobe_coeff("Canon", unique[i].t_model);
strcpy(model, unique[i].t_model);
}
}
if (!strncasecmp(make, "Sony", 4) && unique_id)
{
for (i = 0; i < sizeof sonique / sizeof *sonique; i++)
if (unique_id == sonique[i].id)
{
adobe_coeff("Sony", sonique[i].t_model);
strcpy(model, sonique[i].t_model);
}
}
if (!strncmp(make, "Nikon", 5))
{
if (!load_raw)
load_raw = &CLASS packed_load_raw;
if (model[0] == 'E')
load_flags |= !data_offset << 2 | 2;
}
/* Set parameters based on camera name (for non-DNG files). */
if (!strcmp(model, "KAI-0340") && find_green(16, 16, 3840, 5120) < 25)
{
height = 480;
top_margin = filters = 0;
strcpy(model, "C603");
}
#ifndef LIBRAW_LIBRARY_BUILD
if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0])
black = 128 << (tiff_bps - 12);
#else
/* Always 512 for arw2_load_raw */
if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0])
black = (load_raw == &LibRaw::sony_arw2_load_raw) ? 512 : (128 << (tiff_bps - 12));
#endif
if (is_foveon)
{
if (height * 2 < width)
pixel_aspect = 0.5;
if (height > width)
pixel_aspect = 2;
filters = 0;
#ifdef LIBRAW_DEMOSAIC_PACK_GPL2
if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F))
simple_coeff(0);
#endif
}
else if (!strncmp(make, "Pentax", 6) && !strncmp(model, "K-1", 3))
{
top_margin = 18;
height = raw_height - top_margin;
if (raw_width == 7392)
{
left_margin = 6;
width = 7376;
}
}
else if (!strncmp(make, "Canon", 5) && tiff_bps == 15)
{
switch (width)
{
case 3344:
width -= 66;
case 3872:
width -= 6;
}
if (height > width)
{
SWAP(height, width);
SWAP(raw_height, raw_width);
}
if (width == 7200 && height == 3888)
{
raw_width = width = 6480;
raw_height = height = 4320;
}
filters = 0;
tiff_samples = colors = 3;
load_raw = &CLASS canon_sraw_load_raw;
}
else if (!strcmp(model, "PowerShot 600"))
{
height = 613;
width = 854;
raw_width = 896;
colors = 4;
filters = 0xe1e4e1e4;
load_raw = &CLASS canon_600_load_raw;
}
else if (!strcmp(model, "PowerShot A5") || !strcmp(model, "PowerShot A5 Zoom"))
{
height = 773;
width = 960;
raw_width = 992;
pixel_aspect = 256 / 235.0;
filters = 0x1e4e1e4e;
goto canon_a5;
}
else if (!strcmp(model, "PowerShot A50"))
{
height = 968;
width = 1290;
raw_width = 1320;
filters = 0x1b4e4b1e;
goto canon_a5;
}
else if (!strcmp(model, "PowerShot Pro70"))
{
height = 1024;
width = 1552;
filters = 0x1e4b4e1b;
canon_a5:
colors = 4;
tiff_bps = 10;
load_raw = &CLASS packed_load_raw;
load_flags = 40;
}
else if (!strcmp(model, "PowerShot Pro90 IS") || !strcmp(model, "PowerShot G1"))
{
colors = 4;
filters = 0xb4b4b4b4;
}
else if (!strcmp(model, "PowerShot A610"))
{
if (canon_s2is())
strcpy(model + 10, "S2 IS");
}
else if (!strcmp(model, "PowerShot SX220 HS"))
{
mask[1][3] = -4;
top_margin = 16;
left_margin = 92;
}
else if (!strcmp(model, "PowerShot S120"))
{
raw_width = 4192;
raw_height = 3062;
width = 4022;
height = 3016;
mask[0][0] = top_margin = 31;
mask[0][2] = top_margin + height;
left_margin = 120;
mask[0][1] = 23;
mask[0][3] = 72;
}
else if (!strcmp(model, "PowerShot G16"))
{
mask[0][0] = 0;
mask[0][2] = 80;
mask[0][1] = 0;
mask[0][3] = 16;
top_margin = 29;
left_margin = 120;
width = raw_width - left_margin - 48;
height = raw_height - top_margin - 14;
}
else if (!strcmp(model, "PowerShot SX50 HS"))
{
top_margin = 17;
}
else if (!strcmp(model, "EOS D2000C"))
{
filters = 0x61616161;
if (!black)
black = curve[200];
}
else if (!strcmp(model, "D1"))
{
cam_mul[0] *= 256 / 527.0;
cam_mul[2] *= 256 / 317.0;
}
else if (!strcmp(model, "D1X"))
{
width -= 4;
pixel_aspect = 0.5;
}
else if (!strcmp(model, "D40X") || !strcmp(model, "D60") || !strcmp(model, "D80") || !strcmp(model, "D3000"))
{
height -= 3;
width -= 4;
}
else if (!strcmp(model, "D3") || !strcmp(model, "D3S") || !strcmp(model, "D700"))
{
width -= 4;
left_margin = 2;
}
else if (!strcmp(model, "D3100"))
{
width -= 28;
left_margin = 6;
}
else if (!strcmp(model, "D5000") || !strcmp(model, "D90"))
{
width -= 42;
}
else if (!strcmp(model, "D5100") || !strcmp(model, "D7000") || !strcmp(model, "COOLPIX A"))
{
width -= 44;
}
else if (!strcmp(model, "D3200") || !strncmp(model, "D6", 2) || !strncmp(model, "D800", 4))
{
width -= 46;
}
else if (!strcmp(model, "D4") || !strcmp(model, "Df"))
{
width -= 52;
left_margin = 2;
}
else if (!strcmp(model, "D500"))
{
// Empty - to avoid width-1 below
}
else if (!strncmp(model, "D40", 3) || !strncmp(model, "D50", 3) || !strncmp(model, "D70", 3))
{
width--;
}
else if (!strcmp(model, "D100"))
{
if (load_flags)
raw_width = (width += 3) + 3;
}
else if (!strcmp(model, "D200"))
{
left_margin = 1;
width -= 4;
filters = 0x94949494;
}
else if (!strncmp(model, "D2H", 3))
{
left_margin = 6;
width -= 14;
}
else if (!strncmp(model, "D2X", 3))
{
if (width == 3264)
width -= 32;
else
width -= 8;
}
else if (!strncmp(model, "D300", 4))
{
width -= 32;
}
else if (!strncmp(make, "Nikon", 5) && raw_width == 4032)
{
if (!strcmp(model, "COOLPIX P7700"))
{
adobe_coeff("Nikon", "COOLPIX P7700");
maximum = 65504;
load_flags = 0;
}
else if (!strcmp(model, "COOLPIX P7800"))
{
adobe_coeff("Nikon", "COOLPIX P7800");
maximum = 65504;
load_flags = 0;
}
else if (!strcmp(model, "COOLPIX P340"))
load_flags = 0;
}
else if (!strncmp(model, "COOLPIX P", 9) && raw_width != 4032)
{
load_flags = 24;
filters = 0x94949494;
if (model[9] == '7' && (iso_speed >= 400 || iso_speed == 0) && !strstr(software, "V1.2"))
black = 255;
}
else if (!strncmp(model, "COOLPIX B700", 12))
{
load_flags = 24;
black = 200;
}
else if (!strncmp(model, "1 ", 2))
{
height -= 2;
}
else if (fsize == 1581060)
{
simple_coeff(3);
pre_mul[0] = 1.2085;
pre_mul[1] = 1.0943;
pre_mul[3] = 1.1103;
}
else if (fsize == 3178560)
{
cam_mul[0] *= 4;
cam_mul[2] *= 4;
}
else if (fsize == 4771840)
{
if (!timestamp && nikon_e995())
strcpy(model, "E995");
if (strcmp(model, "E995"))
{
filters = 0xb4b4b4b4;
simple_coeff(3);
pre_mul[0] = 1.196;
pre_mul[1] = 1.246;
pre_mul[2] = 1.018;
}
}
else if (fsize == 2940928)
{
if (!timestamp && !nikon_e2100())
strcpy(model, "E2500");
if (!strcmp(model, "E2500"))
{
height -= 2;
load_flags = 6;
colors = 4;
filters = 0x4b4b4b4b;
}
}
else if (fsize == 4775936)
{
if (!timestamp)
nikon_3700();
if (model[0] == 'E' && atoi(model + 1) < 3700)
filters = 0x49494949;
if (!strcmp(model, "Optio 33WR"))
{
flip = 1;
filters = 0x16161616;
}
if (make[0] == 'O')
{
i = find_green(12, 32, 1188864, 3576832);
c = find_green(12, 32, 2383920, 2387016);
if (abs(i) < abs(c))
{
SWAP(i, c);
load_flags = 24;
}
if (i < 0)
filters = 0x61616161;
}
}
else if (fsize == 5869568)
{
if (!timestamp && minolta_z2())
{
strcpy(make, "Minolta");
strcpy(model, "DiMAGE Z2");
}
load_flags = 6 + 24 * (make[0] == 'M');
}
else if (fsize == 6291456)
{
fseek(ifp, 0x300000, SEEK_SET);
if ((order = guess_byte_order(0x10000)) == 0x4d4d)
{
height -= (top_margin = 16);
width -= (left_margin = 28);
maximum = 0xf5c0;
strcpy(make, "ISG");
model[0] = 0;
}
}
else if (!strncmp(make, "Fujifilm", 8))
{
if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10"))
{
left_margin = 0;
top_margin = 0;
width = raw_width;
height = raw_height;
}
if (!strcmp(model + 7, "S2Pro"))
{
strcpy(model, "S2Pro");
height = 2144;
width = 2880;
flip = 6;
}
else if (load_raw != &CLASS packed_load_raw && strncmp(model, "X-", 2))
maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00;
top_margin = (raw_height - height) >> 2 << 1;
left_margin = (raw_width - width) >> 2 << 1;
if (width == 2848 || width == 3664)
filters = 0x16161616;
if (width == 4032 || width == 4952)
left_margin = 0;
if (width == 3328 && (width -= 66))
left_margin = 34;
if (width == 4936)
left_margin = 4;
if (width == 6032)
left_margin = 0;
if (!strcmp(model, "HS50EXR") || !strcmp(model, "F900EXR"))
{
width += 2;
left_margin = 0;
filters = 0x16161616;
}
if (!strcmp(model, "GFX 50S"))
{
left_margin = 0;
top_margin = 0;
}
if (!strcmp(model, "S5500"))
{
height -= (top_margin = 6);
}
if (fuji_layout)
raw_width *= is_raw;
if (filters == 9)
FORC(36)((char *)xtrans)[c] = xtrans_abs[(c / 6 + top_margin) % 6][(c + left_margin) % 6];
}
else if (!strcmp(model, "KD-400Z"))
{
height = 1712;
width = 2312;
raw_width = 2336;
goto konica_400z;
}
else if (!strcmp(model, "KD-510Z"))
{
goto konica_510z;
}
else if (!strncasecmp(make, "Minolta", 7))
{
if (!load_raw && (maximum = 0xfff))
load_raw = &CLASS unpacked_load_raw;
if (!strncmp(model, "DiMAGE A", 8))
{
if (!strcmp(model, "DiMAGE A200"))
filters = 0x49494949;
tiff_bps = 12;
load_raw = &CLASS packed_load_raw;
}
else if (!strncmp(model, "ALPHA", 5) || !strncmp(model, "DYNAX", 5) || !strncmp(model, "MAXXUM", 6))
{
sprintf(model + 20, "DYNAX %-10s", model + 6 + (model[0] == 'M'));
adobe_coeff(make, model + 20);
load_raw = &CLASS packed_load_raw;
}
else if (!strncmp(model, "DiMAGE G", 8))
{
if (model[8] == '4')
{
height = 1716;
width = 2304;
}
else if (model[8] == '5')
{
konica_510z:
height = 1956;
width = 2607;
raw_width = 2624;
}
else if (model[8] == '6')
{
height = 2136;
width = 2848;
}
data_offset += 14;
filters = 0x61616161;
konica_400z:
load_raw = &CLASS unpacked_load_raw;
maximum = 0x3df;
order = 0x4d4d;
}
}
else if (!strcmp(model, "*ist D"))
{
load_raw = &CLASS unpacked_load_raw;
data_error = -1;
}
else if (!strcmp(model, "*ist DS"))
{
height -= 2;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 4704)
{
height -= top_margin = 8;
width -= 2 * (left_margin = 8);
load_flags = 32;
}
else if (!strncmp(make, "Samsung", 7) && !strcmp(model, "NX3000"))
{
top_margin = 38;
left_margin = 92;
width = 5456;
height = 3634;
filters = 0x61616161;
colors = 3;
}
else if (!strncmp(make, "Samsung", 7) && raw_height == 3714)
{
height -= top_margin = 18;
left_margin = raw_width - (width = 5536);
if (raw_width != 5600)
left_margin = top_margin = 0;
filters = 0x61616161;
colors = 3;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 5632)
{
order = 0x4949;
height = 3694;
top_margin = 2;
width = 5574 - (left_margin = 32 + tiff_bps);
if (tiff_bps == 12)
load_flags = 80;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 5664)
{
height -= top_margin = 17;
left_margin = 96;
width = 5544;
filters = 0x49494949;
}
else if (!strncmp(make, "Samsung", 7) && raw_width == 6496)
{
filters = 0x61616161;
#ifdef LIBRAW_LIBRARY_BUILD
if (!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3])
#endif
black = 1 << (tiff_bps - 7);
}
else if (!strcmp(model, "EX1"))
{
order = 0x4949;
height -= 20;
top_margin = 2;
if ((width -= 6) > 3682)
{
height -= 10;
width -= 46;
top_margin = 8;
}
}
else if (!strcmp(model, "WB2000"))
{
order = 0x4949;
height -= 3;
top_margin = 2;
if ((width -= 10) > 3718)
{
height -= 28;
width -= 56;
top_margin = 8;
}
}
else if (strstr(model, "WB550"))
{
strcpy(model, "WB550");
}
else if (!strcmp(model, "EX2F"))
{
height = 3030;
width = 4040;
top_margin = 15;
left_margin = 24;
order = 0x4949;
filters = 0x49494949;
load_raw = &CLASS unpacked_load_raw;
}
else if (!strcmp(model, "STV680 VGA"))
{
black = 16;
}
else if (!strcmp(model, "N95"))
{
height = raw_height - (top_margin = 2);
}
else if (!strcmp(model, "640x480"))
{
gamma_curve(0.45, 4.5, 1, 255);
}
else if (!strncmp(make, "Hasselblad", 10))
{
if (load_raw == &CLASS lossless_jpeg_load_raw)
load_raw = &CLASS hasselblad_load_raw;
if (raw_width == 7262)
{
height = 5444;
width = 7248;
top_margin = 4;
left_margin = 7;
filters = 0x61616161;
if (!strncasecmp(model, "H3D", 3))
{
adobe_coeff("Hasselblad", "H3DII-39");
strcpy(model, "H3DII-39");
}
}
else if (raw_width == 12000) // H6D 100c
{
left_margin = 64;
width = 11608;
top_margin = 108;
height = raw_height - top_margin;
adobe_coeff("Hasselblad", "H6D-100c");
}
else if (raw_width == 7410 || raw_width == 8282)
{
height -= 84;
width -= 82;
top_margin = 4;
left_margin = 41;
filters = 0x61616161;
adobe_coeff("Hasselblad", "H4D-40");
strcpy(model, "H4D-40");
}
else if (raw_width == 8384) // X1D
{
top_margin = 96;
height -= 96;
left_margin = 48;
width -= 106;
adobe_coeff("Hasselblad", "X1D");
maximum = 0xffff;
tiff_bps = 16;
}
else if (raw_width == 9044)
{
if (black > 500)
{
top_margin = 12;
left_margin = 44;
width = 8956;
height = 6708;
memset(cblack, 0, sizeof(cblack));
adobe_coeff("Hasselblad", "H4D-60");
strcpy(model, "H4D-60");
black = 512;
}
else
{
height = 6716;
width = 8964;
top_margin = 8;
left_margin = 40;
black += load_flags = 256;
maximum = 0x8101;
strcpy(model, "H3DII-60");
}
}
else if (raw_width == 4090)
{
strcpy(model, "V96C");
height -= (top_margin = 6);
width -= (left_margin = 3) + 7;
filters = 0x61616161;
}
else if (raw_width == 8282 && raw_height == 6240)
{
if (!strncasecmp(model, "H5D", 3))
{
/* H5D 50*/
left_margin = 54;
top_margin = 16;
width = 8176;
height = 6132;
black = 256;
strcpy(model, "H5D-50");
}
else if (!strncasecmp(model, "H3D", 3))
{
black = 0;
left_margin = 54;
top_margin = 16;
width = 8176;
height = 6132;
memset(cblack, 0, sizeof(cblack));
adobe_coeff("Hasselblad", "H3D-50");
strcpy(model, "H3D-50");
}
}
else if (raw_width == 8374 && raw_height == 6304)
{
/* H5D 50c*/
left_margin = 52;
top_margin = 100;
width = 8272;
height = 6200;
black = 256;
strcpy(model, "H5D-50c");
}
if (tiff_samples > 1)
{
is_raw = tiff_samples + 1;
if (!shot_select && !half_size)
filters = 0;
}
}
else if (!strncmp(make, "Sinar", 5))
{
if (!load_raw)
load_raw = &CLASS unpacked_load_raw;
if (is_raw > 1 && !shot_select && !half_size)
filters = 0;
maximum = 0x3fff;
}
else if (!strncmp(make, "Leaf", 4))
{
maximum = 0x3fff;
fseek(ifp, data_offset, SEEK_SET);
if (ljpeg_start(&jh, 1) && jh.bits == 15)
maximum = 0x1fff;
if (tiff_samples > 1)
filters = 0;
if (tiff_samples > 1 || tile_length < raw_height)
{
load_raw = &CLASS leaf_hdr_load_raw;
raw_width = tile_width;
}
if ((width | height) == 2048)
{
if (tiff_samples == 1)
{
filters = 1;
strcpy(cdesc, "RBTG");
strcpy(model, "CatchLight");
top_margin = 8;
left_margin = 18;
height = 2032;
width = 2016;
}
else
{
strcpy(model, "DCB2");
top_margin = 10;
left_margin = 16;
height = 2028;
width = 2022;
}
}
else if (width + height == 3144 + 2060)
{
if (!model[0])
strcpy(model, "Cantare");
if (width > height)
{
top_margin = 6;
left_margin = 32;
height = 2048;
width = 3072;
filters = 0x61616161;
}
else
{
left_margin = 6;
top_margin = 32;
width = 2048;
height = 3072;
filters = 0x16161616;
}
if (!cam_mul[0] || model[0] == 'V')
filters = 0;
else
is_raw = tiff_samples;
}
else if (width == 2116)
{
strcpy(model, "Valeo 6");
height -= 2 * (top_margin = 30);
width -= 2 * (left_margin = 55);
filters = 0x49494949;
}
else if (width == 3171)
{
strcpy(model, "Valeo 6");
height -= 2 * (top_margin = 24);
width -= 2 * (left_margin = 24);
filters = 0x16161616;
}
}
else if (!strncmp(make, "Leica", 5) || !strncmp(make, "Panasonic", 9) || !strncasecmp(make, "YUNEEC", 6))
{
if (raw_width > 0 && ((flen - data_offset) / (raw_width * 8 / 7) == raw_height))
load_raw = &CLASS panasonic_load_raw;
if (!load_raw)
{
load_raw = &CLASS unpacked_load_raw;
load_flags = 4;
}
zero_is_bad = 1;
if ((height += 12) > raw_height)
height = raw_height;
for (i = 0; i < sizeof pana / sizeof *pana; i++)
if (raw_width == pana[i][0] && raw_height == pana[i][1])
{
left_margin = pana[i][2];
top_margin = pana[i][3];
width += pana[i][4];
height += pana[i][5];
}
filters = 0x01010101 * (uchar) "\x94\x61\x49\x16"[((filters - 1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3];
}
else if (!strcmp(model, "C770UZ"))
{
height = 1718;
width = 2304;
filters = 0x16161616;
load_raw = &CLASS packed_load_raw;
load_flags = 30;
}
else if (!strncmp(make, "Olympus", 7))
{
height += height & 1;
if (exif_cfa)
filters = exif_cfa;
if (width == 4100)
width -= 4;
if (width == 4080)
width -= 24;
if (width == 9280)
{
width -= 6;
height -= 6;
}
if (load_raw == &CLASS unpacked_load_raw)
load_flags = 4;
tiff_bps = 12;
if (!strcmp(model, "E-300") || !strcmp(model, "E-500"))
{
width -= 20;
if (load_raw == &CLASS unpacked_load_raw)
{
maximum = 0xfc3;
memset(cblack, 0, sizeof cblack);
}
}
else if (!strcmp(model, "STYLUS1"))
{
width -= 14;
maximum = 0xfff;
}
else if (!strcmp(model, "E-330"))
{
width -= 30;
if (load_raw == &CLASS unpacked_load_raw)
maximum = 0xf79;
}
else if (!strcmp(model, "SP550UZ"))
{
thumb_length = flen - (thumb_offset = 0xa39800);
thumb_height = 480;
thumb_width = 640;
}
else if (!strcmp(model, "TG-4"))
{
width -= 16;
}
else if (!strcmp(model, "TG-5"))
{
width -= 26;
}
}
else if (!strcmp(model, "N Digital"))
{
height = 2047;
width = 3072;
filters = 0x61616161;
data_offset = 0x1a00;
load_raw = &CLASS packed_load_raw;
}
else if (!strcmp(model, "DSC-F828"))
{
width = 3288;
left_margin = 5;
mask[1][3] = -17;
data_offset = 862144;
load_raw = &CLASS sony_load_raw;
filters = 0x9c9c9c9c;
colors = 4;
strcpy(cdesc, "RGBE");
}
else if (!strcmp(model, "DSC-V3"))
{
width = 3109;
left_margin = 59;
mask[0][1] = 9;
data_offset = 787392;
load_raw = &CLASS sony_load_raw;
}
else if (!strncmp(make, "Sony", 4) && raw_width == 3984)
{
width = 3925;
order = 0x4d4d;
}
else if (!strncmp(make, "Sony", 4) && raw_width == 4288)
{
width -= 32;
}
else if (!strcmp(make, "Sony") && raw_width == 4600)
{
if (!strcmp(model, "DSLR-A350"))
height -= 4;
black = 0;
}
else if (!strncmp(make, "Sony", 4) && raw_width == 4928)
{
if (height < 3280)
width -= 8;
}
else if (!strncmp(make, "Sony", 4) && raw_width == 5504)
{ // ILCE-3000//5000
width -= height > 3664 ? 8 : 32;
}
else if (!strncmp(make, "Sony", 4) && raw_width == 6048)
{
width -= 24;
if (strstr(model, "RX1") || strstr(model, "A99"))
width -= 6;
}
else if (!strncmp(make, "Sony", 4) && raw_width == 7392)
{
width -= 30;
}
else if (!strncmp(make, "Sony", 4) && raw_width == 8000)
{
width -= 32;
}
else if (!strcmp(model, "DSLR-A100"))
{
if (width == 3880)
{
height--;
width = ++raw_width;
}
else
{
height -= 4;
width -= 4;
order = 0x4d4d;
load_flags = 2;
}
filters = 0x61616161;
}
else if (!strcmp(model, "PIXL"))
{
height -= top_margin = 4;
width -= left_margin = 32;
gamma_curve(0, 7, 1, 255);
}
else if (!strcmp(model, "C603") || !strcmp(model, "C330") || !strcmp(model, "12MP"))
{
order = 0x4949;
if (filters && data_offset)
{
fseek(ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET);
read_shorts(curve, 256);
}
else
gamma_curve(0, 3.875, 1, 255);
load_raw = filters ? &CLASS eight_bit_load_raw
: strcmp(model, "C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw;
load_flags = tiff_bps > 16;
tiff_bps = 8;
}
else if (!strncasecmp(model, "EasyShare", 9))
{
data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000;
load_raw = &CLASS packed_load_raw;
}
else if (!strncasecmp(make, "Kodak", 5))
{
if (filters == UINT_MAX)
filters = 0x61616161;
if (!strncmp(model, "NC2000", 6) || !strncmp(model, "EOSDCS", 6) || !strncmp(model, "DCS4", 4))
{
width -= 4;
left_margin = 2;
if (model[6] == ' ')
model[6] = 0;
if (!strcmp(model, "DCS460A"))
goto bw;
}
else if (!strcmp(model, "DCS660M"))
{
black = 214;
goto bw;
}
else if (!strcmp(model, "DCS760M"))
{
bw:
colors = 1;
filters = 0;
}
if (!strcmp(model + 4, "20X"))
strcpy(cdesc, "MYCY");
if (strstr(model, "DC25"))
{
strcpy(model, "DC25");
data_offset = 15424;
}
if (!strncmp(model, "DC2", 3))
{
raw_height = 2 + (height = 242);
if (!strncmp(model, "DC290", 5))
iso_speed = 100;
if (!strncmp(model, "DC280", 5))
iso_speed = 70;
if (flen < 100000)
{
raw_width = 256;
width = 249;
pixel_aspect = (4.0 * height) / (3.0 * width);
}
else
{
raw_width = 512;
width = 501;
pixel_aspect = (493.0 * height) / (373.0 * width);
}
top_margin = left_margin = 1;
colors = 4;
filters = 0x8d8d8d8d;
simple_coeff(1);
pre_mul[1] = 1.179;
pre_mul[2] = 1.209;
pre_mul[3] = 1.036;
load_raw = &CLASS eight_bit_load_raw;
}
else if (!strcmp(model, "40"))
{
strcpy(model, "DC40");
height = 512;
width = 768;
data_offset = 1152;
load_raw = &CLASS kodak_radc_load_raw;
tiff_bps = 12;
}
else if (strstr(model, "DC50"))
{
strcpy(model, "DC50");
height = 512;
width = 768;
iso_speed = 84;
data_offset = 19712;
load_raw = &CLASS kodak_radc_load_raw;
}
else if (strstr(model, "DC120"))
{
strcpy(model, "DC120");
raw_height = height = 976;
raw_width = width = 848;
iso_speed = 160;
pixel_aspect = height / 0.75 / width;
load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw;
}
else if (!strcmp(model, "DCS200"))
{
thumb_height = 128;
thumb_width = 192;
thumb_offset = 6144;
thumb_misc = 360;
iso_speed = 140;
write_thumb = &CLASS layer_thumb;
black = 17;
}
}
else if (!strcmp(model, "Fotoman Pixtura"))
{
height = 512;
width = 768;
data_offset = 3632;
load_raw = &CLASS kodak_radc_load_raw;
filters = 0x61616161;
simple_coeff(2);
}
else if (!strncmp(model, "QuickTake", 9))
{
if (head[5])
strcpy(model + 10, "200");
fseek(ifp, 544, SEEK_SET);
height = get2();
width = get2();
data_offset = (get4(), get2()) == 30 ? 738 : 736;
if (height > width)
{
SWAP(height, width);
fseek(ifp, data_offset - 6, SEEK_SET);
flip = ~get2() & 3 ? 5 : 6;
}
filters = 0x61616161;
}
else if (!strncmp(make, "Rollei", 6) && !load_raw)
{
switch (raw_width)
{
case 1316:
height = 1030;
width = 1300;
top_margin = 1;
left_margin = 6;
break;
case 2568:
height = 1960;
width = 2560;
top_margin = 2;
left_margin = 8;
}
filters = 0x16161616;
load_raw = &CLASS rollei_load_raw;
}
else if (!strcmp(model, "GRAS-50S5C"))
{
height = 2048;
width = 2440;
load_raw = &CLASS unpacked_load_raw;
data_offset = 0;
filters = 0x49494949;
order = 0x4949;
maximum = 0xfffC;
}
else if (!strcmp(model, "BB-500CL"))
{
height = 2058;
width = 2448;
load_raw = &CLASS unpacked_load_raw;
data_offset = 0;
filters = 0x94949494;
order = 0x4949;
maximum = 0x3fff;
}
else if (!strcmp(model, "BB-500GE"))
{
height = 2058;
width = 2456;
load_raw = &CLASS unpacked_load_raw;
data_offset = 0;
filters = 0x94949494;
order = 0x4949;
maximum = 0x3fff;
}
else if (!strcmp(model, "SVS625CL"))
{
height = 2050;
width = 2448;
load_raw = &CLASS unpacked_load_raw;
data_offset = 0;
filters = 0x94949494;
order = 0x4949;
maximum = 0x0fff;
}
/* Early reject for damaged images */
if (!load_raw || height < 22 || width < 22 ||
#ifdef LIBRAW_LIBRARY_BUILD
(tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw)
#else
tiff_bps > 16
#endif
|| tiff_samples > 4 || colors > 4 || colors < 1)
{
is_raw = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2);
#endif
return;
}
if (!model[0])
sprintf(model, "%dx%d", width, height);
if (filters == UINT_MAX)
filters = 0x94949494;
if (thumb_offset && !thumb_height)
{
fseek(ifp, thumb_offset, SEEK_SET);
if (ljpeg_start(&jh, 1))
{
thumb_width = jh.wide;
thumb_height = jh.high;
}
}
dng_skip:
#ifdef LIBRAW_LIBRARY_BUILD
if (dng_version) /* Override black level by DNG tags */
{
/* copy DNG data from per-IFD field to color.dng */
int iifd = 0; // Active IFD we'll show to user.
for (; iifd < tiff_nifds; iifd++)
if (tiff_ifd[iifd].offset == data_offset) // found
break;
int pifd = -1;
for (int ii = 0; ii < tiff_nifds; ii++)
if (tiff_ifd[ii].offset == thumb_offset) // found
{
pifd = ii;
break;
}
#define CFAROUND(value, filters) filters ? (filters >= 1000 ? ((value + 1) / 2) * 2 : ((value + 5) / 6) * 6) : value
#define IFDCOLORINDEX(ifd, subset, bit) \
(tiff_ifd[ifd].dng_color[subset].parsedfields & bit) ? ifd \
: ((tiff_ifd[0].dng_color[subset].parsedfields & bit) ? 0 : -1)
#define IFDLEVELINDEX(ifd, bit) \
(tiff_ifd[ifd].dng_levels.parsedfields & bit) ? ifd : ((tiff_ifd[0].dng_levels.parsedfields & bit) ? 0 : -1)
#define COPYARR(to, from) memmove(&to, &from, sizeof(from))
if (iifd < tiff_nifds)
{
int sidx;
// Per field, not per structure
if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP)
{
sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPORIGIN);
int sidx2 = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPSIZE);
if (sidx >= 0 && sidx == sidx2)
{
int lm = tiff_ifd[sidx].dng_levels.default_crop[0];
int lmm = CFAROUND(lm, filters);
int tm = tiff_ifd[sidx].dng_levels.default_crop[1];
int tmm = CFAROUND(tm, filters);
int ww = tiff_ifd[sidx].dng_levels.default_crop[2];
int hh = tiff_ifd[sidx].dng_levels.default_crop[3];
if (lmm > lm)
ww -= (lmm - lm);
if (tmm > tm)
hh -= (tmm - tm);
if (left_margin + lm + ww <= raw_width && top_margin + tm + hh <= raw_height)
{
left_margin += lmm;
top_margin += tmm;
width = ww;
height = hh;
}
}
}
if (!(imgdata.color.dng_color[0].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes)
{
sidx = IFDCOLORINDEX(iifd, 0, LIBRAW_DNGFM_FORWARDMATRIX);
if (sidx >= 0)
COPYARR(imgdata.color.dng_color[0].forwardmatrix, tiff_ifd[sidx].dng_color[0].forwardmatrix);
}
if (!(imgdata.color.dng_color[1].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes)
{
sidx = IFDCOLORINDEX(iifd, 1, LIBRAW_DNGFM_FORWARDMATRIX);
if (sidx >= 0)
COPYARR(imgdata.color.dng_color[1].forwardmatrix, tiff_ifd[sidx].dng_color[1].forwardmatrix);
}
for (int ss = 0; ss < 2; ss++)
{
sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_COLORMATRIX);
if (sidx >= 0)
COPYARR(imgdata.color.dng_color[ss].colormatrix, tiff_ifd[sidx].dng_color[ss].colormatrix);
sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_CALIBRATION);
if (sidx >= 0)
COPYARR(imgdata.color.dng_color[ss].calibration, tiff_ifd[sidx].dng_color[ss].calibration);
sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_ILLUMINANT);
if (sidx >= 0)
imgdata.color.dng_color[ss].illuminant = tiff_ifd[sidx].dng_color[ss].illuminant;
}
// Levels
sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE);
if (sidx >= 0)
COPYARR(imgdata.color.dng_levels.analogbalance, tiff_ifd[sidx].dng_levels.analogbalance);
sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_WHITE);
if (sidx >= 0)
COPYARR(imgdata.color.dng_levels.dng_whitelevel, tiff_ifd[sidx].dng_levels.dng_whitelevel);
sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BLACK);
if (sidx >= 0)
{
imgdata.color.dng_levels.dng_black = tiff_ifd[sidx].dng_levels.dng_black;
COPYARR(imgdata.color.dng_levels.dng_cblack, tiff_ifd[sidx].dng_levels.dng_cblack);
}
if (pifd >= 0)
{
sidx = IFDLEVELINDEX(pifd, LIBRAW_DNGFM_PREVIEWCS);
if (sidx >= 0)
imgdata.color.dng_levels.preview_colorspace = tiff_ifd[sidx].dng_levels.preview_colorspace;
}
sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_OPCODE2);
if (sidx >= 0)
meta_offset = tiff_ifd[sidx].opcode2_offset;
sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINTABLE);
INT64 linoff = -1;
int linlen = 0;
if (sidx >= 0)
{
linoff = tiff_ifd[sidx].lineartable_offset;
linlen = tiff_ifd[sidx].lineartable_len;
}
if (linoff >= 0 && linlen > 0)
{
INT64 pos = ftell(ifp);
fseek(ifp, linoff, SEEK_SET);
linear_table(linlen);
fseek(ifp, pos, SEEK_SET);
}
// Need to add curve too
}
/* Copy DNG black level to LibRaw's */
maximum = imgdata.color.dng_levels.dng_whitelevel[0];
black = imgdata.color.dng_levels.dng_black;
int ll = LIM(0, (sizeof(cblack) / sizeof(cblack[0])),
(sizeof(imgdata.color.dng_levels.dng_cblack) / sizeof(imgdata.color.dng_levels.dng_cblack[0])));
for (int i = 0; i < ll; i++)
cblack[i] = imgdata.color.dng_levels.dng_cblack[i];
}
#endif
/* Early reject for damaged images */
if (!load_raw || height < 22 || width < 22 ||
#ifdef LIBRAW_LIBRARY_BUILD
(tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw)
#else
tiff_bps > 16
#endif
|| tiff_samples > 4 || colors > 4 || colors < 1)
{
is_raw = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2);
#endif
return;
}
if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2)) && cmatrix[0][0] > 0.125)
{
memcpy(rgb_cam, cmatrix, sizeof cmatrix);
raw_color = 0;
}
if (raw_color)
adobe_coeff(make, model);
#ifdef LIBRAW_LIBRARY_BUILD
else if (imgdata.color.cam_xyz[0][0] < 0.01)
adobe_coeff(make, model, 1);
#endif
if (load_raw == &CLASS kodak_radc_load_raw)
if (raw_color)
adobe_coeff("Apple", "Quicktake");
#ifdef LIBRAW_LIBRARY_BUILD
// Clear erorneus fuji_width if not set through parse_fuji or for DNG
if(fuji_width && !dng_version && !(imgdata.process_warnings & LIBRAW_WARN_PARSEFUJI_PROCESSED ))
fuji_width = 0;
#endif
if (fuji_width)
{
fuji_width = width >> !fuji_layout;
filters = fuji_width & 1 ? 0x94949494 : 0x49494949;
width = (height >> fuji_layout) + fuji_width;
height = width - 1;
pixel_aspect = 1;
}
else
{
if (raw_height < height)
raw_height = height;
if (raw_width < width)
raw_width = width;
}
if (!tiff_bps)
tiff_bps = 12;
if (!maximum)
{
maximum = (1 << tiff_bps) - 1;
if (maximum < 0x10000 && curve[maximum] > 0 && load_raw == &CLASS sony_arw2_load_raw)
maximum = curve[maximum];
}
if (!load_raw || height < 22 || width < 22 ||
#ifdef LIBRAW_LIBRARY_BUILD
(tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw)
#else
tiff_bps > 16
#endif
|| tiff_samples > 6 || colors > 4)
is_raw = 0;
if (raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_height > 64000)
is_raw = 0;
#ifdef NO_JASPER
if (load_raw == &CLASS redcine_load_raw)
{
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjasper");
#endif
is_raw = 0;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER;
#endif
}
#endif
#ifdef NO_JPEG
if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw)
{
#ifdef DCRAW_VERBOSE
fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg");
#endif
is_raw = 0;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB;
#endif
}
#endif
if (!cdesc[0])
strcpy(cdesc, colors == 3 ? "RGBG" : "GMCY");
if (!raw_height)
raw_height = height;
if (!raw_width)
raw_width = width;
if (filters > 999 && colors == 3)
filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1;
notraw:
if (flip == UINT_MAX)
flip = tiff_flip;
if (flip == UINT_MAX)
flip = 0;
// Convert from degrees to bit-field if needed
if (flip > 89 || flip < -89)
{
switch ((flip + 3600) % 360)
{
case 270:
flip = 5;
break;
case 180:
flip = 3;
break;
case 90:
flip = 6;
break;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2);
#endif
}
void CLASS convert_to_rgb()
{
#ifndef LIBRAW_LIBRARY_BUILD
int row, col, c;
#endif
int i, j, k;
#ifndef LIBRAW_LIBRARY_BUILD
ushort *img;
float out[3];
#endif
float out_cam[3][4];
double num, inverse[3][3];
static const double xyzd50_srgb[3][3] = {
{0.436083, 0.385083, 0.143055}, {0.222507, 0.716888, 0.060608}, {0.013930, 0.097097, 0.714022}};
static const double rgb_rgb[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
static const double adobe_rgb[3][3] = {
{0.715146, 0.284856, 0.000000}, {0.000000, 1.000000, 0.000000}, {0.000000, 0.041166, 0.958839}};
static const double wide_rgb[3][3] = {
{0.593087, 0.404710, 0.002206}, {0.095413, 0.843149, 0.061439}, {0.011621, 0.069091, 0.919288}};
static const double prophoto_rgb[3][3] = {
{0.529317, 0.330092, 0.140588}, {0.098368, 0.873465, 0.028169}, {0.016879, 0.117663, 0.865457}};
static const double aces_rgb[3][3] = {
{0.432996, 0.375380, 0.189317}, {0.089427, 0.816523, 0.102989}, {0.019165, 0.118150, 0.941914}};
static const double(*out_rgb[])[3] = {rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb};
static const char *name[] = {"sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES"};
static const unsigned phead[] = {1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0,
0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0,
0, 0, 0, 0xf6d6, 0x10000, 0xd32d};
unsigned pbody[] = {10, 0x63707274, 0, 36, /* cprt */
0x64657363, 0, 40, /* desc */
0x77747074, 0, 20, /* wtpt */
0x626b7074, 0, 20, /* bkpt */
0x72545243, 0, 14, /* rTRC */
0x67545243, 0, 14, /* gTRC */
0x62545243, 0, 14, /* bTRC */
0x7258595a, 0, 20, /* rXYZ */
0x6758595a, 0, 20, /* gXYZ */
0x6258595a, 0, 20}; /* bXYZ */
static const unsigned pwhite[] = {0xf351, 0x10000, 0x116cc};
unsigned pcurve[] = {0x63757276, 0, 1, 0x1000000};
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 0, 2);
#endif
gamma_curve(gamm[0], gamm[1], 0, 0);
memcpy(out_cam, rgb_cam, sizeof out_cam);
#ifndef LIBRAW_LIBRARY_BUILD
raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6;
#else
raw_color |= colors == 1 || output_color < 1 || output_color > 6;
#endif
if (!raw_color)
{
oprof = (unsigned *)calloc(phead[0], 1);
merror(oprof, "convert_to_rgb()");
memcpy(oprof, phead, sizeof phead);
if (output_color == 5)
oprof[4] = oprof[5];
oprof[0] = 132 + 12 * pbody[0];
for (i = 0; i < pbody[0]; i++)
{
oprof[oprof[0] / 4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874;
pbody[i * 3 + 2] = oprof[0];
oprof[0] += (pbody[i * 3 + 3] + 3) & -4;
}
memcpy(oprof + 32, pbody, sizeof pbody);
oprof[pbody[5] / 4 + 2] = strlen(name[output_color - 1]) + 1;
memcpy((char *)oprof + pbody[8] + 8, pwhite, sizeof pwhite);
pcurve[3] = (short)(256 / gamm[5] + 0.5) << 16;
for (i = 4; i < 7; i++)
memcpy((char *)oprof + pbody[i * 3 + 2], pcurve, sizeof pcurve);
pseudoinverse((double(*)[3])out_rgb[output_color - 1], inverse, 3);
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
{
for (num = k = 0; k < 3; k++)
num += xyzd50_srgb[i][k] * inverse[j][k];
oprof[pbody[j * 3 + 23] / 4 + i + 2] = num * 0x10000 + 0.5;
}
for (i = 0; i < phead[0] / 4; i++)
oprof[i] = htonl(oprof[i]);
strcpy((char *)oprof + pbody[2] + 8, "auto-generated by dcraw");
strcpy((char *)oprof + pbody[5] + 12, name[output_color - 1]);
for (i = 0; i < 3; i++)
for (j = 0; j < colors; j++)
for (out_cam[i][j] = k = 0; k < 3; k++)
out_cam[i][j] += out_rgb[output_color - 1][i][k] * rgb_cam[k][j];
}
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"),
name[output_color - 1]);
#endif
#ifdef LIBRAW_LIBRARY_BUILD
convert_to_rgb_loop(out_cam);
#else
memset(histogram, 0, sizeof histogram);
for (img = image[0], row = 0; row < height; row++)
for (col = 0; col < width; col++, img += 4)
{
if (!raw_color)
{
out[0] = out[1] = out[2] = 0;
FORCC
{
out[0] += out_cam[0][c] * img[c];
out[1] += out_cam[1][c] * img[c];
out[2] += out_cam[2][c] * img[c];
}
FORC3 img[c] = CLIP((int)out[c]);
}
else if (document_mode)
img[0] = img[fcol(row, col)];
FORCC histogram[c][img[c] >> 3]++;
}
#endif
if (colors == 4 && output_color)
colors = 3;
#ifndef LIBRAW_LIBRARY_BUILD
if (document_mode && filters)
colors = 1;
#endif
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 1, 2);
#endif
}
void CLASS fuji_rotate()
{
int i, row, col;
double step;
float r, c, fr, fc;
unsigned ur, uc;
ushort wide, high, (*img)[4], (*pix)[4];
if (!fuji_width)
return;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Rotating image 45 degrees...\n"));
#endif
fuji_width = (fuji_width - 1 + shrink) >> shrink;
step = sqrt(0.5);
wide = fuji_width / step;
high = (height - fuji_width) / step;
img = (ushort(*)[4])calloc(high, wide * sizeof *img);
merror(img, "fuji_rotate()");
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 0, 2);
#endif
for (row = 0; row < high; row++)
for (col = 0; col < wide; col++)
{
ur = r = fuji_width + (row - col) * step;
uc = c = (row + col) * step;
if (ur > height - 2 || uc > width - 2)
continue;
fr = r - ur;
fc = c - uc;
pix = image + ur * width + uc;
for (i = 0; i < colors; i++)
img[row * wide + col][i] = (pix[0][i] * (1 - fc) + pix[1][i] * fc) * (1 - fr) +
(pix[width][i] * (1 - fc) + pix[width + 1][i] * fc) * fr;
}
free(image);
width = wide;
height = high;
image = img;
fuji_width = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 1, 2);
#endif
}
void CLASS stretch()
{
ushort newdim, (*img)[4], *pix0, *pix1;
int row, col, c;
double rc, frac;
if (pixel_aspect == 1)
return;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 0, 2);
#endif
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf(stderr, _("Stretching the image...\n"));
#endif
if (pixel_aspect < 1)
{
newdim = height / pixel_aspect + 0.5;
img = (ushort(*)[4])calloc(width, newdim * sizeof *img);
merror(img, "stretch()");
for (rc = row = 0; row < newdim; row++, rc += pixel_aspect)
{
frac = rc - (c = rc);
pix0 = pix1 = image[c * width];
if (c + 1 < height)
pix1 += width * 4;
for (col = 0; col < width; col++, pix0 += 4, pix1 += 4)
FORCC img[row * width + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5;
}
height = newdim;
}
else
{
newdim = width * pixel_aspect + 0.5;
img = (ushort(*)[4])calloc(height, newdim * sizeof *img);
merror(img, "stretch()");
for (rc = col = 0; col < newdim; col++, rc += 1 / pixel_aspect)
{
frac = rc - (c = rc);
pix0 = pix1 = image[c];
if (c + 1 < width)
pix1 += 4;
for (row = 0; row < height; row++, pix0 += width * 4, pix1 += width * 4)
FORCC img[row * newdim + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5;
}
width = newdim;
}
free(image);
image = img;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 1, 2);
#endif
}
int CLASS flip_index(int row, int col)
{
if (flip & 4)
SWAP(row, col);
if (flip & 2)
row = iheight - 1 - row;
if (flip & 1)
col = iwidth - 1 - col;
return row * iwidth + col;
}
void CLASS tiff_set(struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val)
{
struct tiff_tag *tt;
int c;
tt = (struct tiff_tag *)(ntag + 1) + (*ntag)++;
tt->val.i = val;
if (type == 1 && count <= 4)
FORC(4) tt->val.c[c] = val >> (c << 3);
else if (type == 2)
{
count = strnlen((char *)th + val, count - 1) + 1;
if (count <= 4)
FORC(4) tt->val.c[c] = ((char *)th)[val + c];
}
else if (type == 3 && count <= 2)
FORC(2) tt->val.s[c] = val >> (c << 4);
tt->count = count;
tt->type = type;
tt->tag = tag;
}
#define TOFF(ptr) ((char *)(&(ptr)) - (char *)th)
void CLASS tiff_head(struct tiff_hdr *th, int full)
{
int c, psize = 0;
struct tm *t;
memset(th, 0, sizeof *th);
th->t_order = htonl(0x4d4d4949) >> 16;
th->magic = 42;
th->ifd = 10;
th->rat[0] = th->rat[2] = 300;
th->rat[1] = th->rat[3] = 1;
FORC(6) th->rat[4 + c] = 1000000;
th->rat[4] *= shutter;
th->rat[6] *= aperture;
th->rat[8] *= focal_len;
strncpy(th->t_desc, desc, 512);
strncpy(th->t_make, make, 64);
strncpy(th->t_model, model, 64);
strcpy(th->soft, "dcraw v" DCRAW_VERSION);
t = localtime(×tamp);
sprintf(th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour,
t->tm_min, t->tm_sec);
strncpy(th->t_artist, artist, 64);
if (full)
{
tiff_set(th, &th->ntag, 254, 4, 1, 0);
tiff_set(th, &th->ntag, 256, 4, 1, width);
tiff_set(th, &th->ntag, 257, 4, 1, height);
tiff_set(th, &th->ntag, 258, 3, colors, output_bps);
if (colors > 2)
th->tag[th->ntag - 1].val.i = TOFF(th->bps);
FORC4 th->bps[c] = output_bps;
tiff_set(th, &th->ntag, 259, 3, 1, 1);
tiff_set(th, &th->ntag, 262, 3, 1, 1 + (colors > 1));
}
tiff_set(th, &th->ntag, 270, 2, 512, TOFF(th->t_desc));
tiff_set(th, &th->ntag, 271, 2, 64, TOFF(th->t_make));
tiff_set(th, &th->ntag, 272, 2, 64, TOFF(th->t_model));
if (full)
{
if (oprof)
psize = ntohl(oprof[0]);
tiff_set(th, &th->ntag, 273, 4, 1, sizeof *th + psize);
tiff_set(th, &th->ntag, 277, 3, 1, colors);
tiff_set(th, &th->ntag, 278, 4, 1, height);
tiff_set(th, &th->ntag, 279, 4, 1, height * width * colors * output_bps / 8);
}
else
tiff_set(th, &th->ntag, 274, 3, 1, "12435867"[flip] - '0');
tiff_set(th, &th->ntag, 282, 5, 1, TOFF(th->rat[0]));
tiff_set(th, &th->ntag, 283, 5, 1, TOFF(th->rat[2]));
tiff_set(th, &th->ntag, 284, 3, 1, 1);
tiff_set(th, &th->ntag, 296, 3, 1, 2);
tiff_set(th, &th->ntag, 305, 2, 32, TOFF(th->soft));
tiff_set(th, &th->ntag, 306, 2, 20, TOFF(th->date));
tiff_set(th, &th->ntag, 315, 2, 64, TOFF(th->t_artist));
tiff_set(th, &th->ntag, 34665, 4, 1, TOFF(th->nexif));
if (psize)
tiff_set(th, &th->ntag, 34675, 7, psize, sizeof *th);
tiff_set(th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4]));
tiff_set(th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6]));
tiff_set(th, &th->nexif, 34855, 3, 1, iso_speed);
tiff_set(th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8]));
if (gpsdata[1])
{
tiff_set(th, &th->ntag, 34853, 4, 1, TOFF(th->ngps));
tiff_set(th, &th->ngps, 0, 1, 4, 0x202);
tiff_set(th, &th->ngps, 1, 2, 2, gpsdata[29]);
tiff_set(th, &th->ngps, 2, 5, 3, TOFF(th->gps[0]));
tiff_set(th, &th->ngps, 3, 2, 2, gpsdata[30]);
tiff_set(th, &th->ngps, 4, 5, 3, TOFF(th->gps[6]));
tiff_set(th, &th->ngps, 5, 1, 1, gpsdata[31]);
tiff_set(th, &th->ngps, 6, 5, 1, TOFF(th->gps[18]));
tiff_set(th, &th->ngps, 7, 5, 3, TOFF(th->gps[12]));
tiff_set(th, &th->ngps, 18, 2, 12, TOFF(th->gps[20]));
tiff_set(th, &th->ngps, 29, 2, 12, TOFF(th->gps[23]));
memcpy(th->gps, gpsdata, sizeof th->gps);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS jpeg_thumb_writer(FILE *tfp, char *t_humb, int t_humb_length)
{
ushort exif[5];
struct tiff_hdr th;
fputc(0xff, tfp);
fputc(0xd8, tfp);
if (strcmp(t_humb + 6, "Exif"))
{
memcpy(exif, "\xff\xe1 Exif\0\0", 10);
exif[1] = htons(8 + sizeof th);
fwrite(exif, 1, sizeof exif, tfp);
tiff_head(&th, 0);
fwrite(&th, 1, sizeof th, tfp);
}
fwrite(t_humb + 2, 1, t_humb_length - 2, tfp);
}
void CLASS jpeg_thumb()
{
char *thumb;
thumb = (char *)malloc(thumb_length);
merror(thumb, "jpeg_thumb()");
fread(thumb, 1, thumb_length, ifp);
jpeg_thumb_writer(ofp, thumb, thumb_length);
free(thumb);
}
#else
void CLASS jpeg_thumb()
{
char *thumb;
ushort exif[5];
struct tiff_hdr th;
thumb = (char *)malloc(thumb_length);
merror(thumb, "jpeg_thumb()");
fread(thumb, 1, thumb_length, ifp);
fputc(0xff, ofp);
fputc(0xd8, ofp);
if (strcmp(thumb + 6, "Exif"))
{
memcpy(exif, "\xff\xe1 Exif\0\0", 10);
exif[1] = htons(8 + sizeof th);
fwrite(exif, 1, sizeof exif, ofp);
tiff_head(&th, 0);
fwrite(&th, 1, sizeof th, ofp);
}
fwrite(thumb + 2, 1, thumb_length - 2, ofp);
free(thumb);
}
#endif
void CLASS write_ppm_tiff()
{
struct tiff_hdr th;
uchar *ppm;
ushort *ppm2;
int c, row, col, soff, rstep, cstep;
int perc, val, total, t_white = 0x2000;
#ifdef LIBRAW_LIBRARY_BUILD
perc = width * height * auto_bright_thr;
#else
perc = width * height * 0.01; /* 99th percentile white level */
#endif
if (fuji_width)
perc /= 2;
if (!((highlight & ~2) || no_auto_bright))
for (t_white = c = 0; c < colors; c++)
{
for (val = 0x2000, total = 0; --val > 32;)
if ((total += histogram[c][val]) > perc)
break;
if (t_white < val)
t_white = val;
}
gamma_curve(gamm[0], gamm[1], 2, (t_white << 3) / bright);
iheight = height;
iwidth = width;
if (flip & 4)
SWAP(height, width);
ppm = (uchar *)calloc(width, colors * output_bps / 8);
ppm2 = (ushort *)ppm;
merror(ppm, "write_ppm_tiff()");
if (output_tiff)
{
tiff_head(&th, 1);
fwrite(&th, sizeof th, 1, ofp);
if (oprof)
fwrite(oprof, ntohl(oprof[0]), 1, ofp);
}
else if (colors > 3)
fprintf(ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors,
(1 << output_bps) - 1, cdesc);
else
fprintf(ofp, "P%d\n%d %d\n%d\n", colors / 2 + 5, width, height, (1 << output_bps) - 1);
soff = flip_index(0, 0);
cstep = flip_index(0, 1) - soff;
rstep = flip_index(1, 0) - flip_index(0, width);
for (row = 0; row < height; row++, soff += rstep)
{
for (col = 0; col < width; col++, soff += cstep)
if (output_bps == 8)
FORCC ppm[col * colors + c] = curve[image[soff][c]] >> 8;
else
FORCC ppm2[col * colors + c] = curve[image[soff][c]];
if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa)
swab((char *)ppm2, (char *)ppm2, width * colors * 2);
fwrite(ppm, colors * output_bps / 8, width, ofp);
}
free(ppm);
}
| ./CrossVul/dataset_final_sorted/CWE-119/cpp/bad_578_2 |
crossvul-cpp_data_bad_1636_2 | // Copyright Benoit Blanchon 2014-2015
// MIT License
//
// Arduino JSON library
// https://github.com/bblanchon/ArduinoJson
#include <gtest/gtest.h>
#include <ArduinoJson/Internals/QuotedString.hpp>
using namespace ArduinoJson::Internals;
class QuotedString_ExtractFrom_Tests : public testing::Test {
protected:
void whenInputIs(const char *json) {
strcpy(_jsonString, json);
_result = QuotedString::extractFrom(_jsonString, &_trailing);
}
void resultMustBe(const char *expected) { EXPECT_STREQ(expected, _result); }
void trailingMustBe(const char *expected) {
EXPECT_STREQ(expected, _trailing);
}
private:
char _jsonString[256];
char *_result;
char *_trailing;
};
TEST_F(QuotedString_ExtractFrom_Tests, EmptyDoubleQuotedString) {
whenInputIs("\"\"");
resultMustBe("");
trailingMustBe("");
}
TEST_F(QuotedString_ExtractFrom_Tests, NoQuotes) {
whenInputIs("hello world");
resultMustBe(0);
}
TEST_F(QuotedString_ExtractFrom_Tests, MissingClosingQuote) {
whenInputIs("\"hello world");
resultMustBe(0);
}
TEST_F(QuotedString_ExtractFrom_Tests, EmptySingleQuotedString) {
whenInputIs("''");
resultMustBe("");
trailingMustBe("");
}
TEST_F(QuotedString_ExtractFrom_Tests, SimpleDoubleQuotedString) {
whenInputIs("\"hello world\"");
resultMustBe("hello world");
trailingMustBe("");
}
TEST_F(QuotedString_ExtractFrom_Tests, DoubleQuotedStringWithTrailing) {
whenInputIs("\"hello\" world");
resultMustBe("hello");
trailingMustBe(" world");
}
TEST_F(QuotedString_ExtractFrom_Tests, SingleQuotedStringWithTrailing) {
whenInputIs("'hello' world");
resultMustBe("hello");
trailingMustBe(" world");
}
TEST_F(QuotedString_ExtractFrom_Tests, CurlyBraces) {
whenInputIs("\"{hello:world}\"");
resultMustBe("{hello:world}");
}
TEST_F(QuotedString_ExtractFrom_Tests, SquareBraquets) {
whenInputIs("\"[hello,world]\"");
resultMustBe("[hello,world]");
}
TEST_F(QuotedString_ExtractFrom_Tests, EscapedDoubleQuote) {
whenInputIs("\"hello \\\"world\\\"\"");
resultMustBe("hello \"world\"");
}
TEST_F(QuotedString_ExtractFrom_Tests, EscapedSingleQuote) {
whenInputIs("\"hello \\\'world\\\'\"");
resultMustBe("hello 'world'");
}
TEST_F(QuotedString_ExtractFrom_Tests, EscapedSolidus) {
whenInputIs("\"hello \\/world\\/\"");
resultMustBe("hello /world/");
}
TEST_F(QuotedString_ExtractFrom_Tests, EscapedReverseSolidus) {
whenInputIs("\"hello \\\\world\\\\\"");
resultMustBe("hello \\world\\");
}
TEST_F(QuotedString_ExtractFrom_Tests, EscapedBackspace) {
whenInputIs("\"hello \\bworld\\b\"");
resultMustBe("hello \bworld\b");
}
TEST_F(QuotedString_ExtractFrom_Tests, EscapedFormfeed) {
whenInputIs("\"hello \\fworld\\f\"");
resultMustBe("hello \fworld\f");
}
TEST_F(QuotedString_ExtractFrom_Tests, EscapedNewline) {
whenInputIs("\"hello \\nworld\\n\"");
resultMustBe("hello \nworld\n");
}
TEST_F(QuotedString_ExtractFrom_Tests, EscapedCarriageReturn) {
whenInputIs("\"hello \\rworld\\r\"");
resultMustBe("hello \rworld\r");
}
TEST_F(QuotedString_ExtractFrom_Tests, EscapedTab) {
whenInputIs("\"hello \\tworld\\t\"");
resultMustBe("hello \tworld\t");
}
TEST_F(QuotedString_ExtractFrom_Tests, AllEscapedCharsTogether) {
whenInputIs("\"1\\\"2\\\\3\\/4\\b5\\f6\\n7\\r8\\t9\"");
resultMustBe("1\"2\\3/4\b5\f6\n7\r8\t9");
}
| ./CrossVul/dataset_final_sorted/CWE-119/cpp/bad_1636_2 |
crossvul-cpp_data_good_846_0 | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1998-2010 Zend Technologies Ltd. (http://www.zend.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 2.00 of the Zend license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.zend.com/license/2_00.txt. |
| If you did not receive a copy of the Zend license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@zend.com so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
// NOTE: See also "hphp/zend/zend-string.*".
#include "hphp/runtime/base/zend-string.h"
#include "hphp/runtime/base/zend-printf.h"
#include "hphp/runtime/base/zend-math.h"
#include "hphp/util/lock.h"
#include "hphp/util/overflow.h"
#include <algorithm>
#include <cmath>
#ifndef _MSC_VER
#include <monetary.h>
#endif
#include "hphp/util/bstring.h"
#include "hphp/runtime/base/exceptions.h"
#include "hphp/runtime/base/string-buffer.h"
#include "hphp/runtime/base/runtime-error.h"
#include "hphp/runtime/base/string-util.h"
#include "hphp/runtime/base/builtin-functions.h"
#include <folly/portability/String.h>
#define PHP_QPRINT_MAXL 75
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
// helpers
void string_charmask(const char *sinput, int len, char *mask) {
const unsigned char *input = (unsigned char *)sinput;
const unsigned char *end;
unsigned char c;
memset(mask, 0, 256);
for (end = input+len; input < end; input++) {
c=*input;
if ((input+3 < end) && input[1] == '.' && input[2] == '.'
&& input[3] >= c) {
memset(mask+c, 1, input[3] - c + 1);
input+=3;
} else if ((input+1 < end) && input[0] == '.' && input[1] == '.') {
/* Error, try to be as helpful as possible:
(a range ending/starting with '.' won't be captured here) */
if (end-len >= input) { /* there was no 'left' char */
throw_invalid_argument
("charlist: Invalid '..'-range, missing left of '..'");
continue;
}
if (input+2 >= end) { /* there is no 'right' char */
throw_invalid_argument
("charlist: Invalid '..'-range, missing right of '..'");
continue;
}
if (input[-1] > input[2]) { /* wrong order */
throw_invalid_argument
("charlist: '..'-range needs to be incrementing");
continue;
}
/* FIXME: better error (a..b..c is the only left possibility?) */
throw_invalid_argument("charlist: Invalid '..'-range");
continue;
} else {
mask[c]=1;
}
}
}
///////////////////////////////////////////////////////////////////////////////
void string_to_case(String& s, int (*tocase)(int)) {
assertx(!s.isNull());
assertx(tocase);
auto data = s.mutableData();
auto len = s.size();
for (int i = 0; i < len; i++) {
data[i] = tocase(data[i]);
}
}
///////////////////////////////////////////////////////////////////////////////
#define STR_PAD_LEFT 0
#define STR_PAD_RIGHT 1
#define STR_PAD_BOTH 2
String string_pad(const char *input, int len, int pad_length,
const char *pad_string, int pad_str_len,
int pad_type) {
assertx(input);
int num_pad_chars = pad_length - len;
/* If resulting string turns out to be shorter than input string,
we simply copy the input and return. */
if (pad_length < 0 || num_pad_chars < 0) {
return String(input, len, CopyString);
}
/* Setup the padding string values if specified. */
if (pad_str_len == 0) {
throw_invalid_argument("pad_string: (empty)");
return String();
}
String ret(pad_length, ReserveString);
char *result = ret.mutableData();
/* We need to figure out the left/right padding lengths. */
int left_pad, right_pad;
switch (pad_type) {
case STR_PAD_RIGHT:
left_pad = 0;
right_pad = num_pad_chars;
break;
case STR_PAD_LEFT:
left_pad = num_pad_chars;
right_pad = 0;
break;
case STR_PAD_BOTH:
left_pad = num_pad_chars / 2;
right_pad = num_pad_chars - left_pad;
break;
default:
throw_invalid_argument("pad_type: %d", pad_type);
return String();
}
/* First we pad on the left. */
int result_len = 0;
for (int i = 0; i < left_pad; i++) {
result[result_len++] = pad_string[i % pad_str_len];
}
/* Then we copy the input string. */
memcpy(result + result_len, input, len);
result_len += len;
/* Finally, we pad on the right. */
for (int i = 0; i < right_pad; i++) {
result[result_len++] = pad_string[i % pad_str_len];
}
ret.setSize(result_len);
return ret;
}
///////////////////////////////////////////////////////////////////////////////
int string_find(const char *input, int len, char ch, int pos,
bool case_sensitive) {
assertx(input);
if (pos < 0 || pos > len) {
return -1;
}
const void *ptr;
if (case_sensitive) {
ptr = memchr(input + pos, ch, len - pos);
} else {
ptr = bstrcasechr(input + pos, ch, len - pos);
}
if (ptr != nullptr) {
return (int)((const char *)ptr - input);
}
return -1;
}
int string_rfind(const char *input, int len, char ch, int pos,
bool case_sensitive) {
assertx(input);
if (pos < -len || pos > len) {
return -1;
}
const void *ptr;
if (case_sensitive) {
if (pos >= 0) {
ptr = memrchr(input + pos, ch, len - pos);
} else {
ptr = memrchr(input, ch, len + pos + 1);
}
} else {
if (pos >= 0) {
ptr = bstrrcasechr(input + pos, ch, len - pos);
} else {
ptr = bstrrcasechr(input, ch, len + pos + 1);
}
}
if (ptr != nullptr) {
return (int)((const char *)ptr - input);
}
return -1;
}
int string_find(const char *input, int len, const char *s, int s_len,
int pos, bool case_sensitive) {
assertx(input);
assertx(s);
if (!s_len || pos < 0 || pos > len) {
return -1;
}
void *ptr;
if (case_sensitive) {
ptr = (void*)string_memnstr(input + pos, s, s_len, input + len);
} else {
ptr = bstrcasestr(input + pos, len - pos, s, s_len);
}
if (ptr != nullptr) {
return (int)((const char *)ptr - input);
}
return -1;
}
int string_rfind(const char *input, int len, const char *s, int s_len,
int pos, bool case_sensitive) {
assertx(input);
assertx(s);
if (!s_len || pos < -len || pos > len) {
return -1;
}
void *ptr;
if (case_sensitive) {
if (pos >= 0) {
ptr = bstrrstr(input + pos, len - pos, s, s_len);
} else {
ptr = bstrrstr(input, len + std::min(pos + s_len, 0), s, s_len);
}
} else {
if (pos >= 0) {
ptr = bstrrcasestr(input + pos, len - pos, s, s_len);
} else {
ptr = bstrrcasestr(input, len + std::min(pos + s_len, 0), s, s_len);
}
}
if (ptr != nullptr) {
return (int)((const char *)ptr - input);
}
return -1;
}
const char *string_memnstr(const char *haystack, const char *needle,
int needle_len, const char *end) {
const char *p = haystack;
char ne = needle[needle_len-1];
end -= needle_len;
while (p <= end) {
if ((p = (char *)memchr(p, *needle, (end-p+1))) && ne == p[needle_len-1]) {
if (!memcmp(needle, p, needle_len-1)) {
return p;
}
}
if (p == nullptr) {
return nullptr;
}
p++;
}
return nullptr;
}
String string_replace(const char *s, int len, int start, int length,
const char *replacement, int len_repl) {
assertx(s);
assertx(replacement);
assertx(len >= 0);
// if "start" position is negative, count start position from the end
// of the string
if (start < 0) {
start = len + start;
if (start < 0) {
start = 0;
}
}
if (start > len) {
start = len;
}
// if "length" position is negative, set it to the length
// needed to stop that many chars from the end of the string
if (length < 0) {
length = (len - start) + length;
if (length < 0) {
length = 0;
}
}
// check if length is too large
if (length > len) {
length = len;
}
// check if the length is too large adjusting for non-zero start
// Write this way instead of start + length > len to avoid overflow
if (length > len - start) {
length = len - start;
}
String retString(len + len_repl - length, ReserveString);
char *ret = retString.mutableData();
int ret_len = 0;
if (start) {
memcpy(ret, s, start);
ret_len += start;
}
if (len_repl) {
memcpy(ret + ret_len, replacement, len_repl);
ret_len += len_repl;
}
len -= (start + length);
if (len) {
memcpy(ret + ret_len, s + start + length, len);
ret_len += len;
}
retString.setSize(ret_len);
return retString;
}
String string_replace(const char *input, int len,
const char *search, int len_search,
const char *replacement, int len_replace,
int &count, bool case_sensitive) {
assertx(input);
assertx(search && len_search);
assertx(len >= 0);
assertx(len_search >= 0);
assertx(len_replace >= 0);
if (len == 0) {
return String();
}
req::vector<int> founds;
founds.reserve(16);
if (len_search == 1) {
for (int pos = string_find(input, len, *search, 0, case_sensitive);
pos >= 0;
pos = string_find(input, len, *search, pos + len_search,
case_sensitive)) {
founds.push_back(pos);
}
} else {
for (int pos = string_find(input, len, search, len_search, 0,
case_sensitive);
pos >= 0;
pos = string_find(input, len, search, len_search,
pos + len_search, case_sensitive)) {
founds.push_back(pos);
}
}
count = founds.size();
if (count == 0) {
return String(); // not found
}
int reserve;
// Make sure the new size of the string wouldn't overflow int32_t. Don't
// bother if the replacement wouldn't make the string longer.
if (len_replace > len_search) {
auto raise = [&] { raise_error("String too large"); };
if (mul_overflow(len_replace - len_search, count)) {
raise();
}
int diff = (len_replace - len_search) * count;
if (add_overflow(len, diff)) {
raise();
}
reserve = len + diff;
} else {
reserve = len + (len_replace - len_search) * count;
}
String retString(reserve, ReserveString);
char *ret = retString.mutableData();
char *p = ret;
int pos = 0; // last position in input that hasn't been copied over yet
int n;
for (unsigned int i = 0; i < founds.size(); i++) {
n = founds[i];
if (n > pos) {
n -= pos;
memcpy(p, input, n);
p += n;
input += n;
pos += n;
}
if (len_replace) {
memcpy(p, replacement, len_replace);
p += len_replace;
}
input += len_search;
pos += len_search;
}
n = len;
if (n > pos) {
n -= pos;
memcpy(p, input, n);
p += n;
}
retString.setSize(p - ret);
return retString;
}
///////////////////////////////////////////////////////////////////////////////
String string_chunk_split(const char *src, int srclen, const char *end,
int endlen, int chunklen) {
int chunks = srclen / chunklen; // complete chunks!
int restlen = srclen - chunks * chunklen; /* srclen % chunklen */
String ret(
safe_address(
chunks + 1,
endlen,
srclen
),
ReserveString
);
char *dest = ret.mutableData();
const char *p; char *q;
const char *pMax = src + srclen - chunklen + 1;
for (p = src, q = dest; p < pMax; ) {
memcpy(q, p, chunklen);
q += chunklen;
memcpy(q, end, endlen);
q += endlen;
p += chunklen;
}
if (restlen) {
memcpy(q, p, restlen);
q += restlen;
memcpy(q, end, endlen);
q += endlen;
}
ret.setSize(q - dest);
return ret;
}
///////////////////////////////////////////////////////////////////////////////
#define PHP_TAG_BUF_SIZE 1023
/**
* Check if tag is in a set of tags
*
* states:
*
* 0 start tag
* 1 first non-whitespace char seen
*/
static int string_tag_find(const char *tag, int len, const char *set) {
char c, *n;
const char *t;
int state=0, done=0;
char *norm;
if (len <= 0) {
return 0;
}
norm = (char *)req::malloc_noptrs(len+1);
SCOPE_EXIT { req::free(norm); };
n = norm;
t = tag;
c = tolower(*t);
/*
normalize the tag removing leading and trailing whitespace
and turn any <a whatever...> into just <a> and any </tag>
into <tag>
*/
while (!done) {
switch (c) {
case '<':
*(n++) = c;
break;
case '>':
done =1;
break;
default:
if (!isspace((int)c)) {
if (state == 0) {
state=1;
}
if (c != '/') {
*(n++) = c;
}
} else {
if (state == 1)
done=1;
}
break;
}
c = tolower(*(++t));
}
*(n++) = '>';
*n = '\0';
if (strstr(set, norm)) {
done=1;
} else {
done=0;
}
return done;
}
/**
* A simple little state-machine to strip out html and php tags
*
* State 0 is the output state, State 1 means we are inside a
* normal html tag and state 2 means we are inside a php tag.
*
* The state variable is passed in to allow a function like fgetss
* to maintain state across calls to the function.
*
* lc holds the last significant character read and br is a bracket
* counter.
*
* When an allow string is passed in we keep track of the string
* in state 1 and when the tag is closed check it against the
* allow string to see if we should allow it.
* swm: Added ability to strip <?xml tags without assuming it PHP
* code.
*/
String string_strip_tags(const char *s, const int len,
const char *allow, const int allow_len,
bool allow_tag_spaces) {
const char *abuf, *p;
char *rbuf, *tbuf, *tp, *rp, c, lc;
int br, i=0, depth=0, in_q = 0;
int state = 0, pos;
assertx(s);
assertx(allow);
String retString(s, len, CopyString);
rbuf = retString.mutableData();
String allowString;
c = *s;
lc = '\0';
p = s;
rp = rbuf;
br = 0;
if (allow_len) {
assertx(allow);
allowString = String(allow_len, ReserveString);
char *atmp = allowString.mutableData();
for (const char *tmp = allow; *tmp; tmp++, atmp++) {
*atmp = tolower((int)*(const unsigned char *)tmp);
}
allowString.setSize(allow_len);
abuf = allowString.data();
tbuf = (char *)req::malloc_noptrs(PHP_TAG_BUF_SIZE+1);
tp = tbuf;
} else {
abuf = nullptr;
tbuf = tp = nullptr;
}
auto move = [&pos, &tbuf, &tp]() {
if (tp - tbuf >= PHP_TAG_BUF_SIZE) {
pos = tp - tbuf;
tbuf = (char*)req::realloc_noptrs(tbuf,
(tp - tbuf) + PHP_TAG_BUF_SIZE + 1);
tp = tbuf + pos;
}
};
while (i < len) {
switch (c) {
case '\0':
break;
case '<':
if (isspace(*(p + 1)) && !allow_tag_spaces) {
goto reg_char;
}
if (state == 0) {
lc = '<';
state = 1;
if (allow_len) {
move();
*(tp++) = '<';
}
} else if (state == 1) {
depth++;
}
break;
case '(':
if (state == 2) {
if (lc != '"' && lc != '\'') {
lc = '(';
br++;
}
} else if (allow_len && state == 1) {
move();
*(tp++) = c;
} else if (state == 0) {
*(rp++) = c;
}
break;
case ')':
if (state == 2) {
if (lc != '"' && lc != '\'') {
lc = ')';
br--;
}
} else if (allow_len && state == 1) {
move();
*(tp++) = c;
} else if (state == 0) {
*(rp++) = c;
}
break;
case '>':
if (depth) {
depth--;
break;
}
if (in_q) {
break;
}
switch (state) {
case 1: /* HTML/XML */
lc = '>';
in_q = state = 0;
if (allow_len) {
move();
*(tp++) = '>';
*tp='\0';
if (string_tag_find(tbuf, tp-tbuf, abuf)) {
memcpy(rp, tbuf, tp-tbuf);
rp += tp-tbuf;
}
tp = tbuf;
}
break;
case 2: /* PHP */
if (!br && lc != '\"' && *(p-1) == '?') {
in_q = state = 0;
tp = tbuf;
}
break;
case 3:
in_q = state = 0;
tp = tbuf;
break;
case 4: /* JavaScript/CSS/etc... */
if (p >= s + 2 && *(p-1) == '-' && *(p-2) == '-') {
in_q = state = 0;
tp = tbuf;
}
break;
default:
*(rp++) = c;
break;
}
break;
case '"':
case '\'':
if (state == 4) {
/* Inside <!-- comment --> */
break;
} else if (state == 2 && *(p-1) != '\\') {
if (lc == c) {
lc = '\0';
} else if (lc != '\\') {
lc = c;
}
} else if (state == 0) {
*(rp++) = c;
} else if (allow_len && state == 1) {
move();
*(tp++) = c;
}
if (state && p != s && *(p-1) != '\\' && (!in_q || *p == in_q)) {
if (in_q) {
in_q = 0;
} else {
in_q = *p;
}
}
break;
case '!':
/* JavaScript & Other HTML scripting languages */
if (state == 1 && *(p-1) == '<') {
state = 3;
lc = c;
} else {
if (state == 0) {
*(rp++) = c;
} else if (allow_len && state == 1) {
move();
*(tp++) = c;
}
}
break;
case '-':
if (state == 3 && p >= s + 2 && *(p-1) == '-' && *(p-2) == '!') {
state = 4;
} else {
goto reg_char;
}
break;
case '?':
if (state == 1 && *(p-1) == '<') {
br=0;
state=2;
break;
}
case 'E':
case 'e':
/* !DOCTYPE exception */
if (state==3 && p > s+6
&& tolower(*(p-1)) == 'p'
&& tolower(*(p-2)) == 'y'
&& tolower(*(p-3)) == 't'
&& tolower(*(p-4)) == 'c'
&& tolower(*(p-5)) == 'o'
&& tolower(*(p-6)) == 'd') {
state = 1;
break;
}
/* fall-through */
case 'l':
/* swm: If we encounter '<?xml' then we shouldn't be in
* state == 2 (PHP). Switch back to HTML.
*/
if (state == 2 && p > s+2 && *(p-1) == 'm' && *(p-2) == 'x') {
state = 1;
break;
}
/* fall-through */
default:
reg_char:
if (state == 0) {
*(rp++) = c;
} else if (allow_len && state == 1) {
move();
*(tp++) = c;
}
break;
}
c = *(++p);
i++;
}
if (rp < rbuf + len) {
*rp = '\0';
}
if (allow_len) {
req::free(tbuf);
}
retString.setSize(rp - rbuf);
return retString;
}
///////////////////////////////////////////////////////////////////////////////
static char string_hex2int(int c) {
if (isdigit(c)) {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
return -1;
}
String string_quoted_printable_encode(const char *input, int len) {
size_t length = len;
const unsigned char *str = (unsigned char*)input;
unsigned long lp = 0;
unsigned char c;
char *d, *buffer;
char *hex = "0123456789ABCDEF";
String ret(
safe_address(
3,
length + ((safe_address(3, length, 0)/(PHP_QPRINT_MAXL-9)) + 1),
1),
ReserveString
);
d = buffer = ret.mutableData();
while (length--) {
if (((c = *str++) == '\015') && (*str == '\012') && length > 0) {
*d++ = '\015';
*d++ = *str++;
length--;
lp = 0;
} else {
if (iscntrl (c) || (c == 0x7f) || (c & 0x80) ||
(c == '=') || ((c == ' ') && (*str == '\015'))) {
if ((((lp+= 3) > PHP_QPRINT_MAXL) && (c <= 0x7f))
|| ((c > 0x7f) && (c <= 0xdf) && ((lp + 3) > PHP_QPRINT_MAXL))
|| ((c > 0xdf) && (c <= 0xef) && ((lp + 6) > PHP_QPRINT_MAXL))
|| ((c > 0xef) && (c <= 0xf4) && ((lp + 9) > PHP_QPRINT_MAXL))) {
*d++ = '=';
*d++ = '\015';
*d++ = '\012';
lp = 3;
}
*d++ = '=';
*d++ = hex[c >> 4];
*d++ = hex[c & 0xf];
} else {
if ((++lp) > PHP_QPRINT_MAXL) {
*d++ = '=';
*d++ = '\015';
*d++ = '\012';
lp = 1;
}
*d++ = c;
}
}
}
len = d - buffer;
ret.setSize(len);
return ret;
}
String string_quoted_printable_decode(const char *input, int len, bool is_q) {
assertx(input);
if (len == 0) {
return String();
}
int i = 0, j = 0, k;
const char *str_in = input;
String ret(len, ReserveString);
char *str_out = ret.mutableData();
while (i < len && str_in[i]) {
switch (str_in[i]) {
case '=':
if (i + 2 < len && str_in[i + 1] && str_in[i + 2] &&
isxdigit((int) str_in[i + 1]) && isxdigit((int) str_in[i + 2]))
{
str_out[j++] = (string_hex2int((int) str_in[i + 1]) << 4)
+ string_hex2int((int) str_in[i + 2]);
i += 3;
} else /* check for soft line break according to RFC 2045*/ {
k = 1;
while (str_in[i + k] &&
((str_in[i + k] == 32) || (str_in[i + k] == 9))) {
/* Possibly, skip spaces/tabs at the end of line */
k++;
}
if (!str_in[i + k]) {
/* End of line reached */
i += k;
}
else if ((str_in[i + k] == 13) && (str_in[i + k + 1] == 10)) {
/* CRLF */
i += k + 2;
}
else if ((str_in[i + k] == 13) || (str_in[i + k] == 10)) {
/* CR or LF */
i += k + 1;
}
else {
str_out[j++] = str_in[i++];
}
}
break;
case '_':
if (is_q) {
str_out[j++] = ' ';
i++;
} else {
str_out[j++] = str_in[i++];
}
break;
default:
str_out[j++] = str_in[i++];
}
}
ret.setSize(j);
return ret;
}
Variant string_base_to_numeric(const char *s, int len, int base) {
int64_t num = 0;
double fnum = 0;
int mode = 0;
int64_t cutoff;
int cutlim;
assertx(string_validate_base(base));
cutoff = LONG_MAX / base;
cutlim = LONG_MAX % base;
for (int i = len; i > 0; i--) {
char c = *s++;
/* might not work for EBCDIC */
if (c >= '0' && c <= '9')
c -= '0';
else if (c >= 'A' && c <= 'Z')
c -= 'A' - 10;
else if (c >= 'a' && c <= 'z')
c -= 'a' - 10;
else
continue;
if (c >= base)
continue;
switch (mode) {
case 0: /* Integer */
if (num < cutoff || (num == cutoff && c <= cutlim)) {
num = num * base + c;
break;
} else {
fnum = num;
mode = 1;
}
/* fall-through */
case 1: /* Float */
fnum = fnum * base + c;
}
}
if (mode == 1) {
return fnum;
}
return num;
}
String string_long_to_base(unsigned long value, int base) {
static char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
char buf[(sizeof(unsigned long) << 3) + 1];
char *ptr, *end;
assertx(string_validate_base(base));
end = ptr = buf + sizeof(buf) - 1;
do {
*--ptr = digits[value % base];
value /= base;
} while (ptr > buf && value);
return String(ptr, end - ptr, CopyString);
}
String string_numeric_to_base(const Variant& value, int base) {
static char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
assertx(string_validate_base(base));
if ((!value.isInteger() && !value.isDouble())) {
return empty_string();
}
if (value.isDouble()) {
double fvalue = floor(value.toDouble()); /* floor it just in case */
char *ptr, *end;
char buf[(sizeof(double) << 3) + 1];
/* Don't try to convert +/- infinity */
if (fvalue == HUGE_VAL || fvalue == -HUGE_VAL) {
raise_warning("Number too large");
return empty_string();
}
end = ptr = buf + sizeof(buf) - 1;
do {
*--ptr = digits[(int) fmod(fvalue, base)];
fvalue /= base;
} while (ptr > buf && fabs(fvalue) >= 1);
return String(ptr, end - ptr, CopyString);
}
return string_long_to_base(value.toInt64(), base);
}
///////////////////////////////////////////////////////////////////////////////
// uuencode
#define PHP_UU_ENC(c) \
((c) ? ((c) & 077) + ' ' : '`')
#define PHP_UU_ENC_C2(c) \
PHP_UU_ENC(((*(c) * 16) & 060) | ((*((c) + 1) >> 4) & 017))
#define PHP_UU_ENC_C3(c) \
PHP_UU_ENC(((*(c + 1) * 4) & 074) | ((*((c) + 2) >> 6) & 03))
#define PHP_UU_DEC(c) \
(((c) - ' ') & 077)
String string_uuencode(const char *src, int src_len) {
assertx(src);
assertx(src_len);
int len = 45;
char *p;
const char *s, *e, *ee;
char *dest;
/* encoded length is ~ 38% greater than the original */
String ret((int)ceil(src_len * 1.38) + 45, ReserveString);
p = dest = ret.mutableData();
s = src;
e = src + src_len;
while ((s + 3) < e) {
ee = s + len;
if (ee > e) {
ee = e;
len = ee - s;
if (len % 3) {
ee = s + (int) (floor(len / 3) * 3);
}
}
*p++ = PHP_UU_ENC(len);
while (s < ee) {
*p++ = PHP_UU_ENC(*s >> 2);
*p++ = PHP_UU_ENC_C2(s);
*p++ = PHP_UU_ENC_C3(s);
*p++ = PHP_UU_ENC(*(s + 2) & 077);
s += 3;
}
if (len == 45) {
*p++ = '\n';
}
}
if (s < e) {
if (len == 45) {
*p++ = PHP_UU_ENC(e - s);
len = 0;
}
*p++ = PHP_UU_ENC(*s >> 2);
*p++ = PHP_UU_ENC_C2(s);
*p++ = ((e - s) > 1) ? PHP_UU_ENC_C3(s) : PHP_UU_ENC('\0');
*p++ = ((e - s) > 2) ? PHP_UU_ENC(*(s + 2) & 077) : PHP_UU_ENC('\0');
}
if (len < 45) {
*p++ = '\n';
}
*p++ = PHP_UU_ENC('\0');
*p++ = '\n';
*p = '\0';
ret.setSize(p - dest);
return ret;
}
String string_uudecode(const char *src, int src_len) {
int total_len = 0;
int len;
const char *s, *e, *ee;
char *p, *dest;
String ret(ceil(src_len * 0.75), ReserveString);
p = dest = ret.mutableData();
s = src;
e = src + src_len;
while (s < e) {
if ((len = PHP_UU_DEC(*s++)) <= 0) {
break;
}
/* sanity check */
if (len > src_len) {
goto err;
}
total_len += len;
ee = s + (len == 45 ? 60 : (int) floor(len * 1.33));
/* sanity check */
if (ee > e) {
goto err;
}
while (s < ee) {
if (s + 4 > e) goto err;
*p++ = PHP_UU_DEC(*s) << 2 | PHP_UU_DEC(*(s + 1)) >> 4;
*p++ = PHP_UU_DEC(*(s + 1)) << 4 | PHP_UU_DEC(*(s + 2)) >> 2;
*p++ = PHP_UU_DEC(*(s + 2)) << 6 | PHP_UU_DEC(*(s + 3));
s += 4;
}
if (len < 45) {
break;
}
/* skip \n */
s++;
}
if ((len = total_len > (p - dest))) {
*p++ = PHP_UU_DEC(*s) << 2 | PHP_UU_DEC(*(s + 1)) >> 4;
if (len > 1) {
*p++ = PHP_UU_DEC(*(s + 1)) << 4 | PHP_UU_DEC(*(s + 2)) >> 2;
if (len > 2) {
*p++ = PHP_UU_DEC(*(s + 2)) << 6 | PHP_UU_DEC(*(s + 3));
}
}
}
ret.setSize(total_len);
return ret;
err:
return String();
}
///////////////////////////////////////////////////////////////////////////////
// base64
namespace {
const char base64_table[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', '\0'
};
const char base64_pad = '=';
const short base64_reverse_table[256] = {
-2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -2, -2, -1, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, -2, -2, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2, -2, -2, -2, -2,
-2, 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, -2, -2, -2, -2, -2,
-2, 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, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2
};
folly::Optional<int> maxEncodedSize(int length) {
if ((length + 2) < 0 || ((length + 2) / 3) >= (1 << (sizeof(int) * 8 - 2))) {
return folly::none;
}
return ((length + 2) / 3) * 4;
}
// outstr must be at least maxEncodedSize(length) bytes
size_t php_base64_encode(const unsigned char *str, int length,
unsigned char* outstr) {
const unsigned char *current = str;
unsigned char *p = outstr;
while (length > 2) { /* keep going until we have less than 24 bits */
*p++ = base64_table[current[0] >> 2];
*p++ = base64_table[((current[0] & 0x03) << 4) + (current[1] >> 4)];
*p++ = base64_table[((current[1] & 0x0f) << 2) + (current[2] >> 6)];
*p++ = base64_table[current[2] & 0x3f];
current += 3;
length -= 3; /* we just handle 3 octets of data */
}
/* now deal with the tail end of things */
if (length != 0) {
*p++ = base64_table[current[0] >> 2];
if (length > 1) {
*p++ = base64_table[((current[0] & 0x03) << 4) + (current[1] >> 4)];
*p++ = base64_table[(current[1] & 0x0f) << 2];
*p++ = base64_pad;
} else {
*p++ = base64_table[(current[0] & 0x03) << 4];
*p++ = base64_pad;
*p++ = base64_pad;
}
}
return p - outstr;
}
// outstr must be at least length bytes
ssize_t php_base64_decode(const char *str, int length, bool strict,
unsigned char* outstr) {
const unsigned char *current = (unsigned char*)str;
int ch, i = 0, j = 0, k;
/* this sucks for threaded environments */
unsigned char* result = outstr;
/* run through the whole string, converting as we go */
while ((ch = *current++) != '\0' && length-- > 0) {
if (ch == base64_pad) {
if (*current != '=' && ((i % 4) == 1 || (strict && length > 0))) {
if ((i % 4) != 1) {
while (isspace(*(++current))) {
continue;
}
if (*current == '\0') {
continue;
}
}
return -1;
}
continue;
}
ch = base64_reverse_table[ch];
if ((!strict && ch < 0) || ch == -1) {
/* a space or some other separator character, we simply skip over */
continue;
} else if (ch == -2) {
return -1;
}
switch(i % 4) {
case 0:
result[j] = ch << 2;
break;
case 1:
result[j++] |= ch >> 4;
result[j] = (ch & 0x0f) << 4;
break;
case 2:
result[j++] |= ch >>2;
result[j] = (ch & 0x03) << 6;
break;
case 3:
result[j++] |= ch;
break;
}
i++;
}
k = j;
/* mop things up if we ended on a boundary */
if (ch == base64_pad) {
switch(i % 4) {
case 1:
return -1;
case 2:
k++;
case 3:
result[k] = 0;
}
}
return j;
}
}
String string_base64_encode(const char* input, int len) {
if (auto const wantedSize = maxEncodedSize(len)) {
String ret(*wantedSize, ReserveString);
auto actualSize = php_base64_encode((unsigned char*)input, len,
(unsigned char*)ret.mutableData());
ret.setSize(actualSize);
return ret;
}
return String();
}
String string_base64_decode(const char* input, int len, bool strict) {
String ret(len, ReserveString);
auto actualSize = php_base64_decode(input, len, strict,
(unsigned char*)ret.mutableData());
if (actualSize < 0) return String();
ret.setSize(actualSize);
return ret;
}
std::string base64_encode(const char* input, int len) {
if (auto const wantedSize = maxEncodedSize(len)) {
std::string ret;
ret.resize(*wantedSize);
auto actualSize = php_base64_encode((unsigned char*)input, len,
(unsigned char*)ret.data());
ret.resize(actualSize);
return ret;
}
return std::string();
}
std::string base64_decode(const char* input, int len, bool strict) {
if (!len) return std::string();
std::string ret;
ret.resize(len);
auto actualSize = php_base64_decode(input, len, strict,
(unsigned char*)ret.data());
if (!actualSize) return std::string();
ret.resize(actualSize);
return ret;
}
///////////////////////////////////////////////////////////////////////////////
String string_escape_shell_arg(const char *str) {
int x, y, l;
char *cmd;
y = 0;
l = strlen(str);
String ret(safe_address(l, 4, 3), ReserveString); /* worst case */
cmd = ret.mutableData();
#ifdef _MSC_VER
cmd[y++] = '"';
#else
cmd[y++] = '\'';
#endif
for (x = 0; x < l; x++) {
switch (str[x]) {
#ifdef _MSC_VER
case '"':
case '%':
case '!':
cmd[y++] = ' ';
break;
#else
case '\'':
cmd[y++] = '\'';
cmd[y++] = '\\';
cmd[y++] = '\'';
#endif
/* fall-through */
default:
cmd[y++] = str[x];
}
}
#ifdef _MSC_VER
if (y > 0 && '\\' == cmd[y - 1]) {
int k = 0, n = y - 1;
for (; n >= 0 && '\\' == cmd[n]; n--, k++);
if (k % 2) {
cmd[y++] = '\\';
}
}
cmd[y++] = '"';
#else
cmd[y++] = '\'';
#endif
ret.setSize(y);
return ret;
}
String string_escape_shell_cmd(const char *str) {
register int x, y, l;
char *cmd;
char *p = nullptr;
l = strlen(str);
String ret(safe_address(l, 2, 1), ReserveString);
cmd = ret.mutableData();
for (x = 0, y = 0; x < l; x++) {
switch (str[x]) {
#ifndef _MSC_VER
case '"':
case '\'':
if (!p && (p = (char *)memchr(str + x + 1, str[x], l - x - 1))) {
/* noop */
} else if (p && *p == str[x]) {
p = nullptr;
} else {
cmd[y++] = '\\';
}
cmd[y++] = str[x];
break;
#else
/* % is Windows specific for environmental variables, ^%PATH% will
output PATH while ^%PATH^% will not. escapeshellcmd->val will
escape all % and !.
*/
case '%':
case '!':
case '"':
case '\'':
#endif
case '#': /* This is character-set independent */
case '&':
case ';':
case '`':
case '|':
case '*':
case '?':
case '~':
case '<':
case '>':
case '^':
case '(':
case ')':
case '[':
case ']':
case '{':
case '}':
case '$':
case '\\':
case '\x0A': /* excluding these two */
case '\xFF':
#ifdef _MSC_VER
cmd[y++] = '^';
#else
cmd[y++] = '\\';
#endif
/* fall-through */
default:
cmd[y++] = str[x];
}
}
ret.setSize(y);
return ret;
}
///////////////////////////////////////////////////////////////////////////////
static void string_similar_str(const char *txt1, int len1,
const char *txt2, int len2,
int *pos1, int *pos2, int *max) {
const char *p, *q;
const char *end1 = txt1 + len1;
const char *end2 = txt2 + len2;
int l;
*max = 0;
for (p = txt1; p < end1; p++) {
for (q = txt2; q < end2; q++) {
for (l = 0; (p + l < end1) && (q + l < end2) && (p[l] == q[l]); l++);
if (l > *max) {
*max = l;
*pos1 = p - txt1;
*pos2 = q - txt2;
}
}
}
}
static int string_similar_char(const char *txt1, int len1,
const char *txt2, int len2) {
int sum;
int pos1 = 0, pos2 = 0, max;
string_similar_str(txt1, len1, txt2, len2, &pos1, &pos2, &max);
if ((sum = max)) {
if (pos1 && pos2) {
sum += string_similar_char(txt1, pos1, txt2, pos2);
}
if ((pos1 + max < len1) && (pos2 + max < len2)) {
sum += string_similar_char(txt1 + pos1 + max, len1 - pos1 - max,
txt2 + pos2 + max, len2 - pos2 - max);
}
}
return sum;
}
int string_similar_text(const char *t1, int len1,
const char *t2, int len2, float *percent) {
if (len1 == 0 && len2 == 0) {
if (percent) *percent = 0.0;
return 0;
}
int sim = string_similar_char(t1, len1, t2, len2);
if (percent) *percent = sim * 200.0 / (len1 + len2);
return sim;
}
///////////////////////////////////////////////////////////////////////////////
#define LEVENSHTEIN_MAX_LENTH 255
// reference implementation, only optimized for memory usage, not speed
int string_levenshtein(const char *s1, int l1, const char *s2, int l2,
int cost_ins, int cost_rep, int cost_del ) {
int *p1, *p2, *tmp;
int i1, i2, c0, c1, c2;
if (l1==0) return l2*cost_ins;
if (l2==0) return l1*cost_del;
if ((l1>LEVENSHTEIN_MAX_LENTH)||(l2>LEVENSHTEIN_MAX_LENTH)) {
raise_warning("levenshtein(): Argument string(s) too long");
return -1;
}
p1 = (int*)req::malloc_noptrs((l2+1) * sizeof(int));
SCOPE_EXIT { req::free(p1); };
p2 = (int*)req::malloc_noptrs((l2+1) * sizeof(int));
SCOPE_EXIT { req::free(p2); };
for(i2=0;i2<=l2;i2++) {
p1[i2] = i2*cost_ins;
}
for(i1=0;i1<l1;i1++) {
p2[0]=p1[0]+cost_del;
for(i2=0;i2<l2;i2++) {
c0=p1[i2]+((s1[i1]==s2[i2])?0:cost_rep);
c1=p1[i2+1]+cost_del; if (c1<c0) c0=c1;
c2=p2[i2]+cost_ins; if (c2<c0) c0=c2;
p2[i2+1]=c0;
}
tmp=p1; p1=p2; p2=tmp;
}
c0=p1[l2];
return c0;
}
///////////////////////////////////////////////////////////////////////////////
String string_money_format(const char *format, double value) {
bool check = false;
const char *p = format;
while ((p = strchr(p, '%'))) {
if (*(p + 1) == '%') {
p += 2;
} else if (!check) {
check = true;
p++;
} else {
throw_invalid_argument
("format: Only a single %%i or %%n token can be used");
return String();
}
}
int format_len = strlen(format);
int str_len = safe_address(format_len, 1, 1024);
String ret(str_len, ReserveString);
char *str = ret.mutableData();
if ((str_len = strfmon(str, str_len, format, value)) < 0) {
return String();
}
ret.setSize(str_len);
return ret;
}
///////////////////////////////////////////////////////////////////////////////
String string_number_format(double d, int dec,
const String& dec_point,
const String& thousand_sep) {
char *tmpbuf = nullptr, *resbuf;
char *s, *t; /* source, target */
char *dp;
int integral;
int tmplen, reslen=0;
int count=0;
int is_negative=0;
if (d < 0) {
is_negative = 1;
d = -d;
}
if (dec < 0) dec = 0;
d = php_math_round(d, dec);
// departure from PHP: we got rid of dependencies on spprintf() here.
// This actually means 63 bytes for characters + 1 byte for '\0'
String tmpstr(63, ReserveString);
tmpbuf = tmpstr.mutableData();
tmplen = snprintf(tmpbuf, 64, "%.*F", dec, d);
// From the man page of snprintf, the return value is:
// The number of characters that would have been written if n had been
// sufficiently large, not counting the terminating null character.
if (tmplen < 0) return empty_string();
if (tmplen < 64 && (tmpbuf == nullptr || !isdigit((int)tmpbuf[0]))) {
tmpstr.setSize(tmplen);
return tmpstr;
}
if (tmplen >= 64) {
// Uncommon, asked for more than 64 chars worth of precision
tmpstr = String(tmplen, ReserveString);
tmpbuf = tmpstr.mutableData();
tmplen = snprintf(tmpbuf, tmplen + 1, "%.*F", dec, d);
if (tmplen < 0) return empty_string();
if (tmpbuf == nullptr || !isdigit((int)tmpbuf[0])) {
tmpstr.setSize(tmplen);
return tmpstr;
}
}
/* find decimal point, if expected */
if (dec) {
dp = strpbrk(tmpbuf, ".,");
} else {
dp = nullptr;
}
/* calculate the length of the return buffer */
if (dp) {
integral = dp - tmpbuf;
} else {
/* no decimal point was found */
integral = tmplen;
}
/* allow for thousand separators */
if (!thousand_sep.empty()) {
if (integral + thousand_sep.size() * ((integral-1) / 3) < integral) {
/* overflow */
raise_error("String overflow");
}
integral += ((integral-1) / 3) * thousand_sep.size();
}
reslen = integral;
if (dec) {
reslen += dec;
if (!dec_point.empty()) {
if (reslen + dec_point.size() < dec_point.size()) {
/* overflow */
raise_error("String overflow");
}
reslen += dec_point.size();
}
}
/* add a byte for minus sign */
if (is_negative) {
reslen++;
}
String resstr(reslen, ReserveString);
resbuf = resstr.mutableData();
s = tmpbuf+tmplen-1;
t = resbuf+reslen-1;
/* copy the decimal places.
* Take care, as the sprintf implementation may return less places than
* we requested due to internal buffer limitations */
if (dec) {
int declen = dp ? s - dp : 0;
int topad = dec > declen ? dec - declen : 0;
/* pad with '0's */
while (topad--) {
*t-- = '0';
}
if (dp) {
s -= declen + 1; /* +1 to skip the point */
t -= declen;
/* now copy the chars after the point */
memcpy(t + 1, dp + 1, declen);
}
/* add decimal point */
if (!dec_point.empty()) {
memcpy(t + (1 - dec_point.size()), dec_point.data(), dec_point.size());
t -= dec_point.size();
}
}
/* copy the numbers before the decimal point, adding thousand
* separator every three digits */
while(s >= tmpbuf) {
*t-- = *s--;
if (thousand_sep && (++count%3)==0 && s>=tmpbuf) {
memcpy(t + (1 - thousand_sep.size()),
thousand_sep.data(),
thousand_sep.size());
t -= thousand_sep.size();
}
}
/* and a minus sign, if needed */
if (is_negative) {
*t-- = '-';
}
resstr.setSize(reslen);
return resstr;
}
///////////////////////////////////////////////////////////////////////////////
// soundex
/* Simple soundex algorithm as described by Knuth in TAOCP, vol 3 */
String string_soundex(const String& str) {
assertx(!str.empty());
int _small, code, last;
String retString(4, ReserveString);
char* soundex = retString.mutableData();
static char soundex_table[26] = {
0, /* A */
'1', /* B */
'2', /* C */
'3', /* D */
0, /* E */
'1', /* F */
'2', /* G */
0, /* H */
0, /* I */
'2', /* J */
'2', /* K */
'4', /* L */
'5', /* M */
'5', /* N */
0, /* O */
'1', /* P */
'2', /* Q */
'6', /* R */
'2', /* S */
'3', /* T */
0, /* U */
'1', /* V */
0, /* W */
'2', /* X */
0, /* Y */
'2' /* Z */
};
/* build soundex string */
last = -1;
auto p = str.slice().data();
for (_small = 0; *p && _small < 4; p++) {
/* convert chars to upper case and strip non-letter chars */
/* BUG: should also map here accented letters used in non */
/* English words or names (also found in English text!): */
/* esstsett, thorn, n-tilde, c-cedilla, s-caron, ... */
code = toupper((int)(unsigned char)(*p));
if (code >= 'A' && code <= 'Z') {
if (_small == 0) {
/* remember first valid char */
soundex[_small++] = code;
last = soundex_table[code - 'A'];
} else {
/* ignore sequences of consonants with same soundex */
/* code in trail, and vowels unless they separate */
/* consonant letters */
code = soundex_table[code - 'A'];
if (code != last) {
if (code != 0) {
soundex[_small++] = code;
}
last = code;
}
}
}
}
/* pad with '0' and terminate with 0 ;-) */
while (_small < 4) {
soundex[_small++] = '0';
}
retString.setSize(4);
return retString;
}
///////////////////////////////////////////////////////////////////////////////
// metaphone
/**
* this is now the original code by Michael G Schwern:
* i've changed it just a slightly bit (use emalloc,
* get rid of includes etc)
* - thies - 13.09.1999
*/
/*----------------------------- */
/* this used to be "metaphone.h" */
/*----------------------------- */
/* Special encodings */
#define SH 'X'
#define TH '0'
/*----------------------------- */
/* end of "metaphone.h" */
/*----------------------------- */
/*----------------------------- */
/* this used to be "metachar.h" */
/*----------------------------- */
/* Metachar.h ... little bits about characters for metaphone */
/*-- Character encoding array & accessing macros --*/
/* Stolen directly out of the book... */
char _codes[26] = { 1,16,4,16,9,2,4,16,9,2,0,2,2,2,1,4,0,2,4,4,1,0,0,0,8,0};
#define ENCODE(c) (isalpha(c) ? _codes[((toupper(c)) - 'A')] : 0)
#define isvowel(c) (ENCODE(c) & 1) /* AEIOU */
/* These letters are passed through unchanged */
#define NOCHANGE(c) (ENCODE(c) & 2) /* FJMNR */
/* These form dipthongs when preceding H */
#define AFFECTH(c) (ENCODE(c) & 4) /* CGPST */
/* These make C and G soft */
#define MAKESOFT(c) (ENCODE(c) & 8) /* EIY */
/* These prevent GH from becoming F */
#define NOGHTOF(c) (ENCODE(c) & 16) /* BDH */
/*----------------------------- */
/* end of "metachar.h" */
/*----------------------------- */
/* I suppose I could have been using a character pointer instead of
* accesssing the array directly... */
/* Look at the next letter in the word */
#define Next_Letter ((char)toupper(word[w_idx+1]))
/* Look at the current letter in the word */
#define Curr_Letter ((char)toupper(word[w_idx]))
/* Go N letters back. */
#define Look_Back_Letter(n) (w_idx >= n ? (char)toupper(word[w_idx-n]) : '\0')
/* Previous letter. I dunno, should this return null on failure? */
#define Prev_Letter (Look_Back_Letter(1))
/* Look two letters down. It makes sure you don't walk off the string. */
#define After_Next_Letter (Next_Letter != '\0' ? (char)toupper(word[w_idx+2]) \
: '\0')
#define Look_Ahead_Letter(n) ((char)toupper(Lookahead(word+w_idx, n)))
/* Allows us to safely look ahead an arbitrary # of letters */
/* I probably could have just used strlen... */
static char Lookahead(unsigned char *word, int how_far) {
char letter_ahead = '\0'; /* null by default */
int idx;
for (idx = 0; word[idx] != '\0' && idx < how_far; idx++);
/* Edge forward in the string... */
letter_ahead = (char)word[idx]; /* idx will be either == to how_far or
* at the end of the string
*/
return letter_ahead;
}
/* phonize one letter
* We don't know the buffers size in advance. On way to solve this is to just
* re-allocate the buffer size. We're using an extra of 2 characters (this
* could be one though; or more too). */
#define Phonize(c) { buffer.append(c); }
/* How long is the phoned word? */
#define Phone_Len (buffer.size())
/* Note is a letter is a 'break' in the word */
#define Isbreak(c) (!isalpha(c))
String string_metaphone(const char *input, int word_len, long max_phonemes,
int traditional) {
unsigned char *word = (unsigned char *)input;
int w_idx = 0; /* point in the phonization we're at. */
int max_buffer_len = 0; /* maximum length of the destination buffer */
/*-- Parameter checks --*/
/* Negative phoneme length is meaningless */
if (max_phonemes < 0)
return String();
/* Empty/null string is meaningless */
/* Overly paranoid */
/* always_assert(word != NULL && word[0] != '\0'); */
if (word == nullptr)
return String();
/*-- Allocate memory for our phoned_phrase --*/
if (max_phonemes == 0) { /* Assume largest possible */
max_buffer_len = word_len;
} else {
max_buffer_len = max_phonemes;
}
StringBuffer buffer(max_buffer_len);
/*-- The first phoneme has to be processed specially. --*/
/* Find our first letter */
for (; !isalpha(Curr_Letter); w_idx++) {
/* On the off chance we were given nothing but crap... */
if (Curr_Letter == '\0') {
return buffer.detach(); /* For testing */
}
}
switch (Curr_Letter) {
/* AE becomes E */
case 'A':
if (Next_Letter == 'E') {
Phonize('E');
w_idx += 2;
}
/* Remember, preserve vowels at the beginning */
else {
Phonize('A');
w_idx++;
}
break;
/* [GKP]N becomes N */
case 'G':
case 'K':
case 'P':
if (Next_Letter == 'N') {
Phonize('N');
w_idx += 2;
}
break;
/* WH becomes H,
WR becomes R
W if followed by a vowel */
case 'W':
if (Next_Letter == 'H' ||
Next_Letter == 'R') {
Phonize(Next_Letter);
w_idx += 2;
} else if (isvowel(Next_Letter)) {
Phonize('W');
w_idx += 2;
}
/* else ignore */
break;
/* X becomes S */
case 'X':
Phonize('S');
w_idx++;
break;
/* Vowels are kept */
/* We did A already
case 'A':
case 'a':
*/
case 'E':
case 'I':
case 'O':
case 'U':
Phonize(Curr_Letter);
w_idx++;
break;
default:
/* do nothing */
break;
}
/* On to the metaphoning */
for (; Curr_Letter != '\0' &&
(max_phonemes == 0 || Phone_Len < max_phonemes);
w_idx++) {
/* How many letters to skip because an eariler encoding handled
* multiple letters */
unsigned short int skip_letter = 0;
/* THOUGHT: It would be nice if, rather than having things like...
* well, SCI. For SCI you encode the S, then have to remember
* to skip the C. So the phonome SCI invades both S and C. It would
* be better, IMHO, to skip the C from the S part of the encoding.
* Hell, I'm trying it.
*/
/* Ignore non-alphas */
if (!isalpha(Curr_Letter))
continue;
/* Drop duplicates, except CC */
if (Curr_Letter == Prev_Letter &&
Curr_Letter != 'C')
continue;
switch (Curr_Letter) {
/* B -> B unless in MB */
case 'B':
if (Prev_Letter != 'M')
Phonize('B');
break;
/* 'sh' if -CIA- or -CH, but not SCH, except SCHW.
* (SCHW is handled in S)
* S if -CI-, -CE- or -CY-
* dropped if -SCI-, SCE-, -SCY- (handed in S)
* else K
*/
case 'C':
if (MAKESOFT(Next_Letter)) { /* C[IEY] */
if (After_Next_Letter == 'A' &&
Next_Letter == 'I') { /* CIA */
Phonize(SH);
}
/* SC[IEY] */
else if (Prev_Letter == 'S') {
/* Dropped */
} else {
Phonize('S');
}
} else if (Next_Letter == 'H') {
if ((!traditional) && (After_Next_Letter == 'R' ||
Prev_Letter == 'S')) { /* Christ, School */
Phonize('K');
} else {
Phonize(SH);
}
skip_letter++;
} else {
Phonize('K');
}
break;
/* J if in -DGE-, -DGI- or -DGY-
* else T
*/
case 'D':
if (Next_Letter == 'G' && MAKESOFT(After_Next_Letter)) {
Phonize('J');
skip_letter++;
} else
Phonize('T');
break;
/* F if in -GH and not B--GH, D--GH, -H--GH, -H---GH
* else dropped if -GNED, -GN,
* else dropped if -DGE-, -DGI- or -DGY- (handled in D)
* else J if in -GE-, -GI, -GY and not GG
* else K
*/
case 'G':
if (Next_Letter == 'H') {
if (!(NOGHTOF(Look_Back_Letter(3)) || Look_Back_Letter(4) == 'H')) {
Phonize('F');
skip_letter++;
} else {
/* silent */
}
} else if (Next_Letter == 'N') {
if (Isbreak(After_Next_Letter) ||
(After_Next_Letter == 'E' && Look_Ahead_Letter(3) == 'D')) {
/* dropped */
} else
Phonize('K');
} else if (MAKESOFT(Next_Letter) && Prev_Letter != 'G') {
Phonize('J');
} else {
Phonize('K');
}
break;
/* H if before a vowel and not after C,G,P,S,T */
case 'H':
if (isvowel(Next_Letter) && !AFFECTH(Prev_Letter))
Phonize('H');
break;
/* dropped if after C
* else K
*/
case 'K':
if (Prev_Letter != 'C')
Phonize('K');
break;
/* F if before H
* else P
*/
case 'P':
if (Next_Letter == 'H') {
Phonize('F');
} else {
Phonize('P');
}
break;
/* K
*/
case 'Q':
Phonize('K');
break;
/* 'sh' in -SH-, -SIO- or -SIA- or -SCHW-
* else S
*/
case 'S':
if (Next_Letter == 'I' &&
(After_Next_Letter == 'O' || After_Next_Letter == 'A')) {
Phonize(SH);
} else if (Next_Letter == 'H') {
Phonize(SH);
skip_letter++;
} else if ((!traditional) &&
(Next_Letter == 'C' && Look_Ahead_Letter(2) == 'H' &&
Look_Ahead_Letter(3) == 'W')) {
Phonize(SH);
skip_letter += 2;
} else {
Phonize('S');
}
break;
/* 'sh' in -TIA- or -TIO-
* else 'th' before H
* else T
*/
case 'T':
if (Next_Letter == 'I' &&
(After_Next_Letter == 'O' || After_Next_Letter == 'A')) {
Phonize(SH);
} else if (Next_Letter == 'H') {
Phonize(TH);
skip_letter++;
} else {
Phonize('T');
}
break;
/* F */
case 'V':
Phonize('F');
break;
/* W before a vowel, else dropped */
case 'W':
if (isvowel(Next_Letter))
Phonize('W');
break;
/* KS */
case 'X':
Phonize('K');
Phonize('S');
break;
/* Y if followed by a vowel */
case 'Y':
if (isvowel(Next_Letter))
Phonize('Y');
break;
/* S */
case 'Z':
Phonize('S');
break;
/* No transformation */
case 'F':
case 'J':
case 'L':
case 'M':
case 'N':
case 'R':
Phonize(Curr_Letter);
break;
default:
/* nothing */
break;
} /* END SWITCH */
w_idx += skip_letter;
} /* END FOR */
return buffer.detach();
}
///////////////////////////////////////////////////////////////////////////////
// Cyrillic
/**
* This is codetables for different Cyrillic charsets (relative to koi8-r).
* Each table contains data for 128-255 symbols from ASCII table.
* First 256 symbols are for conversion from koi8-r to corresponding charset,
* second 256 symbols are for reverse conversion, from charset to koi8-r.
*
* Here we have the following tables:
* _cyr_win1251 - for windows-1251 charset
* _cyr_iso88595 - for iso8859-5 charset
* _cyr_cp866 - for x-cp866 charset
* _cyr_mac - for x-mac-cyrillic charset
*/
typedef unsigned char _cyr_charset_table[512];
static const _cyr_charset_table _cyr_win1251 = {
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,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,
46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,
154,174,190,46,159,189,46,46,179,191,180,157,46,46,156,183,
46,46,182,166,173,46,46,158,163,152,164,155,46,46,46,167,
225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240,
242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241,
193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208,
210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,209,
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,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,184,186,32,179,191,32,32,32,32,32,180,162,32,
32,32,32,168,170,32,178,175,32,32,32,32,32,165,161,169,
254,224,225,246,228,229,244,227,245,232,233,234,235,236,237,238,
239,255,240,241,242,243,230,226,252,251,231,248,253,249,247,250,
222,192,193,214,196,197,212,195,213,200,201,202,203,204,205,206,
207,223,208,209,210,211,198,194,220,219,199,216,221,217,215,218,
};
static const _cyr_charset_table _cyr_cp866 = {
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,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240,
242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241,
193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208,
35,35,35,124,124,124,124,43,43,124,124,43,43,43,43,43,
43,45,45,124,45,43,124,124,43,43,45,45,124,45,43,45,
45,45,45,43,43,43,43,43,43,43,43,35,35,124,124,35,
210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,209,
179,163,180,164,183,167,190,174,32,149,158,32,152,159,148,154,
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,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
205,186,213,241,243,201,32,245,187,212,211,200,190,32,247,198,
199,204,181,240,242,185,32,244,203,207,208,202,216,32,246,32,
238,160,161,230,164,165,228,163,229,168,169,170,171,172,173,174,
175,239,224,225,226,227,166,162,236,235,167,232,237,233,231,234,
158,128,129,150,132,133,148,131,149,136,137,138,139,140,141,142,
143,159,144,145,146,147,134,130,156,155,135,152,157,153,151,154,
};
static const _cyr_charset_table _cyr_iso88595 = {
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,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,179,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240,
242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241,
193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208,
210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,209,
32,163,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
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,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,241,32,32,32,32,32,32,32,32,32,32,32,32,
32,32,32,161,32,32,32,32,32,32,32,32,32,32,32,32,
238,208,209,230,212,213,228,211,229,216,217,218,219,220,221,222,
223,239,224,225,226,227,214,210,236,235,215,232,237,233,231,234,
206,176,177,198,180,181,196,179,197,184,185,186,187,188,189,190,
191,207,192,193,194,195,182,178,204,203,183,200,205,201,199,202,
};
static const _cyr_charset_table _cyr_mac = {
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,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240,
242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241,
160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
144,145,146,147,148,149,150,151,152,153,154,155,156,179,163,209,
193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208,
210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,255,
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,59,60,61,62,63,
64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
160,161,162,222,164,165,166,167,168,169,170,171,172,173,174,175,
176,177,178,221,180,181,182,183,184,185,186,187,188,189,190,191,
254,224,225,246,228,229,244,227,245,232,233,234,235,236,237,238,
239,223,240,241,242,243,230,226,252,251,231,248,253,249,247,250,
158,128,129,150,132,133,148,131,149,136,137,138,139,140,141,142,
143,159,144,145,146,147,134,130,156,155,135,152,157,153,151,154,
};
/**
* This is the function that performs real in-place conversion of the string
* between charsets.
* Parameters:
* str - string to be converted
* from,to - one-symbol label of source and destination charset
* The following symbols are used as labels:
* k - koi8-r
* w - windows-1251
* i - iso8859-5
* a - x-cp866
* d - x-cp866
* m - x-mac-cyrillic
*/
String string_convert_cyrillic_string(const String& input, char from, char to) {
const unsigned char *from_table, *to_table;
unsigned char tmp;
auto uinput = (unsigned char*)input.slice().data();
String retString(input.size(), ReserveString);
unsigned char *str = (unsigned char *)retString.mutableData();
from_table = nullptr;
to_table = nullptr;
switch (toupper((int)(unsigned char)from)) {
case 'W': from_table = _cyr_win1251; break;
case 'A':
case 'D': from_table = _cyr_cp866; break;
case 'I': from_table = _cyr_iso88595; break;
case 'M': from_table = _cyr_mac; break;
case 'K':
break;
default:
throw_invalid_argument("Unknown source charset: %c", from);
break;
}
switch (toupper((int)(unsigned char)to)) {
case 'W': to_table = _cyr_win1251; break;
case 'A':
case 'D': to_table = _cyr_cp866; break;
case 'I': to_table = _cyr_iso88595; break;
case 'M': to_table = _cyr_mac; break;
case 'K':
break;
default:
throw_invalid_argument("Unknown destination charset: %c", to);
break;
}
for (int i = 0; i < input.size(); i++) {
tmp = from_table == nullptr ? uinput[i] : from_table[uinput[i]];
str[i] = to_table == nullptr ? tmp : to_table[tmp + 256];
}
retString.setSize(input.size());
return retString;
}
///////////////////////////////////////////////////////////////////////////////
// Hebrew
#define HEB_BLOCK_TYPE_ENG 1
#define HEB_BLOCK_TYPE_HEB 2
#define isheb(c) \
(((((unsigned char) c) >= 224) && (((unsigned char) c) <= 250)) ? 1 : 0)
#define _isblank(c) \
(((((unsigned char) c) == ' ' || ((unsigned char) c) == '\t')) ? 1 : 0)
#define _isnewline(c) \
(((((unsigned char) c) == '\n' || ((unsigned char) c) == '\r')) ? 1 : 0)
/**
* Converts Logical Hebrew text (Hebrew Windows style) to Visual text
* Cheers/complaints/flames - Zeev Suraski <zeev@php.net>
*/
String
string_convert_hebrew_string(const String& inStr, int /*max_chars_per_line*/,
int convert_newlines) {
assertx(!inStr.empty());
auto str = inStr.data();
auto str_len = inStr.size();
const char *tmp;
char *heb_str, *broken_str;
char *target;
int block_start, block_end, block_type, block_length, i;
long max_chars=0;
int begin, end, char_count, orig_begin;
tmp = str;
block_start=block_end=0;
heb_str = (char *) req::malloc_noptrs(str_len + 1);
SCOPE_EXIT { req::free(heb_str); };
target = heb_str+str_len;
*target = 0;
target--;
block_length=0;
if (isheb(*tmp)) {
block_type = HEB_BLOCK_TYPE_HEB;
} else {
block_type = HEB_BLOCK_TYPE_ENG;
}
do {
if (block_type == HEB_BLOCK_TYPE_HEB) {
while ((isheb((int)*(tmp+1)) ||
_isblank((int)*(tmp+1)) ||
ispunct((int)*(tmp+1)) ||
(int)*(tmp+1)=='\n' ) && block_end<str_len-1) {
tmp++;
block_end++;
block_length++;
}
for (i = block_start; i<= block_end; i++) {
*target = str[i];
switch (*target) {
case '(': *target = ')'; break;
case ')': *target = '('; break;
case '[': *target = ']'; break;
case ']': *target = '['; break;
case '{': *target = '}'; break;
case '}': *target = '{'; break;
case '<': *target = '>'; break;
case '>': *target = '<'; break;
case '\\': *target = '/'; break;
case '/': *target = '\\'; break;
default:
break;
}
target--;
}
block_type = HEB_BLOCK_TYPE_ENG;
} else {
while (!isheb(*(tmp+1)) &&
(int)*(tmp+1)!='\n' && block_end < str_len-1) {
tmp++;
block_end++;
block_length++;
}
while ((_isblank((int)*tmp) ||
ispunct((int)*tmp)) && *tmp!='/' &&
*tmp!='-' && block_end > block_start) {
tmp--;
block_end--;
}
for (i = block_end; i >= block_start; i--) {
*target = str[i];
target--;
}
block_type = HEB_BLOCK_TYPE_HEB;
}
block_start=block_end+1;
} while (block_end < str_len-1);
String brokenStr(str_len, ReserveString);
broken_str = brokenStr.mutableData();
begin=end=str_len-1;
target = broken_str;
while (1) {
char_count=0;
while ((!max_chars || char_count < max_chars) && begin > 0) {
char_count++;
begin--;
if (begin <= 0 || _isnewline(heb_str[begin])) {
while (begin > 0 && _isnewline(heb_str[begin-1])) {
begin--;
char_count++;
}
break;
}
}
if (char_count == max_chars) { /* try to avoid breaking words */
int new_char_count=char_count, new_begin=begin;
while (new_char_count > 0) {
if (_isblank(heb_str[new_begin]) || _isnewline(heb_str[new_begin])) {
break;
}
new_begin++;
new_char_count--;
}
if (new_char_count > 0) {
char_count=new_char_count;
begin=new_begin;
}
}
orig_begin=begin;
if (_isblank(heb_str[begin])) {
heb_str[begin]='\n';
}
while (begin <= end && _isnewline(heb_str[begin])) {
/* skip leading newlines */
begin++;
}
for (i = begin; i <= end; i++) { /* copy content */
*target = heb_str[i];
target++;
}
for (i = orig_begin; i <= end && _isnewline(heb_str[i]); i++) {
*target = heb_str[i];
target++;
}
begin=orig_begin;
if (begin <= 0) {
*target = 0;
break;
}
begin--;
end=begin;
}
if (convert_newlines) {
int count;
auto ret = string_replace(broken_str, str_len, "\n", strlen("\n"),
"<br />\n", strlen("<br />\n"), count, true);
if (!ret.isNull()) {
return ret;
}
}
brokenStr.setSize(str_len);
return brokenStr;
}
///////////////////////////////////////////////////////////////////////////////
}
| ./CrossVul/dataset_final_sorted/CWE-119/cpp/good_846_0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.