id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_bad_276_1
/* This file is part of libmspack. * (C) 2003-2011 Stuart Caie. * * libmspack is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License (LGPL) version 2.1 * * For further details, see the file COPYING.LIB distributed with libmspack */ /* CHM decompression implementation */ #include <system.h> #include <chm.h> /* prototypes */ static struct mschmd_header * chmd_open( struct mschm_decompressor *base, const char *filename); static struct mschmd_header * chmd_fast_open( struct mschm_decompressor *base, const char *filename); static struct mschmd_header *chmd_real_open( struct mschm_decompressor *base, const char *filename, int entire); static void chmd_close( struct mschm_decompressor *base, struct mschmd_header *chm); static int chmd_read_headers( struct mspack_system *sys, struct mspack_file *fh, struct mschmd_header *chm, int entire); static int chmd_fast_find( struct mschm_decompressor *base, struct mschmd_header *chm, const char *filename, struct mschmd_file *f_ptr, int f_size); static unsigned char *read_chunk( struct mschm_decompressor_p *self, struct mschmd_header *chm, struct mspack_file *fh, unsigned int chunk); static int search_chunk( struct mschmd_header *chm, const unsigned char *chunk, const char *filename, const unsigned char **result, const unsigned char **result_end); static inline int compare( const char *s1, const char *s2, int l1, int l2); static int chmd_extract( struct mschm_decompressor *base, struct mschmd_file *file, const char *filename); static int chmd_sys_write( struct mspack_file *file, void *buffer, int bytes); static int chmd_init_decomp( struct mschm_decompressor_p *self, struct mschmd_file *file); static int read_reset_table( struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, int entry, off_t *length_ptr, off_t *offset_ptr); static int read_spaninfo( struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, off_t *length_ptr); static int find_sys_file( struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, struct mschmd_file **f_ptr, const char *name); static unsigned char *read_sys_file( struct mschm_decompressor_p *self, struct mschmd_file *file); static int chmd_error( struct mschm_decompressor *base); static int read_off64( off_t *var, unsigned char *mem, struct mspack_system *sys, struct mspack_file *fh); /* filenames of the system files used for decompression. * Content and ControlData are essential. * ResetTable is preferred, but SpanInfo can be used if not available */ static const char *content_name = "::DataSpace/Storage/MSCompressed/Content"; static const char *control_name = "::DataSpace/Storage/MSCompressed/ControlData"; static const char *spaninfo_name = "::DataSpace/Storage/MSCompressed/SpanInfo"; static const char *rtable_name = "::DataSpace/Storage/MSCompressed/Transform/" "{7FC28940-9D31-11D0-9B27-00A0C91E9C7C}/InstanceData/ResetTable"; /*************************************** * MSPACK_CREATE_CHM_DECOMPRESSOR *************************************** * constructor */ struct mschm_decompressor * mspack_create_chm_decompressor(struct mspack_system *sys) { struct mschm_decompressor_p *self = NULL; if (!sys) sys = mspack_default_system; if (!mspack_valid_system(sys)) return NULL; if ((self = (struct mschm_decompressor_p *) sys->alloc(sys, sizeof(struct mschm_decompressor_p)))) { self->base.open = &chmd_open; self->base.close = &chmd_close; self->base.extract = &chmd_extract; self->base.last_error = &chmd_error; self->base.fast_open = &chmd_fast_open; self->base.fast_find = &chmd_fast_find; self->system = sys; self->error = MSPACK_ERR_OK; self->d = NULL; } return (struct mschm_decompressor *) self; } /*************************************** * MSPACK_DESTROY_CAB_DECOMPRESSOR *************************************** * destructor */ void mspack_destroy_chm_decompressor(struct mschm_decompressor *base) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; if (self) { struct mspack_system *sys = self->system; if (self->d) { if (self->d->infh) sys->close(self->d->infh); if (self->d->state) lzxd_free(self->d->state); sys->free(self->d); } sys->free(self); } } /*************************************** * CHMD_OPEN *************************************** * opens a file and tries to read it as a CHM file. * Calls chmd_real_open() with entire=1. */ static struct mschmd_header *chmd_open(struct mschm_decompressor *base, const char *filename) { return chmd_real_open(base, filename, 1); } /*************************************** * CHMD_FAST_OPEN *************************************** * opens a file and tries to read it as a CHM file, but does not read * the file headers. Calls chmd_real_open() with entire=0 */ static struct mschmd_header *chmd_fast_open(struct mschm_decompressor *base, const char *filename) { return chmd_real_open(base, filename, 0); } /*************************************** * CHMD_REAL_OPEN *************************************** * the real implementation of chmd_open() and chmd_fast_open(). It simply * passes the "entire" parameter to chmd_read_headers(), which will then * either read all headers, or a bare mininum. */ static struct mschmd_header *chmd_real_open(struct mschm_decompressor *base, const char *filename, int entire) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; struct mschmd_header *chm = NULL; struct mspack_system *sys; struct mspack_file *fh; int error; if (!base) return NULL; sys = self->system; if ((fh = sys->open(sys, filename, MSPACK_SYS_OPEN_READ))) { if ((chm = (struct mschmd_header *) sys->alloc(sys, sizeof(struct mschmd_header)))) { chm->filename = filename; error = chmd_read_headers(sys, fh, chm, entire); if (error) { /* if the error is DATAFORMAT, and there are some results, return * partial results with a warning, rather than nothing */ if (error == MSPACK_ERR_DATAFORMAT && (chm->files || chm->sysfiles)) { sys->message(fh, "WARNING; contents are corrupt"); error = MSPACK_ERR_OK; } else { chmd_close(base, chm); chm = NULL; } } self->error = error; } else { self->error = MSPACK_ERR_NOMEMORY; } sys->close(fh); } else { self->error = MSPACK_ERR_OPEN; } return chm; } /*************************************** * CHMD_CLOSE *************************************** * frees all memory associated with a given mschmd_header */ static void chmd_close(struct mschm_decompressor *base, struct mschmd_header *chm) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; struct mschmd_file *fi, *nfi; struct mspack_system *sys; unsigned int i; if (!base) return; sys = self->system; self->error = MSPACK_ERR_OK; /* free files */ for (fi = chm->files; fi; fi = nfi) { nfi = fi->next; sys->free(fi); } for (fi = chm->sysfiles; fi; fi = nfi) { nfi = fi->next; sys->free(fi); } /* if this CHM was being decompressed, free decompression state */ if (self->d && (self->d->chm == chm)) { if (self->d->infh) sys->close(self->d->infh); if (self->d->state) lzxd_free(self->d->state); sys->free(self->d); self->d = NULL; } /* if this CHM had a chunk cache, free it and contents */ if (chm->chunk_cache) { for (i = 0; i < chm->num_chunks; i++) sys->free(chm->chunk_cache[i]); sys->free(chm->chunk_cache); } sys->free(chm); } /*************************************** * CHMD_READ_HEADERS *************************************** * reads the basic CHM file headers. If the "entire" parameter is * non-zero, all file entries will also be read. fills out a pre-existing * mschmd_header structure, allocates memory for files as necessary */ /* The GUIDs found in CHM headers */ static const unsigned char guids[32] = { /* {7C01FD10-7BAA-11D0-9E0C-00A0-C922-E6EC} */ 0x10, 0xFD, 0x01, 0x7C, 0xAA, 0x7B, 0xD0, 0x11, 0x9E, 0x0C, 0x00, 0xA0, 0xC9, 0x22, 0xE6, 0xEC, /* {7C01FD11-7BAA-11D0-9E0C-00A0-C922-E6EC} */ 0x11, 0xFD, 0x01, 0x7C, 0xAA, 0x7B, 0xD0, 0x11, 0x9E, 0x0C, 0x00, 0xA0, 0xC9, 0x22, 0xE6, 0xEC }; /* reads an encoded integer into a variable; 7 bits of data per byte, * the high bit is used to indicate that there is another byte */ #define READ_ENCINT(var) do { \ (var) = 0; \ do { \ if (p >= end) goto chunk_end; \ (var) = ((var) << 7) | (*p & 0x7F); \ } while (*p++ & 0x80); \ } while (0) static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mschmd_header *chm, int entire) { unsigned int section, name_len, x, errors, num_chunks; unsigned char buf[0x54], *chunk = NULL, *name, *p, *end; struct mschmd_file *fi, *link = NULL; off_t offset, length; int num_entries; /* initialise pointers */ chm->files = NULL; chm->sysfiles = NULL; chm->chunk_cache = NULL; chm->sec0.base.chm = chm; chm->sec0.base.id = 0; chm->sec1.base.chm = chm; chm->sec1.base.id = 1; chm->sec1.content = NULL; chm->sec1.control = NULL; chm->sec1.spaninfo = NULL; chm->sec1.rtable = NULL; /* read the first header */ if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) { return MSPACK_ERR_READ; } /* check ITSF signature */ if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) { return MSPACK_ERR_SIGNATURE; } /* check both header GUIDs */ if (mspack_memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) { D(("incorrect GUIDs")) return MSPACK_ERR_SIGNATURE; } chm->version = EndGetI32(&buf[chmhead_Version]); chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]); chm->language = EndGetI32(&buf[chmhead_LanguageID]); if (chm->version > 3) { sys->message(fh, "WARNING; CHM version > 3"); } /* read the header section table */ if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) { return MSPACK_ERR_READ; } /* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files. * The offset will be corrected later, once HS1 is read. */ if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) || read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) || read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 0 */ if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 0 */ if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) { return MSPACK_ERR_READ; } if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 1 */ if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 1 */ if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) { return MSPACK_ERR_READ; } chm->dir_offset = sys->tell(fh); chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]); chm->density = EndGetI32(&buf[chmhs1_Density]); chm->depth = EndGetI32(&buf[chmhs1_Depth]); chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]); chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]); chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]); chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]); if (chm->version < 3) { /* versions before 3 don't have chmhst3_OffsetCS0 */ chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks); } /* check if content offset or file size is wrong */ if (chm->sec0.offset > chm->length) { D(("content section begins after file has ended")) return MSPACK_ERR_DATAFORMAT; } /* ensure there are chunks and that chunk size is * large enough for signature and num_entries */ if (chm->chunk_size < (pmgl_Entries + 2)) { D(("chunk size not large enough")) return MSPACK_ERR_DATAFORMAT; } if (chm->num_chunks == 0) { D(("no chunks")) return MSPACK_ERR_DATAFORMAT; } /* The chunk_cache data structure is not great; large values for num_chunks * or num_chunks*chunk_size can exhaust all memory. Until a better chunk * cache is implemented, put arbitrary limits on num_chunks and chunk size. */ if (chm->num_chunks > 100000) { D(("more than 100,000 chunks")) return MSPACK_ERR_DATAFORMAT; } if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) { D(("chunks larger than entire file")) return MSPACK_ERR_DATAFORMAT; } /* common sense checks on header section 1 fields */ if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) { sys->message(fh, "WARNING; chunk size is not a power of two"); } if (chm->first_pmgl != 0) { sys->message(fh, "WARNING; first PMGL chunk is not zero"); } if (chm->first_pmgl > chm->last_pmgl) { D(("first pmgl chunk is after last pmgl chunk")) return MSPACK_ERR_DATAFORMAT; } if (chm->index_root != 0xFFFFFFFF && chm->index_root > chm->num_chunks) { D(("index_root outside valid range")) return MSPACK_ERR_DATAFORMAT; } /* if we are doing a quick read, stop here! */ if (!entire) { return MSPACK_ERR_OK; } /* seek to the first PMGL chunk, and reduce the number of chunks to read */ if ((x = chm->first_pmgl) != 0) { if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) { return MSPACK_ERR_SEEK; } } num_chunks = chm->last_pmgl - x + 1; if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) { return MSPACK_ERR_NOMEMORY; } /* read and process all chunks from FirstPMGL to LastPMGL */ errors = 0; while (num_chunks--) { /* read next chunk */ if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) { sys->free(chunk); return MSPACK_ERR_READ; } /* process only directory (PMGL) chunks */ if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue; if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) { sys->message(fh, "WARNING; PMGL quickref area is too small"); } if (EndGetI32(&chunk[pmgl_QuickRefSize]) > ((int)chm->chunk_size - pmgl_Entries)) { sys->message(fh, "WARNING; PMGL quickref area is too large"); } p = &chunk[pmgl_Entries]; end = &chunk[chm->chunk_size - 2]; num_entries = EndGetI16(end); while (num_entries--) { READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; name = p; p += name_len; READ_ENCINT(section); READ_ENCINT(offset); READ_ENCINT(length); /* empty files and directory names are stored as a file entry at * offset 0 with length 0. We want to keep empty files, but not * directory names, which end with a "/" */ if ((offset == 0) && (length == 0)) { if ((name_len > 0) && (name[name_len-1] == '/')) continue; } if (section > 1) { sys->message(fh, "invalid section number '%u'.", section); continue; } if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) { sys->free(chunk); return MSPACK_ERR_NOMEMORY; } fi->next = NULL; fi->filename = (char *) &fi[1]; fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0) : (struct mschmd_section *) (&chm->sec1)); fi->offset = offset; fi->length = length; sys->copy(name, fi->filename, (size_t) name_len); fi->filename[name_len] = '\0'; if (name[0] == ':' && name[1] == ':') { /* system file */ if (mspack_memcmp(&name[2], &content_name[2], 31L) == 0) { if (mspack_memcmp(&name[33], &content_name[33], 8L) == 0) { chm->sec1.content = fi; } else if (mspack_memcmp(&name[33], &control_name[33], 11L) == 0) { chm->sec1.control = fi; } else if (mspack_memcmp(&name[33], &spaninfo_name[33], 8L) == 0) { chm->sec1.spaninfo = fi; } else if (mspack_memcmp(&name[33], &rtable_name[33], 72L) == 0) { chm->sec1.rtable = fi; } } fi->next = chm->sysfiles; chm->sysfiles = fi; } else { /* normal file */ if (link) link->next = fi; else chm->files = fi; link = fi; } } /* this is reached either when num_entries runs out, or if * reading data from the chunk reached a premature end of chunk */ chunk_end: if (num_entries >= 0) { D(("chunk ended before all entries could be read")) errors++; } } sys->free(chunk); return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK; } /*************************************** * CHMD_FAST_FIND *************************************** * uses PMGI index chunks and quickref data to quickly locate a file * directly from the on-disk index. * * TODO: protect against infinite loops in chunks (where pgml_NextChunk * or a PMGI index entry point to an already visited chunk) */ static int chmd_fast_find(struct mschm_decompressor *base, struct mschmd_header *chm, const char *filename, struct mschmd_file *f_ptr, int f_size) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; struct mspack_system *sys; struct mspack_file *fh; const unsigned char *chunk, *p, *end; int err = MSPACK_ERR_OK, result = -1; unsigned int n, sec; if (!self || !chm || !f_ptr || (f_size != sizeof(struct mschmd_file))) { return MSPACK_ERR_ARGS; } sys = self->system; /* clear the results structure */ memset(f_ptr, 0, f_size); if (!(fh = sys->open(sys, chm->filename, MSPACK_SYS_OPEN_READ))) { return MSPACK_ERR_OPEN; } /* go through PMGI chunk hierarchy to reach PMGL chunk */ if (chm->index_root < chm->num_chunks) { n = chm->index_root; for (;;) { if (!(chunk = read_chunk(self, chm, fh, n))) { sys->close(fh); return self->error; } /* search PMGI/PMGL chunk. exit early if no entry found */ if ((result = search_chunk(chm, chunk, filename, &p, &end)) <= 0) { break; } /* found result. loop around for next chunk if this is PMGI */ if (chunk[3] == 0x4C) break; else READ_ENCINT(n); } } else { /* PMGL chunks only, search from first_pmgl to last_pmgl */ for (n = chm->first_pmgl; n <= chm->last_pmgl; n = EndGetI32(&chunk[pmgl_NextChunk])) { if (!(chunk = read_chunk(self, chm, fh, n))) { err = self->error; break; } /* search PMGL chunk. exit if file found */ if ((result = search_chunk(chm, chunk, filename, &p, &end)) > 0) { break; } /* stop simple infinite loops: can't visit the same chunk twice */ if ((int)n == EndGetI32(&chunk[pmgl_NextChunk])) { break; } } } /* if we found a file, read it */ if (result > 0) { READ_ENCINT(sec); f_ptr->section = (sec == 0) ? (struct mschmd_section *) &chm->sec0 : (struct mschmd_section *) &chm->sec1; READ_ENCINT(f_ptr->offset); READ_ENCINT(f_ptr->length); } else if (result < 0) { err = MSPACK_ERR_DATAFORMAT; } sys->close(fh); return self->error = err; chunk_end: D(("read beyond end of chunk entries")) sys->close(fh); return self->error = MSPACK_ERR_DATAFORMAT; } /* reads the given chunk into memory, storing it in a chunk cache * so it doesn't need to be read from disk more than once */ static unsigned char *read_chunk(struct mschm_decompressor_p *self, struct mschmd_header *chm, struct mspack_file *fh, unsigned int chunk_num) { struct mspack_system *sys = self->system; unsigned char *buf; /* check arguments - most are already checked by chmd_fast_find */ if (chunk_num > chm->num_chunks) return NULL; /* ensure chunk cache is available */ if (!chm->chunk_cache) { size_t size = sizeof(unsigned char *) * chm->num_chunks; if (!(chm->chunk_cache = (unsigned char **) sys->alloc(sys, size))) { self->error = MSPACK_ERR_NOMEMORY; return NULL; } memset(chm->chunk_cache, 0, size); } /* try to answer out of chunk cache */ if (chm->chunk_cache[chunk_num]) return chm->chunk_cache[chunk_num]; /* need to read chunk - allocate memory for it */ if (!(buf = (unsigned char *) sys->alloc(sys, chm->chunk_size))) { self->error = MSPACK_ERR_NOMEMORY; return NULL; } /* seek to block and read it */ if (sys->seek(fh, (off_t) (chm->dir_offset + (chunk_num * chm->chunk_size)), MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; sys->free(buf); return NULL; } if (sys->read(fh, buf, (int)chm->chunk_size) != (int)chm->chunk_size) { self->error = MSPACK_ERR_READ; sys->free(buf); return NULL; } /* check the signature. Is is PMGL or PMGI? */ if (!((buf[0] == 0x50) && (buf[1] == 0x4D) && (buf[2] == 0x47) && ((buf[3] == 0x4C) || (buf[3] == 0x49)))) { self->error = MSPACK_ERR_SEEK; sys->free(buf); return NULL; } /* all OK. Store chunk in cache and return it */ return chm->chunk_cache[chunk_num] = buf; } /* searches a PMGI/PMGL chunk for a given filename entry. Returns -1 on * data format error, 0 if entry definitely not found, 1 if entry * found. In the latter case, *result and *result_end are set pointing * to that entry's data (either the "next chunk" ENCINT for a PMGI or * the section, offset and length ENCINTs for a PMGL). * * In the case of PMGL chunks, the entry has definitely been * found. In the case of PMGI chunks, the entry which points to the * chunk that may eventually contain that entry has been found. */ static int search_chunk(struct mschmd_header *chm, const unsigned char *chunk, const char *filename, const unsigned char **result, const unsigned char **result_end) { const unsigned char *start, *end, *p; unsigned int qr_size, num_entries, qr_entries, qr_density, name_len; unsigned int L, R, M, fname_len, entries_off, is_pmgl; int cmp; fname_len = strlen(filename); /* PMGL chunk or PMGI chunk? (note: read_chunk() has already * checked the rest of the characters in the chunk signature) */ if (chunk[3] == 0x4C) { is_pmgl = 1; entries_off = pmgl_Entries; } else { is_pmgl = 0; entries_off = pmgi_Entries; } /* Step 1: binary search first filename of each QR entry * - target filename == entry * found file * - target filename < all entries * file not found * - target filename > all entries * proceed to step 2 using final entry * - target filename between two searched entries * proceed to step 2 */ qr_size = EndGetI32(&chunk[pmgl_QuickRefSize]); start = &chunk[chm->chunk_size - 2]; end = &chunk[chm->chunk_size - qr_size]; num_entries = EndGetI16(start); qr_density = 1 + (1 << chm->density); qr_entries = (num_entries + qr_density-1) / qr_density; if (num_entries == 0) { D(("chunk has no entries")) return -1; } if (qr_size > chm->chunk_size) { D(("quickref size > chunk size")) return -1; } *result_end = end; if (((int)qr_entries * 2) > (start - end)) { D(("WARNING; more quickrefs than quickref space")) qr_entries = 0; /* but we can live with it */ } if (qr_entries > 0) { L = 0; R = qr_entries - 1; do { /* pick new midpoint */ M = (L + R) >> 1; /* compare filename with entry QR points to */ p = &chunk[entries_off + (M ? EndGetI16(start - (M << 1)) : 0)]; READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; cmp = compare(filename, (char *)p, fname_len, name_len); if (cmp == 0) break; else if (cmp < 0) { if (M) R = M - 1; else return 0; } else if (cmp > 0) L = M + 1; } while (L <= R); M = (L + R) >> 1; if (cmp == 0) { /* exact match! */ p += name_len; *result = p; return 1; } /* otherwise, read the group of entries for QR entry M */ p = &chunk[entries_off + (M ? EndGetI16(start - (M << 1)) : 0)]; num_entries -= (M * qr_density); if (num_entries > qr_density) num_entries = qr_density; } else { p = &chunk[entries_off]; } /* Step 2: linear search through the set of entries reached in step 1. * - filename == any entry * found entry * - filename < all entries (PMGI) or any entry (PMGL) * entry not found, stop now * - filename > all entries * entry not found (PMGL) / maybe found (PMGI) * - */ *result = NULL; while (num_entries-- > 0) { READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; cmp = compare(filename, (char *)p, fname_len, name_len); p += name_len; if (cmp == 0) { /* entry found */ *result = p; return 1; } if (cmp < 0) { /* entry not found (PMGL) / maybe found (PMGI) */ break; } /* read and ignore the rest of this entry */ if (is_pmgl) { READ_ENCINT(R); /* skip section */ READ_ENCINT(R); /* skip offset */ READ_ENCINT(R); /* skip length */ } else { *result = p; /* store potential final result */ READ_ENCINT(R); /* skip chunk number */ } } /* PMGL? not found. PMGI? maybe found */ return (is_pmgl) ? 0 : (*result ? 1 : 0); chunk_end: D(("reached end of chunk data while searching")) return -1; } #if HAVE_TOWLOWER # if HAVE_WCTYPE_H # include <wctype.h> # endif # define TOLOWER(x) towlower(x) #elif HAVE_TOLOWER # if HAVE_CTYPE_H # include <ctype.h> # endif # define TOLOWER(x) tolower(x) #else # define TOLOWER(x) (((x)<0||(x)>255)?(x):mspack_tolower_map[(x)]) /* Map of char -> lowercase char for the first 256 chars. Generated with: * LC_CTYPE=en_GB.utf-8 perl -Mlocale -le 'print map{ord(lc chr).","} 0..255' */ static const unsigned char mspack_tolower_map[256] = { 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,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,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,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,157,158,159,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,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241, 242,243,244,245,246,215,248,249,250,251,252,253,254,223,224,225,226,227,228, 229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247, 248,249,250,251,252,253,254,255 }; #endif /* decodes a UTF-8 character from s[] into c. Will not read past e. * doesn't test that extension bytes are %10xxxxxx. * allows some overlong encodings. */ #define GET_UTF8_CHAR(s, e, c) do { \ unsigned char x = *s++; \ if (x < 0x80) c = x; \ else if (x >= 0xC2 && x < 0xE0 && s < e) { \ c = (x & 0x1F) << 6 | (*s++ & 0x3F); \ } \ else if (x >= 0xE0 && x < 0xF0 && s+1 < e) { \ c = (x & 0x0F) << 12 | (s[0] & 0x3F) << 6 | (s[1] & 0x3F); \ s += 2; \ } \ else if (x >= 0xF0 && x <= 0xF5 && s+2 < e) { \ c = (x & 0x07) << 18 | (s[0] & 0x3F) << 12 | \ (s[1] & 0x3F) << 6 | (s[2] & 0x3F); \ if (c > 0x10FFFF) c = 0xFFFD; \ s += 3; \ } \ else c = 0xFFFD; \ } while (0) /* case-insensitively compares two UTF8 encoded strings. String length for * both strings must be provided, null bytes are not terminators */ static inline int compare(const char *s1, const char *s2, int l1, int l2) { register const unsigned char *p1 = (const unsigned char *) s1; register const unsigned char *p2 = (const unsigned char *) s2; register const unsigned char *e1 = p1 + l1, *e2 = p2 + l2; int c1, c2; while (p1 < e1 && p2 < e2) { GET_UTF8_CHAR(p1, e1, c1); GET_UTF8_CHAR(p2, e2, c2); if (c1 == c2) continue; c1 = TOLOWER(c1); c2 = TOLOWER(c2); if (c1 != c2) return c1 - c2; } return l1 - l2; } /*************************************** * CHMD_EXTRACT *************************************** * extracts a file from a CHM helpfile */ static int chmd_extract(struct mschm_decompressor *base, struct mschmd_file *file, const char *filename) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; struct mspack_system *sys; struct mschmd_header *chm; struct mspack_file *fh; off_t bytes; if (!self) return MSPACK_ERR_ARGS; if (!file || !file->section) return self->error = MSPACK_ERR_ARGS; sys = self->system; chm = file->section->chm; /* create decompression state if it doesn't exist */ if (!self->d) { self->d = (struct mschmd_decompress_state *) sys->alloc(sys, sizeof(struct mschmd_decompress_state)); if (!self->d) return self->error = MSPACK_ERR_NOMEMORY; self->d->chm = chm; self->d->offset = 0; self->d->state = NULL; self->d->sys = *sys; self->d->sys.write = &chmd_sys_write; self->d->infh = NULL; self->d->outfh = NULL; } /* open input chm file if not open, or the open one is a different chm */ if (!self->d->infh || (self->d->chm != chm)) { if (self->d->infh) sys->close(self->d->infh); if (self->d->state) lzxd_free(self->d->state); self->d->chm = chm; self->d->offset = 0; self->d->state = NULL; self->d->infh = sys->open(sys, chm->filename, MSPACK_SYS_OPEN_READ); if (!self->d->infh) return self->error = MSPACK_ERR_OPEN; } /* open file for output */ if (!(fh = sys->open(sys, filename, MSPACK_SYS_OPEN_WRITE))) { return self->error = MSPACK_ERR_OPEN; } /* if file is empty, simply creating it is enough */ if (!file->length) { sys->close(fh); return self->error = MSPACK_ERR_OK; } self->error = MSPACK_ERR_OK; switch (file->section->id) { case 0: /* Uncompressed section file */ /* simple seek + copy */ if (sys->seek(self->d->infh, file->section->chm->sec0.offset + file->offset, MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; } else { unsigned char buf[512]; off_t length = file->length; while (length > 0) { int run = sizeof(buf); if ((off_t)run > length) run = (int)length; if (sys->read(self->d->infh, &buf[0], run) != run) { self->error = MSPACK_ERR_READ; break; } if (sys->write(fh, &buf[0], run) != run) { self->error = MSPACK_ERR_WRITE; break; } length -= run; } } break; case 1: /* MSCompressed section file */ /* (re)initialise compression state if we it is not yet initialised, * or we have advanced too far and have to backtrack */ if (!self->d->state || (file->offset < self->d->offset)) { if (self->d->state) { lzxd_free(self->d->state); self->d->state = NULL; } if (chmd_init_decomp(self, file)) break; } /* seek to input data */ if (sys->seek(self->d->infh, self->d->inoffset, MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; break; } /* get to correct offset. */ self->d->outfh = NULL; if ((bytes = file->offset - self->d->offset)) { self->error = lzxd_decompress(self->d->state, bytes); } /* if getting to the correct offset was error free, unpack file */ if (!self->error) { self->d->outfh = fh; self->error = lzxd_decompress(self->d->state, file->length); } /* save offset in input source stream, in case there is a section 0 * file between now and the next section 1 file extracted */ self->d->inoffset = sys->tell(self->d->infh); /* if an LZX error occured, the LZX decompressor is now useless */ if (self->error) { if (self->d->state) lzxd_free(self->d->state); self->d->state = NULL; } break; } sys->close(fh); return self->error; } /*************************************** * CHMD_SYS_WRITE *************************************** * chmd_sys_write is the internal writer function which the decompressor * uses. If either writes data to disk (self->d->outfh) with the real * sys->write() function, or does nothing with the data when * self->d->outfh == NULL. advances self->d->offset. */ static int chmd_sys_write(struct mspack_file *file, void *buffer, int bytes) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) file; self->d->offset += bytes; if (self->d->outfh) { return self->system->write(self->d->outfh, buffer, bytes); } return bytes; } /*************************************** * CHMD_INIT_DECOMP *************************************** * Initialises the LZX decompressor to decompress the compressed stream, * from the nearest reset offset and length that is needed for the given * file. */ static int chmd_init_decomp(struct mschm_decompressor_p *self, struct mschmd_file *file) { int window_size, window_bits, reset_interval, entry, err; struct mspack_system *sys = self->system; struct mschmd_sec_mscompressed *sec; unsigned char *data; off_t length, offset; sec = (struct mschmd_sec_mscompressed *) file->section; /* ensure we have a mscompressed content section */ err = find_sys_file(self, sec, &sec->content, content_name); if (err) return self->error = err; /* ensure we have a ControlData file */ err = find_sys_file(self, sec, &sec->control, control_name); if (err) return self->error = err; /* read ControlData */ if (sec->control->length < lzxcd_SIZEOF) { D(("ControlData file is too short")) return self->error = MSPACK_ERR_DATAFORMAT; } if (!(data = read_sys_file(self, sec->control))) { D(("can't read mscompressed control data file")) return self->error; } /* check LZXC signature */ if (EndGetI32(&data[lzxcd_Signature]) != 0x43585A4C) { sys->free(data); return self->error = MSPACK_ERR_SIGNATURE; } /* read reset_interval and window_size and validate version number */ switch (EndGetI32(&data[lzxcd_Version])) { case 1: reset_interval = EndGetI32(&data[lzxcd_ResetInterval]); window_size = EndGetI32(&data[lzxcd_WindowSize]); break; case 2: reset_interval = EndGetI32(&data[lzxcd_ResetInterval]) * LZX_FRAME_SIZE; window_size = EndGetI32(&data[lzxcd_WindowSize]) * LZX_FRAME_SIZE; break; default: D(("bad controldata version")) sys->free(data); return self->error = MSPACK_ERR_DATAFORMAT; } /* free ControlData */ sys->free(data); /* find window_bits from window_size */ switch (window_size) { case 0x008000: window_bits = 15; break; case 0x010000: window_bits = 16; break; case 0x020000: window_bits = 17; break; case 0x040000: window_bits = 18; break; case 0x080000: window_bits = 19; break; case 0x100000: window_bits = 20; break; case 0x200000: window_bits = 21; break; default: D(("bad controldata window size")) return self->error = MSPACK_ERR_DATAFORMAT; } /* validate reset_interval */ if (reset_interval == 0 || reset_interval % LZX_FRAME_SIZE) { D(("bad controldata reset interval")) return self->error = MSPACK_ERR_DATAFORMAT; } /* which reset table entry would we like? */ entry = file->offset / reset_interval; /* convert from reset interval multiple (usually 64k) to 32k frames */ entry *= reset_interval / LZX_FRAME_SIZE; /* read the reset table entry */ if (read_reset_table(self, sec, entry, &length, &offset)) { /* the uncompressed length given in the reset table is dishonest. * the uncompressed data is always padded out from the given * uncompressed length up to the next reset interval */ length += reset_interval - 1; length &= -reset_interval; } else { /* if we can't read the reset table entry, just start from * the beginning. Use spaninfo to get the uncompressed length */ entry = 0; offset = 0; err = read_spaninfo(self, sec, &length); } if (err) return self->error = err; /* get offset of compressed data stream: * = offset of uncompressed section from start of file * + offset of compressed stream from start of uncompressed section * + offset of chosen reset interval from start of compressed stream */ self->d->inoffset = file->section->chm->sec0.offset + sec->content->offset + offset; /* set start offset and overall remaining stream length */ self->d->offset = entry * LZX_FRAME_SIZE; length -= self->d->offset; /* initialise LZX stream */ self->d->state = lzxd_init(&self->d->sys, self->d->infh, (struct mspack_file *) self, window_bits, reset_interval / LZX_FRAME_SIZE, 4096, length, 0); if (!self->d->state) self->error = MSPACK_ERR_NOMEMORY; return self->error; } /*************************************** * READ_RESET_TABLE *************************************** * Reads one entry out of the reset table. Also reads the uncompressed * data length. Writes these to offset_ptr and length_ptr respectively. * Returns non-zero for success, zero for failure. */ static int read_reset_table(struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, int entry, off_t *length_ptr, off_t *offset_ptr) { struct mspack_system *sys = self->system; unsigned char *data; unsigned int pos, entrysize; /* do we have a ResetTable file? */ int err = find_sys_file(self, sec, &sec->rtable, rtable_name); if (err) return 0; /* read ResetTable file */ if (sec->rtable->length < lzxrt_headerSIZEOF) { D(("ResetTable file is too short")) return 0; } if (!(data = read_sys_file(self, sec->rtable))) { D(("can't read reset table")) return 0; } /* check sanity of reset table */ if (EndGetI32(&data[lzxrt_FrameLen]) != LZX_FRAME_SIZE) { D(("bad reset table frame length")) sys->free(data); return 0; } /* get the uncompressed length of the LZX stream */ if (read_off64(length_ptr, &data[lzxrt_UncompLen], sys, self->d->infh)) { sys->free(data); return 0; } entrysize = EndGetI32(&data[lzxrt_EntrySize]); pos = EndGetI32(&data[lzxrt_TableOffset]) + (entry * entrysize); /* ensure reset table entry for this offset exists */ if (entry < EndGetI32(&data[lzxrt_NumEntries]) && pos <= (sec->rtable->length - entrysize)) { switch (entrysize) { case 4: *offset_ptr = EndGetI32(&data[pos]); err = 0; break; case 8: err = read_off64(offset_ptr, &data[pos], sys, self->d->infh); break; default: D(("reset table entry size neither 4 nor 8")) err = 1; break; } } else { D(("bad reset interval")) err = 1; } /* free the reset table */ sys->free(data); /* return success */ return (err == 0); } /*************************************** * READ_SPANINFO *************************************** * Reads the uncompressed data length from the spaninfo file. * Returns zero for success or a non-zero error code for failure. */ static int read_spaninfo(struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, off_t *length_ptr) { struct mspack_system *sys = self->system; unsigned char *data; /* find SpanInfo file */ int err = find_sys_file(self, sec, &sec->spaninfo, spaninfo_name); if (err) return MSPACK_ERR_DATAFORMAT; /* check it's large enough */ if (sec->spaninfo->length != 8) { D(("SpanInfo file is wrong size")) return MSPACK_ERR_DATAFORMAT; } /* read the SpanInfo file */ if (!(data = read_sys_file(self, sec->spaninfo))) { D(("can't read SpanInfo file")) return self->error; } /* get the uncompressed length of the LZX stream */ err = read_off64(length_ptr, data, sys, self->d->infh); sys->free(data); if (err) return MSPACK_ERR_DATAFORMAT; if (*length_ptr <= 0) { D(("output length is invalid")) return MSPACK_ERR_DATAFORMAT; } return MSPACK_ERR_OK; } /*************************************** * FIND_SYS_FILE *************************************** * Uses chmd_fast_find to locate a system file, and fills out that system * file's entry and links it into the list of system files. Returns zero * for success, non-zero for both failure and the file not existing. */ static int find_sys_file(struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, struct mschmd_file **f_ptr, const char *name) { struct mspack_system *sys = self->system; struct mschmd_file result; /* already loaded */ if (*f_ptr) return MSPACK_ERR_OK; /* try using fast_find to find the file - return DATAFORMAT error if * it fails, or successfully doesn't find the file */ if (chmd_fast_find((struct mschm_decompressor *) self, sec->base.chm, name, &result, (int)sizeof(result)) || !result.section) { return MSPACK_ERR_DATAFORMAT; } if (!(*f_ptr = (struct mschmd_file *) sys->alloc(sys, sizeof(result)))) { return MSPACK_ERR_NOMEMORY; } /* copy result */ *(*f_ptr) = result; (*f_ptr)->filename = (char *) name; /* link file into sysfiles list */ (*f_ptr)->next = sec->base.chm->sysfiles; sec->base.chm->sysfiles = *f_ptr; return MSPACK_ERR_OK; } /*************************************** * READ_SYS_FILE *************************************** * Allocates memory for a section 0 (uncompressed) file and reads it into * memory. */ static unsigned char *read_sys_file(struct mschm_decompressor_p *self, struct mschmd_file *file) { struct mspack_system *sys = self->system; unsigned char *data = NULL; int len; if (!file || !file->section || (file->section->id != 0)) { self->error = MSPACK_ERR_DATAFORMAT; return NULL; } len = (int) file->length; if (!(data = (unsigned char *) sys->alloc(sys, (size_t) len))) { self->error = MSPACK_ERR_NOMEMORY; return NULL; } if (sys->seek(self->d->infh, file->section->chm->sec0.offset + file->offset, MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; sys->free(data); return NULL; } if (sys->read(self->d->infh, data, len) != len) { self->error = MSPACK_ERR_READ; sys->free(data); return NULL; } return data; } /*************************************** * CHMD_ERROR *************************************** * returns the last error that occurred */ static int chmd_error(struct mschm_decompressor *base) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; return (self) ? self->error : MSPACK_ERR_ARGS; } /*************************************** * READ_OFF64 *************************************** * Reads a 64-bit signed integer from memory in Intel byte order. * If running on a system with a 64-bit off_t, this is simply done. * If running on a system with a 32-bit off_t, offsets up to 0x7FFFFFFF * are accepted, offsets beyond that cause an error message. */ static int read_off64(off_t *var, unsigned char *mem, struct mspack_system *sys, struct mspack_file *fh) { #ifdef LARGEFILE_SUPPORT *var = EndGetI64(mem); #else *var = EndGetI32(mem); if ((*var & 0x80000000) || EndGetI32(mem+4)) { sys->message(fh, (char *)largefile_msg); return 1; } #endif return 0; }
./CrossVul/dataset_final_sorted/CWE-682/c/bad_276_1
crossvul-cpp_data_good_3331_0
// imagew-bmp.c // Part of ImageWorsener, Copyright (c) 2011 by Jason Summers. // For more information, see the readme.txt file. #include "imagew-config.h" #include <stdio.h> // for SEEK_SET #include <stdlib.h> #include <string.h> #define IW_INCLUDE_UTIL_FUNCTIONS #include "imagew.h" #define IWBMP_BI_RGB 0 // = uncompressed #define IWBMP_BI_RLE8 1 #define IWBMP_BI_RLE4 2 #define IWBMP_BI_BITFIELDS 3 #define IWBMP_BI_JPEG 4 #define IWBMP_BI_PNG 5 #define IWBMPCS_CALIBRATED_RGB 0 #define IWBMPCS_DEVICE_RGB 1 // (Unconfirmed) #define IWBMPCS_DEVICE_CMYK 2 // (Unconfirmed) #define IWBMPCS_SRGB 0x73524742 #define IWBMPCS_WINDOWS 0x57696e20 #define IWBMPCS_PROFILE_LINKED 0x4c494e4b #define IWBMPCS_PROFILE_EMBEDDED 0x4d424544 static size_t iwbmp_calc_bpr(int bpp, size_t width) { return ((bpp*width+31)/32)*4; } struct iwbmprcontext { struct iw_iodescr *iodescr; struct iw_context *ctx; struct iw_image *img; int bmpversion; int width, height; int topdown; int has_fileheader; unsigned int bitcount; // bits per pixel unsigned int compression; // IWBMP_BI_* int uses_bitfields; // 'compression' is BI_BITFIELDS int has_alpha_channel; int bitfields_set; int need_16bit; unsigned int palette_entries; size_t fileheader_size; size_t infoheader_size; size_t bitfields_nbytes; // Bytes consumed by BITFIELDs, if not part of the header. size_t palette_nbytes; size_t bfOffBits; struct iw_palette palette; // For 16- & 32-bit images: unsigned int bf_mask[4]; int bf_high_bit[4]; int bf_low_bit[4]; int bf_bits_count[4]; // number of bits in each channel struct iw_csdescr csdescr; }; static int iwbmp_read(struct iwbmprcontext *rctx, iw_byte *buf, size_t buflen) { int ret; size_t bytesread = 0; ret = (*rctx->iodescr->read_fn)(rctx->ctx,rctx->iodescr, buf,buflen,&bytesread); if(!ret || bytesread!=buflen) { return 0; } return 1; } static int iwbmp_skip_bytes(struct iwbmprcontext *rctx, size_t n) { iw_byte buf[1024]; size_t still_to_read; size_t num_to_read; still_to_read = n; while(still_to_read>0) { num_to_read = still_to_read; if(num_to_read>1024) num_to_read=1024; if(!iwbmp_read(rctx,buf,num_to_read)) { return 0; } still_to_read -= num_to_read; } return 1; } static int iwbmp_read_file_header(struct iwbmprcontext *rctx) { iw_byte buf[14]; if(!iwbmp_read(rctx,buf,14)) return 0; rctx->fileheader_size = 14; if(buf[0]=='B' && buf[1]=='A') { // OS/2 Bitmap Array // TODO: This type of file can contain more than one BMP image. // We only support the first one. if(!iwbmp_read(rctx,buf,14)) return 0; rctx->fileheader_size += 14; } if(buf[0]=='B' && buf[1]=='M') { ; } else if((buf[0]=='C' && buf[1]=='I') || // OS/2 Color Icon (buf[0]=='C' && buf[1]=='P') || // OS/2 Color Pointer (buf[0]=='I' && buf[1]=='C') || // OS/2 Icon (buf[0]=='P' && buf[1]=='T')) // OS/2 Pointer { iw_set_error(rctx->ctx,"This type of BMP file is not supported"); return 0; } else { iw_set_error(rctx->ctx,"Not a BMP file"); return 0; } rctx->bfOffBits = iw_get_ui32le(&buf[10]); return 1; } // Read the 12-byte header of a Windows v2 BMP (also known as OS/2 v1 BMP). static int decode_v2_header(struct iwbmprcontext *rctx, const iw_byte *buf) { unsigned int nplanes; rctx->width = iw_get_ui16le(&buf[4]); rctx->height = iw_get_ui16le(&buf[6]); nplanes = iw_get_ui16le(&buf[8]); if(nplanes!=1) return 0; rctx->bitcount = iw_get_ui16le(&buf[10]); if(rctx->bitcount!=1 && rctx->bitcount!=4 && rctx->bitcount!=8 && rctx->bitcount!=24) { return 0; } if(rctx->bitcount<=8) { size_t palette_start, palette_end; rctx->palette_entries = 1<<rctx->bitcount; rctx->palette_nbytes = 3*rctx->palette_entries; // Since v2 BMPs have no direct way to indicate that the palette is not // full-sized, assume the palette ends no later than the start of the // bitmap bits. palette_start = rctx->fileheader_size + rctx->infoheader_size; palette_end = palette_start + rctx->palette_nbytes; if(rctx->bfOffBits >= palette_start+3 && rctx->bfOffBits < palette_end) { rctx->palette_entries = (unsigned int)((rctx->bfOffBits - palette_start)/3); rctx->palette_nbytes = 3*rctx->palette_entries; } } return 1; } // Read a Windows v3 or OS/2 v2 header. static int decode_v3_header_fields(struct iwbmprcontext *rctx, const iw_byte *buf) { unsigned int nplanes; int biXPelsPerMeter, biYPelsPerMeter; unsigned int biClrUsed = 0; //unsigned int biSizeImage; rctx->width = iw_get_i32le(&buf[4]); rctx->height = iw_get_i32le(&buf[8]); if(rctx->height<0) { rctx->height = -rctx->height; rctx->topdown = 1; } nplanes = iw_get_ui16le(&buf[12]); if(nplanes!=1) return 0; rctx->bitcount = iw_get_ui16le(&buf[14]); // We allow bitcount=2 because it's legal in Windows CE BMPs. if(rctx->bitcount!=1 && rctx->bitcount!=2 && rctx->bitcount!=4 && rctx->bitcount!=8 && rctx->bitcount!=16 && rctx->bitcount!=24 && rctx->bitcount!=32) { iw_set_errorf(rctx->ctx,"Bad or unsupported bit count (%d)",(int)rctx->bitcount); return 0; } if(rctx->infoheader_size<=16) { goto infoheaderdone; } rctx->compression = iw_get_ui32le(&buf[16]); if(rctx->compression==IWBMP_BI_BITFIELDS) { if(rctx->bitcount==1) { iw_set_error(rctx->ctx,"Huffman 1D compression not supported"); return 0; } else if(rctx->bitcount!=16 && rctx->bitcount!=32) { iw_set_error(rctx->ctx,"Bad or unsupported image type"); return 0; } // The compression field is overloaded: BITFIELDS is not a type of // compression. Un-overload it. rctx->uses_bitfields = 1; // The v4/v5 documentation for the "BitCount" field says that the // BITFIELDS data comes after the header, the same as with v3. // The v4/v5 documentation for the "Compression" field says that the // BITFIELDS data is stored in the "Mask" fields of the header. // Am I supposed to conclude that it is redundantly stored in both // places? // Evidence and common sense suggests the "BitCount" documentation is // incorrect, and v4/v5 BMPs never have a separate "bitfields" segment. if(rctx->bmpversion==3) { rctx->bitfields_nbytes = 12; } rctx->compression=IWBMP_BI_RGB; } //biSizeImage = iw_get_ui32le(&buf[20]); biXPelsPerMeter = iw_get_i32le(&buf[24]); biYPelsPerMeter = iw_get_i32le(&buf[28]); rctx->img->density_code = IW_DENSITY_UNITS_PER_METER; rctx->img->density_x = (double)biXPelsPerMeter; rctx->img->density_y = (double)biYPelsPerMeter; if(!iw_is_valid_density(rctx->img->density_x,rctx->img->density_y,rctx->img->density_code)) { rctx->img->density_code=IW_DENSITY_UNKNOWN; } biClrUsed = iw_get_ui32le(&buf[32]); if(biClrUsed>100000) return 0; infoheaderdone: // The documentation of the biClrUsed field is not very clear. // I'm going to assume that if biClrUsed is 0 and bitcount<=8, then // the number of palette colors is the maximum that would be useful // for that bitcount. In all other cases, the number of palette colors // equals biClrUsed. if(biClrUsed==0 && rctx->bitcount<=8) { rctx->palette_entries = 1<<rctx->bitcount; } else { rctx->palette_entries = biClrUsed; } rctx->palette_nbytes = 4*rctx->palette_entries; return 1; } static int process_bf_mask(struct iwbmprcontext *rctx, int k); // Decode the fields that are in v4 and not in v3. static int decode_v4_header_fields(struct iwbmprcontext *rctx, const iw_byte *buf) { int k; unsigned int cstype; if(rctx->uses_bitfields) { // Set the bitfields masks here, instead of in iwbmp_read_bitfields(). for(k=0;k<4;k++) { rctx->bf_mask[k] = 0; } for(k=0;k<4;k++) { if(rctx->infoheader_size < (size_t)(40+k*4+4)) break; rctx->bf_mask[k] = iw_get_ui32le(&buf[40+k*4]); if(!process_bf_mask(rctx,k)) return 0; } rctx->bitfields_set=1; // Remember not to overwrite the bf_* fields. if(rctx->bf_mask[3]!=0) { // The documentation says this is the mask that "specifies the // alpha component of each pixel." // It doesn't say whther it's associated, or unassociated alpha. // It doesn't say whether 0=transparent, or 0=opaque. // It doesn't say how to tell whether an image has an alpha // channel. // These are the answers I'm going with: // - Unassociated alpha // - 0=transparent // - 16- and 32-bit images have an alpha channel if 'compression' // is set to BI_BITFIELDS, and this alpha mask is nonzero. rctx->has_alpha_channel = 1; } } if(rctx->infoheader_size < 108) return 1; cstype = iw_get_ui32le(&buf[56]); switch(cstype) { case IWBMPCS_CALIBRATED_RGB: // "indicates that endpoints and gamma values are given in the // appropriate fields." (TODO) break; case IWBMPCS_DEVICE_RGB: case IWBMPCS_SRGB: case IWBMPCS_WINDOWS: break; case IWBMPCS_PROFILE_LINKED: case IWBMPCS_PROFILE_EMBEDDED: if(rctx->bmpversion<5) { iw_warning(rctx->ctx,"Invalid colorspace type for BMPv4"); } break; default: iw_warningf(rctx->ctx,"Unrecognized or unsupported colorspace type (0x%x)",cstype); } // Read Gamma fields if(cstype==IWBMPCS_CALIBRATED_RGB) { unsigned int bmpgamma; double gamma[3]; double avggamma; for(k=0;k<3;k++) { bmpgamma = iw_get_ui32le(&buf[96+k*4]); gamma[k] = ((double)bmpgamma)/65536.0; } avggamma = (gamma[0] + gamma[1] + gamma[2])/3.0; if(avggamma>=0.1 && avggamma<=10.0) { iw_make_gamma_csdescr(&rctx->csdescr,1.0/avggamma); } } return 1; } // Decode the fields that are in v5 and not in v4. static int decode_v5_header_fields(struct iwbmprcontext *rctx, const iw_byte *buf) { unsigned int intent_bmp_style; int intent_iw_style; intent_bmp_style = iw_get_ui32le(&buf[108]); intent_iw_style = IW_INTENT_UNKNOWN; switch(intent_bmp_style) { case 1: intent_iw_style = IW_INTENT_SATURATION; break; // LCS_GM_BUSINESS case 2: intent_iw_style = IW_INTENT_RELATIVE; break; // LCS_GM_GRAPHICS case 4: intent_iw_style = IW_INTENT_PERCEPTUAL; break; // LCS_GM_IMAGES case 8: intent_iw_style = IW_INTENT_ABSOLUTE; break; // LCS_GM_ABS_COLORIMETRIC } rctx->img->rendering_intent = intent_iw_style; // The profile may either be after the color table, or after the bitmap bits. // I'm assuming that we will never need to use the profile size in order to // find the bitmap bits; i.e. that if the bfOffBits field in the file header // is not available, the profile must be after the bits. //profile_offset = iw_get_ui32le(&buf[112]); // bV5ProfileData; //profile_size = iw_get_ui32le(&buf[116]); // bV5ProfileSize; return 1; } static int iwbmp_read_info_header(struct iwbmprcontext *rctx) { iw_byte buf[124]; int retval = 0; size_t n; // First, read just the "size" field. It tells the size of the header // structure, and identifies the BMP version. if(!iwbmp_read(rctx,buf,4)) goto done; rctx->infoheader_size = iw_get_ui32le(&buf[0]); if(rctx->infoheader_size<12) goto done; // Read the rest of the header. n = rctx->infoheader_size; if(n>sizeof(buf)) n=sizeof(buf); if(!iwbmp_read(rctx,&buf[4],n-4)) goto done; if(rctx->infoheader_size==12) { // This is a "Windows BMP v2" or "OS/2 BMP v1" bitmap. rctx->bmpversion=2; if(!decode_v2_header(rctx,buf)) goto done; } else if(rctx->infoheader_size==16 || rctx->infoheader_size==40 || rctx->infoheader_size==64) { // A Windows v3 or OS/2 v2 BMP. // OS/2 v2 BMPs can technically have other header sizes between 16 and 64, // but it's not clear if such files actually exist. rctx->bmpversion=3; if(!decode_v3_header_fields(rctx,buf)) goto done; } else if(rctx->infoheader_size==108 || rctx->infoheader_size==52 || rctx->infoheader_size==56) { // We assume a a 52- or 56-byte header is for BITMAPV2INFOHEADER/BITMAPV3INFOHEADER, // and not OS/2v2 format. But if it OS/2v2, it will probably either work (because // the formats are similar enough), or fail due to an unsupported combination of // compression and bits/pixel. rctx->bmpversion=4; if(!decode_v3_header_fields(rctx,buf)) goto done; if(!decode_v4_header_fields(rctx,buf)) goto done; } else if(rctx->infoheader_size==124) { rctx->bmpversion=5; if(!decode_v3_header_fields(rctx,buf)) goto done; if(!decode_v4_header_fields(rctx,buf)) goto done; if(!decode_v5_header_fields(rctx,buf)) goto done; } else { iw_set_error(rctx->ctx,"Unsupported BMP version"); goto done; } if(!iw_check_image_dimensions(rctx->ctx,rctx->width,rctx->height)) { goto done; } retval = 1; done: return retval; } // Find the highest/lowest bit that is set. static int find_high_bit(unsigned int x) { int i; for(i=31;i>=0;i--) { if(x&(1U<<(unsigned int)i)) return i; } return 0; } static int find_low_bit(unsigned int x) { int i; for(i=0;i<=31;i++) { if(x&(1U<<(unsigned int)i)) return i; } return 0; } // Given .bf_mask[k], set high_bit[k], low_bit[k], etc. static int process_bf_mask(struct iwbmprcontext *rctx, int k) { // The bits representing the mask for each channel are required to be // contiguous, so all we need to do is find the highest and lowest bit. rctx->bf_high_bit[k] = find_high_bit(rctx->bf_mask[k]); rctx->bf_low_bit[k] = find_low_bit(rctx->bf_mask[k]); rctx->bf_bits_count[k] = 1+rctx->bf_high_bit[k]-rctx->bf_low_bit[k]; // Check if the mask specifies an invalid bit if(rctx->bf_high_bit[k] > (int)(rctx->bitcount-1)) return 0; if(rctx->bf_bits_count[k]>16) { // We only support up to 16 bits. Ignore any bits after the 16th. rctx->bf_low_bit[k] = rctx->bf_high_bit[k]-15; rctx->bf_bits_count[k] = 16; } if(rctx->bf_bits_count[k]>8) { rctx->need_16bit = 1; } return 1; } static int iwbmp_read_bitfields(struct iwbmprcontext *rctx) { iw_byte buf[12]; int k; if(!iwbmp_read(rctx,buf,12)) return 0; for(k=0;k<3;k++) { rctx->bf_mask[k] = iw_get_ui32le(&buf[k*4]); if(rctx->bf_mask[k]==0) return 0; // Find the high bit, low bit, etc. if(!process_bf_mask(rctx,k)) return 0; } return 1; } static void iwbmp_set_default_bitfields(struct iwbmprcontext *rctx) { int k; if(rctx->bitfields_set) return; if(rctx->bitcount==16) { // Default is 5 bits for each channel. rctx->bf_mask[0]=0x7c00; // 01111100 00000000 (red) rctx->bf_mask[1]=0x03e0; // 00000011 11100000 (green) rctx->bf_mask[2]=0x001f; // 00000000 00011111 (blue) } else if(rctx->bitcount==32) { rctx->bf_mask[0]=0x00ff0000; rctx->bf_mask[1]=0x0000ff00; rctx->bf_mask[2]=0x000000ff; } else { return; } for(k=0;k<3;k++) { process_bf_mask(rctx,k); } } static int iwbmp_read_palette(struct iwbmprcontext *rctx) { size_t i; iw_byte buf[4*256]; size_t b; unsigned int valid_palette_entries; size_t valid_palette_nbytes; b = (rctx->bmpversion==2) ? 3 : 4; // bytes per palette entry if(rctx->infoheader_size==64) { // According to what little documentation I can find, OS/2v2 BMP files // have 4 bytes per palette entry. But some of the files I've seen have // only 3. This is a little hack to support them. if(rctx->fileheader_size + rctx->infoheader_size + rctx->palette_entries*3 == rctx->bfOffBits) { iw_warning(rctx->ctx,"BMP bitmap overlaps colormap; assuming colormap uses 3 bytes per entry instead of 4"); b = 3; rctx->palette_nbytes = 3*rctx->palette_entries; } } // If the palette has >256 colors, only use the first 256. valid_palette_entries = (rctx->palette_entries<=256) ? rctx->palette_entries : 256; valid_palette_nbytes = valid_palette_entries * b; if(!iwbmp_read(rctx,buf,valid_palette_nbytes)) return 0; rctx->palette.num_entries = valid_palette_entries; for(i=0;i<valid_palette_entries;i++) { rctx->palette.entry[i].b = buf[i*b+0]; rctx->palette.entry[i].g = buf[i*b+1]; rctx->palette.entry[i].r = buf[i*b+2]; rctx->palette.entry[i].a = 255; } // If the palette is oversized, skip over the unused part of it. if(rctx->palette_nbytes > valid_palette_nbytes) { iwbmp_skip_bytes(rctx, rctx->palette_nbytes - valid_palette_nbytes); } return 1; } static void bmpr_convert_row_32_16(struct iwbmprcontext *rctx, const iw_byte *src, size_t row) { int i,k; unsigned int v,x; int numchannels; numchannels = rctx->has_alpha_channel ? 4 : 3; for(i=0;i<rctx->width;i++) { if(rctx->bitcount==32) { x = ((unsigned int)src[i*4+0]) | ((unsigned int)src[i*4+1])<<8 | ((unsigned int)src[i*4+2])<<16 | ((unsigned int)src[i*4+3])<<24; } else { // 16 x = ((unsigned int)src[i*2+0]) | ((unsigned int)src[i*2+1])<<8; } v = 0; for(k=0;k<numchannels;k++) { // For red, green, blue [, alpha]: v = x & rctx->bf_mask[k]; if(rctx->bf_low_bit[k]>0) v >>= rctx->bf_low_bit[k]; if(rctx->img->bit_depth==16) { rctx->img->pixels[row*rctx->img->bpr + i*numchannels*2 + k*2+0] = (iw_byte)(v>>8); rctx->img->pixels[row*rctx->img->bpr + i*numchannels*2 + k*2+1] = (iw_byte)(v&0xff); } else { rctx->img->pixels[row*rctx->img->bpr + i*numchannels + k] = (iw_byte)v; } } } } static void bmpr_convert_row_24(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; for(i=0;i<rctx->width;i++) { rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = src[i*3+2]; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = src[i*3+1]; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = src[i*3+0]; } } static void bmpr_convert_row_8(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; for(i=0;i<rctx->width;i++) { rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = rctx->palette.entry[src[i]].r; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = rctx->palette.entry[src[i]].g; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = rctx->palette.entry[src[i]].b; } } static void bmpr_convert_row_4(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; int pal_index; for(i=0;i<rctx->width;i++) { pal_index = (i&0x1) ? src[i/2]&0x0f : src[i/2]>>4; rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = rctx->palette.entry[pal_index].b; } } static void bmpr_convert_row_2(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; int pal_index; for(i=0;i<rctx->width;i++) { pal_index = (src[i/4]>>(2*(3-i%4)))&0x03; rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = rctx->palette.entry[pal_index].b; } } static void bmpr_convert_row_1(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; int pal_index; for(i=0;i<rctx->width;i++) { pal_index = (src[i/8] & (1<<(7-i%8))) ? 1 : 0; rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = rctx->palette.entry[pal_index].b; } } static int bmpr_read_uncompressed(struct iwbmprcontext *rctx) { iw_byte *rowbuf = NULL; size_t bmp_bpr; int j; int retval = 0; if(rctx->has_alpha_channel) { rctx->img->imgtype = IW_IMGTYPE_RGBA; rctx->img->bit_depth = rctx->need_16bit ? 16 : 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,4*rctx->img->bit_depth); } else { rctx->img->imgtype = IW_IMGTYPE_RGB; rctx->img->bit_depth = rctx->need_16bit ? 16 : 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,3*rctx->img->bit_depth); } bmp_bpr = iwbmp_calc_bpr(rctx->bitcount,rctx->width); rctx->img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx,rctx->img->bpr,rctx->img->height); if(!rctx->img->pixels) goto done; rowbuf = iw_malloc(rctx->ctx,bmp_bpr); for(j=0;j<rctx->img->height;j++) { // Read a row of the BMP file. if(!iwbmp_read(rctx,rowbuf,bmp_bpr)) { goto done; } switch(rctx->bitcount) { case 32: case 16: bmpr_convert_row_32_16(rctx,rowbuf,j); break; case 24: bmpr_convert_row_24(rctx,rowbuf,j); break; case 8: bmpr_convert_row_8(rctx,rowbuf,j); break; case 4: bmpr_convert_row_4(rctx,rowbuf,j); break; case 2: bmpr_convert_row_2(rctx,rowbuf,j); break; case 1: bmpr_convert_row_1(rctx,rowbuf,j); break; } } retval = 1; done: if(rowbuf) iw_free(rctx->ctx,rowbuf); return retval; } // Read and decompress RLE8 or RLE4-compressed bits, and write pixels to // rctx->img->pixels. static int bmpr_read_rle_internal(struct iwbmprcontext *rctx) { int retval = 0; int pos_x, pos_y; iw_byte buf[255]; size_t n_pix; size_t n_bytes; size_t i; size_t pal_index; // The position of the next pixel to set. // pos_y is in IW coordinates (top=0), not BMP coordinates (bottom=0). pos_x = 0; pos_y = 0; // Initially make all pixels transparent, so that any any pixels we // don't modify will be transparent. iw_zeromem(rctx->img->pixels,rctx->img->bpr*rctx->img->height); while(1) { // If we've reached the end of the bitmap, stop. if(pos_y>rctx->img->height-1) break; if(pos_y==rctx->img->height-1 && pos_x>=rctx->img->width) break; if(!iwbmp_read(rctx,buf,2)) goto done; if(buf[0]==0) { if(buf[1]==0) { // End of Line pos_y++; pos_x=0; } else if(buf[1]==1) { // (Premature) End of Bitmap break; } else if(buf[1]==2) { // DELTA: The next two bytes are unsigned values representing // the relative position of the next pixel from the "current // position". // I interpret "current position" to mean the position at which // the next pixel would normally have been. if(!iwbmp_read(rctx,buf,2)) goto done; if(pos_x<rctx->img->width) pos_x += buf[0]; pos_y += buf[1]; } else { // A uncompressed segment n_pix = (size_t)buf[1]; // Number of uncompressed pixels which follow if(rctx->compression==IWBMP_BI_RLE4) { n_bytes = ((n_pix+3)/4)*2; } else { n_bytes = ((n_pix+1)/2)*2; } if(!iwbmp_read(rctx,buf,n_bytes)) goto done; for(i=0;i<n_pix;i++) { if(pos_x<rctx->img->width) { if(rctx->compression==IWBMP_BI_RLE4) { pal_index = (i%2) ? buf[i/2]&0x0f : buf[i/2]>>4; } else { pal_index = buf[i]; } rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 2] = rctx->palette.entry[pal_index].b; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 3] = 255; pos_x++; } } } } else { // An RLE-compressed segment n_pix = (size_t)buf[0]; for(i=0;i<n_pix;i++) { if(pos_x<rctx->img->width) { if(rctx->compression==IWBMP_BI_RLE4) { pal_index = (i%2) ? buf[1]&0x0f : buf[1]>>4; } else { pal_index = buf[1]; } rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 2] = rctx->palette.entry[pal_index].b; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 3] = 255; pos_x++; } } } } retval = 1; done: return retval; } static int bmpr_has_transparency(struct iw_image *img) { int i,j; if(img->imgtype!=IW_IMGTYPE_RGBA) return 0; for(j=0;j<img->height;j++) { for(i=0;i<img->width;i++) { if(img->pixels[j*img->bpr + i*4 + 3] != 255) return 1; } } return 0; } // Remove the alpha channel. // This doesn't free the extra memory used by the alpha channel, it just // moves the pixels around in-place. static void bmpr_strip_alpha(struct iw_image *img) { int i,j; size_t oldbpr; img->imgtype = IW_IMGTYPE_RGB; oldbpr = img->bpr; img->bpr = iw_calc_bytesperrow(img->width,24); for(j=0;j<img->height;j++) { for(i=0;i<img->width;i++) { img->pixels[j*img->bpr + i*3 + 0] = img->pixels[j*oldbpr + i*4 + 0]; img->pixels[j*img->bpr + i*3 + 1] = img->pixels[j*oldbpr + i*4 + 1]; img->pixels[j*img->bpr + i*3 + 2] = img->pixels[j*oldbpr + i*4 + 2]; } } } static int bmpr_read_rle(struct iwbmprcontext *rctx) { int retval = 0; if(!(rctx->compression==IWBMP_BI_RLE8 && rctx->bitcount==8) && !(rctx->compression==IWBMP_BI_RLE4 && rctx->bitcount==4)) { iw_set_error(rctx->ctx,"Compression type incompatible with image type"); } if(rctx->topdown) { // The documentation says that top-down images may not be compressed. iw_set_error(rctx->ctx,"Compression not allowed with top-down images"); } // RLE-compressed BMP images don't have to assign a color to every pixel, // and it's reasonable to interpret undefined pixels as transparent. // I'm not going to worry about handling compressed BMP images as // efficiently as possible, so start with an RGBA image, and convert to // RGB format later if (as is almost always the case) there was no // transparency. rctx->img->imgtype = IW_IMGTYPE_RGBA; rctx->img->bit_depth = 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,32); rctx->img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx,rctx->img->bpr,rctx->img->height); if(!rctx->img->pixels) goto done; if(!bmpr_read_rle_internal(rctx)) goto done; if(!bmpr_has_transparency(rctx->img)) { bmpr_strip_alpha(rctx->img); } retval = 1; done: return retval; } static int iwbmp_read_bits(struct iwbmprcontext *rctx) { int retval = 0; rctx->img->width = rctx->width; rctx->img->height = rctx->height; // If applicable, use the fileheader's "bits offset" field to locate the // bitmap bits. if(rctx->fileheader_size>0) { size_t expected_offbits; expected_offbits = rctx->fileheader_size + rctx->infoheader_size + rctx->bitfields_nbytes + rctx->palette_nbytes; if(rctx->bfOffBits==expected_offbits) { ; } else if(rctx->bfOffBits>expected_offbits && rctx->bfOffBits<1000000) { // Apparently, there's some extra space between the header data and // the bits. If it's not unreasonably large, skip over it. if(!iwbmp_skip_bytes(rctx, rctx->bfOffBits - expected_offbits)) goto done; } else { iw_set_error(rctx->ctx,"Invalid BMP bits offset"); goto done; } } if(rctx->compression==IWBMP_BI_RGB) { if(!bmpr_read_uncompressed(rctx)) goto done; } else if(rctx->compression==IWBMP_BI_RLE8 || rctx->compression==IWBMP_BI_RLE4) { if(!bmpr_read_rle(rctx)) goto done; } else { iw_set_errorf(rctx->ctx,"Unsupported BMP compression or image type (%d)",(int)rctx->compression); goto done; } retval = 1; done: return retval; } static void iwbmpr_misc_config(struct iw_context *ctx, struct iwbmprcontext *rctx) { // Have IW flip the image, if necessary. if(!rctx->topdown) { iw_reorient_image(ctx,IW_REORIENT_FLIP_V); } // Tell IW the colorspace. iw_set_input_colorspace(ctx,&rctx->csdescr); // Tell IW the significant bits. if(rctx->bitcount==16 || rctx->bitcount==32) { if(rctx->bf_bits_count[0]!=8 || rctx->bf_bits_count[1]!=8 || rctx->bf_bits_count[2]!=8 || (IW_IMGTYPE_HAS_ALPHA(rctx->img->imgtype) && rctx->bf_bits_count[3]!=8)) { iw_set_input_max_color_code(ctx,0, (1 << rctx->bf_bits_count[0])-1 ); iw_set_input_max_color_code(ctx,1, (1 << rctx->bf_bits_count[1])-1 ); iw_set_input_max_color_code(ctx,2, (1 << rctx->bf_bits_count[2])-1 ); if(IW_IMGTYPE_HAS_ALPHA(rctx->img->imgtype)) { iw_set_input_max_color_code(ctx,3, (1 << rctx->bf_bits_count[3])-1 ); } } } } IW_IMPL(int) iw_read_bmp_file(struct iw_context *ctx, struct iw_iodescr *iodescr) { struct iwbmprcontext rctx; struct iw_image img; int retval = 0; iw_zeromem(&rctx,sizeof(struct iwbmprcontext)); iw_zeromem(&img,sizeof(struct iw_image)); rctx.ctx = ctx; rctx.img = &img; rctx.iodescr = iodescr; // Start with a default sRGB colorspace. This may be overridden later. iw_make_srgb_csdescr_2(&rctx.csdescr); rctx.has_fileheader = !iw_get_value(ctx,IW_VAL_BMP_NO_FILEHEADER); if(rctx.has_fileheader) { if(!iwbmp_read_file_header(&rctx)) goto done; } if(!iwbmp_read_info_header(&rctx)) goto done; iwbmp_set_default_bitfields(&rctx); if(rctx.bitfields_nbytes>0) { if(!iwbmp_read_bitfields(&rctx)) goto done; } if(rctx.palette_entries>0) { if(!iwbmp_read_palette(&rctx)) goto done; } if(!iwbmp_read_bits(&rctx)) goto done; iw_set_input_image(ctx, &img); iwbmpr_misc_config(ctx, &rctx); retval = 1; done: if(!retval) { iw_set_error(ctx,"BMP read failed"); // If we didn't call iw_set_input_image, 'img' still belongs to us, // so free its contents. iw_free(ctx, img.pixels); } return retval; } struct iwbmpwcontext { int bmpversion; int include_file_header; int bitcount; int palentries; int compressed; int uses_bitfields; size_t header_size; size_t bitfields_size; size_t palsize; size_t unc_dst_bpr; size_t unc_bitssize; struct iw_iodescr *iodescr; struct iw_context *ctx; struct iw_image *img; const struct iw_palette *pal; size_t total_written; int bf_amt_to_shift[4]; // For 16-bit images unsigned int bf_mask[4]; unsigned int maxcolor[4]; // R, G, B -- For 16-bit images. struct iw_csdescr csdescr; int no_cslabel; }; static void iwbmp_write(struct iwbmpwcontext *wctx, const void *buf, size_t n) { (*wctx->iodescr->write_fn)(wctx->ctx,wctx->iodescr,buf,n); wctx->total_written+=n; } static void bmpw_convert_row_1(const iw_byte *srcrow, iw_byte *dstrow, int width) { int i; int m; for(i=0;i<width;i++) { m = i%8; if(m==0) dstrow[i/8] = srcrow[i]<<7; else dstrow[i/8] |= srcrow[i]<<(7-m); } } static void bmpw_convert_row_4(const iw_byte *srcrow, iw_byte *dstrow, int width) { int i; for(i=0;i<width;i++) { if(i%2==0) dstrow[i/2] = srcrow[i]<<4; else dstrow[i/2] |= srcrow[i]; } } static void bmpw_convert_row_8(const iw_byte *srcrow, iw_byte *dstrow, int width) { memcpy(dstrow,srcrow,width); } static void bmpw_convert_row_16_32(struct iwbmpwcontext *wctx, const iw_byte *srcrow, iw_byte *dstrow, int width) { int i,k; unsigned int v; int num_src_samples; unsigned int src_sample[4]; for(k=0;k<4;k++) src_sample[k]=0; num_src_samples = iw_imgtype_num_channels(wctx->img->imgtype); for(i=0;i<width;i++) { // Read the source samples into a convenient format. for(k=0;k<num_src_samples;k++) { if(wctx->img->bit_depth==16) { src_sample[k] = (srcrow[num_src_samples*2*i + k*2]<<8) | srcrow[num_src_samples*2*i + k*2 +1]; } else { src_sample[k] = srcrow[num_src_samples*i + k]; } } // Pack the pixels' bits into a single int. switch(wctx->img->imgtype) { case IW_IMGTYPE_GRAY: v = src_sample[0] << wctx->bf_amt_to_shift[0]; v |= src_sample[0] << wctx->bf_amt_to_shift[1]; v |= src_sample[0] << wctx->bf_amt_to_shift[2]; break; case IW_IMGTYPE_RGBA: v = src_sample[0] << wctx->bf_amt_to_shift[0]; v |= src_sample[1] << wctx->bf_amt_to_shift[1]; v |= src_sample[2] << wctx->bf_amt_to_shift[2]; v |= src_sample[3] << wctx->bf_amt_to_shift[3]; break; case IW_IMGTYPE_GRAYA: v = src_sample[0] << wctx->bf_amt_to_shift[0]; v |= src_sample[0] << wctx->bf_amt_to_shift[1]; v |= src_sample[0] << wctx->bf_amt_to_shift[2]; v |= src_sample[1] << wctx->bf_amt_to_shift[3]; break; default: v = src_sample[0] << wctx->bf_amt_to_shift[0]; v |= src_sample[1] << wctx->bf_amt_to_shift[1]; v |= src_sample[2] << wctx->bf_amt_to_shift[2]; } // Split the int into bytes, and write it to the target image. if(wctx->bitcount==32) { dstrow[i*4+0] = (iw_byte)(v&0xff); dstrow[i*4+1] = (iw_byte)((v&0x0000ff00)>>8); dstrow[i*4+2] = (iw_byte)((v&0x00ff0000)>>16); dstrow[i*4+3] = (iw_byte)((v&0xff000000)>>24); } else { dstrow[i*2+0] = (iw_byte)(v&0xff); dstrow[i*2+1] = (iw_byte)(v>>8); } } } static void bmpw_convert_row_24(struct iwbmpwcontext *wctx, const iw_byte *srcrow, iw_byte *dstrow, int width) { int i; if(wctx->img->imgtype==IW_IMGTYPE_GRAY) { for(i=0;i<width;i++) { dstrow[i*3+0] = srcrow[i]; dstrow[i*3+1] = srcrow[i]; dstrow[i*3+2] = srcrow[i]; } } else { // RGB for(i=0;i<width;i++) { dstrow[i*3+0] = srcrow[i*3+2]; dstrow[i*3+1] = srcrow[i*3+1]; dstrow[i*3+2] = srcrow[i*3+0]; } } } static void iwbmp_write_file_header(struct iwbmpwcontext *wctx) { iw_byte fileheader[14]; if(!wctx->include_file_header) return; iw_zeromem(fileheader,sizeof(fileheader)); fileheader[0] = 66; // 'B' fileheader[1] = 77; // 'M' // This will be overwritten later, if the bitmap was compressed. iw_set_ui32le(&fileheader[ 2], (unsigned int)(14+wctx->header_size+ wctx->bitfields_size+wctx->palsize+wctx->unc_bitssize)); // bfSize iw_set_ui32le(&fileheader[10],(unsigned int)(14+wctx->header_size+ wctx->bitfields_size+wctx->palsize)); // bfOffBits iwbmp_write(wctx,fileheader,14); } static int iwbmp_write_bmp_v2header(struct iwbmpwcontext *wctx) { iw_byte header[12]; if(wctx->img->width>65535 || wctx->img->height>65535) { iw_set_error(wctx->ctx,"Output image is too large for this BMP version"); return 0; } iw_zeromem(header,sizeof(header)); iw_set_ui32le(&header[ 0],12); // bcSize iw_set_ui16le(&header[ 4],wctx->img->width); // bcWidth iw_set_ui16le(&header[ 6],wctx->img->height); // bcHeight iw_set_ui16le(&header[ 8],1); // bcPlanes iw_set_ui16le(&header[10],wctx->bitcount); // bcBitCount iwbmp_write(wctx,header,12); return 1; } static int iwbmp_write_bmp_v3header(struct iwbmpwcontext *wctx) { unsigned int dens_x, dens_y; unsigned int cmpr; iw_byte header[40]; iw_zeromem(header,sizeof(header)); iw_set_ui32le(&header[ 0],(unsigned int)wctx->header_size); // biSize iw_set_ui32le(&header[ 4],wctx->img->width); // biWidth iw_set_ui32le(&header[ 8],wctx->img->height); // biHeight iw_set_ui16le(&header[12],1); // biPlanes iw_set_ui16le(&header[14],wctx->bitcount); // biBitCount cmpr = IWBMP_BI_RGB; if(wctx->compressed) { if(wctx->bitcount==8) cmpr = IWBMP_BI_RLE8; else if(wctx->bitcount==4) cmpr = IWBMP_BI_RLE4; } else if(wctx->uses_bitfields) { cmpr = IWBMP_BI_BITFIELDS; } iw_set_ui32le(&header[16],cmpr); // biCompression iw_set_ui32le(&header[20],(unsigned int)wctx->unc_bitssize); // biSizeImage if(wctx->img->density_code==IW_DENSITY_UNITS_PER_METER) { dens_x = (unsigned int)(0.5+wctx->img->density_x); dens_y = (unsigned int)(0.5+wctx->img->density_y); } else { dens_x = dens_y = 2835; } iw_set_ui32le(&header[24],dens_x); // biXPelsPerMeter iw_set_ui32le(&header[28],dens_y); // biYPelsPerMeter iw_set_ui32le(&header[32],wctx->palentries); // biClrUsed //iw_set_ui32le(&header[36],0); // biClrImportant iwbmp_write(wctx,header,40); return 1; } static int iwbmp_write_bmp_v45header_fields(struct iwbmpwcontext *wctx) { iw_byte header[124]; unsigned int intent_bmp_style; iw_zeromem(header,sizeof(header)); if(wctx->uses_bitfields) { iw_set_ui32le(&header[40],wctx->bf_mask[0]); iw_set_ui32le(&header[44],wctx->bf_mask[1]); iw_set_ui32le(&header[48],wctx->bf_mask[2]); iw_set_ui32le(&header[52],wctx->bf_mask[3]); } // Colorspace Type // TODO: We could support CSTYPE_GAMMA by using LCS_CALIBRATED_RGB, // but documentation about how to do that is hard to find. if(wctx->csdescr.cstype==IW_CSTYPE_SRGB && !wctx->no_cslabel) iw_set_ui32le(&header[56],IWBMPCS_SRGB); else iw_set_ui32le(&header[56],IWBMPCS_DEVICE_RGB); // Intent //intent_bmp_style = 4; // Perceptual //if(wctx->csdescr.cstype==IW_CSTYPE_SRGB && !wctx->no_cslabel) { switch(wctx->img->rendering_intent) { case IW_INTENT_PERCEPTUAL: intent_bmp_style = 4; break; case IW_INTENT_RELATIVE: intent_bmp_style = 2; break; case IW_INTENT_SATURATION: intent_bmp_style = 1; break; case IW_INTENT_ABSOLUTE: intent_bmp_style = 8; break; default: intent_bmp_style = 4; } //} iw_set_ui32le(&header[108],intent_bmp_style); iwbmp_write(wctx,&header[40],124-40); return 1; } static int iwbmp_write_bmp_header(struct iwbmpwcontext *wctx) { if(wctx->bmpversion==2) { return iwbmp_write_bmp_v2header(wctx); } else if(wctx->bmpversion==5) { if(!iwbmp_write_bmp_v3header(wctx)) return 0; return iwbmp_write_bmp_v45header_fields(wctx); } return iwbmp_write_bmp_v3header(wctx); } // Given wctx->maxcolor[*], sets -> bf_mask[*] and bf_amt_to_shift[*], // and sets wctx->bitcount (to 16 or 32). static int iwbmp_calc_bitfields_masks(struct iwbmpwcontext *wctx, int num_masks) { int k; int bits[4]; // R, G, B, A int tot_bits = 0; for(k=0;k<num_masks;k++) { bits[k] = iw_max_color_to_bitdepth(wctx->maxcolor[k]); tot_bits += bits[k]; } if(tot_bits > 32) { iw_set_error(wctx->ctx,"Cannot write a BMP image in this color format"); return 0; } wctx->bitcount = (tot_bits>16) ? 32 : 16; wctx->bf_amt_to_shift[0] = bits[1] + bits[2]; wctx->bf_amt_to_shift[1] = bits[2]; wctx->bf_amt_to_shift[2] = 0; if(num_masks>3) wctx->bf_amt_to_shift[3] = bits[0] + bits[1] + bits[2]; for(k=0;k<num_masks;k++) { wctx->bf_mask[k] = wctx->maxcolor[k] << wctx->bf_amt_to_shift[k]; } return 1; } // Write the BITFIELDS segment, and set the wctx->bf_amt_to_shift[] values. static int iwbmp_write_bitfields(struct iwbmpwcontext *wctx) { iw_byte buf[12]; int k; if(wctx->bitcount!=16 && wctx->bitcount!=32) return 0; for(k=0;k<3;k++) { iw_set_ui32le(&buf[4*k],wctx->bf_mask[k]); } iwbmp_write(wctx,buf,12); return 1; } static void iwbmp_write_palette(struct iwbmpwcontext *wctx) { int i,k; iw_byte buf[4]; if(wctx->palentries<1) return; buf[3] = 0; // Reserved field; always 0. for(i=0;i<wctx->palentries;i++) { if(i<wctx->pal->num_entries) { if(wctx->pal->entry[i].a == 0) { // A transparent color. Because of the way we handle writing // transparent BMP images, the first palette entry may be a // fully transparent color, whose index will not be used when // we write the image. But many apps will interpret our // "transparent" pixels as having color #0. So, set it to // the background label color if available, otherwise to an // arbitrary high-contrast color (magenta). if(wctx->img->has_bkgdlabel) { for(k=0;k<3;k++) { buf[k] = (iw_byte)iw_color_get_int_sample(&wctx->img->bkgdlabel,2-k,255); } } else { buf[0] = 255; buf[1] = 0; buf[2] = 255; } } else { buf[0] = wctx->pal->entry[i].b; buf[1] = wctx->pal->entry[i].g; buf[2] = wctx->pal->entry[i].r; } } else { buf[0] = buf[1] = buf[2] = 0; } if(wctx->bmpversion==2) iwbmp_write(wctx,buf,3); // v2 BMPs don't have the 'reserved' field. else iwbmp_write(wctx,buf,4); } } struct rle_context { struct iw_context *ctx; struct iwbmpwcontext *wctx; const iw_byte *srcrow; size_t img_width; int cur_row; // current row; 0=top (last) // Position in srcrow of the first byte that hasn't been written to the // output file size_t pending_data_start; // Current number of uncompressible bytes that haven't been written yet // (starting at pending_data_start) size_t unc_len; // Current number of identical bytes that haven't been written yet // (starting at pending_data_start+unc_len) size_t run_len; // The value of the bytes referred to by run_len. // Valid if run_len>0. iw_byte run_byte; size_t total_bytes_written; // Bytes written, after compression }; //============================ RLE8 encoder ============================ // TODO: The RLE8 and RLE4 encoders are more different than they should be. // The RLE8 encoder could probably be made more similar to the (more // complicated) RLE4 encoder. static void rle8_write_unc(struct rle_context *rlectx) { size_t i; iw_byte dstbuf[2]; if(rlectx->unc_len<1) return; if(rlectx->unc_len>=3 && (rlectx->unc_len&1)) { iw_set_error(rlectx->ctx,"Internal: RLE encode error 4"); return; } if(rlectx->unc_len>254) { iw_set_error(rlectx->ctx,"Internal: RLE encode error 5"); return; } if(rlectx->unc_len<3) { // The minimum length for a noncompressed run is 3. For shorter runs // write them "compressed". for(i=0;i<rlectx->unc_len;i++) { dstbuf[0] = 0x01; // count dstbuf[1] = rlectx->srcrow[i+rlectx->pending_data_start]; // value iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; } } else { dstbuf[0] = 0x00; dstbuf[1] = (iw_byte)rlectx->unc_len; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; iwbmp_write(rlectx->wctx,&rlectx->srcrow[rlectx->pending_data_start],rlectx->unc_len); rlectx->total_bytes_written+=rlectx->unc_len; if(rlectx->unc_len&0x1) { // Need a padding byte if the length was odd. (This shouldn't // happen, because we never write odd-length UNC segments.) dstbuf[0] = 0x00; iwbmp_write(rlectx->wctx,dstbuf,1); rlectx->total_bytes_written+=1; } } rlectx->pending_data_start+=rlectx->unc_len; rlectx->unc_len=0; } static void rle8_write_unc_and_run(struct rle_context *rlectx) { iw_byte dstbuf[2]; rle8_write_unc(rlectx); if(rlectx->run_len<1) { return; } if(rlectx->run_len>255) { iw_set_error(rlectx->ctx,"Internal: RLE encode error 6"); return; } dstbuf[0] = (iw_byte)rlectx->run_len; dstbuf[1] = rlectx->run_byte; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; rlectx->pending_data_start+=rlectx->run_len; rlectx->run_len=0; } static void rle_write_trns(struct rle_context *rlectx, int num_trns) { iw_byte dstbuf[4]; int num_remaining = num_trns; int num_to_write; while(num_remaining>0) { num_to_write = num_remaining; if(num_to_write>255) num_to_write=255; dstbuf[0]=0x00; // 00 02 = Delta dstbuf[1]=0x02; dstbuf[2]=(iw_byte)num_to_write; // X offset dstbuf[3]=0x00; // Y offset iwbmp_write(rlectx->wctx,dstbuf,4); rlectx->total_bytes_written+=4; num_remaining -= num_to_write; } rlectx->pending_data_start += num_trns; } // The RLE format used by BMP files is pretty simple, but I've gone to some // effort to optimize it for file size, which makes for a complicated // algorithm. // The overall idea: // We defer writing data until certain conditions are met. In the meantime, // we split the unwritten data into two segments: // "UNC": data classified as uncompressible // "RUN": data classified as compressible. All bytes in this segment must be // identical. // The RUN segment always follows the UNC segment. // For each byte in turn, we examine the current state, and do one of a number // of things, such as: // - add it to RUN // - add it to UNC (if there is no RUN) // - move RUN into UNC, then add it to RUN (or to UNC) // - move UNC and RUN to the file, then make it the new RUN // Then, we check to see if we've accumulated enough data that something needs // to be written out. static int rle8_compress_row(struct rle_context *rlectx) { size_t i; iw_byte dstbuf[2]; iw_byte next_byte; int next_pix_is_trns; int num_trns = 0; // number of consecutive transparent pixels seen int retval = 0; rlectx->pending_data_start=0; rlectx->unc_len=0; rlectx->run_len=0; for(i=0;i<rlectx->img_width;i++) { // Read the next byte. next_byte = rlectx->srcrow[i]; next_pix_is_trns = (rlectx->wctx->pal->entry[next_byte].a==0); if(num_trns>0 && !next_pix_is_trns) { rle_write_trns(rlectx,num_trns); num_trns=0; } else if(next_pix_is_trns) { if (rlectx->unc_len>0 || rlectx->run_len>0) { rle8_write_unc_and_run(rlectx); } num_trns++; continue; } // -------------------------------------------------------------- // Add the byte we just read to either the UNC or the RUN data. if(rlectx->run_len>0 && next_byte==rlectx->run_byte) { // Byte fits in the current run; add it. rlectx->run_len++; } else if(rlectx->run_len==0) { // We don't have a RUN, so we can put this byte there. rlectx->run_len = 1; rlectx->run_byte = next_byte; } else if(rlectx->unc_len==0 && rlectx->run_len==1) { // We have one previous byte, and it's different from this one. // Move it to UNC, and make this one the RUN. rlectx->unc_len++; rlectx->run_byte = next_byte; } else if(rlectx->unc_len>0 && rlectx->run_len<(rlectx->unc_len==1 ? 3U : 4U)) { // We have a run, but it's not long enough to be beneficial. // Convert it to uncompressed bytes. // A good rule is that a run length of 4 or more (3 or more if // unc_len=1) should always be run-legth encoded. rlectx->unc_len += rlectx->run_len; rlectx->run_len = 0; // If UNC is now odd and >1, add the next byte to it to make it even. // Otherwise, add it to RUN. if(rlectx->unc_len>=3 && (rlectx->unc_len&0x1)) { rlectx->unc_len++; } else { rlectx->run_len = 1; rlectx->run_byte = next_byte; } } else { // Nowhere to put the byte: write out everything, and start fresh. rle8_write_unc_and_run(rlectx); rlectx->run_len = 1; rlectx->run_byte = next_byte; } // -------------------------------------------------------------- // If we hit certain high water marks, write out the current data. if(rlectx->unc_len>=254) { // Our maximum size for an UNC segment. rle8_write_unc(rlectx); } else if(rlectx->unc_len>0 && (rlectx->unc_len+rlectx->run_len)>254) { // It will not be possible to coalesce the RUN into the UNC (it // would be too big) so write out the UNC. rle8_write_unc(rlectx); } else if(rlectx->run_len>=255) { // The maximum size for an RLE segment. rle8_write_unc_and_run(rlectx); } // -------------------------------------------------------------- // Sanity checks. These can be removed if we're sure the algorithm // is bug-free. // We don't allow unc_len to be odd (except temporarily), except // that it can be 1. // What's special about 1 is that if we add another byte to it, it // increases the cost. For 3,5,...,253, we can add another byte for // free, so we should never fail to do that. if((rlectx->unc_len&0x1) && rlectx->unc_len!=1) { iw_set_errorf(rlectx->ctx,"Internal: BMP RLE encode error 1"); goto done; } // unc_len can be at most 252 at this point. // If it were 254, it should have been written out already. if(rlectx->unc_len>252) { iw_set_error(rlectx->ctx,"Internal: BMP RLE encode error 2"); goto done; } // run_len can be at most 254 at this point. // If it were 255, it should have been written out already. if(rlectx->run_len>254) { iw_set_error(rlectx->ctx,"Internal: BMP RLE encode error 3"); goto done; } } // End of row. Write out anything left over. rle8_write_unc_and_run(rlectx); // Write an end-of-line marker (0 0), or if this is the last row, // an end-of-bitmap marker (0 1). dstbuf[0]=0x00; dstbuf[1]= (rlectx->cur_row==0)? 0x01 : 0x00; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; retval = 1; done: return retval; } //============================ RLE4 encoder ============================ // Calculate the most efficient way to split a run of uncompressible pixels. // This only finds the first place to split the run. If the run is still // over 255 pixels, call it again to find the next split. static size_t rle4_get_best_unc_split(size_t n) { // For <=255 pixels, we can never do better than storing it as one run. if(n<=255) return n; // With runs of 252, we can store 252/128 = 1.96875 pixels/byte. // With runs of 255, we can store 255/130 = 1.96153 pixels/byte. // Hence, using runs of 252 is the most efficient way to store a large // number of uncompressible pixels. // (Lengths other than 252 or 255 are no help.) // However, there are three exceptional cases where, if we split at 252, // the most efficient encoding will no longer be possible: if(n==257 || n==510 || n==765) return 255; return 252; } // Returns the incremental cost of adding a pixel to the current UNC // (which is always either 0 or 2). // To derive this function, I calculated the optimal cost of every length, // and enumerated the exceptions to the (n%4)?0:2 rule. // The exceptions are mostly caused by the cases where // rle4_get_best_unc_split() returns 255 instead of 252. static int rle4_get_incr_unc_cost(struct rle_context *rlectx) { int n; int m; n = (int)rlectx->unc_len; if(n==2 || n==255 || n==257 || n==507 || n==510) return 2; if(n==256 || n==508) return 0; if(n>=759) { m = n%252; if(m==3 || m==6 || m==9) return 2; if(m==4 || m==8) return 0; } return (n%4)?0:2; } static void rle4_write_unc(struct rle_context *rlectx) { iw_byte dstbuf[128]; size_t pixels_to_write; size_t bytes_to_write; if(rlectx->unc_len<1) return; // Note that, unlike the RLE8 encoder, we allow this function to be called // with uncompressed runs of arbitrary length. while(rlectx->unc_len>0) { pixels_to_write = rle4_get_best_unc_split(rlectx->unc_len); if(pixels_to_write<3) { // The minimum length for an uncompressed run is 3. For shorter runs // write them "compressed". dstbuf[0] = (iw_byte)pixels_to_write; dstbuf[1] = (rlectx->srcrow[rlectx->pending_data_start]<<4); if(pixels_to_write>1) dstbuf[1] |= (rlectx->srcrow[rlectx->pending_data_start+1]); // The actual writing will occur below. Just indicate how many bytes // of dstbuf[] to write. bytes_to_write = 2; } else { size_t i; // Write the length of the uncompressed run. dstbuf[0] = 0x00; dstbuf[1] = (iw_byte)pixels_to_write; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; // Put the data to write in dstbuf[]. bytes_to_write = 2*((pixels_to_write+3)/4); iw_zeromem(dstbuf,bytes_to_write); for(i=0;i<pixels_to_write;i++) { if(i&0x1) dstbuf[i/2] |= rlectx->srcrow[rlectx->pending_data_start+i]; else dstbuf[i/2] = rlectx->srcrow[rlectx->pending_data_start+i]<<4; } } iwbmp_write(rlectx->wctx,dstbuf,bytes_to_write); rlectx->total_bytes_written += bytes_to_write; rlectx->unc_len -= pixels_to_write; rlectx->pending_data_start += pixels_to_write; } } static void rle4_write_unc_and_run(struct rle_context *rlectx) { iw_byte dstbuf[2]; rle4_write_unc(rlectx); if(rlectx->run_len<1) { return; } if(rlectx->run_len>255) { iw_set_error(rlectx->ctx,"Internal: RLE encode error 6"); return; } dstbuf[0] = (iw_byte)rlectx->run_len; dstbuf[1] = rlectx->run_byte; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; rlectx->pending_data_start+=rlectx->run_len; rlectx->run_len=0; } // Should we move the pending compressible data to the "uncompressed" // segment (return 1), or should we write it to disk as a compressed run of // pixels (0)? static int ok_to_move_to_unc(struct rle_context *rlectx) { // This logic is probably not optimal in every case. // One possible improvement might be to adjust the thresholds when // unc_len+run_len is around 255 or higher. // Other improvements might require looking ahead at pixels we haven't // read yet. if(rlectx->unc_len==0) { return (rlectx->run_len<4); } else if(rlectx->unc_len<=2) { return (rlectx->run_len<6); } else { return (rlectx->run_len<8); } return 0; } static int rle4_compress_row(struct rle_context *rlectx) { size_t i; iw_byte dstbuf[2]; iw_byte next_pix; int next_pix_is_trns; int num_trns = 0; // number of consecutive transparent pixels seen int retval = 0; iw_byte tmpb; rlectx->pending_data_start=0; rlectx->unc_len=0; rlectx->run_len=0; for(i=0;i<rlectx->img_width;i++) { // Read the next pixel next_pix = rlectx->srcrow[i]; next_pix_is_trns = (rlectx->wctx->pal->entry[next_pix].a==0); if(num_trns>0 && !next_pix_is_trns) { rle_write_trns(rlectx,num_trns); num_trns=0; } else if(next_pix_is_trns) { if (rlectx->unc_len>0 || rlectx->run_len>0) { rle4_write_unc_and_run(rlectx); } num_trns++; continue; } // -------------------------------------------------------------- // Add the pixel we just read to either the UNC or the RUN data. if(rlectx->run_len==0) { // We don't have a RUN, so we can put this pixel there. rlectx->run_len = 1; rlectx->run_byte = next_pix<<4; } else if(rlectx->run_len==1) { // If the run is 1, we can always add a 2nd pixel rlectx->run_byte |= next_pix; rlectx->run_len++; } else if(rlectx->run_len>=2 && (rlectx->run_len&1)==0 && next_pix==(rlectx->run_byte>>4)) { // pixel fits in the current run; add it. rlectx->run_len++; } else if(rlectx->run_len>=3 && (rlectx->run_len&1) && next_pix==(rlectx->run_byte&0x0f)) { // pixel fits in the current run; add it. rlectx->run_len++; } else if(rlectx->unc_len==0 && rlectx->run_len==2) { // We have one previous byte, and it's different from this one. // Move it to UNC, and make this one the RUN. rlectx->unc_len+=rlectx->run_len; rlectx->run_byte = next_pix<<4; rlectx->run_len = 1; } else if(ok_to_move_to_unc(rlectx)) { // We have a compressible run, but we think it's not long enough to be // beneficial. Convert it to uncompressed bytes -- except for the last // pixel, which can be left in the run. rlectx->unc_len += rlectx->run_len-1; if((rlectx->run_len&1)==0) rlectx->run_byte = (rlectx->run_byte&0x0f)<<4; else rlectx->run_byte = (rlectx->run_byte&0xf0); // Put the next byte in RLE. (It might get moved to UNC, below.) rlectx->run_len = 2; rlectx->run_byte |= next_pix; } else { // Nowhere to put the byte: write out everything, and start fresh. rle4_write_unc_and_run(rlectx); rlectx->run_len = 1; rlectx->run_byte = next_pix<<4; } // -------------------------------------------------------------- // If any RUN bytes that can be added to UNC for free, do so. while(rlectx->unc_len>0 && rlectx->run_len>0 && rle4_get_incr_unc_cost(rlectx)==0) { rlectx->unc_len++; rlectx->run_len--; tmpb = rlectx->run_byte; // Reverse the two pixels stored in run_byte. rlectx->run_byte = (tmpb>>4) | ((tmpb&0x0f)<<4); if(rlectx->run_len==1) rlectx->run_byte &= 0xf0; } // -------------------------------------------------------------- // If we hit certain high water marks, write out the current data. if(rlectx->run_len>=255) { // The maximum size for an RLE segment. rle4_write_unc_and_run(rlectx); } // -------------------------------------------------------------- // Sanity check(s). This can be removed if we're sure the algorithm // is bug-free. // run_len can be at most 254 at this point. // If it were 255, it should have been written out already. if(rlectx->run_len>255) { iw_set_error(rlectx->ctx,"Internal: BMP RLE encode error 3"); goto done; } } // End of row. Write out anything left over. rle4_write_unc_and_run(rlectx); // Write an end-of-line marker (0 0), or if this is the last row, // an end-of-bitmap marker (0 1). dstbuf[0]=0x00; dstbuf[1]= (rlectx->cur_row==0)? 0x01 : 0x00; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; retval = 1; done: return retval; } //====================================================================== // Seek back and write the "file size" and "bits size" fields. static int rle_patch_file_size(struct iwbmpwcontext *wctx,size_t rlesize) { iw_byte buf[4]; size_t fileheader_size; int ret; if(!wctx->iodescr->seek_fn) { iw_set_error(wctx->ctx,"Writing compressed BMP requires a seek function"); return 0; } if(wctx->include_file_header) { // Patch the file size in the file header ret=(*wctx->iodescr->seek_fn)(wctx->ctx,wctx->iodescr,2,SEEK_SET); if(!ret) return 0; iw_set_ui32le(buf,(unsigned int)(14+wctx->header_size+wctx->bitfields_size+wctx->palsize+rlesize)); iwbmp_write(wctx,buf,4); fileheader_size = 14; } else { fileheader_size = 0; } // Patch the "bits" size ret=(*wctx->iodescr->seek_fn)(wctx->ctx,wctx->iodescr,fileheader_size+20,SEEK_SET); if(!ret) return 0; iw_set_ui32le(buf,(unsigned int)rlesize); iwbmp_write(wctx,buf,4); (*wctx->iodescr->seek_fn)(wctx->ctx,wctx->iodescr,0,SEEK_END); return 1; } static int iwbmp_write_pixels_compressed(struct iwbmpwcontext *wctx, struct iw_image *img) { struct rle_context rlectx; int j; int retval = 0; iw_zeromem(&rlectx,sizeof(struct rle_context)); rlectx.ctx = wctx->ctx; rlectx.wctx = wctx; rlectx.total_bytes_written = 0; rlectx.img_width = img->width; for(j=img->height-1;j>=0;j--) { // Compress and write a row of pixels rlectx.srcrow = &img->pixels[j*img->bpr]; rlectx.cur_row = j; if(wctx->bitcount==4) { if(!rle4_compress_row(&rlectx)) goto done; } else if(wctx->bitcount==8) { if(!rle8_compress_row(&rlectx)) goto done; } else { goto done; } } // Back-patch the 'file size' and 'bits size' fields if(!rle_patch_file_size(wctx,rlectx.total_bytes_written)) goto done; retval = 1; done: return retval; } static void iwbmp_write_pixels_uncompressed(struct iwbmpwcontext *wctx, struct iw_image *img) { int j; iw_byte *dstrow = NULL; const iw_byte *srcrow; dstrow = iw_mallocz(wctx->ctx,wctx->unc_dst_bpr); if(!dstrow) goto done; for(j=img->height-1;j>=0;j--) { srcrow = &img->pixels[j*img->bpr]; switch(wctx->bitcount) { case 32: bmpw_convert_row_16_32(wctx,srcrow,dstrow,img->width); break; case 24: bmpw_convert_row_24(wctx,srcrow,dstrow,img->width); break; case 16: bmpw_convert_row_16_32(wctx,srcrow,dstrow,img->width); break; case 8: bmpw_convert_row_8(srcrow,dstrow,img->width); break; case 4: bmpw_convert_row_4(srcrow,dstrow,img->width); break; case 1: bmpw_convert_row_1(srcrow,dstrow,img->width); break; } iwbmp_write(wctx,dstrow,wctx->unc_dst_bpr); } done: if(dstrow) iw_free(wctx->ctx,dstrow); return; } // 0 = no transparency // 1 = binary transparency // 2 = partial transparency static int check_palette_transparency(const struct iw_palette *p) { int i; int retval = 0; for(i=0;i<p->num_entries;i++) { if(p->entry[i].a!=255) retval=1; if(p->entry[i].a!=255 && p->entry[i].a!=0) return 2; } return retval; } // Do some preparations needed to write a 16-bit or 32-bit BMP. static int setup_16_32bit(struct iwbmpwcontext *wctx, int mcc_r, int mcc_g, int mcc_b, int mcc_a) { int has_alpha; has_alpha = IW_IMGTYPE_HAS_ALPHA(wctx->img->imgtype); if(wctx->bmpversion<3) { iw_set_errorf(wctx->ctx,"Bit depth incompatible with BMP version %d", wctx->bmpversion); return 0; } if(has_alpha && wctx->bmpversion<5) { iw_set_error(wctx->ctx,"Internal: Attempt to write v3 16- or 32-bit image with transparency"); return 0; } // Make our own copy of the max color codes, so that we don't have to // do "if(grayscale)" so much. wctx->maxcolor[0] = mcc_r; wctx->maxcolor[1] = mcc_g; wctx->maxcolor[2] = mcc_b; if(has_alpha) wctx->maxcolor[3] = mcc_a; if(!iwbmp_calc_bitfields_masks(wctx,has_alpha?4:3)) return 0; if(mcc_r==31 && mcc_g==31 && mcc_b==31 && !has_alpha) { // For the default 5-5-5, set the 'compression' to BI_RGB // instead of BITFIELDS, and don't write a BITFIELDS segment // (or for v5 BMP, don't set the Mask fields). wctx->bitfields_size = 0; } else { wctx->uses_bitfields = 1; wctx->bitfields_size = (wctx->bmpversion==3) ? 12 : 0; } return 1; } static int iwbmp_write_main(struct iwbmpwcontext *wctx) { struct iw_image *img; int cmpr_req; int retval = 0; int x; const char *optv; img = wctx->img; wctx->bmpversion = 0; optv = iw_get_option(wctx->ctx, "bmp:version"); if(optv) { wctx->bmpversion = iw_parse_int(optv); } if(wctx->bmpversion==0) wctx->bmpversion=3; if(wctx->bmpversion==4) { iw_warning(wctx->ctx,"Writing BMP v4 is not supported; using v3 instead"); wctx->bmpversion=3; } if(wctx->bmpversion!=2 && wctx->bmpversion!=3 && wctx->bmpversion!=5) { iw_set_errorf(wctx->ctx,"Unsupported BMP version: %d",wctx->bmpversion); goto done; } if(wctx->bmpversion>=3) cmpr_req = iw_get_value(wctx->ctx,IW_VAL_COMPRESSION); else cmpr_req = IW_COMPRESSION_NONE; if(wctx->bmpversion==2) wctx->header_size = 12; else if(wctx->bmpversion==5) wctx->header_size = 124; else wctx->header_size = 40; wctx->no_cslabel = iw_get_value(wctx->ctx,IW_VAL_NO_CSLABEL); // If any kind of compression was requested, use RLE if possible. if(cmpr_req==IW_COMPRESSION_AUTO || cmpr_req==IW_COMPRESSION_NONE) cmpr_req = IW_COMPRESSION_NONE; else cmpr_req = IW_COMPRESSION_RLE; if(img->imgtype==IW_IMGTYPE_RGB) { if(img->reduced_maxcolors) { if(!setup_16_32bit(wctx,img->maxcolorcode[IW_CHANNELTYPE_RED], img->maxcolorcode[IW_CHANNELTYPE_GREEN], img->maxcolorcode[IW_CHANNELTYPE_BLUE],0)) { goto done; } } else { wctx->bitcount=24; } } else if(img->imgtype==IW_IMGTYPE_PALETTE) { if(!wctx->pal) goto done; x = check_palette_transparency(wctx->pal); if(x!=0 && wctx->bmpversion<3) { iw_set_error(wctx->ctx,"Cannot save as a transparent BMP: Incompatible BMP version"); goto done; } else if(x==2) { iw_set_error(wctx->ctx,"Cannot save this image as a transparent BMP: Has partial transparency"); goto done; } else if(x!=0 && cmpr_req!=IW_COMPRESSION_RLE) { iw_set_error(wctx->ctx,"Cannot save as a transparent BMP: RLE compression required"); goto done; } if(wctx->pal->num_entries<=2 && cmpr_req!=IW_COMPRESSION_RLE) wctx->bitcount=1; else if(wctx->pal->num_entries<=16) wctx->bitcount=4; else wctx->bitcount=8; } else if(img->imgtype==IW_IMGTYPE_RGBA) { if(img->reduced_maxcolors) { if(!setup_16_32bit(wctx,img->maxcolorcode[IW_CHANNELTYPE_RED], img->maxcolorcode[IW_CHANNELTYPE_GREEN], img->maxcolorcode[IW_CHANNELTYPE_BLUE], img->maxcolorcode[IW_CHANNELTYPE_ALPHA])) { goto done; } } else { if(!setup_16_32bit(wctx,255,255,255,255)) { goto done; } } } else if(img->imgtype==IW_IMGTYPE_GRAYA) { if(img->reduced_maxcolors) { if(!setup_16_32bit(wctx,img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_ALPHA])) { goto done; } } else { if(!setup_16_32bit(wctx,255,255,255,255)) { goto done; } } } else if(img->imgtype==IW_IMGTYPE_GRAY) { if(img->reduced_maxcolors) { if(img->maxcolorcode[IW_CHANNELTYPE_GRAY]<=1023) { if(!setup_16_32bit(wctx,img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_GRAY],0)) { goto done; } } else { iw_set_error(wctx->ctx,"Cannot write grayscale BMP at this bit depth"); goto done; } } else { // We normally won't get here, because a grayscale image should have // been optimized and converted to a palette image. // But maybe that optimization was disabled. wctx->bitcount=24; } } else { iw_set_error(wctx->ctx,"Internal: Bad image type for BMP"); goto done; } if(cmpr_req==IW_COMPRESSION_RLE && (wctx->bitcount==4 || wctx->bitcount==8)) { wctx->compressed = 1; } wctx->unc_dst_bpr = iwbmp_calc_bpr(wctx->bitcount,img->width); wctx->unc_bitssize = wctx->unc_dst_bpr * img->height; wctx->palentries = 0; if(wctx->pal) { if(wctx->bmpversion==2) { wctx->palentries = 1<<wctx->bitcount; wctx->palsize = wctx->palentries*3; } else { if(wctx->bitcount==1) { // The documentation says that if the bitdepth is 1, the palette // contains exactly two entries. wctx->palentries=2; } else { wctx->palentries = wctx->pal->num_entries; } wctx->palsize = wctx->palentries*4; } } // File header iwbmp_write_file_header(wctx); // Bitmap header ("BITMAPINFOHEADER") if(!iwbmp_write_bmp_header(wctx)) { goto done; } if(wctx->bitfields_size>0) { if(!iwbmp_write_bitfields(wctx)) goto done; } // Palette iwbmp_write_palette(wctx); // Pixels if(wctx->compressed) { if(!iwbmp_write_pixels_compressed(wctx,img)) goto done; } else { iwbmp_write_pixels_uncompressed(wctx,img); } retval = 1; done: return retval; } IW_IMPL(int) iw_write_bmp_file(struct iw_context *ctx, struct iw_iodescr *iodescr) { struct iwbmpwcontext wctx; int retval=0; struct iw_image img1; iw_zeromem(&img1,sizeof(struct iw_image)); iw_zeromem(&wctx,sizeof(struct iwbmpwcontext)); wctx.ctx = ctx; wctx.include_file_header = 1; wctx.iodescr=iodescr; iw_get_output_image(ctx,&img1); wctx.img = &img1; if(wctx.img->imgtype==IW_IMGTYPE_PALETTE) { wctx.pal = iw_get_output_palette(ctx); if(!wctx.pal) goto done; } iw_get_output_colorspace(ctx,&wctx.csdescr); if(!iwbmp_write_main(&wctx)) { iw_set_error(ctx,"BMP write failed"); goto done; } retval=1; done: return retval; }
./CrossVul/dataset_final_sorted/CWE-682/c/good_3331_0
crossvul-cpp_data_bad_2652_0
#include <config.h> #include <view.h> #include <controller.h> #include <configparser.h> #include <configcontainer.h> #include <exceptions.h> #include <downloadthread.h> #include <colormanager.h> #include <logger.h> #include <utils.h> #include <strprintf.h> #include <stflpp.h> #include <exception.h> #include <formatstring.h> #include <regexmanager.h> #include <rss_parser.h> #include <remote_api.h> #include <oldreader_api.h> #include <feedhq_api.h> #include <ttrss_api.h> #include <newsblur_api.h> #include <ocnews_api.h> #include <xlicense.h> #include <cstdlib> #include <cstring> #include <iostream> #include <fstream> #include <cerrno> #include <algorithm> #include <functional> #include <mutex> #include <sys/time.h> #include <ctime> #include <cassert> #include <signal.h> #include <unistd.h> #include <getopt.h> #include <sys/utsname.h> #include <langinfo.h> #include <libgen.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <pwd.h> #include <ncurses.h> #include <libxml/xmlversion.h> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/xmlsave.h> #include <libxml/uri.h> #include <curl/curl.h> namespace newsbeuter { #define LOCK_SUFFIX ".lock" std::string lock_file; int ctrl_c_hit = 0; void ctrl_c_action(int sig) { LOG(level::DEBUG,"caught signal %d",sig); if (SIGINT == sig) { ctrl_c_hit = 1; } else { stfl::reset(); utils::remove_fs_lock(lock_file); ::exit(EXIT_FAILURE); } } void ignore_signal(int sig) { LOG(level::WARN, "caught signal %d but ignored it", sig); } void omg_a_child_died(int /* sig */) { pid_t pid; int stat; while ((pid = waitpid(-1,&stat,WNOHANG)) > 0) { } ::signal(SIGCHLD, omg_a_child_died); /* in case of unreliable signals */ } controller::controller() : v(0), urlcfg(0), rsscache(0), url_file("urls"), cache_file("cache.db"), config_file("config"), queue_file("queue"), refresh_on_start(false), api(0) { } /** * \brief Try to setup XDG style dirs. * * returns false, if that fails */ bool controller::setup_dirs_xdg(const char *env_home, bool silent) { const char *env_xdg_config; const char *env_xdg_data; std::string xdg_config_dir; std::string xdg_data_dir; env_xdg_config = ::getenv("XDG_CONFIG_HOME"); if (env_xdg_config) { xdg_config_dir = env_xdg_config; } else { xdg_config_dir = env_home; xdg_config_dir.append(NEWSBEUTER_PATH_SEP); xdg_config_dir.append(".config"); } env_xdg_data = ::getenv("XDG_DATA_HOME"); if (env_xdg_data) { xdg_data_dir = env_xdg_data; } else { xdg_data_dir = env_home; xdg_data_dir.append(NEWSBEUTER_PATH_SEP); xdg_data_dir.append(".local"); xdg_data_dir.append(NEWSBEUTER_PATH_SEP); xdg_data_dir.append("share"); } xdg_config_dir.append(NEWSBEUTER_PATH_SEP); xdg_config_dir.append(NEWSBEUTER_SUBDIR_XDG); xdg_data_dir.append(NEWSBEUTER_PATH_SEP); xdg_data_dir.append(NEWSBEUTER_SUBDIR_XDG); bool config_dir_exists = 0 == access(xdg_config_dir.c_str(), R_OK | X_OK); if (!config_dir_exists) { if (!silent) { std::cerr << strprintf::fmt( _("XDG: configuration directory '%s' not accessible, " "using '%s' instead."), xdg_config_dir, config_dir) << std::endl; } return false; } /* Invariant: config dir exists. * * At this point, we're confident we'll be using XDG. We don't check if * data dir exists, because if it doesn't we'll create it. */ config_dir = xdg_config_dir; // create data directory if it doesn't exist utils::mkdir_parents(xdg_data_dir, 0700); /* in config */ url_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + url_file; config_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + config_file; /* in data */ cache_file = xdg_data_dir + std::string(NEWSBEUTER_PATH_SEP) + cache_file; lock_file = cache_file + LOCK_SUFFIX; queue_file = xdg_data_dir + std::string(NEWSBEUTER_PATH_SEP) + queue_file; searchfile = strprintf::fmt("%s%shistory.search", xdg_data_dir, NEWSBEUTER_PATH_SEP); cmdlinefile = strprintf::fmt("%s%shistory.cmdline", xdg_data_dir, NEWSBEUTER_PATH_SEP); return true; } void controller::setup_dirs(bool silent) { const char * env_home; if (!(env_home = ::getenv("HOME"))) { struct passwd * spw = ::getpwuid(::getuid()); if (spw) { env_home = spw->pw_dir; } else { std::cerr << _("Fatal error: couldn't determine home directory!") << std::endl; std::cerr << strprintf::fmt(_("Please set the HOME environment variable or add a valid user for UID %u!"), ::getuid()) << std::endl; ::exit(EXIT_FAILURE); } } config_dir = env_home; config_dir.append(NEWSBEUTER_PATH_SEP); config_dir.append(NEWSBEUTER_CONFIG_SUBDIR); if (setup_dirs_xdg(env_home, silent)) return; mkdir(config_dir.c_str(),0700); // create configuration directory if it doesn't exist url_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + url_file; cache_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + cache_file; lock_file = cache_file + LOCK_SUFFIX; config_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + config_file; queue_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + queue_file; searchfile = strprintf::fmt("%s%shistory.search", config_dir, NEWSBEUTER_PATH_SEP); cmdlinefile = strprintf::fmt("%s%shistory.cmdline", config_dir, NEWSBEUTER_PATH_SEP); } controller::~controller() { delete rsscache; delete urlcfg; delete api; std::lock_guard<std::mutex> feedslock(feeds_mutex); for (auto feed : feeds) { std::lock_guard<std::mutex> lock(feed->item_mutex); feed->clear_items(); } feeds.clear(); } void controller::set_view(view * vv) { v = vv; } void controller::run(int argc, char * argv[]) { int c; ::signal(SIGINT, ctrl_c_action); ::signal(SIGPIPE, ignore_signal); ::signal(SIGHUP, ctrl_c_action); ::signal(SIGCHLD, omg_a_child_died); bool do_import = false, do_export = false, cachefile_given_on_cmdline = false, do_vacuum = false; std::string importfile; bool do_read_import = false, do_read_export = false; std::string readinfofile; unsigned int show_version = 0; bool silent = false; bool execute_cmds = false; static const char getopt_str[] = "i:erhqu:c:C:d:l:vVoxXI:E:"; static const struct option longopts[] = { {"cache-file" , required_argument, 0, 'c'}, {"config-file" , required_argument, 0, 'C'}, {"execute" , required_argument, 0, 'x'}, {"export-to-file" , required_argument, 0, 'E'}, {"export-to-opml" , no_argument , 0, 'e'}, {"help" , no_argument , 0, 'h'}, {"import-from-file", required_argument, 0, 'I'}, {"import-from-opml", required_argument, 0, 'i'}, {"log-file" , required_argument, 0, 'd'}, {"log-level" , required_argument, 0, 'l'}, {"quiet" , no_argument , 0, 'q'}, {"refresh-on-start", no_argument , 0, 'r'}, {"url-file" , required_argument, 0, 'u'}, {"vacuum" , no_argument , 0, 'X'}, {"version" , no_argument , 0, 'v'}, {0 , 0 , 0, 0 } }; /* First of all, let's check for options that imply silencing of the * output: import, export, command execution and, well, quiet mode */ while ((c = ::getopt_long(argc, argv, getopt_str, longopts, nullptr)) != -1) { if (strchr("iexq", c) != nullptr) { silent = true; break; } } setup_dirs(silent); /* Now that silencing's set up, let's rewind to the beginning of argv and * process the options */ optind = 1; while ((c = ::getopt_long(argc, argv, getopt_str, longopts, nullptr)) != -1) { switch (c) { case ':': /* fall-through */ case '?': /* missing option */ usage(argv[0]); break; case 'i': if (do_export) usage(argv[0]); do_import = true; importfile = optarg; break; case 'r': refresh_on_start = true; break; case 'e': if (do_import) usage(argv[0]); do_export = true; break; case 'h': usage(argv[0]); break; case 'u': url_file = optarg; break; case 'c': cache_file = optarg; lock_file = std::string(cache_file) + LOCK_SUFFIX; cachefile_given_on_cmdline = true; break; case 'C': config_file = optarg; break; case 'X': do_vacuum = true; break; case 'v': case 'V': show_version++; break; case 'x': execute_cmds = true; break; case 'q': break; case 'd': logger::getInstance().set_logfile(optarg); break; case 'l': { level l = static_cast<level>(atoi(optarg)); if (l > level::NONE && l <= level::DEBUG) { logger::getInstance().set_loglevel(l); } else { std::cerr << strprintf::fmt(_("%s: %d: invalid loglevel value"), argv[0], l) << std::endl; ::std::exit(EXIT_FAILURE); } } break; case 'I': if (do_read_export) usage(argv[0]); do_read_import = true; readinfofile = optarg; break; case 'E': if (do_read_import) usage(argv[0]); do_read_export = true; readinfofile = optarg; break; default: std::cout << strprintf::fmt(_("%s: unknown option - %c"), argv[0], static_cast<char>(c)) << std::endl; usage(argv[0]); break; } }; if (show_version) { version_information(argv[0], show_version); } if (do_import) { LOG(level::INFO,"Importing OPML file from %s",importfile); urlcfg = new file_urlreader(url_file); urlcfg->reload(); import_opml(importfile); return; } LOG(level::INFO, "nl_langinfo(CODESET): %s", nl_langinfo(CODESET)); if (!do_export) { if (!silent) std::cout << strprintf::fmt(_("Starting %s %s..."), PROGRAM_NAME, PROGRAM_VERSION) << std::endl; pid_t pid; if (!utils::try_fs_lock(lock_file, pid)) { if (pid > 0) { LOG(level::ERROR,"an instance is already running: pid = %u",pid); } else { LOG(level::ERROR,"something went wrong with the lock: %s", strerror(errno)); } if (!execute_cmds) { std::cout << strprintf::fmt(_("Error: an instance of %s is already running (PID: %u)"), PROGRAM_NAME, pid) << std::endl; } return; } } if (!silent) std::cout << _("Loading configuration..."); std::cout.flush(); cfg.register_commands(cfgparser); colorman.register_commands(cfgparser); keymap keys(KM_NEWSBEUTER); cfgparser.register_handler("bind-key",&keys); cfgparser.register_handler("unbind-key",&keys); cfgparser.register_handler("macro", &keys); cfgparser.register_handler("ignore-article",&ign); cfgparser.register_handler("always-download",&ign); cfgparser.register_handler("reset-unread-on-update",&ign); cfgparser.register_handler("define-filter",&filters); cfgparser.register_handler("highlight", &rxman); cfgparser.register_handler("highlight-article", &rxman); try { cfgparser.parse("/etc/" PROGRAM_NAME "/config"); cfgparser.parse(config_file); } catch (const configexception& ex) { LOG(level::ERROR,"an exception occurred while parsing the configuration file: %s",ex.what()); std::cout << ex.what() << std::endl; utils::remove_fs_lock(lock_file); return; } update_config(); if (!silent) std::cout << _("done.") << std::endl; // create cache object std::string cachefilepath = cfg.get_configvalue("cache-file"); if (cachefilepath.length() > 0 && !cachefile_given_on_cmdline) { cache_file = cachefilepath.c_str(); // ok, we got another cache file path via the configuration // that means we need to remove the old lock file, assemble // the new lock file's name, and then try to lock it. utils::remove_fs_lock(lock_file); lock_file = std::string(cache_file) + LOCK_SUFFIX; pid_t pid; if (!utils::try_fs_lock(lock_file, pid)) { if (pid > 0) { LOG(level::ERROR,"an instance is already running: pid = %u",pid); } else { LOG(level::ERROR,"something went wrong with the lock: %s", strerror(errno)); } std::cout << strprintf::fmt(_("Error: an instance of %s is already running (PID: %u)"), PROGRAM_NAME, pid) << std::endl; return; } } if (!silent) { std::cout << _("Opening cache..."); std::cout.flush(); } try { rsscache = new cache(cache_file,&cfg); } catch (const dbexception& e) { std::cerr << strprintf::fmt(_("Error: opening the cache file `%s' failed: %s"), cache_file, e.what()) << std::endl; utils::remove_fs_lock(lock_file); ::exit(EXIT_FAILURE); } if (!silent) { std::cout << _("done.") << std::endl; } std::string type = cfg.get_configvalue("urls-source"); if (type == "local") { urlcfg = new file_urlreader(url_file); } else if (type == "opml") { urlcfg = new opml_urlreader(&cfg); } else if (type == "oldreader") { api = new oldreader_api(&cfg); urlcfg = new oldreader_urlreader(&cfg, url_file, api); } else if (type == "ttrss") { api = new ttrss_api(&cfg); urlcfg = new ttrss_urlreader(url_file, api); } else if (type == "newsblur") { api = new newsblur_api(&cfg); urlcfg = new newsblur_urlreader(url_file, api); } else if (type == "feedhq") { api = new feedhq_api(&cfg); urlcfg = new feedhq_urlreader(&cfg, url_file, api); } else if (type == "ocnews") { api = new ocnews_api(&cfg); urlcfg = new ocnews_urlreader(url_file, api); } else { LOG(level::ERROR,"unknown urls-source `%s'", urlcfg->get_source()); } if (!do_export && !silent) { std::cout << strprintf::fmt(_("Loading URLs from %s..."), urlcfg->get_source()); std::cout.flush(); } if (api) { if (!api->authenticate()) { std::cout << "Authentication failed." << std::endl; utils::remove_fs_lock(lock_file); return; } } urlcfg->reload(); if (!do_export && !silent) { std::cout << _("done.") << std::endl; } if (urlcfg->get_urls().size() == 0) { LOG(level::ERROR,"no URLs configured."); std::string msg; if (type == "local") { msg = strprintf::fmt(_("Error: no URLs configured. Please fill the file %s with RSS feed URLs or import an OPML file."), url_file); } else if (type == "opml") { msg = strprintf::fmt(_("It looks like the OPML feed you subscribed contains no feeds. Please fill it with feeds, and try again.")); } else if (type == "oldreader") { msg = strprintf::fmt(_("It looks like you haven't configured any feeds in your The Old Reader account. Please do so, and try again.")); } else if (type == "ttrss") { msg = strprintf::fmt(_("It looks like you haven't configured any feeds in your Tiny Tiny RSS account. Please do so, and try again.")); } else if (type == "newsblur") { msg = strprintf::fmt(_("It looks like you haven't configured any feeds in your NewsBlur account. Please do so, and try again.")); } else { assert(0); // shouldn't happen } std::cout << msg << std::endl << std::endl; usage(argv[0]); } if (!do_export && !do_vacuum && !silent) std::cout << _("Loading articles from cache..."); if (do_vacuum) std::cout << _("Opening cache..."); std::cout.flush(); if (do_vacuum) { std::cout << _("done.") << std::endl; std::cout << _("Cleaning up cache thoroughly..."); std::cout.flush(); rsscache->do_vacuum(); std::cout << _("done.") << std::endl; utils::remove_fs_lock(lock_file); return; } unsigned int i=0; for (auto url : urlcfg->get_urls()) { try { bool ignore_disp = (cfg.get_configvalue("ignore-mode") == "display"); std::shared_ptr<rss_feed> feed = rsscache->internalize_rssfeed(url, ignore_disp ? &ign : nullptr); feed->set_tags(urlcfg->get_tags(url)); feed->set_order(i); std::lock_guard<std::mutex> feedslock(feeds_mutex); feeds.push_back(feed); } catch(const dbexception& e) { std::cout << _("Error while loading feeds from database: ") << e.what() << std::endl; utils::remove_fs_lock(lock_file); return; } catch(const std::string& str) { std::cout << strprintf::fmt(_("Error while loading feed '%s': %s"), url, str) << std::endl; utils::remove_fs_lock(lock_file); return; } i++; } std::vector<std::string> tags = urlcfg->get_alltags(); if (!do_export && !silent) std::cout << _("done.") << std::endl; // if configured, we fill all query feeds with some data; no need to sort it, it will be refilled when actually opening it. if (cfg.get_configvalue_as_bool("prepopulate-query-feeds")) { std::cout << _("Prepopulating query feeds..."); std::cout.flush(); std::lock_guard<std::mutex> feedslock(feeds_mutex); for (auto feed : feeds) { if (feed->rssurl().substr(0,6) == "query:") { feed->update_items(get_all_feeds_unlocked()); } } std::cout << _("done.") << std::endl; } sort_feeds(); if (do_export) { export_opml(); utils::remove_fs_lock(lock_file); return; } if (do_read_import) { LOG(level::INFO,"Importing read information file from %s",readinfofile); std::cout << _("Importing list of read articles..."); std::cout.flush(); import_read_information(readinfofile); std::cout << _("done.") << std::endl; return; } if (do_read_export) { LOG(level::INFO,"Exporting read information file to %s",readinfofile); std::cout << _("Exporting list of read articles..."); std::cout.flush(); export_read_information(readinfofile); std::cout << _("done.") << std::endl; return; } // hand over the important objects to the view v->set_config_container(&cfg); v->set_keymap(&keys); v->set_tags(tags); if (execute_cmds) { execute_commands(argv, optind); utils::remove_fs_lock(lock_file); return; } // if the user wants to refresh on startup via configuration file, then do so, // but only if -r hasn't been supplied. if (!refresh_on_start && cfg.get_configvalue_as_bool("refresh-on-startup")) { refresh_on_start = true; } formaction::load_histories(searchfile, cmdlinefile); // run the view v->run(); unsigned int history_limit = cfg.get_configvalue_as_int("history-limit"); LOG(level::DEBUG, "controller::run: history-limit = %u", history_limit); formaction::save_histories(searchfile, cmdlinefile, history_limit); if (!silent) { std::cout << _("Cleaning up cache..."); std::cout.flush(); } try { std::lock_guard<std::mutex> feedslock(feeds_mutex); rsscache->cleanup_cache(feeds); if (!silent) { std::cout << _("done.") << std::endl; } } catch (const dbexception& e) { LOG(level::USERERROR, "Cleaning up cache failed: %s", e.what()); if (!silent) { std::cout << _("failed: ") << e.what() << std::endl; } } utils::remove_fs_lock(lock_file); } void controller::update_feedlist() { std::lock_guard<std::mutex> feedslock(feeds_mutex); v->set_feedlist(feeds); } void controller::update_visible_feeds() { std::lock_guard<std::mutex> feedslock(feeds_mutex); v->update_visible_feeds(feeds); } void controller::mark_all_read(const std::string& feedurl) { try { rsscache->mark_all_read(feedurl); } catch (const dbexception& e) { v->show_error(strprintf::fmt(_("Error: couldn't mark all feeds read: %s"), e.what())); return; } std::lock_guard<std::mutex> feedslock(feeds_mutex); for (const auto& feed : feeds) { std::lock_guard<std::mutex> lock(feed->item_mutex); if (feedurl.length() > 0 && feed->rssurl() != feedurl) continue; if (feed->total_item_count() > 0) { if (api) { api->mark_all_read(feed->rssurl()); } for (auto item : feed->items()) { item->set_unread_nowrite(false); } } // no point in going on - there is only one feed with a given URL if (feedurl.length() > 0) break; } } void controller::mark_article_read(const std::string& guid, bool read) { if (api) { api->mark_article_read(guid, read); } } void controller::mark_all_read(unsigned int pos) { if (pos < feeds.size()) { scope_measure m("controller::mark_all_read"); std::lock_guard<std::mutex> feedslock(feeds_mutex); std::shared_ptr<rss_feed> feed = feeds[pos]; if (feed->rssurl().substr(0,6) == "query:") { rsscache->mark_all_read(feed); } else { rsscache->mark_all_read(feed->rssurl()); if (api) { api->mark_all_read(feed->rssurl()); } } m.stopover("after rsscache->mark_all_read, before iteration over items"); std::lock_guard<std::mutex> lock(feed->item_mutex); std::vector<std::shared_ptr<rss_item>>& items = feed->items(); if (items.size() > 0) { bool notify = items[0]->feedurl() != feed->rssurl(); LOG(level::DEBUG, "controller::mark_all_read: notify = %s", notify ? "yes" : "no"); for (auto item : items) { item->set_unread_nowrite_notify(false, notify); } } } } void controller::reload(unsigned int pos, unsigned int max, bool unattended, curl_handle *easyhandle) { LOG(level::DEBUG, "controller::reload: pos = %u max = %u", pos, max); if (pos < feeds.size()) { std::shared_ptr<rss_feed> oldfeed = feeds[pos]; std::string errmsg; if (!unattended) v->set_status(strprintf::fmt(_("%sLoading %s..."), prepare_message(pos+1, max), utils::censor_url(oldfeed->rssurl()))); bool ignore_dl = (cfg.get_configvalue("ignore-mode") == "download"); rss_parser parser(oldfeed->rssurl(), rsscache, &cfg, ignore_dl ? &ign : nullptr, api); parser.set_easyhandle(easyhandle); LOG(level::DEBUG, "controller::reload: created parser"); try { oldfeed->set_status(dl_status::DURING_DOWNLOAD); std::shared_ptr<rss_feed> newfeed = parser.parse(); if (newfeed->total_item_count() > 0) { std::lock_guard<std::mutex> feedslock(feeds_mutex); save_feed(newfeed, pos); newfeed->clear_items(); bool ignore_disp = (cfg.get_configvalue("ignore-mode") == "display"); std::shared_ptr<rss_feed> feed = rsscache->internalize_rssfeed(oldfeed->rssurl(), ignore_disp ? &ign : nullptr); feed->set_tags(urlcfg->get_tags(oldfeed->rssurl())); feed->set_order(oldfeed->get_order()); feeds[pos] = feed; enqueue_items(feed); oldfeed->clear_items(); v->notify_itemlist_change(feeds[pos]); if (!unattended) { v->set_feedlist(feeds); } } else { LOG(level::DEBUG, "controller::reload: feed is empty"); } oldfeed->set_status(dl_status::SUCCESS); v->set_status(""); } catch (const dbexception& e) { errmsg = strprintf::fmt(_("Error while retrieving %s: %s"), utils::censor_url(oldfeed->rssurl()), e.what()); } catch (const std::string& emsg) { errmsg = strprintf::fmt(_("Error while retrieving %s: %s"), utils::censor_url(oldfeed->rssurl()), emsg); } catch (rsspp::exception& e) { errmsg = strprintf::fmt(_("Error while retrieving %s: %s"), utils::censor_url(oldfeed->rssurl()), e.what()); } if (errmsg != "") { oldfeed->set_status(dl_status::DL_ERROR); v->set_status(errmsg); LOG(level::USERERROR, "%s", errmsg); } } else { v->show_error(_("Error: invalid feed!")); } } std::shared_ptr<rss_feed> controller::get_feed(unsigned int pos) { std::lock_guard<std::mutex> feedslock(feeds_mutex); if (pos >= feeds.size()) { throw std::out_of_range(_("invalid feed index (bug)")); } std::shared_ptr<rss_feed> feed = feeds[pos]; return feed; } void controller::reload_indexes(const std::vector<int>& indexes, bool unattended) { scope_measure m1("controller::reload_indexes"); unsigned int unread_feeds, unread_articles; compute_unread_numbers(unread_feeds, unread_articles); unsigned long size; { std::lock_guard<std::mutex> feedslock(feeds_mutex); size = feeds.size(); } for (auto idx : indexes) { this->reload(idx, size, unattended); } unsigned int unread_feeds2, unread_articles2; compute_unread_numbers(unread_feeds2, unread_articles2); bool notify_always = cfg.get_configvalue_as_bool("notify-always"); if (notify_always || unread_feeds2 != unread_feeds || unread_articles2 != unread_articles) { fmtstr_formatter fmt; fmt.register_fmt('f', std::to_string(unread_feeds2)); fmt.register_fmt('n', std::to_string(unread_articles2)); fmt.register_fmt('d', std::to_string(unread_articles2 - unread_articles)); fmt.register_fmt('D', std::to_string(unread_feeds2 - unread_feeds)); this->notify(fmt.do_format(cfg.get_configvalue("notify-format"))); } if (!unattended) v->set_status(""); } void controller::reload_range(unsigned int start, unsigned int end, unsigned int size, bool unattended) { std::vector<unsigned int> v; for (unsigned int i=start; i<=end; ++i) v.push_back(i); auto extract = [](std::string& s, const std::string& url) { size_t p = url.find("//"); p = (p == std::string::npos) ? 0 : p+2; std::string suff(url.substr(p)); p = suff.find('/'); s = suff.substr(0, p); }; std::sort(v.begin(), v.end(), [&](unsigned int a, unsigned int b) { std::string domain1, domain2; extract(domain1, feeds[a]->rssurl()); extract(domain2, feeds[b]->rssurl()); std::reverse(domain1.begin(), domain1.end()); std::reverse(domain2.begin(), domain2.end()); return domain1 < domain2; }); curl_handle easyhandle; for (auto i : v) { LOG(level::DEBUG, "controller::reload_range: reloading feed #%u", i); this->reload(i, size, unattended, &easyhandle); } } void controller::reload_all(bool unattended) { unsigned int unread_feeds, unread_articles; compute_unread_numbers(unread_feeds, unread_articles); unsigned int num_threads = cfg.get_configvalue_as_int("reload-threads"); time_t t1, t2, dt; unsigned int size; { std::lock_guard<std::mutex> feedlock(feeds_mutex); for (auto feed : feeds) { feed->reset_status(); } size = feeds.size(); } if (num_threads < 1) num_threads = 1; if (num_threads > size) { num_threads = size; } t1 = time(nullptr); LOG(level::DEBUG,"controller::reload_all: starting with reload all..."); if (num_threads <= 1) { this->reload_range(0, size-1, size, unattended); } else { std::vector<std::pair<unsigned int, unsigned int>> partitions = utils::partition_indexes(0, size-1, num_threads); std::vector<std::thread> threads; LOG(level::DEBUG, "controller::reload_all: starting reload threads..."); for (unsigned int i=0; i<num_threads-1; i++) { threads.push_back(std::thread(reloadrangethread(this, partitions[i].first, partitions[i].second, size, unattended))); } LOG(level::DEBUG, "controller::reload_all: starting my own reload..."); this->reload_range(partitions[num_threads-1].first, partitions[num_threads-1].second, size, unattended); LOG(level::DEBUG, "controller::reload_all: joining other threads..."); for (size_t i=0; i<threads.size(); i++) { threads[i].join(); } } // refresh query feeds (update and sort) LOG(level::DEBUG, "controller::reload_all: refresh query feeds"); for (auto feed : feeds) { v->prepare_query_feed(feed); } v->force_redraw(); sort_feeds(); update_feedlist(); t2 = time(nullptr); dt = t2 - t1; LOG(level::INFO, "controller::reload_all: reload took %d seconds", dt); unsigned int unread_feeds2, unread_articles2; compute_unread_numbers(unread_feeds2, unread_articles2); bool notify_always = cfg.get_configvalue_as_bool("notify-always"); if (notify_always || unread_feeds2 > unread_feeds || unread_articles2 > unread_articles) { int article_count = unread_articles2 - unread_articles; int feed_count = unread_feeds2 - unread_feeds; LOG(level::DEBUG, "unread article count: %d", article_count); LOG(level::DEBUG, "unread feed count: %d", feed_count); fmtstr_formatter fmt; fmt.register_fmt('f', std::to_string(unread_feeds2)); fmt.register_fmt('n', std::to_string(unread_articles2)); fmt.register_fmt('d', std::to_string(article_count >= 0 ? article_count : 0)); fmt.register_fmt('D', std::to_string(feed_count >= 0 ? feed_count : 0)); this->notify(fmt.do_format(cfg.get_configvalue("notify-format"))); } } void controller::notify(const std::string& msg) { if (cfg.get_configvalue_as_bool("notify-screen")) { LOG(level::DEBUG, "controller:notify: notifying screen"); std::cout << "\033^" << msg << "\033\\"; std::cout.flush(); } if (cfg.get_configvalue_as_bool("notify-xterm")) { LOG(level::DEBUG, "controller:notify: notifying xterm"); std::cout << "\033]2;" << msg << "\033\\"; std::cout.flush(); } if (cfg.get_configvalue_as_bool("notify-beep")) { LOG(level::DEBUG, "controller:notify: notifying beep"); ::beep(); } if (cfg.get_configvalue("notify-program").length() > 0) { std::string prog = cfg.get_configvalue("notify-program"); LOG(level::DEBUG, "controller:notify: notifying external program `%s'", prog); utils::run_command(prog, msg); } } void controller::compute_unread_numbers(unsigned int& unread_feeds, unsigned int& unread_articles) { unread_feeds = 0; unread_articles = 0; for (auto feed : feeds) { unsigned int items = feed->unread_item_count(); if (items > 0) { ++unread_feeds; unread_articles += items; } } } bool controller::trylock_reload_mutex() { if (reload_mutex.try_lock()) { LOG(level::DEBUG, "controller::trylock_reload_mutex succeeded"); return true; } LOG(level::DEBUG, "controller::trylock_reload_mutex failed"); return false; } void controller::start_reload_all_thread(std::vector<int> * indexes) { LOG(level::INFO,"starting reload all thread"); std::thread t(downloadthread(this, indexes)); t.detach(); } void controller::version_information(const char * argv0, unsigned int level) { if (level<=1) { std::cout << PROGRAM_NAME << " " << PROGRAM_VERSION << " - " << PROGRAM_URL << std::endl; std::cout << "Copyright (C) 2006-2015 Andreas Krennmair" << std::endl; std::cout << "Copyright (C) 2015-2017 Alexander Batischev" << std::endl; std::cout << "Copyright (C) 2006-2017 Newsbeuter contributors" << std::endl; std::cout << std::endl; std::cout << _("newsbeuter is free software and licensed under the MIT/X Consortium License.") << std::endl; std::cout << strprintf::fmt(_("Type `%s -vv' for more information."), argv0) << std::endl << std::endl; struct utsname xuts; uname(&xuts); std::cout << PROGRAM_NAME << " " << PROGRAM_VERSION << std::endl; std::cout << "System: " << xuts.sysname << " " << xuts.release << " (" << xuts.machine << ")" << std::endl; #if defined(__GNUC__) && defined(__VERSION__) std::cout << "Compiler: g++ " << __VERSION__ << std::endl; #endif std::cout << "ncurses: " << curses_version() << " (compiled with " << NCURSES_VERSION << ")" << std::endl; std::cout << "libcurl: " << curl_version() << " (compiled with " << LIBCURL_VERSION << ")" << std::endl; std::cout << "SQLite: " << sqlite3_libversion() << " (compiled with " << SQLITE_VERSION << ")" << std::endl; std::cout << "libxml2: compiled with " << LIBXML_DOTTED_VERSION << std::endl << std::endl; } else { std::cout << LICENSE_str << std::endl; } ::exit(EXIT_SUCCESS); } void controller::usage(char * argv0) { auto msg = strprintf::fmt(_("%s %s\nusage: %s [-i <file>|-e] [-u <urlfile>] " "[-c <cachefile>] [-x <command> ...] [-h]\n"), PROGRAM_NAME, PROGRAM_VERSION, argv0); std::cout << msg; struct arg { const char name; const std::string longname; const std::string params; const std::string desc; }; static const std::vector<arg> args = { { 'e', "export-to-opml" , "" , _s("export OPML feed to stdout") } , { 'r', "refresh-on-start", "" , _s("refresh feeds on start") } , { 'i', "import-from-opml", _s("<file>") , _s("import OPML file") } , { 'u', "url-file" , _s("<urlfile>") , _s("read RSS feed URLs from <urlfile>") } , { 'c', "cache-file" , _s("<cachefile>") , _s("use <cachefile> as cache file") } , { 'C', "config-file" , _s("<configfile>"), _s("read configuration from <configfile>") } , { 'X', "vacuum" , "" , _s("compact the cache") } , { 'x', "execute" , _s("<command>..."), _s("execute list of commands") } , { 'q', "quiet" , "" , _s("quiet startup") } , { 'v', "version" , "" , _s("get version information") } , { 'l', "log-level" , _s("<loglevel>") , _s("write a log with a certain loglevel (valid values: 1 to 6)") } , { 'd', "log-file" , _s("<logfile>") , _s("use <logfile> as output log file") } , { 'E', "export-to-file" , _s("<file>") , _s("export list of read articles to <file>") } , { 'I', "import-from-file", _s("<file>") , _s("import list of read articles from <file>") } , { 'h', "help" , "" , _s("this help") } }; for (const auto & a : args) { std::string longcolumn("-"); longcolumn += a.name; longcolumn += ", --" + a.longname; longcolumn += a.params.size() > 0 ? "=" + a.params : ""; std::cout << "\t" << longcolumn; for (unsigned int j = 0; j < utils::gentabs(longcolumn); j++) { std::cout << "\t"; } std::cout << a.desc << std::endl; } ::exit(EXIT_FAILURE); } void controller::import_opml(const std::string& filename) { xmlDoc * doc = xmlReadFile(filename.c_str(), nullptr, 0); if (doc == nullptr) { std::cout << strprintf::fmt(_("An error occurred while parsing %s."), filename) << std::endl; return; } xmlNode * root = xmlDocGetRootElement(doc); for (xmlNode * node = root->children; node != nullptr; node = node->next) { if (strcmp((const char *)node->name, "body")==0) { LOG(level::DEBUG, "import_opml: found body"); rec_find_rss_outlines(node->children, ""); urlcfg->write_config(); } } xmlFreeDoc(doc); std::cout << strprintf::fmt(_("Import of %s finished."), filename) << std::endl; } void controller::export_opml() { xmlDocPtr root = xmlNewDoc((const xmlChar *)"1.0"); xmlNodePtr opml_node = xmlNewDocNode(root, nullptr, (const xmlChar *)"opml", nullptr); xmlSetProp(opml_node, (const xmlChar *)"version", (const xmlChar *)"1.0"); xmlDocSetRootElement(root, opml_node); xmlNodePtr head = xmlNewTextChild(opml_node, nullptr, (const xmlChar *)"head", nullptr); xmlNewTextChild(head, nullptr, (const xmlChar *)"title", (const xmlChar *)PROGRAM_NAME " - Exported Feeds"); xmlNodePtr body = xmlNewTextChild(opml_node, nullptr, (const xmlChar *)"body", nullptr); for (auto feed : feeds) { if (!utils::is_special_url(feed->rssurl())) { std::string rssurl = feed->rssurl(); std::string link = feed->link(); std::string title = feed->title(); xmlNodePtr outline = xmlNewTextChild(body, nullptr, (const xmlChar *)"outline", nullptr); xmlSetProp(outline, (const xmlChar *)"type", (const xmlChar *)"rss"); xmlSetProp(outline, (const xmlChar *)"xmlUrl", (const xmlChar *)rssurl.c_str()); xmlSetProp(outline, (const xmlChar *)"htmlUrl", (const xmlChar *)link.c_str()); xmlSetProp(outline, (const xmlChar *)"title", (const xmlChar *)title.c_str()); } } xmlSaveCtxtPtr savectx = xmlSaveToFd(1, nullptr, 1); xmlSaveDoc(savectx, root); xmlSaveClose(savectx); xmlFreeNode(opml_node); } void controller::rec_find_rss_outlines(xmlNode * node, std::string tag) { while (node) { std::string newtag = tag; if (strcmp((const char *)node->name, "outline")==0) { char * url = (char *)xmlGetProp(node, (const xmlChar *)"xmlUrl"); if (!url) { url = (char *)xmlGetProp(node, (const xmlChar *)"url"); } if (url) { LOG(level::DEBUG,"OPML import: found RSS outline with url = %s",url); std::string nurl = std::string(url); // Liferea uses a pipe to signal feeds read from the output of // a program in its OPMLs. Convert them to our syntax. if (*url == '|') { nurl = strprintf::fmt("exec:%s", url+1); LOG(level::DEBUG,"OPML import: liferea-style url %s converted to %s", url, nurl); } // Handle OPML filters. char * filtercmd = (char *)xmlGetProp(node, (const xmlChar *)"filtercmd"); if (filtercmd) { LOG(level::DEBUG,"OPML import: adding filter command %s to url %s", filtercmd, nurl); nurl.insert(0, strprintf::fmt("filter:%s:", filtercmd)); xmlFree(filtercmd); } xmlFree(url); // Filters and scripts may have arguments, so, quote them when needed. url = (char*) xmlStrdup((const xmlChar*)utils::quote_if_necessary(nurl).c_str()); assert(url); bool found = false; LOG(level::DEBUG, "OPML import: size = %u", urlcfg->get_urls().size()); if (urlcfg->get_urls().size() > 0) { for (auto u : urlcfg->get_urls()) { if (u == url) { found = true; } } } if (!found) { LOG(level::DEBUG,"OPML import: added url = %s",url); urlcfg->get_urls().push_back(std::string(url)); if (tag.length() > 0) { LOG(level::DEBUG, "OPML import: appending tag %s to url %s", tag, url); urlcfg->get_tags(url).push_back(tag); } } else { LOG(level::DEBUG,"OPML import: url = %s is already in list",url); } xmlFree(url); } else { char * text = (char *)xmlGetProp(node, (const xmlChar *)"text"); if (!text) text = (char *)xmlGetProp(node, (const xmlChar *)"title"); if (text) { if (newtag.length() > 0) { newtag.append("/"); } newtag.append(text); xmlFree(text); } } } rec_find_rss_outlines(node->children, newtag); node = node->next; } } std::vector<std::shared_ptr<rss_item>> controller::search_for_items(const std::string& query, std::shared_ptr<rss_feed> feed) { std::vector<std::shared_ptr<rss_item>> items; LOG(level::DEBUG, "controller::search_for_items: setting feed pointers"); if (feed != nullptr && feed->rssurl().substr(0,6) == "query:") { for (auto item : feed->items()) { if (!item->deleted() && (item->title().find(query) != std::string::npos || item->description().find(query) != std::string::npos)) { std::shared_ptr<rss_item> newitem(new rss_item(nullptr)); newitem->set_guid(item->guid()); newitem->set_title(item->title()); newitem->set_author(item->author()); newitem->set_link(item->link()); newitem->set_pubDate(item->pubDate_timestamp()); newitem->set_size(item->size()); newitem->set_unread(item->unread()); newitem->set_feedurl(item->feedurl()); newitem->set_enclosure_url(item->enclosure_url()); newitem->set_enclosure_type(item->enclosure_type()); newitem->set_enqueued(item->enqueued()); newitem->set_flags(item->flags()); newitem->set_base(item->get_base()); newitem->set_feedptr(item->get_feedptr()); newitem->set_cache(get_cache()); items.push_back(newitem); } } } else { items = rsscache->search_for_items(query, (feed != nullptr ? feed->rssurl() : "")); for (auto item : items) { item->set_feedptr(get_feed_by_url(item->feedurl())); } } return items; } std::shared_ptr<rss_feed> controller::get_feed_by_url(const std::string& feedurl) { for (auto feed : feeds) { if (feedurl == feed->rssurl()) return feed; } LOG(level::ERROR, "controller:get_feed_by_url failed for %s", feedurl); return std::shared_ptr<rss_feed>(); } bool controller::is_valid_podcast_type(const std::string& /* mimetype */) { return true; } void controller::enqueue_url(const std::string& url, std::shared_ptr<rss_feed> feed) { bool url_found = false; std::fstream f; f.open(queue_file.c_str(), std::fstream::in); if (f.is_open()) { do { std::string line; getline(f, line); if (!f.eof() && line.length() > 0) { std::vector<std::string> fields = utils::tokenize_quoted(line); if (!fields.empty() && fields[0] == url) { url_found = true; break; } } } while (!f.eof()); f.close(); } if (!url_found) { f.open(queue_file.c_str(), std::fstream::app | std::fstream::out); std::string filename = generate_enqueue_filename(url, feed); f << url << " " << stfl::quote(filename) << std::endl; f.close(); } } void controller::reload_urls_file() { urlcfg->reload(); std::vector<std::shared_ptr<rss_feed>> new_feeds; unsigned int i = 0; for (auto url : urlcfg->get_urls()) { bool found = false; for (auto feed : feeds) { if (url == feed->rssurl()) { found = true; feed->set_tags(urlcfg->get_tags(url)); feed->set_order(i); new_feeds.push_back(feed); break; } } if (!found) { try { bool ignore_disp = (cfg.get_configvalue("ignore-mode") == "display"); std::shared_ptr<rss_feed> new_feed = rsscache->internalize_rssfeed(url, ignore_disp ? &ign : nullptr); new_feed->set_tags(urlcfg->get_tags(url)); new_feed->set_order(i); new_feeds.push_back(new_feed); } catch(const dbexception& e) { LOG(level::ERROR, "controller::reload_urls_file: caught exception: %s", e.what()); throw; } } i++; } v->set_tags(urlcfg->get_alltags()); { std::lock_guard<std::mutex> feedslock(feeds_mutex); feeds = new_feeds; } sort_feeds(); update_feedlist(); } void controller::edit_urls_file() { const char * editor; editor = getenv("VISUAL"); if (!editor) editor = getenv("EDITOR"); if (!editor) editor = "vi"; std::string cmdline = strprintf::fmt("%s \"%s\"", editor, utils::replace_all(url_file,"\"","\\\"")); v->push_empty_formaction(); stfl::reset(); utils::run_interactively(cmdline, "controller::edit_urls_file"); v->pop_current_formaction(); reload_urls_file(); } /* When passing an argument to a shell script, empty string should be * represented as '' (two quote marks), otherwise shell won't be able to tell * that the parameter is empty */ std::string quote_empty(const std::string& input) { if (input.empty()) { return "''"; } else { return input; } } std::string controller::bookmark( const std::string& url, const std::string& title, const std::string& description, const std::string& feed_title) { std::string bookmark_cmd = cfg.get_configvalue("bookmark-cmd"); bool is_interactive = cfg.get_configvalue_as_bool("bookmark-interactive"); if (bookmark_cmd.length() > 0) { std::string cmdline = strprintf::fmt("%s '%s' %s %s %s", bookmark_cmd, utils::replace_all(url,"'", "%27"), quote_empty(stfl::quote(title)), quote_empty(stfl::quote(description)), quote_empty(stfl::quote(feed_title))); LOG(level::DEBUG, "controller::bookmark: cmd = %s", cmdline); if (is_interactive) { v->push_empty_formaction(); stfl::reset(); utils::run_interactively(cmdline, "controller::bookmark"); v->pop_current_formaction(); return ""; } else { char * my_argv[4]; my_argv[0] = const_cast<char *>("/bin/sh"); my_argv[1] = const_cast<char *>("-c"); my_argv[2] = const_cast<char *>(cmdline.c_str()); my_argv[3] = nullptr; return utils::run_program(my_argv, ""); } } else { return _("bookmarking support is not configured. Please set the configuration variable `bookmark-cmd' accordingly."); } } void controller::execute_commands(char ** argv, unsigned int i) { if (v->formaction_stack_size() > 0) v->pop_current_formaction(); for (; argv[i]; ++i) { LOG(level::DEBUG, "controller::execute_commands: executing `%s'", argv[i]); std::string cmd(argv[i]); if (cmd == "reload") { reload_all(true); } else if (cmd == "print-unread") { std::cout << strprintf::fmt(_("%u unread articles"), rsscache->get_unread_count()) << std::endl; } else { std::cerr << strprintf::fmt(_("%s: %s: unknown command"), argv[0], argv[i]) << std::endl; ::std::exit(EXIT_FAILURE); } } } std::string controller::write_temporary_item(std::shared_ptr<rss_item> item) { char filename[_POSIX_PATH_MAX]; snprintf(filename, sizeof(filename), "/tmp/newsbeuter-article.XXXXXX"); int fd = mkstemp(filename); if (fd != -1) { write_item(item, filename); close(fd); return std::string(filename); } else { return ""; } } void controller::write_item(std::shared_ptr<rss_item> item, const std::string& filename) { std::fstream f; f.open(filename.c_str(),std::fstream::out); if (!f.is_open()) throw exception(errno); write_item(item, f); } void controller::write_item(std::shared_ptr<rss_item> item, std::ostream& ostr) { std::vector<std::pair<LineType, std::string>> lines; std::vector<linkpair> links; // not used std::string title(_("Title: ")); title.append(item->title()); lines.push_back(std::make_pair(LineType::wrappable, title)); std::string author(_("Author: ")); author.append(item->author()); lines.push_back(std::make_pair(LineType::wrappable, author)); std::string date(_("Date: ")); date.append(item->pubDate()); lines.push_back(std::make_pair(LineType::wrappable, date)); std::string link(_("Link: ")); link.append(item->link()); lines.push_back(std::make_pair(LineType::softwrappable, link)); if (item->enclosure_url() != "") { std::string dlurl(_("Podcast Download URL: ")); dlurl.append(item->enclosure_url()); lines.push_back(std::make_pair(LineType::softwrappable, dlurl)); } lines.push_back(std::make_pair(LineType::wrappable, std::string(""))); htmlrenderer rnd(true); rnd.render(item->description(), lines, links, item->feedurl()); textformatter txtfmt; txtfmt.add_lines(lines); unsigned int width = cfg.get_configvalue_as_int("text-width"); if (width == 0) width = 80; ostr << txtfmt.format_text_plain(width) << std::endl; } void controller::mark_deleted(const std::string& guid, bool b) { rsscache->mark_item_deleted(guid, b); } std::string controller::prepare_message(unsigned int pos, unsigned int max) { if (max > 0) { return strprintf::fmt("(%u/%u) ", pos, max); } return ""; } void controller::save_feed(std::shared_ptr<rss_feed> feed, unsigned int pos) { if (!feed->is_empty()) { LOG(level::DEBUG, "controller::save_feed: feed is nonempty, saving"); rsscache->externalize_rssfeed(feed, ign.matches_resetunread(feed->rssurl())); LOG(level::DEBUG, "controller::save_feed: after externalize_rssfeed"); bool ignore_disp = (cfg.get_configvalue("ignore-mode") == "display"); feed = rsscache->internalize_rssfeed(feed->rssurl(), ignore_disp ? &ign : nullptr); LOG(level::DEBUG, "controller::save_feed: after internalize_rssfeed"); feed->set_tags(urlcfg->get_tags(feed->rssurl())); { unsigned int order = feeds[pos]->get_order(); std::lock_guard<std::mutex> itemlock(feeds[pos]->item_mutex); feeds[pos]->clear_items(); feed->set_order(order); } feeds[pos] = feed; v->notify_itemlist_change(feeds[pos]); } else { LOG(level::DEBUG, "controller::save_feed: feed is empty, not saving"); } } void controller::enqueue_items(std::shared_ptr<rss_feed> feed) { if (!cfg.get_configvalue_as_bool("podcast-auto-enqueue")) return; std::lock_guard<std::mutex> lock(feed->item_mutex); for (auto item : feed->items()) { if (!item->enqueued() && item->enclosure_url().length() > 0) { LOG(level::DEBUG, "controller::enqueue_items: enclosure_url = `%s' enclosure_type = `%s'", item->enclosure_url(), item->enclosure_type()); if (is_valid_podcast_type(item->enclosure_type()) && utils::is_http_url(item->enclosure_url())) { LOG(level::INFO, "controller::enqueue_items: enqueuing `%s'", item->enclosure_url()); enqueue_url(item->enclosure_url(), feed); item->set_enqueued(true); rsscache->update_rssitem_unread_and_enqueued(item, feed->rssurl()); } } } } std::string controller::generate_enqueue_filename(const std::string& url, std::shared_ptr<rss_feed> feed) { std::string dlformat = cfg.get_configvalue("download-path"); if (dlformat[dlformat.length()-1] != NEWSBEUTER_PATH_SEP[0]) dlformat.append(NEWSBEUTER_PATH_SEP); fmtstr_formatter fmt; fmt.register_fmt('n', feed->title()); fmt.register_fmt('h', get_hostname_from_url(url)); std::string dlpath = fmt.do_format(dlformat); char buf[2048]; snprintf(buf, sizeof(buf), "%s", url.c_str()); char * base = basename(buf); if (!base || strlen(base) == 0) { char lbuf[128]; time_t t = time(nullptr); strftime(lbuf, sizeof(lbuf), "%Y-%b-%d-%H%M%S.unknown", localtime(&t)); dlpath.append(lbuf); } else { dlpath.append(base); } return dlpath; } std::string controller::get_hostname_from_url(const std::string& url) { xmlURIPtr uri = xmlParseURI(url.c_str()); std::string hostname; if (uri) { hostname = uri->server; xmlFreeURI(uri); } return hostname; } void controller::import_read_information(const std::string& readinfofile) { std::vector<std::string> guids; std::ifstream f(readinfofile.c_str()); std::string line; getline(f,line); if (!f.is_open()) { return; } while (f.is_open() && !f.eof()) { guids.push_back(line); getline(f, line); } rsscache->mark_items_read_by_guid(guids); } void controller::export_read_information(const std::string& readinfofile) { std::vector<std::string> guids = rsscache->get_read_item_guids(); std::fstream f; f.open(readinfofile.c_str(), std::fstream::out); if (f.is_open()) { for (auto guid : guids) { f << guid << std::endl; } } } void controller::sort_feeds() { std::lock_guard<std::mutex> feedslock(feeds_mutex); std::vector<std::string> sortmethod_info = utils::tokenize(cfg.get_configvalue("feed-sort-order"), "-"); std::string sortmethod = sortmethod_info[0]; std::string direction = "desc"; if (sortmethod_info.size() > 1) direction = sortmethod_info[1]; if (sortmethod == "none") { std::stable_sort(feeds.begin(), feeds.end(), [](std::shared_ptr<rss_feed> a, std::shared_ptr<rss_feed> b) { return a->get_order() < b->get_order(); }); } else if (sortmethod == "firsttag") { std::stable_sort(feeds.begin(), feeds.end(), [](std::shared_ptr<rss_feed> a, std::shared_ptr<rss_feed> b) { if (a->get_firsttag().length() == 0 || b->get_firsttag().length() == 0) { return a->get_firsttag().length() > b->get_firsttag().length(); } return strcasecmp(a->get_firsttag().c_str(), b->get_firsttag().c_str()) < 0; }); } else if (sortmethod == "title") { std::stable_sort(feeds.begin(), feeds.end(), [](std::shared_ptr<rss_feed> a, std::shared_ptr<rss_feed> b) { return strcasecmp(a->title().c_str(), b->title().c_str()) < 0; }); } else if (sortmethod == "articlecount") { std::stable_sort(feeds.begin(), feeds.end(), [](std::shared_ptr<rss_feed> a, std::shared_ptr<rss_feed> b) { return a->total_item_count() < b->total_item_count(); }); } else if (sortmethod == "unreadarticlecount") { std::stable_sort(feeds.begin(), feeds.end(), [](std::shared_ptr<rss_feed> a, std::shared_ptr<rss_feed> b) { return a->unread_item_count() < b->unread_item_count(); }); } if (direction == "asc") { std::reverse(feeds.begin(), feeds.end()); } } void controller::update_config() { v->set_regexmanager(&rxman); v->update_bindings(); if (colorman.colors_loaded()) { v->set_colors(colorman.get_fgcolors(), colorman.get_bgcolors(), colorman.get_attributes()); v->apply_colors_to_all_formactions(); } if (cfg.get_configvalue("error-log").length() > 0) { logger::getInstance().set_errorlogfile(cfg.get_configvalue("error-log")); } } void controller::load_configfile(const std::string& filename) { if (cfgparser.parse(filename, true)) { update_config(); } else { v->show_error(strprintf::fmt(_("Error: couldn't open configuration file `%s'!"), filename)); } } void controller::dump_config(const std::string& filename) { std::vector<std::string> configlines; cfg.dump_config(configlines); if (v) { v->get_keys()->dump_config(configlines); } ign.dump_config(configlines); filters.dump_config(configlines); colorman.dump_config(configlines); rxman.dump_config(configlines); std::fstream f; f.open(filename.c_str(), std::fstream::out); if (f.is_open()) { for (auto line : configlines) { f << line << std::endl; } } } unsigned int controller::get_pos_of_next_unread(unsigned int pos) { std::lock_guard<std::mutex> feedslock(feeds_mutex); for (pos++; pos < feeds.size(); pos++) { if (feeds[pos]->unread_item_count() > 0) break; } return pos; } void controller::update_flags(std::shared_ptr<rss_item> item) { if (api) { api->update_article_flags(item->oldflags(), item->flags(), item->guid()); } item->update_flags(); } std::vector<std::shared_ptr<rss_feed>> controller::get_all_feeds() { std::vector<std::shared_ptr<rss_feed>> tmpfeeds; { std::lock_guard<std::mutex> feedslock(feeds_mutex); tmpfeeds = feeds; } return tmpfeeds; } std::vector<std::shared_ptr<rss_feed>> controller::get_all_feeds_unlocked() { return feeds; } unsigned int controller::get_feed_count_per_tag(const std::string& tag) { unsigned int count = 0; std::lock_guard<std::mutex> feedslock(feeds_mutex); for (auto feed : feeds) { if (feed->matches_tag(tag)) { count++; } } return count; } }
./CrossVul/dataset_final_sorted/CWE-943/cpp/bad_2652_0
crossvul-cpp_data_good_2652_0
#include <config.h> #include <view.h> #include <controller.h> #include <configparser.h> #include <configcontainer.h> #include <exceptions.h> #include <downloadthread.h> #include <colormanager.h> #include <logger.h> #include <utils.h> #include <strprintf.h> #include <stflpp.h> #include <exception.h> #include <formatstring.h> #include <regexmanager.h> #include <rss_parser.h> #include <remote_api.h> #include <oldreader_api.h> #include <feedhq_api.h> #include <ttrss_api.h> #include <newsblur_api.h> #include <ocnews_api.h> #include <xlicense.h> #include <cstdlib> #include <cstring> #include <iostream> #include <fstream> #include <cerrno> #include <algorithm> #include <functional> #include <mutex> #include <sys/time.h> #include <ctime> #include <cassert> #include <signal.h> #include <unistd.h> #include <getopt.h> #include <sys/utsname.h> #include <langinfo.h> #include <libgen.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <pwd.h> #include <ncurses.h> #include <libxml/xmlversion.h> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/xmlsave.h> #include <libxml/uri.h> #include <curl/curl.h> namespace newsbeuter { #define LOCK_SUFFIX ".lock" std::string lock_file; int ctrl_c_hit = 0; void ctrl_c_action(int sig) { LOG(level::DEBUG,"caught signal %d",sig); if (SIGINT == sig) { ctrl_c_hit = 1; } else { stfl::reset(); utils::remove_fs_lock(lock_file); ::exit(EXIT_FAILURE); } } void ignore_signal(int sig) { LOG(level::WARN, "caught signal %d but ignored it", sig); } void omg_a_child_died(int /* sig */) { pid_t pid; int stat; while ((pid = waitpid(-1,&stat,WNOHANG)) > 0) { } ::signal(SIGCHLD, omg_a_child_died); /* in case of unreliable signals */ } controller::controller() : v(0), urlcfg(0), rsscache(0), url_file("urls"), cache_file("cache.db"), config_file("config"), queue_file("queue"), refresh_on_start(false), api(0) { } /** * \brief Try to setup XDG style dirs. * * returns false, if that fails */ bool controller::setup_dirs_xdg(const char *env_home, bool silent) { const char *env_xdg_config; const char *env_xdg_data; std::string xdg_config_dir; std::string xdg_data_dir; env_xdg_config = ::getenv("XDG_CONFIG_HOME"); if (env_xdg_config) { xdg_config_dir = env_xdg_config; } else { xdg_config_dir = env_home; xdg_config_dir.append(NEWSBEUTER_PATH_SEP); xdg_config_dir.append(".config"); } env_xdg_data = ::getenv("XDG_DATA_HOME"); if (env_xdg_data) { xdg_data_dir = env_xdg_data; } else { xdg_data_dir = env_home; xdg_data_dir.append(NEWSBEUTER_PATH_SEP); xdg_data_dir.append(".local"); xdg_data_dir.append(NEWSBEUTER_PATH_SEP); xdg_data_dir.append("share"); } xdg_config_dir.append(NEWSBEUTER_PATH_SEP); xdg_config_dir.append(NEWSBEUTER_SUBDIR_XDG); xdg_data_dir.append(NEWSBEUTER_PATH_SEP); xdg_data_dir.append(NEWSBEUTER_SUBDIR_XDG); bool config_dir_exists = 0 == access(xdg_config_dir.c_str(), R_OK | X_OK); if (!config_dir_exists) { if (!silent) { std::cerr << strprintf::fmt( _("XDG: configuration directory '%s' not accessible, " "using '%s' instead."), xdg_config_dir, config_dir) << std::endl; } return false; } /* Invariant: config dir exists. * * At this point, we're confident we'll be using XDG. We don't check if * data dir exists, because if it doesn't we'll create it. */ config_dir = xdg_config_dir; // create data directory if it doesn't exist utils::mkdir_parents(xdg_data_dir, 0700); /* in config */ url_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + url_file; config_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + config_file; /* in data */ cache_file = xdg_data_dir + std::string(NEWSBEUTER_PATH_SEP) + cache_file; lock_file = cache_file + LOCK_SUFFIX; queue_file = xdg_data_dir + std::string(NEWSBEUTER_PATH_SEP) + queue_file; searchfile = strprintf::fmt("%s%shistory.search", xdg_data_dir, NEWSBEUTER_PATH_SEP); cmdlinefile = strprintf::fmt("%s%shistory.cmdline", xdg_data_dir, NEWSBEUTER_PATH_SEP); return true; } void controller::setup_dirs(bool silent) { const char * env_home; if (!(env_home = ::getenv("HOME"))) { struct passwd * spw = ::getpwuid(::getuid()); if (spw) { env_home = spw->pw_dir; } else { std::cerr << _("Fatal error: couldn't determine home directory!") << std::endl; std::cerr << strprintf::fmt(_("Please set the HOME environment variable or add a valid user for UID %u!"), ::getuid()) << std::endl; ::exit(EXIT_FAILURE); } } config_dir = env_home; config_dir.append(NEWSBEUTER_PATH_SEP); config_dir.append(NEWSBEUTER_CONFIG_SUBDIR); if (setup_dirs_xdg(env_home, silent)) return; mkdir(config_dir.c_str(),0700); // create configuration directory if it doesn't exist url_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + url_file; cache_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + cache_file; lock_file = cache_file + LOCK_SUFFIX; config_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + config_file; queue_file = config_dir + std::string(NEWSBEUTER_PATH_SEP) + queue_file; searchfile = strprintf::fmt("%s%shistory.search", config_dir, NEWSBEUTER_PATH_SEP); cmdlinefile = strprintf::fmt("%s%shistory.cmdline", config_dir, NEWSBEUTER_PATH_SEP); } controller::~controller() { delete rsscache; delete urlcfg; delete api; std::lock_guard<std::mutex> feedslock(feeds_mutex); for (auto feed : feeds) { std::lock_guard<std::mutex> lock(feed->item_mutex); feed->clear_items(); } feeds.clear(); } void controller::set_view(view * vv) { v = vv; } void controller::run(int argc, char * argv[]) { int c; ::signal(SIGINT, ctrl_c_action); ::signal(SIGPIPE, ignore_signal); ::signal(SIGHUP, ctrl_c_action); ::signal(SIGCHLD, omg_a_child_died); bool do_import = false, do_export = false, cachefile_given_on_cmdline = false, do_vacuum = false; std::string importfile; bool do_read_import = false, do_read_export = false; std::string readinfofile; unsigned int show_version = 0; bool silent = false; bool execute_cmds = false; static const char getopt_str[] = "i:erhqu:c:C:d:l:vVoxXI:E:"; static const struct option longopts[] = { {"cache-file" , required_argument, 0, 'c'}, {"config-file" , required_argument, 0, 'C'}, {"execute" , required_argument, 0, 'x'}, {"export-to-file" , required_argument, 0, 'E'}, {"export-to-opml" , no_argument , 0, 'e'}, {"help" , no_argument , 0, 'h'}, {"import-from-file", required_argument, 0, 'I'}, {"import-from-opml", required_argument, 0, 'i'}, {"log-file" , required_argument, 0, 'd'}, {"log-level" , required_argument, 0, 'l'}, {"quiet" , no_argument , 0, 'q'}, {"refresh-on-start", no_argument , 0, 'r'}, {"url-file" , required_argument, 0, 'u'}, {"vacuum" , no_argument , 0, 'X'}, {"version" , no_argument , 0, 'v'}, {0 , 0 , 0, 0 } }; /* First of all, let's check for options that imply silencing of the * output: import, export, command execution and, well, quiet mode */ while ((c = ::getopt_long(argc, argv, getopt_str, longopts, nullptr)) != -1) { if (strchr("iexq", c) != nullptr) { silent = true; break; } } setup_dirs(silent); /* Now that silencing's set up, let's rewind to the beginning of argv and * process the options */ optind = 1; while ((c = ::getopt_long(argc, argv, getopt_str, longopts, nullptr)) != -1) { switch (c) { case ':': /* fall-through */ case '?': /* missing option */ usage(argv[0]); break; case 'i': if (do_export) usage(argv[0]); do_import = true; importfile = optarg; break; case 'r': refresh_on_start = true; break; case 'e': if (do_import) usage(argv[0]); do_export = true; break; case 'h': usage(argv[0]); break; case 'u': url_file = optarg; break; case 'c': cache_file = optarg; lock_file = std::string(cache_file) + LOCK_SUFFIX; cachefile_given_on_cmdline = true; break; case 'C': config_file = optarg; break; case 'X': do_vacuum = true; break; case 'v': case 'V': show_version++; break; case 'x': execute_cmds = true; break; case 'q': break; case 'd': logger::getInstance().set_logfile(optarg); break; case 'l': { level l = static_cast<level>(atoi(optarg)); if (l > level::NONE && l <= level::DEBUG) { logger::getInstance().set_loglevel(l); } else { std::cerr << strprintf::fmt(_("%s: %d: invalid loglevel value"), argv[0], l) << std::endl; ::std::exit(EXIT_FAILURE); } } break; case 'I': if (do_read_export) usage(argv[0]); do_read_import = true; readinfofile = optarg; break; case 'E': if (do_read_import) usage(argv[0]); do_read_export = true; readinfofile = optarg; break; default: std::cout << strprintf::fmt(_("%s: unknown option - %c"), argv[0], static_cast<char>(c)) << std::endl; usage(argv[0]); break; } }; if (show_version) { version_information(argv[0], show_version); } if (do_import) { LOG(level::INFO,"Importing OPML file from %s",importfile); urlcfg = new file_urlreader(url_file); urlcfg->reload(); import_opml(importfile); return; } LOG(level::INFO, "nl_langinfo(CODESET): %s", nl_langinfo(CODESET)); if (!do_export) { if (!silent) std::cout << strprintf::fmt(_("Starting %s %s..."), PROGRAM_NAME, PROGRAM_VERSION) << std::endl; pid_t pid; if (!utils::try_fs_lock(lock_file, pid)) { if (pid > 0) { LOG(level::ERROR,"an instance is already running: pid = %u",pid); } else { LOG(level::ERROR,"something went wrong with the lock: %s", strerror(errno)); } if (!execute_cmds) { std::cout << strprintf::fmt(_("Error: an instance of %s is already running (PID: %u)"), PROGRAM_NAME, pid) << std::endl; } return; } } if (!silent) std::cout << _("Loading configuration..."); std::cout.flush(); cfg.register_commands(cfgparser); colorman.register_commands(cfgparser); keymap keys(KM_NEWSBEUTER); cfgparser.register_handler("bind-key",&keys); cfgparser.register_handler("unbind-key",&keys); cfgparser.register_handler("macro", &keys); cfgparser.register_handler("ignore-article",&ign); cfgparser.register_handler("always-download",&ign); cfgparser.register_handler("reset-unread-on-update",&ign); cfgparser.register_handler("define-filter",&filters); cfgparser.register_handler("highlight", &rxman); cfgparser.register_handler("highlight-article", &rxman); try { cfgparser.parse("/etc/" PROGRAM_NAME "/config"); cfgparser.parse(config_file); } catch (const configexception& ex) { LOG(level::ERROR,"an exception occurred while parsing the configuration file: %s",ex.what()); std::cout << ex.what() << std::endl; utils::remove_fs_lock(lock_file); return; } update_config(); if (!silent) std::cout << _("done.") << std::endl; // create cache object std::string cachefilepath = cfg.get_configvalue("cache-file"); if (cachefilepath.length() > 0 && !cachefile_given_on_cmdline) { cache_file = cachefilepath.c_str(); // ok, we got another cache file path via the configuration // that means we need to remove the old lock file, assemble // the new lock file's name, and then try to lock it. utils::remove_fs_lock(lock_file); lock_file = std::string(cache_file) + LOCK_SUFFIX; pid_t pid; if (!utils::try_fs_lock(lock_file, pid)) { if (pid > 0) { LOG(level::ERROR,"an instance is already running: pid = %u",pid); } else { LOG(level::ERROR,"something went wrong with the lock: %s", strerror(errno)); } std::cout << strprintf::fmt(_("Error: an instance of %s is already running (PID: %u)"), PROGRAM_NAME, pid) << std::endl; return; } } if (!silent) { std::cout << _("Opening cache..."); std::cout.flush(); } try { rsscache = new cache(cache_file,&cfg); } catch (const dbexception& e) { std::cerr << strprintf::fmt(_("Error: opening the cache file `%s' failed: %s"), cache_file, e.what()) << std::endl; utils::remove_fs_lock(lock_file); ::exit(EXIT_FAILURE); } if (!silent) { std::cout << _("done.") << std::endl; } std::string type = cfg.get_configvalue("urls-source"); if (type == "local") { urlcfg = new file_urlreader(url_file); } else if (type == "opml") { urlcfg = new opml_urlreader(&cfg); } else if (type == "oldreader") { api = new oldreader_api(&cfg); urlcfg = new oldreader_urlreader(&cfg, url_file, api); } else if (type == "ttrss") { api = new ttrss_api(&cfg); urlcfg = new ttrss_urlreader(url_file, api); } else if (type == "newsblur") { api = new newsblur_api(&cfg); urlcfg = new newsblur_urlreader(url_file, api); } else if (type == "feedhq") { api = new feedhq_api(&cfg); urlcfg = new feedhq_urlreader(&cfg, url_file, api); } else if (type == "ocnews") { api = new ocnews_api(&cfg); urlcfg = new ocnews_urlreader(url_file, api); } else { LOG(level::ERROR,"unknown urls-source `%s'", urlcfg->get_source()); } if (!do_export && !silent) { std::cout << strprintf::fmt(_("Loading URLs from %s..."), urlcfg->get_source()); std::cout.flush(); } if (api) { if (!api->authenticate()) { std::cout << "Authentication failed." << std::endl; utils::remove_fs_lock(lock_file); return; } } urlcfg->reload(); if (!do_export && !silent) { std::cout << _("done.") << std::endl; } if (urlcfg->get_urls().size() == 0) { LOG(level::ERROR,"no URLs configured."); std::string msg; if (type == "local") { msg = strprintf::fmt(_("Error: no URLs configured. Please fill the file %s with RSS feed URLs or import an OPML file."), url_file); } else if (type == "opml") { msg = strprintf::fmt(_("It looks like the OPML feed you subscribed contains no feeds. Please fill it with feeds, and try again.")); } else if (type == "oldreader") { msg = strprintf::fmt(_("It looks like you haven't configured any feeds in your The Old Reader account. Please do so, and try again.")); } else if (type == "ttrss") { msg = strprintf::fmt(_("It looks like you haven't configured any feeds in your Tiny Tiny RSS account. Please do so, and try again.")); } else if (type == "newsblur") { msg = strprintf::fmt(_("It looks like you haven't configured any feeds in your NewsBlur account. Please do so, and try again.")); } else { assert(0); // shouldn't happen } std::cout << msg << std::endl << std::endl; usage(argv[0]); } if (!do_export && !do_vacuum && !silent) std::cout << _("Loading articles from cache..."); if (do_vacuum) std::cout << _("Opening cache..."); std::cout.flush(); if (do_vacuum) { std::cout << _("done.") << std::endl; std::cout << _("Cleaning up cache thoroughly..."); std::cout.flush(); rsscache->do_vacuum(); std::cout << _("done.") << std::endl; utils::remove_fs_lock(lock_file); return; } unsigned int i=0; for (auto url : urlcfg->get_urls()) { try { bool ignore_disp = (cfg.get_configvalue("ignore-mode") == "display"); std::shared_ptr<rss_feed> feed = rsscache->internalize_rssfeed(url, ignore_disp ? &ign : nullptr); feed->set_tags(urlcfg->get_tags(url)); feed->set_order(i); std::lock_guard<std::mutex> feedslock(feeds_mutex); feeds.push_back(feed); } catch(const dbexception& e) { std::cout << _("Error while loading feeds from database: ") << e.what() << std::endl; utils::remove_fs_lock(lock_file); return; } catch(const std::string& str) { std::cout << strprintf::fmt(_("Error while loading feed '%s': %s"), url, str) << std::endl; utils::remove_fs_lock(lock_file); return; } i++; } std::vector<std::string> tags = urlcfg->get_alltags(); if (!do_export && !silent) std::cout << _("done.") << std::endl; // if configured, we fill all query feeds with some data; no need to sort it, it will be refilled when actually opening it. if (cfg.get_configvalue_as_bool("prepopulate-query-feeds")) { std::cout << _("Prepopulating query feeds..."); std::cout.flush(); std::lock_guard<std::mutex> feedslock(feeds_mutex); for (auto feed : feeds) { if (feed->rssurl().substr(0,6) == "query:") { feed->update_items(get_all_feeds_unlocked()); } } std::cout << _("done.") << std::endl; } sort_feeds(); if (do_export) { export_opml(); utils::remove_fs_lock(lock_file); return; } if (do_read_import) { LOG(level::INFO,"Importing read information file from %s",readinfofile); std::cout << _("Importing list of read articles..."); std::cout.flush(); import_read_information(readinfofile); std::cout << _("done.") << std::endl; return; } if (do_read_export) { LOG(level::INFO,"Exporting read information file to %s",readinfofile); std::cout << _("Exporting list of read articles..."); std::cout.flush(); export_read_information(readinfofile); std::cout << _("done.") << std::endl; return; } // hand over the important objects to the view v->set_config_container(&cfg); v->set_keymap(&keys); v->set_tags(tags); if (execute_cmds) { execute_commands(argv, optind); utils::remove_fs_lock(lock_file); return; } // if the user wants to refresh on startup via configuration file, then do so, // but only if -r hasn't been supplied. if (!refresh_on_start && cfg.get_configvalue_as_bool("refresh-on-startup")) { refresh_on_start = true; } formaction::load_histories(searchfile, cmdlinefile); // run the view v->run(); unsigned int history_limit = cfg.get_configvalue_as_int("history-limit"); LOG(level::DEBUG, "controller::run: history-limit = %u", history_limit); formaction::save_histories(searchfile, cmdlinefile, history_limit); if (!silent) { std::cout << _("Cleaning up cache..."); std::cout.flush(); } try { std::lock_guard<std::mutex> feedslock(feeds_mutex); rsscache->cleanup_cache(feeds); if (!silent) { std::cout << _("done.") << std::endl; } } catch (const dbexception& e) { LOG(level::USERERROR, "Cleaning up cache failed: %s", e.what()); if (!silent) { std::cout << _("failed: ") << e.what() << std::endl; } } utils::remove_fs_lock(lock_file); } void controller::update_feedlist() { std::lock_guard<std::mutex> feedslock(feeds_mutex); v->set_feedlist(feeds); } void controller::update_visible_feeds() { std::lock_guard<std::mutex> feedslock(feeds_mutex); v->update_visible_feeds(feeds); } void controller::mark_all_read(const std::string& feedurl) { try { rsscache->mark_all_read(feedurl); } catch (const dbexception& e) { v->show_error(strprintf::fmt(_("Error: couldn't mark all feeds read: %s"), e.what())); return; } std::lock_guard<std::mutex> feedslock(feeds_mutex); for (const auto& feed : feeds) { std::lock_guard<std::mutex> lock(feed->item_mutex); if (feedurl.length() > 0 && feed->rssurl() != feedurl) continue; if (feed->total_item_count() > 0) { if (api) { api->mark_all_read(feed->rssurl()); } for (auto item : feed->items()) { item->set_unread_nowrite(false); } } // no point in going on - there is only one feed with a given URL if (feedurl.length() > 0) break; } } void controller::mark_article_read(const std::string& guid, bool read) { if (api) { api->mark_article_read(guid, read); } } void controller::mark_all_read(unsigned int pos) { if (pos < feeds.size()) { scope_measure m("controller::mark_all_read"); std::lock_guard<std::mutex> feedslock(feeds_mutex); std::shared_ptr<rss_feed> feed = feeds[pos]; if (feed->rssurl().substr(0,6) == "query:") { rsscache->mark_all_read(feed); } else { rsscache->mark_all_read(feed->rssurl()); if (api) { api->mark_all_read(feed->rssurl()); } } m.stopover("after rsscache->mark_all_read, before iteration over items"); std::lock_guard<std::mutex> lock(feed->item_mutex); std::vector<std::shared_ptr<rss_item>>& items = feed->items(); if (items.size() > 0) { bool notify = items[0]->feedurl() != feed->rssurl(); LOG(level::DEBUG, "controller::mark_all_read: notify = %s", notify ? "yes" : "no"); for (auto item : items) { item->set_unread_nowrite_notify(false, notify); } } } } void controller::reload(unsigned int pos, unsigned int max, bool unattended, curl_handle *easyhandle) { LOG(level::DEBUG, "controller::reload: pos = %u max = %u", pos, max); if (pos < feeds.size()) { std::shared_ptr<rss_feed> oldfeed = feeds[pos]; std::string errmsg; if (!unattended) v->set_status(strprintf::fmt(_("%sLoading %s..."), prepare_message(pos+1, max), utils::censor_url(oldfeed->rssurl()))); bool ignore_dl = (cfg.get_configvalue("ignore-mode") == "download"); rss_parser parser(oldfeed->rssurl(), rsscache, &cfg, ignore_dl ? &ign : nullptr, api); parser.set_easyhandle(easyhandle); LOG(level::DEBUG, "controller::reload: created parser"); try { oldfeed->set_status(dl_status::DURING_DOWNLOAD); std::shared_ptr<rss_feed> newfeed = parser.parse(); if (newfeed->total_item_count() > 0) { std::lock_guard<std::mutex> feedslock(feeds_mutex); save_feed(newfeed, pos); newfeed->clear_items(); bool ignore_disp = (cfg.get_configvalue("ignore-mode") == "display"); std::shared_ptr<rss_feed> feed = rsscache->internalize_rssfeed(oldfeed->rssurl(), ignore_disp ? &ign : nullptr); feed->set_tags(urlcfg->get_tags(oldfeed->rssurl())); feed->set_order(oldfeed->get_order()); feeds[pos] = feed; enqueue_items(feed); oldfeed->clear_items(); v->notify_itemlist_change(feeds[pos]); if (!unattended) { v->set_feedlist(feeds); } } else { LOG(level::DEBUG, "controller::reload: feed is empty"); } oldfeed->set_status(dl_status::SUCCESS); v->set_status(""); } catch (const dbexception& e) { errmsg = strprintf::fmt(_("Error while retrieving %s: %s"), utils::censor_url(oldfeed->rssurl()), e.what()); } catch (const std::string& emsg) { errmsg = strprintf::fmt(_("Error while retrieving %s: %s"), utils::censor_url(oldfeed->rssurl()), emsg); } catch (rsspp::exception& e) { errmsg = strprintf::fmt(_("Error while retrieving %s: %s"), utils::censor_url(oldfeed->rssurl()), e.what()); } if (errmsg != "") { oldfeed->set_status(dl_status::DL_ERROR); v->set_status(errmsg); LOG(level::USERERROR, "%s", errmsg); } } else { v->show_error(_("Error: invalid feed!")); } } std::shared_ptr<rss_feed> controller::get_feed(unsigned int pos) { std::lock_guard<std::mutex> feedslock(feeds_mutex); if (pos >= feeds.size()) { throw std::out_of_range(_("invalid feed index (bug)")); } std::shared_ptr<rss_feed> feed = feeds[pos]; return feed; } void controller::reload_indexes(const std::vector<int>& indexes, bool unattended) { scope_measure m1("controller::reload_indexes"); unsigned int unread_feeds, unread_articles; compute_unread_numbers(unread_feeds, unread_articles); unsigned long size; { std::lock_guard<std::mutex> feedslock(feeds_mutex); size = feeds.size(); } for (auto idx : indexes) { this->reload(idx, size, unattended); } unsigned int unread_feeds2, unread_articles2; compute_unread_numbers(unread_feeds2, unread_articles2); bool notify_always = cfg.get_configvalue_as_bool("notify-always"); if (notify_always || unread_feeds2 != unread_feeds || unread_articles2 != unread_articles) { fmtstr_formatter fmt; fmt.register_fmt('f', std::to_string(unread_feeds2)); fmt.register_fmt('n', std::to_string(unread_articles2)); fmt.register_fmt('d', std::to_string(unread_articles2 - unread_articles)); fmt.register_fmt('D', std::to_string(unread_feeds2 - unread_feeds)); this->notify(fmt.do_format(cfg.get_configvalue("notify-format"))); } if (!unattended) v->set_status(""); } void controller::reload_range(unsigned int start, unsigned int end, unsigned int size, bool unattended) { std::vector<unsigned int> v; for (unsigned int i=start; i<=end; ++i) v.push_back(i); auto extract = [](std::string& s, const std::string& url) { size_t p = url.find("//"); p = (p == std::string::npos) ? 0 : p+2; std::string suff(url.substr(p)); p = suff.find('/'); s = suff.substr(0, p); }; std::sort(v.begin(), v.end(), [&](unsigned int a, unsigned int b) { std::string domain1, domain2; extract(domain1, feeds[a]->rssurl()); extract(domain2, feeds[b]->rssurl()); std::reverse(domain1.begin(), domain1.end()); std::reverse(domain2.begin(), domain2.end()); return domain1 < domain2; }); curl_handle easyhandle; for (auto i : v) { LOG(level::DEBUG, "controller::reload_range: reloading feed #%u", i); this->reload(i, size, unattended, &easyhandle); } } void controller::reload_all(bool unattended) { unsigned int unread_feeds, unread_articles; compute_unread_numbers(unread_feeds, unread_articles); unsigned int num_threads = cfg.get_configvalue_as_int("reload-threads"); time_t t1, t2, dt; unsigned int size; { std::lock_guard<std::mutex> feedlock(feeds_mutex); for (auto feed : feeds) { feed->reset_status(); } size = feeds.size(); } if (num_threads < 1) num_threads = 1; if (num_threads > size) { num_threads = size; } t1 = time(nullptr); LOG(level::DEBUG,"controller::reload_all: starting with reload all..."); if (num_threads <= 1) { this->reload_range(0, size-1, size, unattended); } else { std::vector<std::pair<unsigned int, unsigned int>> partitions = utils::partition_indexes(0, size-1, num_threads); std::vector<std::thread> threads; LOG(level::DEBUG, "controller::reload_all: starting reload threads..."); for (unsigned int i=0; i<num_threads-1; i++) { threads.push_back(std::thread(reloadrangethread(this, partitions[i].first, partitions[i].second, size, unattended))); } LOG(level::DEBUG, "controller::reload_all: starting my own reload..."); this->reload_range(partitions[num_threads-1].first, partitions[num_threads-1].second, size, unattended); LOG(level::DEBUG, "controller::reload_all: joining other threads..."); for (size_t i=0; i<threads.size(); i++) { threads[i].join(); } } // refresh query feeds (update and sort) LOG(level::DEBUG, "controller::reload_all: refresh query feeds"); for (auto feed : feeds) { v->prepare_query_feed(feed); } v->force_redraw(); sort_feeds(); update_feedlist(); t2 = time(nullptr); dt = t2 - t1; LOG(level::INFO, "controller::reload_all: reload took %d seconds", dt); unsigned int unread_feeds2, unread_articles2; compute_unread_numbers(unread_feeds2, unread_articles2); bool notify_always = cfg.get_configvalue_as_bool("notify-always"); if (notify_always || unread_feeds2 > unread_feeds || unread_articles2 > unread_articles) { int article_count = unread_articles2 - unread_articles; int feed_count = unread_feeds2 - unread_feeds; LOG(level::DEBUG, "unread article count: %d", article_count); LOG(level::DEBUG, "unread feed count: %d", feed_count); fmtstr_formatter fmt; fmt.register_fmt('f', std::to_string(unread_feeds2)); fmt.register_fmt('n', std::to_string(unread_articles2)); fmt.register_fmt('d', std::to_string(article_count >= 0 ? article_count : 0)); fmt.register_fmt('D', std::to_string(feed_count >= 0 ? feed_count : 0)); this->notify(fmt.do_format(cfg.get_configvalue("notify-format"))); } } void controller::notify(const std::string& msg) { if (cfg.get_configvalue_as_bool("notify-screen")) { LOG(level::DEBUG, "controller:notify: notifying screen"); std::cout << "\033^" << msg << "\033\\"; std::cout.flush(); } if (cfg.get_configvalue_as_bool("notify-xterm")) { LOG(level::DEBUG, "controller:notify: notifying xterm"); std::cout << "\033]2;" << msg << "\033\\"; std::cout.flush(); } if (cfg.get_configvalue_as_bool("notify-beep")) { LOG(level::DEBUG, "controller:notify: notifying beep"); ::beep(); } if (cfg.get_configvalue("notify-program").length() > 0) { std::string prog = cfg.get_configvalue("notify-program"); LOG(level::DEBUG, "controller:notify: notifying external program `%s'", prog); utils::run_command(prog, msg); } } void controller::compute_unread_numbers(unsigned int& unread_feeds, unsigned int& unread_articles) { unread_feeds = 0; unread_articles = 0; for (auto feed : feeds) { unsigned int items = feed->unread_item_count(); if (items > 0) { ++unread_feeds; unread_articles += items; } } } bool controller::trylock_reload_mutex() { if (reload_mutex.try_lock()) { LOG(level::DEBUG, "controller::trylock_reload_mutex succeeded"); return true; } LOG(level::DEBUG, "controller::trylock_reload_mutex failed"); return false; } void controller::start_reload_all_thread(std::vector<int> * indexes) { LOG(level::INFO,"starting reload all thread"); std::thread t(downloadthread(this, indexes)); t.detach(); } void controller::version_information(const char * argv0, unsigned int level) { if (level<=1) { std::cout << PROGRAM_NAME << " " << PROGRAM_VERSION << " - " << PROGRAM_URL << std::endl; std::cout << "Copyright (C) 2006-2015 Andreas Krennmair" << std::endl; std::cout << "Copyright (C) 2015-2017 Alexander Batischev" << std::endl; std::cout << "Copyright (C) 2006-2017 Newsbeuter contributors" << std::endl; std::cout << std::endl; std::cout << _("newsbeuter is free software and licensed under the MIT/X Consortium License.") << std::endl; std::cout << strprintf::fmt(_("Type `%s -vv' for more information."), argv0) << std::endl << std::endl; struct utsname xuts; uname(&xuts); std::cout << PROGRAM_NAME << " " << PROGRAM_VERSION << std::endl; std::cout << "System: " << xuts.sysname << " " << xuts.release << " (" << xuts.machine << ")" << std::endl; #if defined(__GNUC__) && defined(__VERSION__) std::cout << "Compiler: g++ " << __VERSION__ << std::endl; #endif std::cout << "ncurses: " << curses_version() << " (compiled with " << NCURSES_VERSION << ")" << std::endl; std::cout << "libcurl: " << curl_version() << " (compiled with " << LIBCURL_VERSION << ")" << std::endl; std::cout << "SQLite: " << sqlite3_libversion() << " (compiled with " << SQLITE_VERSION << ")" << std::endl; std::cout << "libxml2: compiled with " << LIBXML_DOTTED_VERSION << std::endl << std::endl; } else { std::cout << LICENSE_str << std::endl; } ::exit(EXIT_SUCCESS); } void controller::usage(char * argv0) { auto msg = strprintf::fmt(_("%s %s\nusage: %s [-i <file>|-e] [-u <urlfile>] " "[-c <cachefile>] [-x <command> ...] [-h]\n"), PROGRAM_NAME, PROGRAM_VERSION, argv0); std::cout << msg; struct arg { const char name; const std::string longname; const std::string params; const std::string desc; }; static const std::vector<arg> args = { { 'e', "export-to-opml" , "" , _s("export OPML feed to stdout") } , { 'r', "refresh-on-start", "" , _s("refresh feeds on start") } , { 'i', "import-from-opml", _s("<file>") , _s("import OPML file") } , { 'u', "url-file" , _s("<urlfile>") , _s("read RSS feed URLs from <urlfile>") } , { 'c', "cache-file" , _s("<cachefile>") , _s("use <cachefile> as cache file") } , { 'C', "config-file" , _s("<configfile>"), _s("read configuration from <configfile>") } , { 'X', "vacuum" , "" , _s("compact the cache") } , { 'x', "execute" , _s("<command>..."), _s("execute list of commands") } , { 'q', "quiet" , "" , _s("quiet startup") } , { 'v', "version" , "" , _s("get version information") } , { 'l', "log-level" , _s("<loglevel>") , _s("write a log with a certain loglevel (valid values: 1 to 6)") } , { 'd', "log-file" , _s("<logfile>") , _s("use <logfile> as output log file") } , { 'E', "export-to-file" , _s("<file>") , _s("export list of read articles to <file>") } , { 'I', "import-from-file", _s("<file>") , _s("import list of read articles from <file>") } , { 'h', "help" , "" , _s("this help") } }; for (const auto & a : args) { std::string longcolumn("-"); longcolumn += a.name; longcolumn += ", --" + a.longname; longcolumn += a.params.size() > 0 ? "=" + a.params : ""; std::cout << "\t" << longcolumn; for (unsigned int j = 0; j < utils::gentabs(longcolumn); j++) { std::cout << "\t"; } std::cout << a.desc << std::endl; } ::exit(EXIT_FAILURE); } void controller::import_opml(const std::string& filename) { xmlDoc * doc = xmlReadFile(filename.c_str(), nullptr, 0); if (doc == nullptr) { std::cout << strprintf::fmt(_("An error occurred while parsing %s."), filename) << std::endl; return; } xmlNode * root = xmlDocGetRootElement(doc); for (xmlNode * node = root->children; node != nullptr; node = node->next) { if (strcmp((const char *)node->name, "body")==0) { LOG(level::DEBUG, "import_opml: found body"); rec_find_rss_outlines(node->children, ""); urlcfg->write_config(); } } xmlFreeDoc(doc); std::cout << strprintf::fmt(_("Import of %s finished."), filename) << std::endl; } void controller::export_opml() { xmlDocPtr root = xmlNewDoc((const xmlChar *)"1.0"); xmlNodePtr opml_node = xmlNewDocNode(root, nullptr, (const xmlChar *)"opml", nullptr); xmlSetProp(opml_node, (const xmlChar *)"version", (const xmlChar *)"1.0"); xmlDocSetRootElement(root, opml_node); xmlNodePtr head = xmlNewTextChild(opml_node, nullptr, (const xmlChar *)"head", nullptr); xmlNewTextChild(head, nullptr, (const xmlChar *)"title", (const xmlChar *)PROGRAM_NAME " - Exported Feeds"); xmlNodePtr body = xmlNewTextChild(opml_node, nullptr, (const xmlChar *)"body", nullptr); for (auto feed : feeds) { if (!utils::is_special_url(feed->rssurl())) { std::string rssurl = feed->rssurl(); std::string link = feed->link(); std::string title = feed->title(); xmlNodePtr outline = xmlNewTextChild(body, nullptr, (const xmlChar *)"outline", nullptr); xmlSetProp(outline, (const xmlChar *)"type", (const xmlChar *)"rss"); xmlSetProp(outline, (const xmlChar *)"xmlUrl", (const xmlChar *)rssurl.c_str()); xmlSetProp(outline, (const xmlChar *)"htmlUrl", (const xmlChar *)link.c_str()); xmlSetProp(outline, (const xmlChar *)"title", (const xmlChar *)title.c_str()); } } xmlSaveCtxtPtr savectx = xmlSaveToFd(1, nullptr, 1); xmlSaveDoc(savectx, root); xmlSaveClose(savectx); xmlFreeNode(opml_node); } void controller::rec_find_rss_outlines(xmlNode * node, std::string tag) { while (node) { std::string newtag = tag; if (strcmp((const char *)node->name, "outline")==0) { char * url = (char *)xmlGetProp(node, (const xmlChar *)"xmlUrl"); if (!url) { url = (char *)xmlGetProp(node, (const xmlChar *)"url"); } if (url) { LOG(level::DEBUG,"OPML import: found RSS outline with url = %s",url); std::string nurl = std::string(url); // Liferea uses a pipe to signal feeds read from the output of // a program in its OPMLs. Convert them to our syntax. if (*url == '|') { nurl = strprintf::fmt("exec:%s", url+1); LOG(level::DEBUG,"OPML import: liferea-style url %s converted to %s", url, nurl); } // Handle OPML filters. char * filtercmd = (char *)xmlGetProp(node, (const xmlChar *)"filtercmd"); if (filtercmd) { LOG(level::DEBUG,"OPML import: adding filter command %s to url %s", filtercmd, nurl); nurl.insert(0, strprintf::fmt("filter:%s:", filtercmd)); xmlFree(filtercmd); } xmlFree(url); // Filters and scripts may have arguments, so, quote them when needed. url = (char*) xmlStrdup((const xmlChar*)utils::quote_if_necessary(nurl).c_str()); assert(url); bool found = false; LOG(level::DEBUG, "OPML import: size = %u", urlcfg->get_urls().size()); if (urlcfg->get_urls().size() > 0) { for (auto u : urlcfg->get_urls()) { if (u == url) { found = true; } } } if (!found) { LOG(level::DEBUG,"OPML import: added url = %s",url); urlcfg->get_urls().push_back(std::string(url)); if (tag.length() > 0) { LOG(level::DEBUG, "OPML import: appending tag %s to url %s", tag, url); urlcfg->get_tags(url).push_back(tag); } } else { LOG(level::DEBUG,"OPML import: url = %s is already in list",url); } xmlFree(url); } else { char * text = (char *)xmlGetProp(node, (const xmlChar *)"text"); if (!text) text = (char *)xmlGetProp(node, (const xmlChar *)"title"); if (text) { if (newtag.length() > 0) { newtag.append("/"); } newtag.append(text); xmlFree(text); } } } rec_find_rss_outlines(node->children, newtag); node = node->next; } } std::vector<std::shared_ptr<rss_item>> controller::search_for_items(const std::string& query, std::shared_ptr<rss_feed> feed) { std::vector<std::shared_ptr<rss_item>> items; LOG(level::DEBUG, "controller::search_for_items: setting feed pointers"); if (feed != nullptr && feed->rssurl().substr(0,6) == "query:") { for (auto item : feed->items()) { if (!item->deleted() && (item->title().find(query) != std::string::npos || item->description().find(query) != std::string::npos)) { std::shared_ptr<rss_item> newitem(new rss_item(nullptr)); newitem->set_guid(item->guid()); newitem->set_title(item->title()); newitem->set_author(item->author()); newitem->set_link(item->link()); newitem->set_pubDate(item->pubDate_timestamp()); newitem->set_size(item->size()); newitem->set_unread(item->unread()); newitem->set_feedurl(item->feedurl()); newitem->set_enclosure_url(item->enclosure_url()); newitem->set_enclosure_type(item->enclosure_type()); newitem->set_enqueued(item->enqueued()); newitem->set_flags(item->flags()); newitem->set_base(item->get_base()); newitem->set_feedptr(item->get_feedptr()); newitem->set_cache(get_cache()); items.push_back(newitem); } } } else { items = rsscache->search_for_items(query, (feed != nullptr ? feed->rssurl() : "")); for (auto item : items) { item->set_feedptr(get_feed_by_url(item->feedurl())); } } return items; } std::shared_ptr<rss_feed> controller::get_feed_by_url(const std::string& feedurl) { for (auto feed : feeds) { if (feedurl == feed->rssurl()) return feed; } LOG(level::ERROR, "controller:get_feed_by_url failed for %s", feedurl); return std::shared_ptr<rss_feed>(); } bool controller::is_valid_podcast_type(const std::string& /* mimetype */) { return true; } void controller::enqueue_url(const std::string& url, std::shared_ptr<rss_feed> feed) { bool url_found = false; std::fstream f; f.open(queue_file.c_str(), std::fstream::in); if (f.is_open()) { do { std::string line; getline(f, line); if (!f.eof() && line.length() > 0) { std::vector<std::string> fields = utils::tokenize_quoted(line); if (!fields.empty() && fields[0] == url) { url_found = true; break; } } } while (!f.eof()); f.close(); } if (!url_found) { f.open(queue_file.c_str(), std::fstream::app | std::fstream::out); std::string filename = generate_enqueue_filename(url, feed); f << url << " " << stfl::quote(filename) << std::endl; f.close(); } } void controller::reload_urls_file() { urlcfg->reload(); std::vector<std::shared_ptr<rss_feed>> new_feeds; unsigned int i = 0; for (auto url : urlcfg->get_urls()) { bool found = false; for (auto feed : feeds) { if (url == feed->rssurl()) { found = true; feed->set_tags(urlcfg->get_tags(url)); feed->set_order(i); new_feeds.push_back(feed); break; } } if (!found) { try { bool ignore_disp = (cfg.get_configvalue("ignore-mode") == "display"); std::shared_ptr<rss_feed> new_feed = rsscache->internalize_rssfeed(url, ignore_disp ? &ign : nullptr); new_feed->set_tags(urlcfg->get_tags(url)); new_feed->set_order(i); new_feeds.push_back(new_feed); } catch(const dbexception& e) { LOG(level::ERROR, "controller::reload_urls_file: caught exception: %s", e.what()); throw; } } i++; } v->set_tags(urlcfg->get_alltags()); { std::lock_guard<std::mutex> feedslock(feeds_mutex); feeds = new_feeds; } sort_feeds(); update_feedlist(); } void controller::edit_urls_file() { const char * editor; editor = getenv("VISUAL"); if (!editor) editor = getenv("EDITOR"); if (!editor) editor = "vi"; std::string cmdline = strprintf::fmt("%s \"%s\"", editor, utils::replace_all(url_file,"\"","\\\"")); v->push_empty_formaction(); stfl::reset(); utils::run_interactively(cmdline, "controller::edit_urls_file"); v->pop_current_formaction(); reload_urls_file(); } /* When passing an argument to a shell script, empty string should be * represented as '' (two quote marks), otherwise shell won't be able to tell * that the parameter is empty */ std::string quote_empty(const std::string& input) { if (input.empty()) { return "''"; } else { return input; } } std::string controller::bookmark( const std::string& url, const std::string& title, const std::string& description, const std::string& feed_title) { std::string bookmark_cmd = cfg.get_configvalue("bookmark-cmd"); bool is_interactive = cfg.get_configvalue_as_bool("bookmark-interactive"); if (bookmark_cmd.length() > 0) { std::string cmdline = strprintf::fmt("%s '%s' '%s' '%s' '%s'", bookmark_cmd, utils::replace_all(url,"'", "%27"), utils::replace_all(title,"'", "%27"), utils::replace_all(description,"'", "%27"), utils::replace_all(feed_title,"'", "%27")); LOG(level::DEBUG, "controller::bookmark: cmd = %s", cmdline); if (is_interactive) { v->push_empty_formaction(); stfl::reset(); utils::run_interactively(cmdline, "controller::bookmark"); v->pop_current_formaction(); return ""; } else { char * my_argv[4]; my_argv[0] = const_cast<char *>("/bin/sh"); my_argv[1] = const_cast<char *>("-c"); my_argv[2] = const_cast<char *>(cmdline.c_str()); my_argv[3] = nullptr; return utils::run_program(my_argv, ""); } } else { return _("bookmarking support is not configured. Please set the configuration variable `bookmark-cmd' accordingly."); } } void controller::execute_commands(char ** argv, unsigned int i) { if (v->formaction_stack_size() > 0) v->pop_current_formaction(); for (; argv[i]; ++i) { LOG(level::DEBUG, "controller::execute_commands: executing `%s'", argv[i]); std::string cmd(argv[i]); if (cmd == "reload") { reload_all(true); } else if (cmd == "print-unread") { std::cout << strprintf::fmt(_("%u unread articles"), rsscache->get_unread_count()) << std::endl; } else { std::cerr << strprintf::fmt(_("%s: %s: unknown command"), argv[0], argv[i]) << std::endl; ::std::exit(EXIT_FAILURE); } } } std::string controller::write_temporary_item(std::shared_ptr<rss_item> item) { char filename[_POSIX_PATH_MAX]; snprintf(filename, sizeof(filename), "/tmp/newsbeuter-article.XXXXXX"); int fd = mkstemp(filename); if (fd != -1) { write_item(item, filename); close(fd); return std::string(filename); } else { return ""; } } void controller::write_item(std::shared_ptr<rss_item> item, const std::string& filename) { std::fstream f; f.open(filename.c_str(),std::fstream::out); if (!f.is_open()) throw exception(errno); write_item(item, f); } void controller::write_item(std::shared_ptr<rss_item> item, std::ostream& ostr) { std::vector<std::pair<LineType, std::string>> lines; std::vector<linkpair> links; // not used std::string title(_("Title: ")); title.append(item->title()); lines.push_back(std::make_pair(LineType::wrappable, title)); std::string author(_("Author: ")); author.append(item->author()); lines.push_back(std::make_pair(LineType::wrappable, author)); std::string date(_("Date: ")); date.append(item->pubDate()); lines.push_back(std::make_pair(LineType::wrappable, date)); std::string link(_("Link: ")); link.append(item->link()); lines.push_back(std::make_pair(LineType::softwrappable, link)); if (item->enclosure_url() != "") { std::string dlurl(_("Podcast Download URL: ")); dlurl.append(item->enclosure_url()); lines.push_back(std::make_pair(LineType::softwrappable, dlurl)); } lines.push_back(std::make_pair(LineType::wrappable, std::string(""))); htmlrenderer rnd(true); rnd.render(item->description(), lines, links, item->feedurl()); textformatter txtfmt; txtfmt.add_lines(lines); unsigned int width = cfg.get_configvalue_as_int("text-width"); if (width == 0) width = 80; ostr << txtfmt.format_text_plain(width) << std::endl; } void controller::mark_deleted(const std::string& guid, bool b) { rsscache->mark_item_deleted(guid, b); } std::string controller::prepare_message(unsigned int pos, unsigned int max) { if (max > 0) { return strprintf::fmt("(%u/%u) ", pos, max); } return ""; } void controller::save_feed(std::shared_ptr<rss_feed> feed, unsigned int pos) { if (!feed->is_empty()) { LOG(level::DEBUG, "controller::save_feed: feed is nonempty, saving"); rsscache->externalize_rssfeed(feed, ign.matches_resetunread(feed->rssurl())); LOG(level::DEBUG, "controller::save_feed: after externalize_rssfeed"); bool ignore_disp = (cfg.get_configvalue("ignore-mode") == "display"); feed = rsscache->internalize_rssfeed(feed->rssurl(), ignore_disp ? &ign : nullptr); LOG(level::DEBUG, "controller::save_feed: after internalize_rssfeed"); feed->set_tags(urlcfg->get_tags(feed->rssurl())); { unsigned int order = feeds[pos]->get_order(); std::lock_guard<std::mutex> itemlock(feeds[pos]->item_mutex); feeds[pos]->clear_items(); feed->set_order(order); } feeds[pos] = feed; v->notify_itemlist_change(feeds[pos]); } else { LOG(level::DEBUG, "controller::save_feed: feed is empty, not saving"); } } void controller::enqueue_items(std::shared_ptr<rss_feed> feed) { if (!cfg.get_configvalue_as_bool("podcast-auto-enqueue")) return; std::lock_guard<std::mutex> lock(feed->item_mutex); for (auto item : feed->items()) { if (!item->enqueued() && item->enclosure_url().length() > 0) { LOG(level::DEBUG, "controller::enqueue_items: enclosure_url = `%s' enclosure_type = `%s'", item->enclosure_url(), item->enclosure_type()); if (is_valid_podcast_type(item->enclosure_type()) && utils::is_http_url(item->enclosure_url())) { LOG(level::INFO, "controller::enqueue_items: enqueuing `%s'", item->enclosure_url()); enqueue_url(item->enclosure_url(), feed); item->set_enqueued(true); rsscache->update_rssitem_unread_and_enqueued(item, feed->rssurl()); } } } } std::string controller::generate_enqueue_filename(const std::string& url, std::shared_ptr<rss_feed> feed) { std::string dlformat = cfg.get_configvalue("download-path"); if (dlformat[dlformat.length()-1] != NEWSBEUTER_PATH_SEP[0]) dlformat.append(NEWSBEUTER_PATH_SEP); fmtstr_formatter fmt; fmt.register_fmt('n', feed->title()); fmt.register_fmt('h', get_hostname_from_url(url)); std::string dlpath = fmt.do_format(dlformat); char buf[2048]; snprintf(buf, sizeof(buf), "%s", url.c_str()); char * base = basename(buf); if (!base || strlen(base) == 0) { char lbuf[128]; time_t t = time(nullptr); strftime(lbuf, sizeof(lbuf), "%Y-%b-%d-%H%M%S.unknown", localtime(&t)); dlpath.append(lbuf); } else { dlpath.append(base); } return dlpath; } std::string controller::get_hostname_from_url(const std::string& url) { xmlURIPtr uri = xmlParseURI(url.c_str()); std::string hostname; if (uri) { hostname = uri->server; xmlFreeURI(uri); } return hostname; } void controller::import_read_information(const std::string& readinfofile) { std::vector<std::string> guids; std::ifstream f(readinfofile.c_str()); std::string line; getline(f,line); if (!f.is_open()) { return; } while (f.is_open() && !f.eof()) { guids.push_back(line); getline(f, line); } rsscache->mark_items_read_by_guid(guids); } void controller::export_read_information(const std::string& readinfofile) { std::vector<std::string> guids = rsscache->get_read_item_guids(); std::fstream f; f.open(readinfofile.c_str(), std::fstream::out); if (f.is_open()) { for (auto guid : guids) { f << guid << std::endl; } } } void controller::sort_feeds() { std::lock_guard<std::mutex> feedslock(feeds_mutex); std::vector<std::string> sortmethod_info = utils::tokenize(cfg.get_configvalue("feed-sort-order"), "-"); std::string sortmethod = sortmethod_info[0]; std::string direction = "desc"; if (sortmethod_info.size() > 1) direction = sortmethod_info[1]; if (sortmethod == "none") { std::stable_sort(feeds.begin(), feeds.end(), [](std::shared_ptr<rss_feed> a, std::shared_ptr<rss_feed> b) { return a->get_order() < b->get_order(); }); } else if (sortmethod == "firsttag") { std::stable_sort(feeds.begin(), feeds.end(), [](std::shared_ptr<rss_feed> a, std::shared_ptr<rss_feed> b) { if (a->get_firsttag().length() == 0 || b->get_firsttag().length() == 0) { return a->get_firsttag().length() > b->get_firsttag().length(); } return strcasecmp(a->get_firsttag().c_str(), b->get_firsttag().c_str()) < 0; }); } else if (sortmethod == "title") { std::stable_sort(feeds.begin(), feeds.end(), [](std::shared_ptr<rss_feed> a, std::shared_ptr<rss_feed> b) { return strcasecmp(a->title().c_str(), b->title().c_str()) < 0; }); } else if (sortmethod == "articlecount") { std::stable_sort(feeds.begin(), feeds.end(), [](std::shared_ptr<rss_feed> a, std::shared_ptr<rss_feed> b) { return a->total_item_count() < b->total_item_count(); }); } else if (sortmethod == "unreadarticlecount") { std::stable_sort(feeds.begin(), feeds.end(), [](std::shared_ptr<rss_feed> a, std::shared_ptr<rss_feed> b) { return a->unread_item_count() < b->unread_item_count(); }); } if (direction == "asc") { std::reverse(feeds.begin(), feeds.end()); } } void controller::update_config() { v->set_regexmanager(&rxman); v->update_bindings(); if (colorman.colors_loaded()) { v->set_colors(colorman.get_fgcolors(), colorman.get_bgcolors(), colorman.get_attributes()); v->apply_colors_to_all_formactions(); } if (cfg.get_configvalue("error-log").length() > 0) { logger::getInstance().set_errorlogfile(cfg.get_configvalue("error-log")); } } void controller::load_configfile(const std::string& filename) { if (cfgparser.parse(filename, true)) { update_config(); } else { v->show_error(strprintf::fmt(_("Error: couldn't open configuration file `%s'!"), filename)); } } void controller::dump_config(const std::string& filename) { std::vector<std::string> configlines; cfg.dump_config(configlines); if (v) { v->get_keys()->dump_config(configlines); } ign.dump_config(configlines); filters.dump_config(configlines); colorman.dump_config(configlines); rxman.dump_config(configlines); std::fstream f; f.open(filename.c_str(), std::fstream::out); if (f.is_open()) { for (auto line : configlines) { f << line << std::endl; } } } unsigned int controller::get_pos_of_next_unread(unsigned int pos) { std::lock_guard<std::mutex> feedslock(feeds_mutex); for (pos++; pos < feeds.size(); pos++) { if (feeds[pos]->unread_item_count() > 0) break; } return pos; } void controller::update_flags(std::shared_ptr<rss_item> item) { if (api) { api->update_article_flags(item->oldflags(), item->flags(), item->guid()); } item->update_flags(); } std::vector<std::shared_ptr<rss_feed>> controller::get_all_feeds() { std::vector<std::shared_ptr<rss_feed>> tmpfeeds; { std::lock_guard<std::mutex> feedslock(feeds_mutex); tmpfeeds = feeds; } return tmpfeeds; } std::vector<std::shared_ptr<rss_feed>> controller::get_all_feeds_unlocked() { return feeds; } unsigned int controller::get_feed_count_per_tag(const std::string& tag) { unsigned int count = 0; std::lock_guard<std::mutex> feedslock(feeds_mutex); for (auto feed : feeds) { if (feed->matches_tag(tag)) { count++; } } return count; } }
./CrossVul/dataset_final_sorted/CWE-943/cpp/good_2652_0
crossvul-cpp_data_good_4751_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | 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. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/server/fastcgi/fastcgi-transport.h" #include "hphp/runtime/base/runtime-error.h" #include "hphp/runtime/server/fastcgi/fastcgi-server.h" #include "hphp/runtime/server/http-protocol.h" #include "hphp/runtime/server/transport.h" #include <folly/io/Cursor.h> #include <folly/io/IOBuf.h> #include <folly/io/IOBufQueue.h> namespace HPHP { using folly::IOBuf; using folly::IOBufQueue; using folly::io::Cursor; /////////////////////////////////////////////////////////////////////////////// /* * The logic used here for reading POST data buffers is mostly borrowed from * proxygen server. Currently the RequestBodyReadLimit is not supported by * FastCGI so we don't ever pause ingress and POST data is always received * during VM execution. * * NB: locking is important when accessing m_bodyQueue as the session will * also write into that structure via onBody. */ const void *FastCGITransport::getPostData(size_t& size) { // the API contract is that you can call getPostData repeatedly until // you call getMorePostData if (m_firstBody) { CHECK(m_currBody); size = m_currBody->length(); return m_currBody->data(); } return getMorePostData(size); } const void *FastCGITransport::getMorePostData(size_t& size) { // session will terminate the request if we don't receive data in // this much time long maxWait = RuntimeOption::ConnectionTimeoutSeconds; if (maxWait <= 0) { maxWait = 50; // this was the default read timeout in LibEventServer } Lock lock(this); while (m_bodyQueue.empty() && !m_bodyComplete) { wait(maxWait); } // For chunk encodings, we way receive an EOM with no data, such that // hasMorePostData returns true (because client is not yet complete), // client sends EOM, getMorePostData should return 0/nullptr size = 0; if (!m_bodyQueue.empty()) { // this is the first body if it wasn't set and buf is unset m_firstBody = !(m_firstBody && m_currBody); m_currBody = m_bodyQueue.pop_front(); CHECK(m_currBody && m_currBody->length() > 0); size = m_currBody->length(); return m_currBody->data(); } return nullptr; } bool FastCGITransport::hasMorePostData() { Lock lock(this); return !m_bodyComplete || !m_bodyQueue.empty(); } /////////////////////////////////////////////////////////////////////////////// // takes an unmangled header name std::string FastCGITransport::getHeader(const char* name) { std::string key("HTTP_"); for (auto p = name; *p; ++p) { key += (*p == '-') ? '_' : toupper(*p); } if (m_requestParams.count(key)) { return m_requestParams[key]; } // Special headers that are not prefixed with HTTP_ if (strcasecmp(name, "Authorization") == 0) { return getParamTyped<std::string>("Authorization"); } if (strcasecmp(name, "Content-Length") == 0) { return getParamTyped<std::string>("CONTENT_LENGTH"); } if (strcasecmp(name, "Content-Type") == 0) { return getParamTyped<std::string>("CONTENT_TYPE"); } return ""; } void FastCGITransport::getHeaders(HeaderMap& headers) { for (auto& pair : m_requestParams) { auto key = unmangleHeader(pair.first); if (!key.empty()) { headers[key] = { pair.second }; } } } void FastCGITransport::getTransportParams(HeaderMap& serverParams) { for (auto& pair : m_requestParams) { serverParams[pair.first] = { pair.second }; } } /////////////////////////////////////////////////////////////////////////////// void FastCGITransport::addHeaderImpl(const char* name, const char* value) { CHECK(!m_headersSent); m_responseHeaders[name].emplace_back(value); } void FastCGITransport::removeHeaderImpl(const char* name) { CHECK(!m_headersSent); m_responseHeaders.erase(name); } void FastCGITransport::sendResponseHeaders(IOBufQueue& queue, int code) { auto appender = [&](folly::StringPiece sp) mutable { queue.append(sp); }; if (code != 200) { auto info = getResponseInfo(); auto reason = !info.empty() ? info : HttpProtocol::GetReasonString(code); folly::format("Status: {} {}\r\n", code, reason)(appender); } for (auto& header : m_responseHeaders) { for (auto& value : header.second) { folly::format("{}: {}\r\n", header.first, value)(appender); } } queue.append("\r\n", 2); } /////////////////////////////////////////////////////////////////////////////// void FastCGITransport::sendImpl(const void *data, int size, int code, bool chunked, bool eom) { if (!m_headersSent) { m_headersSent = true; sendResponseHeaders(m_txBuf, code); } m_txBuf.append(data, size); m_session->onStdOut(m_txBuf.move()); // session will handle locking if (eom) { onSendEndImpl(); } } void FastCGITransport::onSendEndImpl() { // Don't send onComplete() more than once (required because of the eom flag // on sendImpl). if (m_sendEnded) { return; } m_sendEnded = true; // NB: onSendEnd() is only sent when the VM is finished with the transport. // at this point we are free to do whatever we'd like with the transport. m_session->onComplete(); } /////////////////////////////////////////////////////////////////////////////// void FastCGITransport::onBody(std::unique_ptr<folly::IOBuf> chain) { Lock lock(this); m_bodyQueue.append(std::move(chain)); notify(); // wake-up the VM } void FastCGITransport::onBodyComplete() { Lock lock(this); m_bodyComplete = true; notify(); // wake-up the VM } void FastCGITransport::onHeader(std::unique_ptr<folly::IOBuf> key_chain, std::unique_ptr<folly::IOBuf> value_chain) { Cursor keyCur(key_chain.get()); auto key = keyCur.readFixedString(key_chain->computeChainDataLength()); // Don't allow requests to inject an HTTP_PROXY environment variable by // sending a Proxy header. if (strcasecmp(key.c_str(), "HTTP_PROXY") == 0) return; Cursor valCur(value_chain.get()); auto value = valCur.readFixedString(value_chain->computeChainDataLength()); m_requestParams[key] = value; } void FastCGITransport::onHeadersComplete() { m_scriptName = getParamTyped<std::string>("SCRIPT_FILENAME"); m_docRoot = getParamTyped<std::string>("DOCUMENT_ROOT"); m_pathTrans = getParamTyped<std::string>("PATH_TRANSLATED"); m_serverObject = getParamTyped<std::string>("SCRIPT_NAME"); if (!m_docRoot.empty() && *m_docRoot.rbegin() != '/') { m_docRoot += '/'; } if (m_scriptName.empty() || RuntimeOption::ServerFixPathInfo) { // According to php-fpm, some servers don't set SCRIPT_FILENAME. In // this case, it uses PATH_TRANSLATED. // Added runtime option to change m_scriptFilename to s_pathTran // which will allow mod_fastcgi and mod_action to work correctly. m_scriptName = getPathTranslated(); } [&] { // do a check for mod_proxy_fcgi and remove the extra portions of // the string if (!strncmp(m_scriptName.c_str(), "proxy:", sizeof("proxy:") - 1)) { folly::StringPiece newName {m_scriptName}; // remove the proxy:type + :// from the start. auto proxyPos = newName.find("://"); if (proxyPos == std::string::npos) return; // invalid mod_proxy newName.advance(proxyPos + sizeof("://")); // remove everything before the first / which is host:port auto slashPos = newName.find('/'); if (slashPos == std::string::npos) { m_scriptName.clear(); // empty path return; } newName.advance(slashPos); // remove everything after the first ? auto questionPos = newName.find('?'); if (questionPos != std::string::npos) { newName.subtract(newName.size() - questionPos); } m_scriptName = newName.str(); } }(); // RequestURI needs script_filename and path_translated to not include // the document root if (!m_scriptName.empty()) { if (m_scriptName.find(m_docRoot) == 0) { m_scriptName.erase(0, m_docRoot.length()); } else { // if the document root isn't in the url set document root to / m_docRoot = "/"; } } // XXX: This was originally done before remapping scriptName but that seemed // wrong as the value of docRoot may change. I haven't been able to confirm // that this is correct either. if (m_pathTrans.find(m_docRoot) == 0) { m_pathTrans.erase(0, m_docRoot.length()); } auto qs = getParamTyped<std::string>("QUERY_STRING"); if (!qs.empty()) { m_serverObject += "?"; m_serverObject += qs; } // Treat everything apart from GET and HEAD as a post to be like php-src. auto const ex = getExtendedMethod(); if (!strcmp(ex, "GET")) { m_method = Method::GET; } else if (!strcmp(ex, "HEAD")) { m_method = Method::HEAD; } else { m_method = Method::POST; } // IIS sets this value but sets it to off when SSL is off. if (m_requestParams.count("HTTPS") && !m_requestParams["HTTPS"].empty() && strcasecmp(m_requestParams["HTTPS"].c_str(), "OFF")) { setSSL(); } } /////////////////////////////////////////////////////////////////////////////// std::string FastCGITransport::unmangleHeader(const std::string& name) const { if (name == "Authorization") { return name; // Already unmangled } if (name == "CONTENT_LENGTH") { return "Content-Length"; } if (name == "CONTENT_TYPE") { return "Content-Type"; } if (strncasecmp(name.c_str(), "HTTP_", 5)) { return ""; } std::string ret; bool is_upper = true; for (auto const& c : folly::StringPiece(name, 5)) { if (c == '_') { ret += '-'; is_upper = true; } else { ret += is_upper ? toupper(c) : tolower(c); is_upper = false; } } return ret; } /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-665/cpp/good_4751_0
crossvul-cpp_data_bad_4751_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | 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. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/server/fastcgi/fastcgi-transport.h" #include "hphp/runtime/base/runtime-error.h" #include "hphp/runtime/server/fastcgi/fastcgi-server.h" #include "hphp/runtime/server/http-protocol.h" #include "hphp/runtime/server/transport.h" #include <folly/io/Cursor.h> #include <folly/io/IOBuf.h> #include <folly/io/IOBufQueue.h> namespace HPHP { using folly::IOBuf; using folly::IOBufQueue; using folly::io::Cursor; /////////////////////////////////////////////////////////////////////////////// /* * The logic used here for reading POST data buffers is mostly borrowed from * proxygen server. Currently the RequestBodyReadLimit is not supported by * FastCGI so we don't ever pause ingress and POST data is always received * during VM execution. * * NB: locking is important when accessing m_bodyQueue as the session will * also write into that structure via onBody. */ const void *FastCGITransport::getPostData(size_t& size) { // the API contract is that you can call getPostData repeatedly until // you call getMorePostData if (m_firstBody) { CHECK(m_currBody); size = m_currBody->length(); return m_currBody->data(); } return getMorePostData(size); } const void *FastCGITransport::getMorePostData(size_t& size) { // session will terminate the request if we don't receive data in // this much time long maxWait = RuntimeOption::ConnectionTimeoutSeconds; if (maxWait <= 0) { maxWait = 50; // this was the default read timeout in LibEventServer } Lock lock(this); while (m_bodyQueue.empty() && !m_bodyComplete) { wait(maxWait); } // For chunk encodings, we way receive an EOM with no data, such that // hasMorePostData returns true (because client is not yet complete), // client sends EOM, getMorePostData should return 0/nullptr size = 0; if (!m_bodyQueue.empty()) { // this is the first body if it wasn't set and buf is unset m_firstBody = !(m_firstBody && m_currBody); m_currBody = m_bodyQueue.pop_front(); CHECK(m_currBody && m_currBody->length() > 0); size = m_currBody->length(); return m_currBody->data(); } return nullptr; } bool FastCGITransport::hasMorePostData() { Lock lock(this); return !m_bodyComplete || !m_bodyQueue.empty(); } /////////////////////////////////////////////////////////////////////////////// // takes an unmangled header name std::string FastCGITransport::getHeader(const char* name) { std::string key("HTTP_"); for (auto p = name; *p; ++p) { key += (*p == '-') ? '_' : toupper(*p); } if (m_requestParams.count(key)) { return m_requestParams[key]; } // Special headers that are not prefixed with HTTP_ if (strcasecmp(name, "Authorization") == 0) { return getParamTyped<std::string>("Authorization"); } if (strcasecmp(name, "Content-Length") == 0) { return getParamTyped<std::string>("CONTENT_LENGTH"); } if (strcasecmp(name, "Content-Type") == 0) { return getParamTyped<std::string>("CONTENT_TYPE"); } return ""; } void FastCGITransport::getHeaders(HeaderMap& headers) { for (auto& pair : m_requestParams) { auto key = unmangleHeader(pair.first); if (!key.empty()) { headers[key] = { pair.second }; } } } void FastCGITransport::getTransportParams(HeaderMap& serverParams) { for (auto& pair : m_requestParams) { serverParams[pair.first] = { pair.second }; } } /////////////////////////////////////////////////////////////////////////////// void FastCGITransport::addHeaderImpl(const char* name, const char* value) { CHECK(!m_headersSent); m_responseHeaders[name].emplace_back(value); } void FastCGITransport::removeHeaderImpl(const char* name) { CHECK(!m_headersSent); m_responseHeaders.erase(name); } void FastCGITransport::sendResponseHeaders(IOBufQueue& queue, int code) { auto appender = [&](folly::StringPiece sp) mutable { queue.append(sp); }; if (code != 200) { auto info = getResponseInfo(); auto reason = !info.empty() ? info : HttpProtocol::GetReasonString(code); folly::format("Status: {} {}\r\n", code, reason)(appender); } for (auto& header : m_responseHeaders) { for (auto& value : header.second) { folly::format("{}: {}\r\n", header.first, value)(appender); } } queue.append("\r\n", 2); } /////////////////////////////////////////////////////////////////////////////// void FastCGITransport::sendImpl(const void *data, int size, int code, bool chunked, bool eom) { if (!m_headersSent) { m_headersSent = true; sendResponseHeaders(m_txBuf, code); } m_txBuf.append(data, size); m_session->onStdOut(m_txBuf.move()); // session will handle locking if (eom) { onSendEndImpl(); } } void FastCGITransport::onSendEndImpl() { // Don't send onComplete() more than once (required because of the eom flag // on sendImpl). if (m_sendEnded) { return; } m_sendEnded = true; // NB: onSendEnd() is only sent when the VM is finished with the transport. // at this point we are free to do whatever we'd like with the transport. m_session->onComplete(); } /////////////////////////////////////////////////////////////////////////////// void FastCGITransport::onBody(std::unique_ptr<folly::IOBuf> chain) { Lock lock(this); m_bodyQueue.append(std::move(chain)); notify(); // wake-up the VM } void FastCGITransport::onBodyComplete() { Lock lock(this); m_bodyComplete = true; notify(); // wake-up the VM } void FastCGITransport::onHeader(std::unique_ptr<folly::IOBuf> key_chain, std::unique_ptr<folly::IOBuf> value_chain) { Cursor keyCur(key_chain.get()); auto key = keyCur.readFixedString(key_chain->computeChainDataLength()); Cursor valCur(value_chain.get()); auto value = valCur.readFixedString(value_chain->computeChainDataLength()); m_requestParams[key] = value; } void FastCGITransport::onHeadersComplete() { m_scriptName = getParamTyped<std::string>("SCRIPT_FILENAME"); m_docRoot = getParamTyped<std::string>("DOCUMENT_ROOT"); m_pathTrans = getParamTyped<std::string>("PATH_TRANSLATED"); m_serverObject = getParamTyped<std::string>("SCRIPT_NAME"); if (!m_docRoot.empty() && *m_docRoot.rbegin() != '/') { m_docRoot += '/'; } if (m_scriptName.empty() || RuntimeOption::ServerFixPathInfo) { // According to php-fpm, some servers don't set SCRIPT_FILENAME. In // this case, it uses PATH_TRANSLATED. // Added runtime option to change m_scriptFilename to s_pathTran // which will allow mod_fastcgi and mod_action to work correctly. m_scriptName = getPathTranslated(); } [&] { // do a check for mod_proxy_fcgi and remove the extra portions of // the string if (!strncmp(m_scriptName.c_str(), "proxy:", sizeof("proxy:") - 1)) { folly::StringPiece newName {m_scriptName}; // remove the proxy:type + :// from the start. auto proxyPos = newName.find("://"); if (proxyPos == std::string::npos) return; // invalid mod_proxy newName.advance(proxyPos + sizeof("://")); // remove everything before the first / which is host:port auto slashPos = newName.find('/'); if (slashPos == std::string::npos) { m_scriptName.clear(); // empty path return; } newName.advance(slashPos); // remove everything after the first ? auto questionPos = newName.find('?'); if (questionPos != std::string::npos) { newName.subtract(newName.size() - questionPos); } m_scriptName = newName.str(); } }(); // RequestURI needs script_filename and path_translated to not include // the document root if (!m_scriptName.empty()) { if (m_scriptName.find(m_docRoot) == 0) { m_scriptName.erase(0, m_docRoot.length()); } else { // if the document root isn't in the url set document root to / m_docRoot = "/"; } } // XXX: This was originally done before remapping scriptName but that seemed // wrong as the value of docRoot may change. I haven't been able to confirm // that this is correct either. if (m_pathTrans.find(m_docRoot) == 0) { m_pathTrans.erase(0, m_docRoot.length()); } auto qs = getParamTyped<std::string>("QUERY_STRING"); if (!qs.empty()) { m_serverObject += "?"; m_serverObject += qs; } // Treat everything apart from GET and HEAD as a post to be like php-src. auto const ex = getExtendedMethod(); if (!strcmp(ex, "GET")) { m_method = Method::GET; } else if (!strcmp(ex, "HEAD")) { m_method = Method::HEAD; } else { m_method = Method::POST; } // IIS sets this value but sets it to off when SSL is off. if (m_requestParams.count("HTTPS") && !m_requestParams["HTTPS"].empty() && strcasecmp(m_requestParams["HTTPS"].c_str(), "OFF")) { setSSL(); } } /////////////////////////////////////////////////////////////////////////////// std::string FastCGITransport::unmangleHeader(const std::string& name) const { if (name == "Authorization") { return name; // Already unmangled } if (name == "CONTENT_LENGTH") { return "Content-Length"; } if (name == "CONTENT_TYPE") { return "Content-Type"; } if (strncasecmp(name.c_str(), "HTTP_", 5)) { return ""; } std::string ret; bool is_upper = true; for (auto const& c : folly::StringPiece(name, 5)) { if (c == '_') { ret += '-'; is_upper = true; } else { ret += is_upper ? toupper(c) : tolower(c); is_upper = false; } } return ret; } /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-665/cpp/bad_4751_0
crossvul-cpp_data_bad_1128_0
/* * Copyright (c) 2016 Hisilicon Limited. * Copyright (c) 2007, 2008 Mellanox Technologies. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - 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. * * 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 <linux/acpi.h> #include <linux/of_platform.h> #include <linux/module.h> #include <rdma/ib_addr.h> #include <rdma/ib_smi.h> #include <rdma/ib_user_verbs.h> #include <rdma/ib_cache.h> #include "hns_roce_common.h" #include "hns_roce_device.h" #include <rdma/hns-abi.h> #include "hns_roce_hem.h" /** * hns_get_gid_index - Get gid index. * @hr_dev: pointer to structure hns_roce_dev. * @port: port, value range: 0 ~ MAX * @gid_index: gid_index, value range: 0 ~ MAX * Description: * N ports shared gids, allocation method as follow: * GID[0][0], GID[1][0],.....GID[N - 1][0], * GID[0][0], GID[1][0],.....GID[N - 1][0], * And so on */ int hns_get_gid_index(struct hns_roce_dev *hr_dev, u8 port, int gid_index) { return gid_index * hr_dev->caps.num_ports + port; } EXPORT_SYMBOL_GPL(hns_get_gid_index); static int hns_roce_set_mac(struct hns_roce_dev *hr_dev, u8 port, u8 *addr) { u8 phy_port; u32 i = 0; if (!memcmp(hr_dev->dev_addr[port], addr, MAC_ADDR_OCTET_NUM)) return 0; for (i = 0; i < MAC_ADDR_OCTET_NUM; i++) hr_dev->dev_addr[port][i] = addr[i]; phy_port = hr_dev->iboe.phy_port[port]; return hr_dev->hw->set_mac(hr_dev, phy_port, addr); } static int hns_roce_add_gid(struct ib_device *device, u8 port_num, unsigned int index, const union ib_gid *gid, const struct ib_gid_attr *attr, void **context) { struct hns_roce_dev *hr_dev = to_hr_dev(device); u8 port = port_num - 1; unsigned long flags; int ret; if (port >= hr_dev->caps.num_ports) return -EINVAL; spin_lock_irqsave(&hr_dev->iboe.lock, flags); ret = hr_dev->hw->set_gid(hr_dev, port, index, (union ib_gid *)gid, attr); spin_unlock_irqrestore(&hr_dev->iboe.lock, flags); return ret; } static int hns_roce_del_gid(struct ib_device *device, u8 port_num, unsigned int index, void **context) { struct hns_roce_dev *hr_dev = to_hr_dev(device); struct ib_gid_attr zattr = { }; union ib_gid zgid = { {0} }; u8 port = port_num - 1; unsigned long flags; int ret; if (port >= hr_dev->caps.num_ports) return -EINVAL; spin_lock_irqsave(&hr_dev->iboe.lock, flags); ret = hr_dev->hw->set_gid(hr_dev, port, index, &zgid, &zattr); spin_unlock_irqrestore(&hr_dev->iboe.lock, flags); return ret; } static int handle_en_event(struct hns_roce_dev *hr_dev, u8 port, unsigned long event) { struct device *dev = hr_dev->dev; struct net_device *netdev; int ret = 0; netdev = hr_dev->iboe.netdevs[port]; if (!netdev) { dev_err(dev, "port(%d) can't find netdev\n", port); return -ENODEV; } switch (event) { case NETDEV_UP: case NETDEV_CHANGE: case NETDEV_REGISTER: case NETDEV_CHANGEADDR: ret = hns_roce_set_mac(hr_dev, port, netdev->dev_addr); break; case NETDEV_DOWN: /* * In v1 engine, only support all ports closed together. */ break; default: dev_dbg(dev, "NETDEV event = 0x%x!\n", (u32)(event)); break; } return ret; } static int hns_roce_netdev_event(struct notifier_block *self, unsigned long event, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); struct hns_roce_ib_iboe *iboe = NULL; struct hns_roce_dev *hr_dev = NULL; u8 port = 0; int ret = 0; hr_dev = container_of(self, struct hns_roce_dev, iboe.nb); iboe = &hr_dev->iboe; for (port = 0; port < hr_dev->caps.num_ports; port++) { if (dev == iboe->netdevs[port]) { ret = handle_en_event(hr_dev, port, event); if (ret) return NOTIFY_DONE; break; } } return NOTIFY_DONE; } static int hns_roce_setup_mtu_mac(struct hns_roce_dev *hr_dev) { int ret; u8 i; for (i = 0; i < hr_dev->caps.num_ports; i++) { if (hr_dev->hw->set_mtu) hr_dev->hw->set_mtu(hr_dev, hr_dev->iboe.phy_port[i], hr_dev->caps.max_mtu); ret = hns_roce_set_mac(hr_dev, i, hr_dev->iboe.netdevs[i]->dev_addr); if (ret) return ret; } return 0; } static int hns_roce_query_device(struct ib_device *ib_dev, struct ib_device_attr *props, struct ib_udata *uhw) { struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev); memset(props, 0, sizeof(*props)); props->sys_image_guid = cpu_to_be32(hr_dev->sys_image_guid); props->max_mr_size = (u64)(~(0ULL)); props->page_size_cap = hr_dev->caps.page_size_cap; props->vendor_id = hr_dev->vendor_id; props->vendor_part_id = hr_dev->vendor_part_id; props->hw_ver = hr_dev->hw_rev; props->max_qp = hr_dev->caps.num_qps; props->max_qp_wr = hr_dev->caps.max_wqes; props->device_cap_flags = IB_DEVICE_PORT_ACTIVE_EVENT | IB_DEVICE_RC_RNR_NAK_GEN; props->max_sge = max(hr_dev->caps.max_sq_sg, hr_dev->caps.max_rq_sg); props->max_sge_rd = 1; props->max_cq = hr_dev->caps.num_cqs; props->max_cqe = hr_dev->caps.max_cqes; props->max_mr = hr_dev->caps.num_mtpts; props->max_pd = hr_dev->caps.num_pds; props->max_qp_rd_atom = hr_dev->caps.max_qp_dest_rdma; props->max_qp_init_rd_atom = hr_dev->caps.max_qp_init_rdma; props->atomic_cap = IB_ATOMIC_NONE; props->max_pkeys = 1; props->local_ca_ack_delay = hr_dev->caps.local_ca_ack_delay; return 0; } static struct net_device *hns_roce_get_netdev(struct ib_device *ib_dev, u8 port_num) { struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev); struct net_device *ndev; if (port_num < 1 || port_num > hr_dev->caps.num_ports) return NULL; rcu_read_lock(); ndev = hr_dev->iboe.netdevs[port_num - 1]; if (ndev) dev_hold(ndev); rcu_read_unlock(); return ndev; } static int hns_roce_query_port(struct ib_device *ib_dev, u8 port_num, struct ib_port_attr *props) { struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev); struct device *dev = hr_dev->dev; struct net_device *net_dev; unsigned long flags; enum ib_mtu mtu; u8 port; assert(port_num > 0); port = port_num - 1; /* props being zeroed by the caller, avoid zeroing it here */ props->max_mtu = hr_dev->caps.max_mtu; props->gid_tbl_len = hr_dev->caps.gid_table_len[port]; props->port_cap_flags = IB_PORT_CM_SUP | IB_PORT_REINIT_SUP | IB_PORT_VENDOR_CLASS_SUP | IB_PORT_BOOT_MGMT_SUP; props->max_msg_sz = HNS_ROCE_MAX_MSG_LEN; props->pkey_tbl_len = 1; props->active_width = IB_WIDTH_4X; props->active_speed = 1; spin_lock_irqsave(&hr_dev->iboe.lock, flags); net_dev = hr_dev->iboe.netdevs[port]; if (!net_dev) { spin_unlock_irqrestore(&hr_dev->iboe.lock, flags); dev_err(dev, "find netdev %d failed!\r\n", port); return -EINVAL; } mtu = iboe_get_mtu(net_dev->mtu); props->active_mtu = mtu ? min(props->max_mtu, mtu) : IB_MTU_256; props->state = (netif_running(net_dev) && netif_carrier_ok(net_dev)) ? IB_PORT_ACTIVE : IB_PORT_DOWN; props->phys_state = (props->state == IB_PORT_ACTIVE) ? 5 : 3; spin_unlock_irqrestore(&hr_dev->iboe.lock, flags); return 0; } static enum rdma_link_layer hns_roce_get_link_layer(struct ib_device *device, u8 port_num) { return IB_LINK_LAYER_ETHERNET; } static int hns_roce_query_gid(struct ib_device *ib_dev, u8 port_num, int index, union ib_gid *gid) { return 0; } static int hns_roce_query_pkey(struct ib_device *ib_dev, u8 port, u16 index, u16 *pkey) { *pkey = PKEY_ID; return 0; } static int hns_roce_modify_device(struct ib_device *ib_dev, int mask, struct ib_device_modify *props) { unsigned long flags; if (mask & ~IB_DEVICE_MODIFY_NODE_DESC) return -EOPNOTSUPP; if (mask & IB_DEVICE_MODIFY_NODE_DESC) { spin_lock_irqsave(&to_hr_dev(ib_dev)->sm_lock, flags); memcpy(ib_dev->node_desc, props->node_desc, NODE_DESC_SIZE); spin_unlock_irqrestore(&to_hr_dev(ib_dev)->sm_lock, flags); } return 0; } static int hns_roce_modify_port(struct ib_device *ib_dev, u8 port_num, int mask, struct ib_port_modify *props) { return 0; } static struct ib_ucontext *hns_roce_alloc_ucontext(struct ib_device *ib_dev, struct ib_udata *udata) { int ret = 0; struct hns_roce_ucontext *context; struct hns_roce_ib_alloc_ucontext_resp resp; struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev); resp.qp_tab_size = hr_dev->caps.num_qps; context = kmalloc(sizeof(*context), GFP_KERNEL); if (!context) return ERR_PTR(-ENOMEM); ret = hns_roce_uar_alloc(hr_dev, &context->uar); if (ret) goto error_fail_uar_alloc; if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_RECORD_DB) { INIT_LIST_HEAD(&context->page_list); mutex_init(&context->page_mutex); } ret = ib_copy_to_udata(udata, &resp, sizeof(resp)); if (ret) goto error_fail_copy_to_udata; return &context->ibucontext; error_fail_copy_to_udata: hns_roce_uar_free(hr_dev, &context->uar); error_fail_uar_alloc: kfree(context); return ERR_PTR(ret); } static int hns_roce_dealloc_ucontext(struct ib_ucontext *ibcontext) { struct hns_roce_ucontext *context = to_hr_ucontext(ibcontext); hns_roce_uar_free(to_hr_dev(ibcontext->device), &context->uar); kfree(context); return 0; } static int hns_roce_mmap(struct ib_ucontext *context, struct vm_area_struct *vma) { struct hns_roce_dev *hr_dev = to_hr_dev(context->device); if (((vma->vm_end - vma->vm_start) % PAGE_SIZE) != 0) return -EINVAL; if (vma->vm_pgoff == 0) { vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); if (io_remap_pfn_range(vma, vma->vm_start, to_hr_ucontext(context)->uar.pfn, PAGE_SIZE, vma->vm_page_prot)) return -EAGAIN; } else if (vma->vm_pgoff == 1 && hr_dev->tptr_dma_addr && hr_dev->tptr_size) { /* vm_pgoff: 1 -- TPTR */ if (io_remap_pfn_range(vma, vma->vm_start, hr_dev->tptr_dma_addr >> PAGE_SHIFT, hr_dev->tptr_size, vma->vm_page_prot)) return -EAGAIN; } else return -EINVAL; return 0; } static int hns_roce_port_immutable(struct ib_device *ib_dev, u8 port_num, struct ib_port_immutable *immutable) { struct ib_port_attr attr; int ret; ret = ib_query_port(ib_dev, port_num, &attr); if (ret) return ret; immutable->pkey_tbl_len = attr.pkey_tbl_len; immutable->gid_tbl_len = attr.gid_tbl_len; immutable->max_mad_size = IB_MGMT_MAD_SIZE; immutable->core_cap_flags = RDMA_CORE_PORT_IBA_ROCE; if (to_hr_dev(ib_dev)->caps.flags & HNS_ROCE_CAP_FLAG_ROCE_V1_V2) immutable->core_cap_flags |= RDMA_CORE_PORT_IBA_ROCE_UDP_ENCAP; return 0; } static void hns_roce_unregister_device(struct hns_roce_dev *hr_dev) { struct hns_roce_ib_iboe *iboe = &hr_dev->iboe; unregister_netdevice_notifier(&iboe->nb); ib_unregister_device(&hr_dev->ib_dev); } static int hns_roce_register_device(struct hns_roce_dev *hr_dev) { int ret; struct hns_roce_ib_iboe *iboe = NULL; struct ib_device *ib_dev = NULL; struct device *dev = hr_dev->dev; iboe = &hr_dev->iboe; spin_lock_init(&iboe->lock); ib_dev = &hr_dev->ib_dev; strlcpy(ib_dev->name, "hns_%d", IB_DEVICE_NAME_MAX); ib_dev->owner = THIS_MODULE; ib_dev->node_type = RDMA_NODE_IB_CA; ib_dev->dev.parent = dev; ib_dev->phys_port_cnt = hr_dev->caps.num_ports; ib_dev->local_dma_lkey = hr_dev->caps.reserved_lkey; ib_dev->num_comp_vectors = hr_dev->caps.num_comp_vectors; ib_dev->uverbs_abi_ver = 1; ib_dev->uverbs_cmd_mask = (1ULL << IB_USER_VERBS_CMD_GET_CONTEXT) | (1ULL << IB_USER_VERBS_CMD_QUERY_DEVICE) | (1ULL << IB_USER_VERBS_CMD_QUERY_PORT) | (1ULL << IB_USER_VERBS_CMD_ALLOC_PD) | (1ULL << IB_USER_VERBS_CMD_DEALLOC_PD) | (1ULL << IB_USER_VERBS_CMD_REG_MR) | (1ULL << IB_USER_VERBS_CMD_DEREG_MR) | (1ULL << IB_USER_VERBS_CMD_CREATE_COMP_CHANNEL) | (1ULL << IB_USER_VERBS_CMD_CREATE_CQ) | (1ULL << IB_USER_VERBS_CMD_DESTROY_CQ) | (1ULL << IB_USER_VERBS_CMD_CREATE_QP) | (1ULL << IB_USER_VERBS_CMD_MODIFY_QP) | (1ULL << IB_USER_VERBS_CMD_QUERY_QP) | (1ULL << IB_USER_VERBS_CMD_DESTROY_QP); /* HCA||device||port */ ib_dev->modify_device = hns_roce_modify_device; ib_dev->query_device = hns_roce_query_device; ib_dev->query_port = hns_roce_query_port; ib_dev->modify_port = hns_roce_modify_port; ib_dev->get_link_layer = hns_roce_get_link_layer; ib_dev->get_netdev = hns_roce_get_netdev; ib_dev->query_gid = hns_roce_query_gid; ib_dev->add_gid = hns_roce_add_gid; ib_dev->del_gid = hns_roce_del_gid; ib_dev->query_pkey = hns_roce_query_pkey; ib_dev->alloc_ucontext = hns_roce_alloc_ucontext; ib_dev->dealloc_ucontext = hns_roce_dealloc_ucontext; ib_dev->mmap = hns_roce_mmap; /* PD */ ib_dev->alloc_pd = hns_roce_alloc_pd; ib_dev->dealloc_pd = hns_roce_dealloc_pd; /* AH */ ib_dev->create_ah = hns_roce_create_ah; ib_dev->query_ah = hns_roce_query_ah; ib_dev->destroy_ah = hns_roce_destroy_ah; /* QP */ ib_dev->create_qp = hns_roce_create_qp; ib_dev->modify_qp = hns_roce_modify_qp; ib_dev->query_qp = hr_dev->hw->query_qp; ib_dev->destroy_qp = hr_dev->hw->destroy_qp; ib_dev->post_send = hr_dev->hw->post_send; ib_dev->post_recv = hr_dev->hw->post_recv; /* CQ */ ib_dev->create_cq = hns_roce_ib_create_cq; ib_dev->modify_cq = hr_dev->hw->modify_cq; ib_dev->destroy_cq = hns_roce_ib_destroy_cq; ib_dev->req_notify_cq = hr_dev->hw->req_notify_cq; ib_dev->poll_cq = hr_dev->hw->poll_cq; /* MR */ ib_dev->get_dma_mr = hns_roce_get_dma_mr; ib_dev->reg_user_mr = hns_roce_reg_user_mr; ib_dev->dereg_mr = hns_roce_dereg_mr; if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_REREG_MR) { ib_dev->rereg_user_mr = hns_roce_rereg_user_mr; ib_dev->uverbs_cmd_mask |= (1ULL << IB_USER_VERBS_CMD_REREG_MR); } /* OTHERS */ ib_dev->get_port_immutable = hns_roce_port_immutable; ret = ib_register_device(ib_dev, NULL); if (ret) { dev_err(dev, "ib_register_device failed!\n"); return ret; } ret = hns_roce_setup_mtu_mac(hr_dev); if (ret) { dev_err(dev, "setup_mtu_mac failed!\n"); goto error_failed_setup_mtu_mac; } iboe->nb.notifier_call = hns_roce_netdev_event; ret = register_netdevice_notifier(&iboe->nb); if (ret) { dev_err(dev, "register_netdevice_notifier failed!\n"); goto error_failed_setup_mtu_mac; } return 0; error_failed_setup_mtu_mac: ib_unregister_device(ib_dev); return ret; } static int hns_roce_init_hem(struct hns_roce_dev *hr_dev) { int ret; struct device *dev = hr_dev->dev; ret = hns_roce_init_hem_table(hr_dev, &hr_dev->mr_table.mtt_table, HEM_TYPE_MTT, hr_dev->caps.mtt_entry_sz, hr_dev->caps.num_mtt_segs, 1); if (ret) { dev_err(dev, "Failed to init MTT context memory, aborting.\n"); return ret; } if (hns_roce_check_whether_mhop(hr_dev, HEM_TYPE_CQE)) { ret = hns_roce_init_hem_table(hr_dev, &hr_dev->mr_table.mtt_cqe_table, HEM_TYPE_CQE, hr_dev->caps.mtt_entry_sz, hr_dev->caps.num_cqe_segs, 1); if (ret) { dev_err(dev, "Failed to init MTT CQE context memory, aborting.\n"); goto err_unmap_cqe; } } ret = hns_roce_init_hem_table(hr_dev, &hr_dev->mr_table.mtpt_table, HEM_TYPE_MTPT, hr_dev->caps.mtpt_entry_sz, hr_dev->caps.num_mtpts, 1); if (ret) { dev_err(dev, "Failed to init MTPT context memory, aborting.\n"); goto err_unmap_mtt; } ret = hns_roce_init_hem_table(hr_dev, &hr_dev->qp_table.qp_table, HEM_TYPE_QPC, hr_dev->caps.qpc_entry_sz, hr_dev->caps.num_qps, 1); if (ret) { dev_err(dev, "Failed to init QP context memory, aborting.\n"); goto err_unmap_dmpt; } ret = hns_roce_init_hem_table(hr_dev, &hr_dev->qp_table.irrl_table, HEM_TYPE_IRRL, hr_dev->caps.irrl_entry_sz * hr_dev->caps.max_qp_init_rdma, hr_dev->caps.num_qps, 1); if (ret) { dev_err(dev, "Failed to init irrl_table memory, aborting.\n"); goto err_unmap_qp; } if (hr_dev->caps.trrl_entry_sz) { ret = hns_roce_init_hem_table(hr_dev, &hr_dev->qp_table.trrl_table, HEM_TYPE_TRRL, hr_dev->caps.trrl_entry_sz * hr_dev->caps.max_qp_dest_rdma, hr_dev->caps.num_qps, 1); if (ret) { dev_err(dev, "Failed to init trrl_table memory, aborting.\n"); goto err_unmap_irrl; } } ret = hns_roce_init_hem_table(hr_dev, &hr_dev->cq_table.table, HEM_TYPE_CQC, hr_dev->caps.cqc_entry_sz, hr_dev->caps.num_cqs, 1); if (ret) { dev_err(dev, "Failed to init CQ context memory, aborting.\n"); goto err_unmap_trrl; } return 0; err_unmap_trrl: if (hr_dev->caps.trrl_entry_sz) hns_roce_cleanup_hem_table(hr_dev, &hr_dev->qp_table.trrl_table); err_unmap_irrl: hns_roce_cleanup_hem_table(hr_dev, &hr_dev->qp_table.irrl_table); err_unmap_qp: hns_roce_cleanup_hem_table(hr_dev, &hr_dev->qp_table.qp_table); err_unmap_dmpt: hns_roce_cleanup_hem_table(hr_dev, &hr_dev->mr_table.mtpt_table); err_unmap_mtt: if (hns_roce_check_whether_mhop(hr_dev, HEM_TYPE_CQE)) hns_roce_cleanup_hem_table(hr_dev, &hr_dev->mr_table.mtt_cqe_table); err_unmap_cqe: hns_roce_cleanup_hem_table(hr_dev, &hr_dev->mr_table.mtt_table); return ret; } /** * hns_roce_setup_hca - setup host channel adapter * @hr_dev: pointer to hns roce device * Return : int */ static int hns_roce_setup_hca(struct hns_roce_dev *hr_dev) { int ret; struct device *dev = hr_dev->dev; spin_lock_init(&hr_dev->sm_lock); spin_lock_init(&hr_dev->bt_cmd_lock); if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_RECORD_DB) { INIT_LIST_HEAD(&hr_dev->pgdir_list); mutex_init(&hr_dev->pgdir_mutex); } ret = hns_roce_init_uar_table(hr_dev); if (ret) { dev_err(dev, "Failed to initialize uar table. aborting\n"); return ret; } ret = hns_roce_uar_alloc(hr_dev, &hr_dev->priv_uar); if (ret) { dev_err(dev, "Failed to allocate priv_uar.\n"); goto err_uar_table_free; } ret = hns_roce_init_pd_table(hr_dev); if (ret) { dev_err(dev, "Failed to init protected domain table.\n"); goto err_uar_alloc_free; } ret = hns_roce_init_mr_table(hr_dev); if (ret) { dev_err(dev, "Failed to init memory region table.\n"); goto err_pd_table_free; } ret = hns_roce_init_cq_table(hr_dev); if (ret) { dev_err(dev, "Failed to init completion queue table.\n"); goto err_mr_table_free; } ret = hns_roce_init_qp_table(hr_dev); if (ret) { dev_err(dev, "Failed to init queue pair table.\n"); goto err_cq_table_free; } return 0; err_cq_table_free: hns_roce_cleanup_cq_table(hr_dev); err_mr_table_free: hns_roce_cleanup_mr_table(hr_dev); err_pd_table_free: hns_roce_cleanup_pd_table(hr_dev); err_uar_alloc_free: hns_roce_uar_free(hr_dev, &hr_dev->priv_uar); err_uar_table_free: hns_roce_cleanup_uar_table(hr_dev); return ret; } int hns_roce_init(struct hns_roce_dev *hr_dev) { int ret; struct device *dev = hr_dev->dev; if (hr_dev->hw->reset) { ret = hr_dev->hw->reset(hr_dev, true); if (ret) { dev_err(dev, "Reset RoCE engine failed!\n"); return ret; } } if (hr_dev->hw->cmq_init) { ret = hr_dev->hw->cmq_init(hr_dev); if (ret) { dev_err(dev, "Init RoCE Command Queue failed!\n"); goto error_failed_cmq_init; } } ret = hr_dev->hw->hw_profile(hr_dev); if (ret) { dev_err(dev, "Get RoCE engine profile failed!\n"); goto error_failed_cmd_init; } ret = hns_roce_cmd_init(hr_dev); if (ret) { dev_err(dev, "cmd init failed!\n"); goto error_failed_cmd_init; } ret = hr_dev->hw->init_eq(hr_dev); if (ret) { dev_err(dev, "eq init failed!\n"); goto error_failed_eq_table; } if (hr_dev->cmd_mod) { ret = hns_roce_cmd_use_events(hr_dev); if (ret) { dev_err(dev, "Switch to event-driven cmd failed!\n"); goto error_failed_use_event; } } ret = hns_roce_init_hem(hr_dev); if (ret) { dev_err(dev, "init HEM(Hardware Entry Memory) failed!\n"); goto error_failed_init_hem; } ret = hns_roce_setup_hca(hr_dev); if (ret) { dev_err(dev, "setup hca failed!\n"); goto error_failed_setup_hca; } if (hr_dev->hw->hw_init) { ret = hr_dev->hw->hw_init(hr_dev); if (ret) { dev_err(dev, "hw_init failed!\n"); goto error_failed_engine_init; } } ret = hns_roce_register_device(hr_dev); if (ret) goto error_failed_register_device; return 0; error_failed_register_device: if (hr_dev->hw->hw_exit) hr_dev->hw->hw_exit(hr_dev); error_failed_engine_init: hns_roce_cleanup_bitmap(hr_dev); error_failed_setup_hca: hns_roce_cleanup_hem(hr_dev); error_failed_init_hem: if (hr_dev->cmd_mod) hns_roce_cmd_use_polling(hr_dev); error_failed_use_event: hr_dev->hw->cleanup_eq(hr_dev); error_failed_eq_table: hns_roce_cmd_cleanup(hr_dev); error_failed_cmd_init: if (hr_dev->hw->cmq_exit) hr_dev->hw->cmq_exit(hr_dev); error_failed_cmq_init: if (hr_dev->hw->reset) { ret = hr_dev->hw->reset(hr_dev, false); if (ret) dev_err(dev, "Dereset RoCE engine failed!\n"); } return ret; } EXPORT_SYMBOL_GPL(hns_roce_init); void hns_roce_exit(struct hns_roce_dev *hr_dev) { hns_roce_unregister_device(hr_dev); if (hr_dev->hw->hw_exit) hr_dev->hw->hw_exit(hr_dev); hns_roce_cleanup_bitmap(hr_dev); hns_roce_cleanup_hem(hr_dev); if (hr_dev->cmd_mod) hns_roce_cmd_use_polling(hr_dev); hr_dev->hw->cleanup_eq(hr_dev); hns_roce_cmd_cleanup(hr_dev); if (hr_dev->hw->cmq_exit) hr_dev->hw->cmq_exit(hr_dev); if (hr_dev->hw->reset) hr_dev->hw->reset(hr_dev, false); } EXPORT_SYMBOL_GPL(hns_roce_exit); MODULE_LICENSE("Dual BSD/GPL"); MODULE_AUTHOR("Wei Hu <xavier.huwei@huawei.com>"); MODULE_AUTHOR("Nenglong Zhao <zhaonenglong@hisilicon.com>"); MODULE_AUTHOR("Lijun Ou <oulijun@huawei.com>"); MODULE_DESCRIPTION("HNS RoCE Driver");
./CrossVul/dataset_final_sorted/CWE-665/c/bad_1128_0
crossvul-cpp_data_bad_2629_2
/***************************************************************************** * * NAGIOS.C - Core Program Code For Nagios * * Program: Nagios Core * License: GPL * * First Written: 01-28-1999 (start of development) * * Description: * * Nagios is a network monitoring tool that will check hosts and services * that you specify. It has the ability to notify contacts via email, pager, * or other user-defined methods when a service or host goes down and * recovers. Service and host monitoring is done through the use of external * plugins which can be developed independently of Nagios. * * License: * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 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. * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * *****************************************************************************/ #include "../include/config.h" #include "../include/common.h" #include "../include/objects.h" #include "../include/comments.h" #include "../include/downtime.h" #include "../include/statusdata.h" #include "../include/macros.h" #include "../include/nagios.h" #include "../include/sretention.h" #include "../include/perfdata.h" #include "../include/broker.h" #include "../include/nebmods.h" #include "../include/nebmodules.h" #include "../include/workers.h" /*#define DEBUG_MEMORY 1*/ #ifdef DEBUG_MEMORY #include <mcheck.h> #endif static int is_worker; static void set_loadctl_defaults(void) { struct rlimit rlim; /* Workers need to up 'em, master needs to know 'em */ getrlimit(RLIMIT_NOFILE, &rlim); rlim.rlim_cur = rlim.rlim_max; setrlimit(RLIMIT_NOFILE, &rlim); loadctl.nofile_limit = rlim.rlim_max; #ifdef RLIMIT_NPROC getrlimit(RLIMIT_NPROC, &rlim); rlim.rlim_cur = rlim.rlim_max; setrlimit(RLIMIT_NPROC, &rlim); loadctl.nproc_limit = rlim.rlim_max; #else loadctl.nproc_limit = loadctl.nofile_limit / 2; #endif /* * things may have been configured already. Otherwise we * set some sort of sane defaults here */ if (!loadctl.jobs_max) { loadctl.jobs_max = loadctl.nproc_limit - 100; if (!is_worker && loadctl.jobs_max > (loadctl.nofile_limit - 50) * wproc_num_workers_online) { loadctl.jobs_max = (loadctl.nofile_limit - 50) * wproc_num_workers_online; } } if (!loadctl.jobs_limit) loadctl.jobs_limit = loadctl.jobs_max; if (!loadctl.backoff_limit) loadctl.backoff_limit = online_cpus() * 2.5; if (!loadctl.rampup_limit) loadctl.rampup_limit = online_cpus() * 0.8; if (!loadctl.backoff_change) loadctl.backoff_change = loadctl.jobs_limit * 0.3; if (!loadctl.rampup_change) loadctl.rampup_change = loadctl.backoff_change * 0.25; if (!loadctl.check_interval) loadctl.check_interval = 60; if (!loadctl.jobs_min) loadctl.jobs_min = online_cpus() * 20; /* pessimistic */ } static int test_path_access(const char *program, int mode) { char *envpath, *p, *colon; int ret, our_errno = 1500; /* outside errno range */ if (program[0] == '/' || !(envpath = getenv("PATH"))) return access(program, mode); if (!(envpath = strdup(envpath))) { errno = ENOMEM; return -1; } for (p = envpath; p; p = colon + 1) { char *path; colon = strchr(p, ':'); if (colon) *colon = 0; asprintf(&path, "%s/%s", p, program); ret = access(path, mode); free(path); if (!ret) break; if (ret < 0) { if (errno == ENOENT) continue; if (our_errno > errno) our_errno = errno; } if (!colon) break; } free(envpath); if (!ret) errno = 0; else errno = our_errno; return ret; } static int nagios_core_worker(const char *path) { int sd, ret; char response[128]; is_worker = 1; set_loadctl_defaults(); sd = nsock_unix(path, NSOCK_TCP | NSOCK_CONNECT); if (sd < 0) { printf("Failed to connect to query socket '%s': %s: %s\n", path, nsock_strerror(sd), strerror(errno)); return 1; } ret = nsock_printf_nul(sd, "@wproc register name=Core Worker %ld;pid=%ld", (long)getpid(), (long)getpid()); if (ret < 0) { printf("Failed to register as worker.\n"); return 1; } ret = read(sd, response, 3); if (ret != 3) { printf("Failed to read response from wproc manager\n"); return 1; } if (memcmp(response, "OK", 3)) { read(sd, response + 3, sizeof(response) - 4); response[sizeof(response) - 2] = 0; printf("Failed to register with wproc manager: %s\n", response); return 1; } enter_worker(sd, start_cmd); return 0; } /* * only handles logfile for now, which we stash in macros to * make sure we can log *somewhere* in case the new path is * completely inaccessible. */ static int test_configured_paths(void) { FILE *fp; nagios_macros *mac; mac = get_global_macros(); fp = fopen(log_file, "a+"); if (!fp) { /* * we do some variable trashing here so logit() can * open the old logfile (if any), in case we got a * restart command or a SIGHUP */ char *value_absolute = log_file; log_file = mac->x[MACRO_LOGFILE]; logit(NSLOG_CONFIG_ERROR, TRUE, "Error: Failed to open logfile '%s' for writing: %s\n", value_absolute, strerror(errno)); return ERROR; } fclose(fp); /* save the macro */ mac->x[MACRO_LOGFILE] = log_file; return OK; } int main(int argc, char **argv) { int result; int error = FALSE; int display_license = FALSE; int display_help = FALSE; int c = 0; struct tm *tm, tm_s; time_t now; char datestring[256]; nagios_macros *mac; const char *worker_socket = NULL; int i; #ifdef HAVE_SIGACTION struct sigaction sig_action; #endif #ifdef HAVE_GETOPT_H int option_index = 0; static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, {"license", no_argument, 0, 'V'}, {"verify-config", no_argument, 0, 'v'}, {"daemon", no_argument, 0, 'd'}, {"test-scheduling", no_argument, 0, 's'}, {"precache-objects", no_argument, 0, 'p'}, {"use-precached-objects", no_argument, 0, 'u'}, {"enable-timing-point", no_argument, 0, 'T'}, {"worker", required_argument, 0, 'W'}, {0, 0, 0, 0} }; #define getopt(argc, argv, o) getopt_long(argc, argv, o, long_options, &option_index) #endif memset(&loadctl, 0, sizeof(loadctl)); mac = get_global_macros(); /* make sure we have the correct number of command line arguments */ if(argc < 2) error = TRUE; /* get all command line arguments */ while(1) { c = getopt(argc, argv, "+hVvdspuxTW"); if(c == -1 || c == EOF) break; switch(c) { case '?': /* usage */ case 'h': display_help = TRUE; break; case 'V': /* version */ display_license = TRUE; break; case 'v': /* verify */ verify_config++; break; case 's': /* scheduling check */ test_scheduling = TRUE; break; case 'd': /* daemon mode */ daemon_mode = TRUE; break; case 'p': /* precache object config */ precache_objects = TRUE; break; case 'u': /* use precached object config */ use_precached_objects = TRUE; break; case 'T': enable_timing_point = TRUE; break; case 'W': worker_socket = optarg; break; case 'x': printf("Warning: -x is deprecated and will be removed\n"); break; default: break; } } #ifdef DEBUG_MEMORY mtrace(); #endif /* if we're a worker we can skip everything below */ if(worker_socket) { exit(nagios_core_worker(worker_socket)); } /* Initialize configuration variables */ init_main_cfg_vars(1); init_shared_cfg_vars(1); if(daemon_mode == FALSE) { printf("\nNagios Core %s\n", PROGRAM_VERSION); printf("Copyright (c) 2009-present Nagios Core Development Team and Community Contributors\n"); printf("Copyright (c) 1999-2009 Ethan Galstad\n"); printf("Last Modified: %s\n", PROGRAM_MODIFICATION_DATE); printf("License: GPL\n\n"); printf("Website: https://www.nagios.org\n"); } /* just display the license */ if(display_license == TRUE) { printf("This program is free software; you can redistribute it and/or modify\n"); printf("it under the terms of the GNU General Public License version 2 as\n"); printf("published by the Free Software Foundation.\n\n"); printf("This program is distributed in the hope that it will be useful,\n"); printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"); printf("GNU General Public License for more details.\n\n"); printf("You should have received a copy of the GNU General Public License\n"); printf("along with this program; if not, write to the Free Software\n"); printf("Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n"); exit(OK); } /* make sure we got the main config file on the command line... */ if(optind >= argc) error = TRUE; /* if there are no command line options (or if we encountered an error), print usage */ if(error == TRUE || display_help == TRUE) { printf("Usage: %s [options] <main_config_file>\n", argv[0]); printf("\n"); printf("Options:\n"); printf("\n"); printf(" -v, --verify-config Verify all configuration data (-v -v for more info)\n"); printf(" -s, --test-scheduling Shows projected/recommended check scheduling and other\n"); printf(" diagnostic info based on the current configuration files.\n"); printf(" -T, --enable-timing-point Enable timed commentary on initialization\n"); printf(" -x, --dont-verify-paths Deprecated (Don't check for circular object paths)\n"); printf(" -p, --precache-objects Precache object configuration\n"); printf(" -u, --use-precached-objects Use precached object config file\n"); printf(" -d, --daemon Starts Nagios in daemon mode, instead of as a foreground process\n"); printf(" -W, --worker /path/to/socket Act as a worker for an already running daemon\n"); printf("\n"); printf("Visit the Nagios website at https://www.nagios.org/ for bug fixes, new\n"); printf("releases, online documentation, FAQs, information on subscribing to\n"); printf("the mailing lists, and commercial support options for Nagios.\n"); printf("\n"); exit(ERROR); } /* * config file is last argument specified. * Make sure it uses an absolute path */ config_file = nspath_absolute(argv[optind], NULL); if(config_file == NULL) { printf("Error allocating memory.\n"); exit(ERROR); } config_file_dir = nspath_absolute_dirname(config_file, NULL); /* * Set the signal handler for the SIGXFSZ signal here because * we may encounter this signal before the other signal handlers * are set. */ #ifdef HAVE_SIGACTION sig_action.sa_sigaction = NULL; sig_action.sa_handler = handle_sigxfsz; sigfillset(&sig_action.sa_mask); sig_action.sa_flags = SA_NODEFER|SA_RESTART; sigaction(SIGXFSZ, &sig_action, NULL); #else signal(SIGXFSZ, handle_sigxfsz); #endif /* * let's go to town. We'll be noisy if we're verifying config * or running scheduling tests. */ if(verify_config || test_scheduling || precache_objects) { reset_variables(); /* * if we don't beef up our resource limits as much as * we can, it's quite possible we'll run headlong into * EAGAIN due to too many processes when we try to * drop privileges later. */ set_loadctl_defaults(); if(verify_config) printf("Reading configuration data...\n"); /* read our config file */ result = read_main_config_file(config_file); if(result != OK) { printf(" Error processing main config file!\n\n"); exit(EXIT_FAILURE); } if(verify_config) printf(" Read main config file okay...\n"); /* drop privileges */ if((result = drop_privileges(nagios_user, nagios_group)) == ERROR) { printf(" Failed to drop privileges. Aborting."); exit(EXIT_FAILURE); } /* * this must come after dropping privileges, so we make * sure to test access permissions as the right user. */ if (!verify_config && test_configured_paths() == ERROR) { printf(" One or more path problems detected. Aborting.\n"); exit(EXIT_FAILURE); } /* read object config files */ result = read_all_object_data(config_file); if(result != OK) { printf(" Error processing object config files!\n\n"); /* if the config filename looks fishy, warn the user */ if(!strstr(config_file, "nagios.cfg")) { printf("\n***> The name of the main configuration file looks suspicious...\n"); printf("\n"); printf(" Make sure you are specifying the name of the MAIN configuration file on\n"); printf(" the command line and not the name of another configuration file. The\n"); printf(" main configuration file is typically '%s'\n", DEFAULT_CONFIG_FILE); } printf("\n***> One or more problems was encountered while processing the config files...\n"); printf("\n"); printf(" Check your configuration file(s) to ensure that they contain valid\n"); printf(" directives and data definitions. If you are upgrading from a previous\n"); printf(" version of Nagios, you should be aware that some variables/definitions\n"); printf(" may have been removed or modified in this version. Make sure to read\n"); printf(" the HTML documentation regarding the config files, as well as the\n"); printf(" 'Whats New' section to find out what has changed.\n\n"); exit(EXIT_FAILURE); } if(verify_config) { printf(" Read object config files okay...\n\n"); printf("Running pre-flight check on configuration data...\n\n"); } /* run the pre-flight check to make sure things look okay... */ result = pre_flight_check(); if(result != OK) { printf("\n***> One or more problems was encountered while running the pre-flight check...\n"); printf("\n"); printf(" Check your configuration file(s) to ensure that they contain valid\n"); printf(" directives and data definitions. If you are upgrading from a previous\n"); printf(" version of Nagios, you should be aware that some variables/definitions\n"); printf(" may have been removed or modified in this version. Make sure to read\n"); printf(" the HTML documentation regarding the config files, as well as the\n"); printf(" 'Whats New' section to find out what has changed.\n\n"); exit(EXIT_FAILURE); } if(verify_config) { printf("\nThings look okay - No serious problems were detected during the pre-flight check\n"); } /* scheduling tests need a bit more than config verifications */ if(test_scheduling == TRUE) { /* we'll need the event queue here so we can time insertions */ init_event_queue(); timing_point("Done initializing event queue\n"); /* read initial service and host state information */ initialize_retention_data(config_file); read_initial_state_information(); timing_point("Retention data and initial state parsed\n"); /* initialize the event timing loop */ init_timing_loop(); timing_point("Timing loop initialized\n"); /* display scheduling information */ display_scheduling_info(); } if(precache_objects) { result = fcache_objects(object_precache_file); timing_point("Done precaching objects\n"); if(result == OK) { printf("Object precache file created:\n%s\n", object_precache_file); } else { printf("Failed to precache objects to '%s': %s\n", object_precache_file, strerror(errno)); } } /* clean up after ourselves */ cleanup(); /* exit */ timing_point("Exiting\n"); /* make valgrind shut up about still reachable memory */ neb_free_module_list(); free(config_file_dir); free(config_file); exit(result); } /* else start to monitor things... */ else { /* * if we're called with a relative path we must make * it absolute so we can launch our workers. * If not, we needn't bother, as we're using execvp() */ if (strchr(argv[0], '/')) nagios_binary_path = nspath_absolute(argv[0], NULL); else nagios_binary_path = strdup(argv[0]); if (!nagios_binary_path) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Unable to allocate memory for nagios_binary_path\n"); exit(EXIT_FAILURE); } if (!(nagios_iobs = iobroker_create())) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Failed to create IO broker set: %s\n", strerror(errno)); exit(EXIT_FAILURE); } /* keep monitoring things until we get a shutdown command */ do { /* reset internal book-keeping (in case we're restarting) */ wproc_num_workers_spawned = wproc_num_workers_online = 0; caught_signal = sigshutdown = FALSE; sig_id = 0; /* reset program variables */ reset_variables(); timing_point("Variables reset\n"); /* get PID */ nagios_pid = (int)getpid(); /* read in the configuration files (main and resource config files) */ result = read_main_config_file(config_file); if (result != OK) { logit(NSLOG_CONFIG_ERROR, TRUE, "Error: Failed to process config file '%s'. Aborting\n", config_file); exit(EXIT_FAILURE); } timing_point("Main config file read\n"); /* NOTE 11/06/07 EG moved to after we read config files, as user may have overridden timezone offset */ /* get program (re)start time and save as macro */ program_start = time(NULL); my_free(mac->x[MACRO_PROCESSSTARTTIME]); asprintf(&mac->x[MACRO_PROCESSSTARTTIME], "%llu", (unsigned long long)program_start); /* drop privileges */ if(drop_privileges(nagios_user, nagios_group) == ERROR) { logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, "Failed to drop privileges. Aborting."); cleanup(); exit(ERROR); } if (test_path_access(nagios_binary_path, X_OK)) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: failed to access() %s: %s\n", nagios_binary_path, strerror(errno)); logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Spawning workers will be impossible. Aborting.\n"); exit(EXIT_FAILURE); } if (test_configured_paths() == ERROR) { /* error has already been logged */ exit(EXIT_FAILURE); } /* enter daemon mode (unless we're restarting...) */ if(daemon_mode == TRUE && sigrestart == FALSE) { result = daemon_init(); /* we had an error daemonizing, so bail... */ if(result == ERROR) { logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR, TRUE, "Bailing out due to failure to daemonize. (PID=%d)", (int)getpid()); cleanup(); exit(EXIT_FAILURE); } /* get new PID */ nagios_pid = (int)getpid(); } /* this must be logged after we read config data, as user may have changed location of main log file */ logit(NSLOG_PROCESS_INFO, TRUE, "Nagios %s starting... (PID=%d)\n", PROGRAM_VERSION, (int)getpid()); /* log the local time - may be different than clock time due to timezone offset */ now = time(NULL); tm = localtime_r(&now, &tm_s); strftime(datestring, sizeof(datestring), "%a %b %d %H:%M:%S %Z %Y", tm); logit(NSLOG_PROCESS_INFO, TRUE, "Local time is %s", datestring); /* write log version/info */ write_log_file_info(NULL); /* open debug log now that we're the right user */ open_debug_log(); #ifdef USE_EVENT_BROKER /* initialize modules */ neb_init_modules(); neb_init_callback_list(); #endif timing_point("NEB module API initialized\n"); /* handle signals (interrupts) before we do any socket I/O */ setup_sighandler(); /* * Initialize query handler and event subscription service. * This must be done before modules are initialized, so * the modules can use our in-core stuff properly */ if (qh_init(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET) != OK) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Failed to initialize query handler. Aborting\n"); exit(EXIT_FAILURE); } timing_point("Query handler initialized\n"); nerd_init(); timing_point("NERD initialized\n"); /* initialize check workers */ if(init_workers(num_check_workers) < 0) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Failed to spawn workers. Aborting\n"); exit(EXIT_FAILURE); } timing_point("%u workers spawned\n", wproc_num_workers_spawned); i = 0; while (i < 50 && wproc_num_workers_online < wproc_num_workers_spawned) { iobroker_poll(nagios_iobs, 50); i++; } timing_point("%u workers connected\n", wproc_num_workers_online); /* now that workers have arrived we can set the defaults */ set_loadctl_defaults(); #ifdef USE_EVENT_BROKER /* load modules */ if (neb_load_all_modules() != OK) { logit(NSLOG_CONFIG_ERROR, ERROR, "Error: Module loading failed. Aborting.\n"); /* if we're dumping core, we must remove all dl-files */ if (daemon_dumps_core) neb_unload_all_modules(NEBMODULE_FORCE_UNLOAD, NEBMODULE_NEB_SHUTDOWN); exit(EXIT_FAILURE); } timing_point("Modules loaded\n"); /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_PRELAUNCH, NEBFLAG_NONE, NEBATTR_NONE, NULL); timing_point("First callback made\n"); #endif /* read in all object config data */ if(result == OK) result = read_all_object_data(config_file); /* there was a problem reading the config files */ if(result != OK) logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, "Bailing out due to one or more errors encountered in the configuration files. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)", (int)getpid()); else { /* run the pre-flight check to make sure everything looks okay*/ if((result = pre_flight_check()) != OK) logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_VERIFICATION_ERROR, TRUE, "Bailing out due to errors encountered while running the pre-flight check. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)\n", (int)getpid()); } /* an error occurred that prevented us from (re)starting */ if(result != OK) { /* if we were restarting, we need to cleanup from the previous run */ if(sigrestart == TRUE) { /* clean up the status data */ cleanup_status_data(TRUE); } #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_PROCESS_INITIATED, NEBATTR_SHUTDOWN_ABNORMAL, NULL); #endif cleanup(); exit(ERROR); } timing_point("Object configuration parsed and understood\n"); /* write the objects.cache file */ fcache_objects(object_cache_file); timing_point("Objects cached\n"); init_event_queue(); timing_point("Event queue initialized\n"); #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_START, NEBFLAG_NONE, NEBATTR_NONE, NULL); #endif /* initialize status data unless we're starting */ if(sigrestart == FALSE) { initialize_status_data(config_file); timing_point("Status data initialized\n"); } /* initialize scheduled downtime data */ initialize_downtime_data(); timing_point("Downtime data initialized\n"); /* read initial service and host state information */ initialize_retention_data(config_file); timing_point("Retention data initialized\n"); read_initial_state_information(); timing_point("Initial state information read\n"); /* initialize comment data */ initialize_comment_data(); timing_point("Comment data initialized\n"); /* initialize performance data */ initialize_performance_data(config_file); timing_point("Performance data initialized\n"); /* initialize the event timing loop */ init_timing_loop(); timing_point("Event timing loop initialized\n"); /* initialize check statistics */ init_check_stats(); timing_point("check stats initialized\n"); /* check for updates */ check_for_nagios_updates(FALSE, TRUE); timing_point("Update check concluded\n"); /* update all status data (with retained information) */ update_all_status_data(); timing_point("Status data updated\n"); /* log initial host and service state */ log_host_states(INITIAL_STATES, NULL); log_service_states(INITIAL_STATES, NULL); timing_point("Initial states logged\n"); /* reset the restart flag */ sigrestart = FALSE; /* fire up command file worker */ launch_command_file_worker(); timing_point("Command file worker launched\n"); #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_EVENTLOOPSTART, NEBFLAG_NONE, NEBATTR_NONE, NULL); #endif /* get event start time and save as macro */ event_start = time(NULL); my_free(mac->x[MACRO_EVENTSTARTTIME]); asprintf(&mac->x[MACRO_EVENTSTARTTIME], "%llu", (unsigned long long)event_start); timing_point("Entering event execution loop\n"); /***** start monitoring all services *****/ /* (doesn't return until a restart or shutdown signal is encountered) */ event_execution_loop(); /* * immediately deinitialize the query handler so it * can remove modules that have stashed data with it */ qh_deinit(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET); /* 03/01/2007 EG Moved from sighandler() to prevent FUTEX locking problems under NPTL */ /* 03/21/2007 EG SIGSEGV signals are still logged in sighandler() so we don't loose them */ /* did we catch a signal? */ if(caught_signal == TRUE) { if(sig_id == SIGHUP) logit(NSLOG_PROCESS_INFO, TRUE, "Caught SIGHUP, restarting...\n"); } #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_EVENTLOOPEND, NEBFLAG_NONE, NEBATTR_NONE, NULL); if(sigshutdown == TRUE) broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_USER_INITIATED, NEBATTR_SHUTDOWN_NORMAL, NULL); else if(sigrestart == TRUE) broker_program_state(NEBTYPE_PROCESS_RESTART, NEBFLAG_USER_INITIATED, NEBATTR_RESTART_NORMAL, NULL); #endif /* save service and host state information */ save_state_information(FALSE); cleanup_retention_data(); /* clean up performance data */ cleanup_performance_data(); /* clean up the scheduled downtime data */ cleanup_downtime_data(); /* clean up the status data unless we're restarting */ if(sigrestart == FALSE) { cleanup_status_data(TRUE); } free_worker_memory(WPROC_FORCE); /* shutdown stuff... */ if(sigshutdown == TRUE) { iobroker_destroy(nagios_iobs, IOBROKER_CLOSE_SOCKETS); nagios_iobs = NULL; /* log a shutdown message */ logit(NSLOG_PROCESS_INFO, TRUE, "Successfully shutdown... (PID=%d)\n", (int)getpid()); } /* clean up after ourselves */ cleanup(); /* close debug log */ close_debug_log(); } while(sigrestart == TRUE && sigshutdown == FALSE); if(daemon_mode == TRUE) unlink(lock_file); /* free misc memory */ my_free(lock_file); my_free(config_file); my_free(config_file_dir); my_free(nagios_binary_path); } return OK; }
./CrossVul/dataset_final_sorted/CWE-665/c/bad_2629_2
crossvul-cpp_data_bad_738_0
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2019 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // caff.c // This module is a helper to the WavPack command-line programs to support CAF files. #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <ctype.h> #include "wavpack.h" #include "utils.h" #include "md5.h" #ifdef _WIN32 #define strdup(x) _strdup(x) #endif #define WAVPACK_NO_ERROR 0 #define WAVPACK_SOFT_ERROR 1 #define WAVPACK_HARD_ERROR 2 extern int debug_logging_mode; typedef struct { char mFileType [4]; uint16_t mFileVersion; uint16_t mFileFlags; } CAFFileHeader; #define CAFFileHeaderFormat "4SS" #pragma pack(push,4) typedef struct { char mChunkType [4]; int64_t mChunkSize; } CAFChunkHeader; #pragma pack(pop) #define CAFChunkHeaderFormat "4D" typedef struct { double mSampleRate; char mFormatID [4]; uint32_t mFormatFlags; uint32_t mBytesPerPacket; uint32_t mFramesPerPacket; uint32_t mChannelsPerFrame; uint32_t mBitsPerChannel; } CAFAudioFormat; #define CAFAudioFormatFormat "D4LLLLL" #define CAF_FORMAT_FLOAT 0x1 #define CAF_FORMAT_LITTLE_ENDIAN 0x2 typedef struct { uint32_t mChannelLayoutTag; uint32_t mChannelBitmap; uint32_t mNumberChannelDescriptions; } CAFChannelLayout; #define CAFChannelLayoutFormat "LLL" enum { kCAFChannelLayoutTag_UseChannelDescriptions = (0<<16) | 0, // use the array of AudioChannelDescriptions to define the mapping. kCAFChannelLayoutTag_UseChannelBitmap = (1<<16) | 0, // use the bitmap to define the mapping. }; typedef struct { uint32_t mChannelLabel; uint32_t mChannelFlags; float mCoordinates [3]; } CAFChannelDescription; #define CAFChannelDescriptionFormat "LLLLL" static const char TMH_full [] = { 1,2,3,13,9,10,5,6,12,14,15,16,17,9,4,18,7,8,19,20,21,0 }; static const char TMH_std [] = { 1,2,3,11,8,9,5,6,10,12,13,14,15,7,4,16,0 }; static struct { uint32_t mChannelLayoutTag; // Core Audio layout, 100 - 146 in high word, num channels in low word uint32_t mChannelBitmap; // Microsoft standard mask (for those channels that appear) const char *mChannelReorder; // reorder string if layout is NOT in Microsoft standard order const char *mChannelIdentities; // identities of any channels NOT in Microsoft standard } layouts [] = { { (100<<16) | 1, 0x004, NULL, NULL }, // FC { (101<<16) | 2, 0x003, NULL, NULL }, // FL, FR { (102<<16) | 2, 0x003, NULL, NULL }, // FL, FR (headphones) { (103<<16) | 2, 0x000, NULL, "\46\47" }, // [Lt, Rt] (matrix encoded) { (104<<16) | 2, 0x000, NULL, "\314\315" }, // [Mid, Side] { (105<<16) | 2, 0x000, NULL, "\316\317" }, // [X, Y] { (106<<16) | 2, 0x003, NULL, NULL }, // FL, FR (binaural) { (107<<16) | 4, 0x000, NULL, "\310\311\312\313" }, // [W, X, Y, Z] (ambisonics) { (108<<16) | 4, 0x033, NULL, NULL }, // FL, FR, BL, BR (quad) { (109<<16) | 5, 0x037, "12453", NULL }, // FL, FR, BL, BR, FC (pentagonal) { (110<<16) | 6, 0x137, "124536", NULL }, // FL, FR, BL, BR, FC, BC (hexagonal) { (111<<16) | 8, 0x737, "12453678", NULL }, // FL, FR, BL, BR, FC, BC, SL, SR (octagonal) { (112<<16) | 8, 0x2d033, NULL, NULL }, // FL, FR, BL, BR, TFL, TFR, TBL, TBR (cubic) { (113<<16) | 3, 0x007, NULL, NULL }, // FL, FR, FC { (114<<16) | 3, 0x007, "312", NULL }, // FC, FL, FR { (115<<16) | 4, 0x107, NULL, NULL }, // FL, FR, FC, BC { (116<<16) | 4, 0x107, "3124", NULL }, // FC, FL, FR, BC { (117<<16) | 5, 0x037, NULL, NULL }, // FL, FR, FC, BL, BR { (118<<16) | 5, 0x037, "12453", NULL }, // FL, FR, BL, BR, FC { (119<<16) | 5, 0x037, "13245", NULL }, // FL, FC, FR, BL, BR { (120<<16) | 5, 0x037, "31245", NULL }, // FC, FL, FR, BL, BR { (121<<16) | 6, 0x03f, NULL, NULL }, // FL, FR, FC, LFE, BL, BR { (122<<16) | 6, 0x03f, "125634", NULL }, // FL, FR, BL, BR, FC, LFE { (123<<16) | 6, 0x03f, "132564", NULL }, // FL, FC, FR, BL, BR, LFE { (124<<16) | 6, 0x03f, "312564", NULL }, // FC, FL, FR, BL, BR, LFE { (125<<16) | 7, 0x13f, NULL, NULL }, // FL, FR, FC, LFE, BL, BR, BC { (126<<16) | 8, 0x0ff, NULL, NULL }, // FL, FR, FC, LFE, BL, BR, FLC, FRC { (127<<16) | 8, 0x0ff, "37812564", NULL }, // FC, FLC, FRC, FL, FR, BL, BR, LFE { (128<<16) | 8, 0x03f, NULL, "\41\42" }, // FL, FR, FC, LFE, BL, BR, [Rls, Rrs] { (129<<16) | 8, 0x0ff, "12563478", NULL }, // FL, FR, BL, BR, FC, LFE, FLC, FRC { (130<<16) | 8, 0x03f, NULL, "\46\47" }, // FL, FR, FC, LFE, BL, BR, [Lt, Rt] { (131<<16) | 3, 0x103, NULL, NULL }, // FL, FR, BC { (132<<16) | 4, 0x033, NULL, NULL }, // FL, FR, BL, BR { (133<<16) | 3, 0x00B, NULL, NULL }, // FL, FR, LFE { (134<<16) | 4, 0x10B, NULL, NULL }, // FL, FR, LFE, BC { (135<<16) | 5, 0x03B, NULL, NULL }, // FL, FR, LFE, BL, BR { (136<<16) | 4, 0x00F, NULL, NULL }, // FL, FR, FC, LFE { (137<<16) | 5, 0x10f, NULL, NULL }, // FL, FR, FC, LFE, BC { (138<<16) | 5, 0x03b, "12453", NULL }, // FL, FR, BL, BR, LFE { (139<<16) | 6, 0x137, "124536", NULL }, // FL, FR, BL, BR, FC, BC { (140<<16) | 7, 0x037, "1245367", "\41\42" }, // FL, FR, BL, BR, FC, [Rls, Rrs] { (141<<16) | 6, 0x137, "312456", NULL }, // FC, FL, FR, BL, BR, BC { (142<<16) | 7, 0x13f, "3125674", NULL }, // FC, FL, FR, BL, BR, BC, LFE { (143<<16) | 7, 0x037, "3124567", "\41\42" }, // FC, FL, FR, BL, BR, [Rls, Rrs] { (144<<16) | 8, 0x137, "31245786", "\41\42" }, // FC, FL, FR, BL, BR, [Rls, Rrs], BC { (145<<16) | 16, 0x773f, TMH_std, "\43\44\54\45" }, // FL, FR, FC, TFC, SL, SR, BL, BR, TFL, TFR, [Lw, Rw, Csd], BC, LFE, [LFE2] { (146<<16) | 21, 0x77ff, TMH_full, "\43\44\54\45" }, // FL, FR, FC, TFC, SL, SR, BL, BR, TFL, TFR, [Lw, Rw, Csd], BC, LFE, [LFE2], // FLC, FRC, [HI, VI, Haptic] }; #define NUM_LAYOUTS (sizeof (layouts) / sizeof (layouts [0])) int ParseCaffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { uint32_t chan_chunk = 0, channel_layout = 0, bcount; unsigned char *channel_identities = NULL; unsigned char *channel_reorder = NULL; int64_t total_samples = 0, infilesize; CAFFileHeader caf_file_header; CAFChunkHeader caf_chunk_header; CAFAudioFormat caf_audio_format; int i; infilesize = DoGetFileSize (infile); memcpy (&caf_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &caf_file_header) + 4, sizeof (CAFFileHeader) - 4, &bcount) || bcount != sizeof (CAFFileHeader) - 4)) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &caf_file_header, sizeof (CAFFileHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&caf_file_header, CAFFileHeaderFormat); if (caf_file_header.mFileVersion != 1) { error_line ("%s: can't handle version %d .CAF files!", infilename, caf_file_header.mFileVersion); return WAVPACK_SOFT_ERROR; } // loop through all elements of the RIFF wav header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &caf_chunk_header, sizeof (CAFChunkHeader), &bcount) || bcount != sizeof (CAFChunkHeader)) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &caf_chunk_header, sizeof (CAFChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&caf_chunk_header, CAFChunkHeaderFormat); // if it's the format chunk, we want to get some info out of there and // make sure it's a .caf file we can handle if (!strncmp (caf_chunk_header.mChunkType, "desc", 4)) { int supported = TRUE; if (caf_chunk_header.mChunkSize != sizeof (CAFAudioFormat) || !DoReadFile (infile, &caf_audio_format, (uint32_t) caf_chunk_header.mChunkSize, &bcount) || bcount != caf_chunk_header.mChunkSize) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &caf_audio_format, (uint32_t) caf_chunk_header.mChunkSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&caf_audio_format, CAFAudioFormatFormat); if (debug_logging_mode) { char formatstr [5]; memcpy (formatstr, caf_audio_format.mFormatID, 4); formatstr [4] = 0; error_line ("format = %s, flags = %x, sampling rate = %g", formatstr, caf_audio_format.mFormatFlags, caf_audio_format.mSampleRate); error_line ("packet = %d bytes and %d frames", caf_audio_format.mBytesPerPacket, caf_audio_format.mFramesPerPacket); error_line ("channels per frame = %d, bits per channel = %d", caf_audio_format.mChannelsPerFrame, caf_audio_format.mBitsPerChannel); } if (strncmp (caf_audio_format.mFormatID, "lpcm", 4) || (caf_audio_format.mFormatFlags & ~3)) supported = FALSE; else if (caf_audio_format.mSampleRate < 1.0 || caf_audio_format.mSampleRate > 16777215.0 || caf_audio_format.mSampleRate != floor (caf_audio_format.mSampleRate)) supported = FALSE; else if (!caf_audio_format.mChannelsPerFrame || caf_audio_format.mChannelsPerFrame > 256) supported = FALSE; else if (caf_audio_format.mBitsPerChannel < 1 || caf_audio_format.mBitsPerChannel > 32 || ((caf_audio_format.mFormatFlags & CAF_FORMAT_FLOAT) && caf_audio_format.mBitsPerChannel != 32)) supported = FALSE; else if (caf_audio_format.mFramesPerPacket != 1 || caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame < (caf_audio_format.mBitsPerChannel + 7) / 8 || caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame > 4 || caf_audio_format.mBytesPerPacket % caf_audio_format.mChannelsPerFrame) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .CAF format!", infilename); return WAVPACK_SOFT_ERROR; } config->bytes_per_sample = caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame; config->float_norm_exp = (caf_audio_format.mFormatFlags & CAF_FORMAT_FLOAT) ? 127 : 0; config->bits_per_sample = caf_audio_format.mBitsPerChannel; config->num_channels = caf_audio_format.mChannelsPerFrame; config->sample_rate = (int) caf_audio_format.mSampleRate; if (!(caf_audio_format.mFormatFlags & CAF_FORMAT_LITTLE_ENDIAN) && config->bytes_per_sample > 1) config->qmode |= QMODE_BIG_ENDIAN; if (config->bytes_per_sample == 1) config->qmode |= QMODE_SIGNED_BYTES; if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: 32-bit %s-endian floating point", (config->qmode & QMODE_BIG_ENDIAN) ? "big" : "little"); else error_line ("data format: %d-bit %s-endian integers stored in %d byte(s)", config->bits_per_sample, (config->qmode & QMODE_BIG_ENDIAN) ? "big" : "little", config->bytes_per_sample); } } else if (!strncmp (caf_chunk_header.mChunkType, "chan", 4)) { CAFChannelLayout *caf_channel_layout; if (caf_chunk_header.mChunkSize < 0 || caf_chunk_header.mChunkSize > 1024 || caf_chunk_header.mChunkSize < sizeof (CAFChannelLayout)) { error_line ("this .CAF file has an invalid 'chan' chunk!"); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("'chan' chunk is %d bytes", (int) caf_chunk_header.mChunkSize); caf_channel_layout = malloc ((size_t) caf_chunk_header.mChunkSize); if (!DoReadFile (infile, caf_channel_layout, (uint32_t) caf_chunk_header.mChunkSize, &bcount) || bcount != caf_chunk_header.mChunkSize) { error_line ("%s is not a valid .CAF file!", infilename); free (caf_channel_layout); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, caf_channel_layout, (uint32_t) caf_chunk_header.mChunkSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (caf_channel_layout); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (caf_channel_layout, CAFChannelLayoutFormat); chan_chunk = 1; if (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED)) { error_line ("this CAF file already has channel order information!"); free (caf_channel_layout); return WAVPACK_SOFT_ERROR; } switch (caf_channel_layout->mChannelLayoutTag) { case kCAFChannelLayoutTag_UseChannelDescriptions: { CAFChannelDescription *descriptions = (CAFChannelDescription *) (caf_channel_layout + 1); int num_descriptions = caf_channel_layout->mNumberChannelDescriptions; int label, cindex = 0, idents = 0; if (caf_chunk_header.mChunkSize != sizeof (CAFChannelLayout) + sizeof (CAFChannelDescription) * num_descriptions || num_descriptions != config->num_channels) { error_line ("channel descriptions in 'chan' chunk are the wrong size!"); free (caf_channel_layout); return WAVPACK_SOFT_ERROR; } if (num_descriptions >= 256) { error_line ("%d channel descriptions is more than we can handle...ignoring!"); break; } // we allocate (and initialize to invalid values) a channel reorder array // (even though we might not end up doing any reordering) and a string for // any non-Microsoft channels we encounter channel_reorder = malloc (num_descriptions); memset (channel_reorder, -1, num_descriptions); channel_identities = malloc (num_descriptions+1); // convert the descriptions array to our native endian so it's easy to access for (i = 0; i < num_descriptions; ++i) { WavpackBigEndianToNative (descriptions + i, CAFChannelDescriptionFormat); if (debug_logging_mode) error_line ("chan %d --> %d", i + 1, descriptions [i].mChannelLabel); } // first, we go though and find any MS channels present, and move those to the beginning for (label = 1; label <= 18; ++label) for (i = 0; i < num_descriptions; ++i) if (descriptions [i].mChannelLabel == label) { config->channel_mask |= 1 << (label - 1); channel_reorder [i] = cindex++; break; } // next, we go though the channels again assigning any we haven't done for (i = 0; i < num_descriptions; ++i) if (channel_reorder [i] == (unsigned char) -1) { uint32_t clabel = descriptions [i].mChannelLabel; if (clabel == 0 || clabel == 0xffffffff || clabel == 100) channel_identities [idents++] = 0xff; else if ((clabel >= 33 && clabel <= 44) || (clabel >= 200 && clabel <= 207) || (clabel >= 301 && clabel <= 305)) channel_identities [idents++] = clabel >= 301 ? clabel - 80 : clabel; else { error_line ("warning: unknown channel descriptions label: %d", clabel); channel_identities [idents++] = 0xff; } channel_reorder [i] = cindex++; } // then, go through the reordering array and see if we really have to reorder for (i = 0; i < num_descriptions; ++i) if (channel_reorder [i] != i) break; if (i == num_descriptions) { free (channel_reorder); // no reordering required, so don't channel_reorder = NULL; } else { config->qmode |= QMODE_REORDERED_CHANS; // reordering required, put channel count into layout channel_layout = num_descriptions; } if (!idents) { // if no non-MS channels, free the identities string free (channel_identities); channel_identities = NULL; } else channel_identities [idents] = 0; // otherwise NULL terminate it if (debug_logging_mode) { error_line ("layout_tag = 0x%08x, so generated bitmap of 0x%08x from %d descriptions, %d non-MS", caf_channel_layout->mChannelLayoutTag, config->channel_mask, caf_channel_layout->mNumberChannelDescriptions, idents); // if debugging, display the reordering as a string (but only little ones) if (channel_reorder && num_descriptions <= 8) { char reorder_string [] = "12345678"; for (i = 0; i < num_descriptions; ++i) reorder_string [i] = channel_reorder [i] + '1'; reorder_string [i] = 0; error_line ("reordering string = \"%s\"\n", reorder_string); } } } break; case kCAFChannelLayoutTag_UseChannelBitmap: config->channel_mask = caf_channel_layout->mChannelBitmap; if (debug_logging_mode) error_line ("layout_tag = 0x%08x, so using supplied bitmap of 0x%08x", caf_channel_layout->mChannelLayoutTag, caf_channel_layout->mChannelBitmap); break; default: for (i = 0; i < NUM_LAYOUTS; ++i) if (caf_channel_layout->mChannelLayoutTag == layouts [i].mChannelLayoutTag) { config->channel_mask = layouts [i].mChannelBitmap; channel_layout = layouts [i].mChannelLayoutTag; if (layouts [i].mChannelReorder) { channel_reorder = (unsigned char *) strdup (layouts [i].mChannelReorder); config->qmode |= QMODE_REORDERED_CHANS; } if (layouts [i].mChannelIdentities) channel_identities = (unsigned char *) strdup (layouts [i].mChannelIdentities); if (debug_logging_mode) error_line ("layout_tag 0x%08x found in table, bitmap = 0x%08x, reorder = %s, identities = %s", channel_layout, config->channel_mask, channel_reorder ? "yes" : "no", channel_identities ? "yes" : "no"); break; } if (i == NUM_LAYOUTS && debug_logging_mode) error_line ("layout_tag 0x%08x not found in table...all channels unassigned", caf_channel_layout->mChannelLayoutTag); break; } free (caf_channel_layout); } else if (!strncmp (caf_chunk_header.mChunkType, "data", 4)) { // on the data chunk, get size and exit loop uint32_t mEditCount; if (!DoReadFile (infile, &mEditCount, sizeof (mEditCount), &bcount) || bcount != sizeof (mEditCount)) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &mEditCount, sizeof (mEditCount))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } if ((config->qmode & QMODE_IGNORE_LENGTH) || caf_chunk_header.mChunkSize == -1) { config->qmode |= QMODE_IGNORE_LENGTH; if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / caf_audio_format.mBytesPerPacket; else total_samples = -1; } else { if (infilesize && infilesize - caf_chunk_header.mChunkSize > 16777216) { error_line (".CAF file %s has over 16 MB of extra CAFF data, probably is corrupt!", infilename); return WAVPACK_SOFT_ERROR; } if ((caf_chunk_header.mChunkSize - 4) % caf_audio_format.mBytesPerPacket) { error_line (".CAF file %s has an invalid data chunk size, probably is corrupt!", infilename); return WAVPACK_SOFT_ERROR; } total_samples = (caf_chunk_header.mChunkSize - 4) / caf_audio_format.mBytesPerPacket; if (!total_samples) { error_line ("this .CAF file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } break; } else { // just copy unknown chunks to output file uint32_t bytes_to_copy = (uint32_t) caf_chunk_header.mChunkSize; char *buff; if (caf_chunk_header.mChunkSize < 0 || caf_chunk_header.mChunkSize > 1048576) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", caf_chunk_header.mChunkType [0], caf_chunk_header.mChunkType [1], caf_chunk_header.mChunkType [2], caf_chunk_header.mChunkType [3], caf_chunk_header.mChunkSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!chan_chunk && !config->channel_mask && config->num_channels <= 2 && !(config->qmode & QMODE_CHANS_UNASSIGNED)) config->channel_mask = 0x5 - config->num_channels; if (!WavpackSetConfiguration64 (wpc, config, total_samples, channel_identities)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } if (channel_identities) free (channel_identities); if (channel_layout || channel_reorder) { if (!WavpackSetChannelLayout (wpc, channel_layout, channel_reorder)) { error_line ("problem with setting channel layout (should not happen)"); return WAVPACK_SOFT_ERROR; } if (channel_reorder) free (channel_reorder); } return WAVPACK_NO_ERROR; } int WriteCaffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { CAFChunkHeader caf_desc_chunk_header, caf_chan_chunk_header, caf_data_chunk_header; CAFChannelLayout caf_channel_layout; CAFAudioFormat caf_audio_format; CAFFileHeader caf_file_header; uint32_t mEditCount, bcount; int num_channels = WavpackGetNumChannels (wpc); int32_t channel_mask = WavpackGetChannelMask (wpc); int32_t sample_rate = WavpackGetSampleRate (wpc); int bytes_per_sample = WavpackGetBytesPerSample (wpc); int bits_per_sample = WavpackGetBitsPerSample (wpc); int float_norm_exp = WavpackGetFloatNormExp (wpc); uint32_t channel_layout_tag = WavpackGetChannelLayout (wpc, NULL); unsigned char *channel_identities = malloc (num_channels + 1); int num_identified_chans, i; if (float_norm_exp && float_norm_exp != 127) { error_line ("can't create valid CAFF header for non-normalized floating data!"); free (channel_identities); return FALSE; } // get the channel identities (including Microsoft) and count up the defined ones WavpackGetChannelIdentities (wpc, channel_identities); for (num_identified_chans = i = 0; i < num_channels; ++i) if (channel_identities [i] != 0xff) num_identified_chans++; // format and write the CAF File Header strncpy (caf_file_header.mFileType, "caff", sizeof (caf_file_header.mFileType)); caf_file_header.mFileVersion = 1; caf_file_header.mFileFlags = 0; WavpackNativeToBigEndian (&caf_file_header, CAFFileHeaderFormat); if (!DoWriteFile (outfile, &caf_file_header, sizeof (caf_file_header), &bcount) || bcount != sizeof (caf_file_header)) return FALSE; // format and write the Audio Description Chunk strncpy (caf_desc_chunk_header.mChunkType, "desc", sizeof (caf_desc_chunk_header.mChunkType)); caf_desc_chunk_header.mChunkSize = sizeof (caf_audio_format); WavpackNativeToBigEndian (&caf_desc_chunk_header, CAFChunkHeaderFormat); if (!DoWriteFile (outfile, &caf_desc_chunk_header, sizeof (caf_desc_chunk_header), &bcount) || bcount != sizeof (caf_desc_chunk_header)) return FALSE; caf_audio_format.mSampleRate = (double) sample_rate; strncpy (caf_audio_format.mFormatID, "lpcm", sizeof (caf_audio_format.mFormatID)); caf_audio_format.mFormatFlags = float_norm_exp ? CAF_FORMAT_FLOAT : 0; if (!(qmode & QMODE_BIG_ENDIAN)) caf_audio_format.mFormatFlags |= CAF_FORMAT_LITTLE_ENDIAN; caf_audio_format.mBytesPerPacket = bytes_per_sample * num_channels; caf_audio_format.mFramesPerPacket = 1; caf_audio_format.mChannelsPerFrame = num_channels; caf_audio_format.mBitsPerChannel = bits_per_sample; WavpackNativeToBigEndian (&caf_audio_format, CAFAudioFormatFormat); if (!DoWriteFile (outfile, &caf_audio_format, sizeof (caf_audio_format), &bcount) || bcount != sizeof (caf_audio_format)) return FALSE; // we write the Channel Layout Chunk if any of these are true: // 1. a specific CAF layout was specified (100 - 147) // 2. there are more than 2 channels and ANY are defined // 3. there are 1 or 2 channels and NOT regular mono/stereo if (channel_layout_tag || (num_channels > 2 ? num_identified_chans : channel_mask != 5 - num_channels)) { int bits = 0, bmask; for (bmask = 1; bmask; bmask <<= 1) // count the set bits in the channel mask if (bmask & channel_mask) ++bits; // we use a layout tag if there is a specific CAF layout (100 - 147) or // all the channels are MS defined and in MS order...otherwise we have to // write a full channel description array if ((channel_layout_tag & 0xff0000) || (bits == num_channels && !(qmode & QMODE_REORDERED_CHANS))) { strncpy (caf_chan_chunk_header.mChunkType, "chan", sizeof (caf_chan_chunk_header.mChunkType)); caf_chan_chunk_header.mChunkSize = sizeof (caf_channel_layout); WavpackNativeToBigEndian (&caf_chan_chunk_header, CAFChunkHeaderFormat); if (!DoWriteFile (outfile, &caf_chan_chunk_header, sizeof (caf_chan_chunk_header), &bcount) || bcount != sizeof (caf_chan_chunk_header)) return FALSE; if (channel_layout_tag) { if (debug_logging_mode) error_line ("writing \"chan\" chunk with layout tag 0x%08x", channel_layout_tag); caf_channel_layout.mChannelLayoutTag = channel_layout_tag; caf_channel_layout.mChannelBitmap = 0; } else { if (debug_logging_mode) error_line ("writing \"chan\" chunk with UseChannelBitmap tag, bitmap = 0x%08x", channel_mask); caf_channel_layout.mChannelLayoutTag = kCAFChannelLayoutTag_UseChannelBitmap; caf_channel_layout.mChannelBitmap = channel_mask; } caf_channel_layout.mNumberChannelDescriptions = 0; WavpackNativeToBigEndian (&caf_channel_layout, CAFChannelLayoutFormat); if (!DoWriteFile (outfile, &caf_channel_layout, sizeof (caf_channel_layout), &bcount) || bcount != sizeof (caf_channel_layout)) return FALSE; } else { // write a channel description array because a single layout or bitmap won't do it... CAFChannelDescription caf_channel_description; unsigned char *new_channel_order = NULL; int i; if (debug_logging_mode) error_line ("writing \"chan\" chunk with UseChannelDescriptions tag, bitmap = 0x%08x, reordered = %s", channel_mask, (qmode & QMODE_REORDERED_CHANS) ? "yes" : "no"); if (qmode & QMODE_REORDERED_CHANS) { if ((int)(channel_layout_tag & 0xff) <= num_channels) { new_channel_order = malloc (num_channels); for (i = 0; i < num_channels; ++i) new_channel_order [i] = i; WavpackGetChannelLayout (wpc, new_channel_order); } } strncpy (caf_chan_chunk_header.mChunkType, "chan", sizeof (caf_chan_chunk_header.mChunkType)); caf_chan_chunk_header.mChunkSize = sizeof (caf_channel_layout) + sizeof (caf_channel_description) * num_channels; WavpackNativeToBigEndian (&caf_chan_chunk_header, CAFChunkHeaderFormat); if (!DoWriteFile (outfile, &caf_chan_chunk_header, sizeof (caf_chan_chunk_header), &bcount) || bcount != sizeof (caf_chan_chunk_header)) return FALSE; caf_channel_layout.mChannelLayoutTag = kCAFChannelLayoutTag_UseChannelDescriptions; caf_channel_layout.mChannelBitmap = 0; caf_channel_layout.mNumberChannelDescriptions = num_channels; WavpackNativeToBigEndian (&caf_channel_layout, CAFChannelLayoutFormat); if (!DoWriteFile (outfile, &caf_channel_layout, sizeof (caf_channel_layout), &bcount) || bcount != sizeof (caf_channel_layout)) return FALSE; for (i = 0; i < num_channels; ++i) { unsigned char chan_id = new_channel_order ? channel_identities [new_channel_order [i]] : channel_identities [i]; CLEAR (caf_channel_description); if ((chan_id >= 1 && chan_id <= 18) || (chan_id >= 33 && chan_id <= 44) || (chan_id >= 200 && chan_id <= 207)) caf_channel_description.mChannelLabel = chan_id; else if (chan_id >= 221 && chan_id <= 225) caf_channel_description.mChannelLabel = chan_id + 80; if (debug_logging_mode) error_line ("chan %d --> %d", i + 1, caf_channel_description.mChannelLabel); WavpackNativeToBigEndian (&caf_channel_description, CAFChannelDescriptionFormat); if (!DoWriteFile (outfile, &caf_channel_description, sizeof (caf_channel_description), &bcount) || bcount != sizeof (caf_channel_description)) return FALSE; } if (new_channel_order) free (new_channel_order); } } // format and write the Audio Data Chunk strncpy (caf_data_chunk_header.mChunkType, "data", sizeof (caf_data_chunk_header.mChunkType)); if (total_samples == -1) caf_data_chunk_header.mChunkSize = -1; else caf_data_chunk_header.mChunkSize = (total_samples * bytes_per_sample * num_channels) + sizeof (mEditCount); WavpackNativeToBigEndian (&caf_data_chunk_header, CAFChunkHeaderFormat); if (!DoWriteFile (outfile, &caf_data_chunk_header, sizeof (caf_data_chunk_header), &bcount) || bcount != sizeof (caf_data_chunk_header)) return FALSE; mEditCount = 0; WavpackNativeToBigEndian (&mEditCount, "L"); if (!DoWriteFile (outfile, &mEditCount, sizeof (mEditCount), &bcount) || bcount != sizeof (mEditCount)) return FALSE; free (channel_identities); return TRUE; }
./CrossVul/dataset_final_sorted/CWE-665/c/bad_738_0
crossvul-cpp_data_good_881_0
/* * Audible AA demuxer * Copyright (c) 2015 Vesselin Bontchev * * Header parsing is borrowed from https://github.com/jteeuwen/audible project. * Copyright (c) 2001-2014, Jim Teeuwen * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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 "avformat.h" #include "internal.h" #include "libavutil/dict.h" #include "libavutil/intreadwrite.h" #include "libavutil/tea.h" #include "libavutil/opt.h" #define AA_MAGIC 1469084982 /* this identifies an audible .aa file */ #define MAX_CODEC_SECOND_SIZE 3982 #define MAX_TOC_ENTRIES 16 #define MAX_DICTIONARY_ENTRIES 128 #define TEA_BLOCK_SIZE 8 #define CHAPTER_HEADER_SIZE 8 #define TIMEPREC 1000 #define MP3_FRAME_SIZE 104 typedef struct AADemuxContext { AVClass *class; uint8_t *aa_fixed_key; int aa_fixed_key_len; int codec_second_size; int current_codec_second_size; int chapter_idx; struct AVTEA *tea_ctx; uint8_t file_key[16]; int64_t current_chapter_size; int64_t content_start; int64_t content_end; int seek_offset; } AADemuxContext; static int get_second_size(char *codec_name) { int result = -1; if (!strcmp(codec_name, "mp332")) { result = 3982; } else if (!strcmp(codec_name, "acelp16")) { result = 2000; } else if (!strcmp(codec_name, "acelp85")) { result = 1045; } return result; } static int aa_read_header(AVFormatContext *s) { int i, j, idx, largest_idx = -1; uint32_t nkey, nval, toc_size, npairs, header_seed = 0, start; char key[128], val[128], codec_name[64] = {0}; uint8_t output[24], dst[8], src[8]; int64_t largest_size = -1, current_size = -1, chapter_pos; struct toc_entry { uint32_t offset; uint32_t size; } TOC[MAX_TOC_ENTRIES]; uint32_t header_key_part[4]; uint8_t header_key[16] = {0}; AADemuxContext *c = s->priv_data; AVIOContext *pb = s->pb; AVStream *st; int ret; /* parse .aa header */ avio_skip(pb, 4); // file size avio_skip(pb, 4); // magic string toc_size = avio_rb32(pb); // TOC size avio_skip(pb, 4); // unidentified integer if (toc_size > MAX_TOC_ENTRIES) return AVERROR_INVALIDDATA; for (i = 0; i < toc_size; i++) { // read TOC avio_skip(pb, 4); // TOC entry index TOC[i].offset = avio_rb32(pb); // block offset TOC[i].size = avio_rb32(pb); // block size } avio_skip(pb, 24); // header termination block (ignored) npairs = avio_rb32(pb); // read dictionary entries if (npairs > MAX_DICTIONARY_ENTRIES) return AVERROR_INVALIDDATA; for (i = 0; i < npairs; i++) { memset(val, 0, sizeof(val)); memset(key, 0, sizeof(key)); avio_skip(pb, 1); // unidentified integer nkey = avio_rb32(pb); // key string length nval = avio_rb32(pb); // value string length avio_get_str(pb, nkey, key, sizeof(key)); avio_get_str(pb, nval, val, sizeof(val)); if (!strcmp(key, "codec")) { av_log(s, AV_LOG_DEBUG, "Codec is <%s>\n", val); strncpy(codec_name, val, sizeof(codec_name) - 1); } else if (!strcmp(key, "HeaderSeed")) { av_log(s, AV_LOG_DEBUG, "HeaderSeed is <%s>\n", val); header_seed = atoi(val); } else if (!strcmp(key, "HeaderKey")) { // this looks like "1234567890 1234567890 1234567890 1234567890" av_log(s, AV_LOG_DEBUG, "HeaderKey is <%s>\n", val); ret = sscanf(val, "%"SCNu32"%"SCNu32"%"SCNu32"%"SCNu32, &header_key_part[0], &header_key_part[1], &header_key_part[2], &header_key_part[3]); if (ret != 4) return AVERROR_INVALIDDATA; for (idx = 0; idx < 4; idx++) { AV_WB32(&header_key[idx * 4], header_key_part[idx]); // convert each part to BE! } av_log(s, AV_LOG_DEBUG, "Processed HeaderKey is "); for (i = 0; i < 16; i++) av_log(s, AV_LOG_DEBUG, "%02x", header_key[i]); av_log(s, AV_LOG_DEBUG, "\n"); } else { av_dict_set(&s->metadata, key, val, 0); } } /* verify fixed key */ if (c->aa_fixed_key_len != 16) { av_log(s, AV_LOG_ERROR, "aa_fixed_key value needs to be 16 bytes!\n"); return AVERROR(EINVAL); } /* verify codec */ if ((c->codec_second_size = get_second_size(codec_name)) == -1) { av_log(s, AV_LOG_ERROR, "unknown codec <%s>!\n", codec_name); return AVERROR(EINVAL); } /* decryption key derivation */ c->tea_ctx = av_tea_alloc(); if (!c->tea_ctx) return AVERROR(ENOMEM); av_tea_init(c->tea_ctx, c->aa_fixed_key, 16); output[0] = output[1] = 0; // purely for padding purposes memcpy(output + 2, header_key, 16); idx = 0; for (i = 0; i < 3; i++) { // TEA CBC with weird mixed endianness AV_WB32(src, header_seed); AV_WB32(src + 4, header_seed + 1); header_seed += 2; av_tea_crypt(c->tea_ctx, dst, src, 1, NULL, 0); // TEA ECB encrypt for (j = 0; j < TEA_BLOCK_SIZE && idx < 18; j+=1, idx+=1) { output[idx] = output[idx] ^ dst[j]; } } memcpy(c->file_key, output + 2, 16); // skip first 2 bytes of output av_log(s, AV_LOG_DEBUG, "File key is "); for (i = 0; i < 16; i++) av_log(s, AV_LOG_DEBUG, "%02x", c->file_key[i]); av_log(s, AV_LOG_DEBUG, "\n"); /* decoder setup */ st = avformat_new_stream(s, NULL); if (!st) { av_freep(&c->tea_ctx); return AVERROR(ENOMEM); } st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; if (!strcmp(codec_name, "mp332")) { st->codecpar->codec_id = AV_CODEC_ID_MP3; st->codecpar->sample_rate = 22050; st->need_parsing = AVSTREAM_PARSE_FULL_RAW; avpriv_set_pts_info(st, 64, 8, 32000 * TIMEPREC); // encoded audio frame is MP3_FRAME_SIZE bytes (+1 with padding, unlikely) } else if (!strcmp(codec_name, "acelp85")) { st->codecpar->codec_id = AV_CODEC_ID_SIPR; st->codecpar->block_align = 19; st->codecpar->channels = 1; st->codecpar->sample_rate = 8500; st->codecpar->bit_rate = 8500; st->need_parsing = AVSTREAM_PARSE_FULL_RAW; avpriv_set_pts_info(st, 64, 8, 8500 * TIMEPREC); } else if (!strcmp(codec_name, "acelp16")) { st->codecpar->codec_id = AV_CODEC_ID_SIPR; st->codecpar->block_align = 20; st->codecpar->channels = 1; st->codecpar->sample_rate = 16000; st->codecpar->bit_rate = 16000; st->need_parsing = AVSTREAM_PARSE_FULL_RAW; avpriv_set_pts_info(st, 64, 8, 16000 * TIMEPREC); } /* determine, and jump to audio start offset */ for (i = 1; i < toc_size; i++) { // skip the first entry! current_size = TOC[i].size; if (current_size > largest_size) { largest_idx = i; largest_size = current_size; } } start = TOC[largest_idx].offset; avio_seek(pb, start, SEEK_SET); // extract chapter positions. since all formats have constant bit rate, use it // as time base in bytes/s, for easy stream position <-> timestamp conversion st->start_time = 0; c->content_start = start; c->content_end = start + largest_size; while ((chapter_pos = avio_tell(pb)) >= 0 && chapter_pos < c->content_end) { int chapter_idx = s->nb_chapters; uint32_t chapter_size = avio_rb32(pb); if (chapter_size == 0) break; chapter_pos -= start + CHAPTER_HEADER_SIZE * chapter_idx; avio_skip(pb, 4 + chapter_size); if (!avpriv_new_chapter(s, chapter_idx, st->time_base, chapter_pos * TIMEPREC, (chapter_pos + chapter_size) * TIMEPREC, NULL)) return AVERROR(ENOMEM); } st->duration = (largest_size - CHAPTER_HEADER_SIZE * s->nb_chapters) * TIMEPREC; ff_update_cur_dts(s, st, 0); avio_seek(pb, start, SEEK_SET); c->current_chapter_size = 0; c->seek_offset = 0; return 0; } static int aa_read_packet(AVFormatContext *s, AVPacket *pkt) { uint8_t dst[TEA_BLOCK_SIZE]; uint8_t src[TEA_BLOCK_SIZE]; int i; int trailing_bytes; int blocks; uint8_t buf[MAX_CODEC_SECOND_SIZE * 2]; int written = 0; int ret; AADemuxContext *c = s->priv_data; uint64_t pos = avio_tell(s->pb); // are we at the end of the audio content? if (pos >= c->content_end) { return AVERROR_EOF; } // are we at the start of a chapter? if (c->current_chapter_size == 0) { c->current_chapter_size = avio_rb32(s->pb); if (c->current_chapter_size == 0) { return AVERROR_EOF; } av_log(s, AV_LOG_DEBUG, "Chapter %d (%" PRId64 " bytes)\n", c->chapter_idx, c->current_chapter_size); c->chapter_idx = c->chapter_idx + 1; avio_skip(s->pb, 4); // data start offset pos += 8; c->current_codec_second_size = c->codec_second_size; } // is this the last block in this chapter? if (c->current_chapter_size / c->current_codec_second_size == 0) { c->current_codec_second_size = c->current_chapter_size % c->current_codec_second_size; } // decrypt c->current_codec_second_size bytes blocks = c->current_codec_second_size / TEA_BLOCK_SIZE; for (i = 0; i < blocks; i++) { ret = avio_read(s->pb, src, TEA_BLOCK_SIZE); if (ret != TEA_BLOCK_SIZE) return (ret < 0) ? ret : AVERROR_EOF; av_tea_init(c->tea_ctx, c->file_key, 16); av_tea_crypt(c->tea_ctx, dst, src, 1, NULL, 1); memcpy(buf + written, dst, TEA_BLOCK_SIZE); written = written + TEA_BLOCK_SIZE; } trailing_bytes = c->current_codec_second_size % TEA_BLOCK_SIZE; if (trailing_bytes != 0) { // trailing bytes are left unencrypted! ret = avio_read(s->pb, src, trailing_bytes); if (ret != trailing_bytes) return (ret < 0) ? ret : AVERROR_EOF; memcpy(buf + written, src, trailing_bytes); written = written + trailing_bytes; } // update state c->current_chapter_size = c->current_chapter_size - c->current_codec_second_size; if (c->current_chapter_size <= 0) c->current_chapter_size = 0; if (c->seek_offset > written) c->seek_offset = 0; // ignore wrong estimate ret = av_new_packet(pkt, written - c->seek_offset); if (ret < 0) return ret; memcpy(pkt->data, buf + c->seek_offset, written - c->seek_offset); pkt->pos = pos; c->seek_offset = 0; return 0; } static int aa_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { AADemuxContext *c = s->priv_data; AVChapter *ch; int64_t chapter_pos, chapter_start, chapter_size; int chapter_idx = 0; // find chapter containing seek timestamp if (timestamp < 0) timestamp = 0; while (chapter_idx < s->nb_chapters && timestamp >= s->chapters[chapter_idx]->end) { ++chapter_idx; } if (chapter_idx >= s->nb_chapters) { chapter_idx = s->nb_chapters - 1; if (chapter_idx < 0) return -1; // there is no chapter. timestamp = s->chapters[chapter_idx]->end; } ch = s->chapters[chapter_idx]; // sync by clamping timestamp to nearest valid block position in its chapter chapter_size = ch->end / TIMEPREC - ch->start / TIMEPREC; chapter_pos = av_rescale_rnd((timestamp - ch->start) / TIMEPREC, 1, c->codec_second_size, (flags & AVSEEK_FLAG_BACKWARD) ? AV_ROUND_DOWN : AV_ROUND_UP) * c->codec_second_size; if (chapter_pos >= chapter_size) chapter_pos = chapter_size; chapter_start = c->content_start + (ch->start / TIMEPREC) + CHAPTER_HEADER_SIZE * (1 + chapter_idx); // reinit read state avio_seek(s->pb, chapter_start + chapter_pos, SEEK_SET); c->current_codec_second_size = c->codec_second_size; c->current_chapter_size = chapter_size - chapter_pos; c->chapter_idx = 1 + chapter_idx; // for unaligned frames, estimate offset of first frame in block (assume no padding) if (s->streams[0]->codecpar->codec_id == AV_CODEC_ID_MP3) { c->seek_offset = (MP3_FRAME_SIZE - chapter_pos % MP3_FRAME_SIZE) % MP3_FRAME_SIZE; } ff_update_cur_dts(s, s->streams[0], ch->start + (chapter_pos + c->seek_offset) * TIMEPREC); return 1; } static int aa_probe(const AVProbeData *p) { uint8_t *buf = p->buf; // first 4 bytes are file size, next 4 bytes are the magic if (AV_RB32(buf+4) != AA_MAGIC) return 0; return AVPROBE_SCORE_MAX / 2; } static int aa_read_close(AVFormatContext *s) { AADemuxContext *c = s->priv_data; av_freep(&c->tea_ctx); return 0; } #define OFFSET(x) offsetof(AADemuxContext, x) static const AVOption aa_options[] = { { "aa_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files! "Fixed key used for handling Audible AA files", OFFSET(aa_fixed_key), AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd2a51d673"}, .flags = AV_OPT_FLAG_DECODING_PARAM }, { NULL }, }; static const AVClass aa_class = { .class_name = "aa", .item_name = av_default_item_name, .option = aa_options, .version = LIBAVUTIL_VERSION_INT, }; AVInputFormat ff_aa_demuxer = { .name = "aa", .long_name = NULL_IF_CONFIG_SMALL("Audible AA format files"), .priv_class = &aa_class, .priv_data_size = sizeof(AADemuxContext), .extensions = "aa", .read_probe = aa_probe, .read_header = aa_read_header, .read_packet = aa_read_packet, .read_seek = aa_read_seek, .read_close = aa_read_close, .flags = AVFMT_NO_BYTE_SEEK | AVFMT_NOGENSEARCH, };
./CrossVul/dataset_final_sorted/CWE-665/c/good_881_0
crossvul-cpp_data_bad_739_0
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2019 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // wave64.c // This module is a helper to the WavPack command-line programs to support Sony's // Wave64 WAV file variant. Note that unlike the WAV/RF64 version, this does not // fall back to conventional WAV in the < 4GB case. #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <ctype.h> #include "wavpack.h" #include "utils.h" #include "md5.h" typedef struct { char ckID [16]; int64_t ckSize; char formType [16]; } Wave64FileHeader; typedef struct { char ckID [16]; int64_t ckSize; } Wave64ChunkHeader; #define Wave64ChunkHeaderFormat "88D" static const unsigned char riff_guid [16] = { 'r','i','f','f', 0x2e,0x91,0xcf,0x11,0xa5,0xd6,0x28,0xdb,0x04,0xc1,0x00,0x00 }; static const unsigned char wave_guid [16] = { 'w','a','v','e', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a }; static const unsigned char fmt_guid [16] = { 'f','m','t',' ', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a }; static const unsigned char data_guid [16] = { 'd','a','t','a', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a }; #define WAVPACK_NO_ERROR 0 #define WAVPACK_SOFT_ERROR 1 #define WAVPACK_HARD_ERROR 2 extern int debug_logging_mode; int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t total_samples = 0, infilesize; Wave64ChunkHeader chunk_header; Wave64FileHeader filehdr; WaveHeader WaveHeader; int format_chunk = 0; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&filehdr, fourcc, 4); if (!DoReadFile (infile, ((char *) &filehdr) + 4, sizeof (Wave64FileHeader) - 4, &bcount) || bcount != sizeof (Wave64FileHeader) - 4 || memcmp (filehdr.ckID, riff_guid, sizeof (riff_guid)) || memcmp (filehdr.formType, wave_guid, sizeof (wave_guid))) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &filehdr, sizeof (filehdr))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackLittleEndianToNative (&filehdr, Wave64ChunkHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && filehdr.ckSize && filehdr.ckSize + 1 && filehdr.ckSize != infilesize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } #endif // loop through all elements of the wave64 header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (Wave64ChunkHeader), &bcount) || bcount != sizeof (Wave64ChunkHeader)) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (Wave64ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, Wave64ChunkHeaderFormat); chunk_header.ckSize -= sizeof (chunk_header); // if it's the format chunk, we want to get some info out of there and // make sure it's a .wav file we can handle if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) { int supported = TRUE, format; if (format_chunk++) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L; if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, (uint32_t) chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, (uint32_t) chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .W64 format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this W64 file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!memcmp (chunk_header.ckID, data_guid, sizeof (data_guid))) { // on the data chunk, get size and exit loop if (!WaveHeader.NumChannels) { // make sure we saw "fmt" chunk error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } if ((config->qmode & QMODE_IGNORE_LENGTH) || chunk_header.ckSize <= 0) { config->qmode |= QMODE_IGNORE_LENGTH; if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { if (infilesize && infilesize - chunk_header.ckSize > 16777216) { error_line ("this .W64 file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } total_samples = chunk_header.ckSize / WaveHeader.BlockAlign; if (!total_samples) { error_line ("this .W64 file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 7) & ~7L; char *buff; if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } int WriteWave64Header (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { Wave64ChunkHeader datahdr, fmthdr; Wave64FileHeader filehdr; WaveHeader wavhdr; uint32_t bcount; int64_t total_data_bytes, total_file_bytes; int num_channels = WavpackGetNumChannels (wpc); int32_t channel_mask = WavpackGetChannelMask (wpc); int32_t sample_rate = WavpackGetSampleRate (wpc); int bytes_per_sample = WavpackGetBytesPerSample (wpc); int bits_per_sample = WavpackGetBitsPerSample (wpc); int format = WavpackGetFloatNormExp (wpc) ? 3 : 1; int wavhdrsize = 16; if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) { error_line ("can't create valid Wave64 header for non-normalized floating data!"); return FALSE; } if (total_samples == -1) total_samples = 0x7ffff000 / (bytes_per_sample * num_channels); total_data_bytes = total_samples * bytes_per_sample * num_channels; CLEAR (wavhdr); wavhdr.FormatTag = format; wavhdr.NumChannels = num_channels; wavhdr.SampleRate = sample_rate; wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample; wavhdr.BlockAlign = bytes_per_sample * num_channels; wavhdr.BitsPerSample = bits_per_sample; if (num_channels > 2 || channel_mask != 0x5 - num_channels) { wavhdrsize = sizeof (wavhdr); wavhdr.cbSize = 22; wavhdr.ValidBitsPerSample = bits_per_sample; wavhdr.SubFormat = format; wavhdr.ChannelMask = channel_mask; wavhdr.FormatTag = 0xfffe; wavhdr.BitsPerSample = bytes_per_sample * 8; wavhdr.GUID [4] = 0x10; wavhdr.GUID [6] = 0x80; wavhdr.GUID [9] = 0xaa; wavhdr.GUID [11] = 0x38; wavhdr.GUID [12] = 0x9b; wavhdr.GUID [13] = 0x71; } total_file_bytes = sizeof (filehdr) + sizeof (fmthdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 7) & ~(int64_t)7); memcpy (filehdr.ckID, riff_guid, sizeof (riff_guid)); memcpy (filehdr.formType, wave_guid, sizeof (wave_guid)); filehdr.ckSize = total_file_bytes; memcpy (fmthdr.ckID, fmt_guid, sizeof (fmt_guid)); fmthdr.ckSize = sizeof (fmthdr) + wavhdrsize; memcpy (datahdr.ckID, data_guid, sizeof (data_guid)); datahdr.ckSize = total_data_bytes + sizeof (datahdr); // write the RIFF chunks up to just before the data starts WavpackNativeToLittleEndian (&filehdr, Wave64ChunkHeaderFormat); WavpackNativeToLittleEndian (&fmthdr, Wave64ChunkHeaderFormat); WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat); WavpackNativeToLittleEndian (&datahdr, Wave64ChunkHeaderFormat); if (!DoWriteFile (outfile, &filehdr, sizeof (filehdr), &bcount) || bcount != sizeof (filehdr) || !DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) || !DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize || !DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) { error_line ("can't write .W64 data, disk probably full!"); return FALSE; } return TRUE; }
./CrossVul/dataset_final_sorted/CWE-665/c/bad_739_0
crossvul-cpp_data_good_1128_0
/* * Copyright (c) 2016 Hisilicon Limited. * Copyright (c) 2007, 2008 Mellanox Technologies. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - 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. * * 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 <linux/acpi.h> #include <linux/of_platform.h> #include <linux/module.h> #include <rdma/ib_addr.h> #include <rdma/ib_smi.h> #include <rdma/ib_user_verbs.h> #include <rdma/ib_cache.h> #include "hns_roce_common.h" #include "hns_roce_device.h" #include <rdma/hns-abi.h> #include "hns_roce_hem.h" /** * hns_get_gid_index - Get gid index. * @hr_dev: pointer to structure hns_roce_dev. * @port: port, value range: 0 ~ MAX * @gid_index: gid_index, value range: 0 ~ MAX * Description: * N ports shared gids, allocation method as follow: * GID[0][0], GID[1][0],.....GID[N - 1][0], * GID[0][0], GID[1][0],.....GID[N - 1][0], * And so on */ int hns_get_gid_index(struct hns_roce_dev *hr_dev, u8 port, int gid_index) { return gid_index * hr_dev->caps.num_ports + port; } EXPORT_SYMBOL_GPL(hns_get_gid_index); static int hns_roce_set_mac(struct hns_roce_dev *hr_dev, u8 port, u8 *addr) { u8 phy_port; u32 i = 0; if (!memcmp(hr_dev->dev_addr[port], addr, MAC_ADDR_OCTET_NUM)) return 0; for (i = 0; i < MAC_ADDR_OCTET_NUM; i++) hr_dev->dev_addr[port][i] = addr[i]; phy_port = hr_dev->iboe.phy_port[port]; return hr_dev->hw->set_mac(hr_dev, phy_port, addr); } static int hns_roce_add_gid(struct ib_device *device, u8 port_num, unsigned int index, const union ib_gid *gid, const struct ib_gid_attr *attr, void **context) { struct hns_roce_dev *hr_dev = to_hr_dev(device); u8 port = port_num - 1; unsigned long flags; int ret; if (port >= hr_dev->caps.num_ports) return -EINVAL; spin_lock_irqsave(&hr_dev->iboe.lock, flags); ret = hr_dev->hw->set_gid(hr_dev, port, index, (union ib_gid *)gid, attr); spin_unlock_irqrestore(&hr_dev->iboe.lock, flags); return ret; } static int hns_roce_del_gid(struct ib_device *device, u8 port_num, unsigned int index, void **context) { struct hns_roce_dev *hr_dev = to_hr_dev(device); struct ib_gid_attr zattr = { }; union ib_gid zgid = { {0} }; u8 port = port_num - 1; unsigned long flags; int ret; if (port >= hr_dev->caps.num_ports) return -EINVAL; spin_lock_irqsave(&hr_dev->iboe.lock, flags); ret = hr_dev->hw->set_gid(hr_dev, port, index, &zgid, &zattr); spin_unlock_irqrestore(&hr_dev->iboe.lock, flags); return ret; } static int handle_en_event(struct hns_roce_dev *hr_dev, u8 port, unsigned long event) { struct device *dev = hr_dev->dev; struct net_device *netdev; int ret = 0; netdev = hr_dev->iboe.netdevs[port]; if (!netdev) { dev_err(dev, "port(%d) can't find netdev\n", port); return -ENODEV; } switch (event) { case NETDEV_UP: case NETDEV_CHANGE: case NETDEV_REGISTER: case NETDEV_CHANGEADDR: ret = hns_roce_set_mac(hr_dev, port, netdev->dev_addr); break; case NETDEV_DOWN: /* * In v1 engine, only support all ports closed together. */ break; default: dev_dbg(dev, "NETDEV event = 0x%x!\n", (u32)(event)); break; } return ret; } static int hns_roce_netdev_event(struct notifier_block *self, unsigned long event, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); struct hns_roce_ib_iboe *iboe = NULL; struct hns_roce_dev *hr_dev = NULL; u8 port = 0; int ret = 0; hr_dev = container_of(self, struct hns_roce_dev, iboe.nb); iboe = &hr_dev->iboe; for (port = 0; port < hr_dev->caps.num_ports; port++) { if (dev == iboe->netdevs[port]) { ret = handle_en_event(hr_dev, port, event); if (ret) return NOTIFY_DONE; break; } } return NOTIFY_DONE; } static int hns_roce_setup_mtu_mac(struct hns_roce_dev *hr_dev) { int ret; u8 i; for (i = 0; i < hr_dev->caps.num_ports; i++) { if (hr_dev->hw->set_mtu) hr_dev->hw->set_mtu(hr_dev, hr_dev->iboe.phy_port[i], hr_dev->caps.max_mtu); ret = hns_roce_set_mac(hr_dev, i, hr_dev->iboe.netdevs[i]->dev_addr); if (ret) return ret; } return 0; } static int hns_roce_query_device(struct ib_device *ib_dev, struct ib_device_attr *props, struct ib_udata *uhw) { struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev); memset(props, 0, sizeof(*props)); props->sys_image_guid = cpu_to_be32(hr_dev->sys_image_guid); props->max_mr_size = (u64)(~(0ULL)); props->page_size_cap = hr_dev->caps.page_size_cap; props->vendor_id = hr_dev->vendor_id; props->vendor_part_id = hr_dev->vendor_part_id; props->hw_ver = hr_dev->hw_rev; props->max_qp = hr_dev->caps.num_qps; props->max_qp_wr = hr_dev->caps.max_wqes; props->device_cap_flags = IB_DEVICE_PORT_ACTIVE_EVENT | IB_DEVICE_RC_RNR_NAK_GEN; props->max_sge = max(hr_dev->caps.max_sq_sg, hr_dev->caps.max_rq_sg); props->max_sge_rd = 1; props->max_cq = hr_dev->caps.num_cqs; props->max_cqe = hr_dev->caps.max_cqes; props->max_mr = hr_dev->caps.num_mtpts; props->max_pd = hr_dev->caps.num_pds; props->max_qp_rd_atom = hr_dev->caps.max_qp_dest_rdma; props->max_qp_init_rd_atom = hr_dev->caps.max_qp_init_rdma; props->atomic_cap = IB_ATOMIC_NONE; props->max_pkeys = 1; props->local_ca_ack_delay = hr_dev->caps.local_ca_ack_delay; return 0; } static struct net_device *hns_roce_get_netdev(struct ib_device *ib_dev, u8 port_num) { struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev); struct net_device *ndev; if (port_num < 1 || port_num > hr_dev->caps.num_ports) return NULL; rcu_read_lock(); ndev = hr_dev->iboe.netdevs[port_num - 1]; if (ndev) dev_hold(ndev); rcu_read_unlock(); return ndev; } static int hns_roce_query_port(struct ib_device *ib_dev, u8 port_num, struct ib_port_attr *props) { struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev); struct device *dev = hr_dev->dev; struct net_device *net_dev; unsigned long flags; enum ib_mtu mtu; u8 port; assert(port_num > 0); port = port_num - 1; /* props being zeroed by the caller, avoid zeroing it here */ props->max_mtu = hr_dev->caps.max_mtu; props->gid_tbl_len = hr_dev->caps.gid_table_len[port]; props->port_cap_flags = IB_PORT_CM_SUP | IB_PORT_REINIT_SUP | IB_PORT_VENDOR_CLASS_SUP | IB_PORT_BOOT_MGMT_SUP; props->max_msg_sz = HNS_ROCE_MAX_MSG_LEN; props->pkey_tbl_len = 1; props->active_width = IB_WIDTH_4X; props->active_speed = 1; spin_lock_irqsave(&hr_dev->iboe.lock, flags); net_dev = hr_dev->iboe.netdevs[port]; if (!net_dev) { spin_unlock_irqrestore(&hr_dev->iboe.lock, flags); dev_err(dev, "find netdev %d failed!\r\n", port); return -EINVAL; } mtu = iboe_get_mtu(net_dev->mtu); props->active_mtu = mtu ? min(props->max_mtu, mtu) : IB_MTU_256; props->state = (netif_running(net_dev) && netif_carrier_ok(net_dev)) ? IB_PORT_ACTIVE : IB_PORT_DOWN; props->phys_state = (props->state == IB_PORT_ACTIVE) ? 5 : 3; spin_unlock_irqrestore(&hr_dev->iboe.lock, flags); return 0; } static enum rdma_link_layer hns_roce_get_link_layer(struct ib_device *device, u8 port_num) { return IB_LINK_LAYER_ETHERNET; } static int hns_roce_query_gid(struct ib_device *ib_dev, u8 port_num, int index, union ib_gid *gid) { return 0; } static int hns_roce_query_pkey(struct ib_device *ib_dev, u8 port, u16 index, u16 *pkey) { *pkey = PKEY_ID; return 0; } static int hns_roce_modify_device(struct ib_device *ib_dev, int mask, struct ib_device_modify *props) { unsigned long flags; if (mask & ~IB_DEVICE_MODIFY_NODE_DESC) return -EOPNOTSUPP; if (mask & IB_DEVICE_MODIFY_NODE_DESC) { spin_lock_irqsave(&to_hr_dev(ib_dev)->sm_lock, flags); memcpy(ib_dev->node_desc, props->node_desc, NODE_DESC_SIZE); spin_unlock_irqrestore(&to_hr_dev(ib_dev)->sm_lock, flags); } return 0; } static int hns_roce_modify_port(struct ib_device *ib_dev, u8 port_num, int mask, struct ib_port_modify *props) { return 0; } static struct ib_ucontext *hns_roce_alloc_ucontext(struct ib_device *ib_dev, struct ib_udata *udata) { int ret = 0; struct hns_roce_ucontext *context; struct hns_roce_ib_alloc_ucontext_resp resp = {}; struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev); resp.qp_tab_size = hr_dev->caps.num_qps; context = kmalloc(sizeof(*context), GFP_KERNEL); if (!context) return ERR_PTR(-ENOMEM); ret = hns_roce_uar_alloc(hr_dev, &context->uar); if (ret) goto error_fail_uar_alloc; if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_RECORD_DB) { INIT_LIST_HEAD(&context->page_list); mutex_init(&context->page_mutex); } ret = ib_copy_to_udata(udata, &resp, sizeof(resp)); if (ret) goto error_fail_copy_to_udata; return &context->ibucontext; error_fail_copy_to_udata: hns_roce_uar_free(hr_dev, &context->uar); error_fail_uar_alloc: kfree(context); return ERR_PTR(ret); } static int hns_roce_dealloc_ucontext(struct ib_ucontext *ibcontext) { struct hns_roce_ucontext *context = to_hr_ucontext(ibcontext); hns_roce_uar_free(to_hr_dev(ibcontext->device), &context->uar); kfree(context); return 0; } static int hns_roce_mmap(struct ib_ucontext *context, struct vm_area_struct *vma) { struct hns_roce_dev *hr_dev = to_hr_dev(context->device); if (((vma->vm_end - vma->vm_start) % PAGE_SIZE) != 0) return -EINVAL; if (vma->vm_pgoff == 0) { vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); if (io_remap_pfn_range(vma, vma->vm_start, to_hr_ucontext(context)->uar.pfn, PAGE_SIZE, vma->vm_page_prot)) return -EAGAIN; } else if (vma->vm_pgoff == 1 && hr_dev->tptr_dma_addr && hr_dev->tptr_size) { /* vm_pgoff: 1 -- TPTR */ if (io_remap_pfn_range(vma, vma->vm_start, hr_dev->tptr_dma_addr >> PAGE_SHIFT, hr_dev->tptr_size, vma->vm_page_prot)) return -EAGAIN; } else return -EINVAL; return 0; } static int hns_roce_port_immutable(struct ib_device *ib_dev, u8 port_num, struct ib_port_immutable *immutable) { struct ib_port_attr attr; int ret; ret = ib_query_port(ib_dev, port_num, &attr); if (ret) return ret; immutable->pkey_tbl_len = attr.pkey_tbl_len; immutable->gid_tbl_len = attr.gid_tbl_len; immutable->max_mad_size = IB_MGMT_MAD_SIZE; immutable->core_cap_flags = RDMA_CORE_PORT_IBA_ROCE; if (to_hr_dev(ib_dev)->caps.flags & HNS_ROCE_CAP_FLAG_ROCE_V1_V2) immutable->core_cap_flags |= RDMA_CORE_PORT_IBA_ROCE_UDP_ENCAP; return 0; } static void hns_roce_unregister_device(struct hns_roce_dev *hr_dev) { struct hns_roce_ib_iboe *iboe = &hr_dev->iboe; unregister_netdevice_notifier(&iboe->nb); ib_unregister_device(&hr_dev->ib_dev); } static int hns_roce_register_device(struct hns_roce_dev *hr_dev) { int ret; struct hns_roce_ib_iboe *iboe = NULL; struct ib_device *ib_dev = NULL; struct device *dev = hr_dev->dev; iboe = &hr_dev->iboe; spin_lock_init(&iboe->lock); ib_dev = &hr_dev->ib_dev; strlcpy(ib_dev->name, "hns_%d", IB_DEVICE_NAME_MAX); ib_dev->owner = THIS_MODULE; ib_dev->node_type = RDMA_NODE_IB_CA; ib_dev->dev.parent = dev; ib_dev->phys_port_cnt = hr_dev->caps.num_ports; ib_dev->local_dma_lkey = hr_dev->caps.reserved_lkey; ib_dev->num_comp_vectors = hr_dev->caps.num_comp_vectors; ib_dev->uverbs_abi_ver = 1; ib_dev->uverbs_cmd_mask = (1ULL << IB_USER_VERBS_CMD_GET_CONTEXT) | (1ULL << IB_USER_VERBS_CMD_QUERY_DEVICE) | (1ULL << IB_USER_VERBS_CMD_QUERY_PORT) | (1ULL << IB_USER_VERBS_CMD_ALLOC_PD) | (1ULL << IB_USER_VERBS_CMD_DEALLOC_PD) | (1ULL << IB_USER_VERBS_CMD_REG_MR) | (1ULL << IB_USER_VERBS_CMD_DEREG_MR) | (1ULL << IB_USER_VERBS_CMD_CREATE_COMP_CHANNEL) | (1ULL << IB_USER_VERBS_CMD_CREATE_CQ) | (1ULL << IB_USER_VERBS_CMD_DESTROY_CQ) | (1ULL << IB_USER_VERBS_CMD_CREATE_QP) | (1ULL << IB_USER_VERBS_CMD_MODIFY_QP) | (1ULL << IB_USER_VERBS_CMD_QUERY_QP) | (1ULL << IB_USER_VERBS_CMD_DESTROY_QP); /* HCA||device||port */ ib_dev->modify_device = hns_roce_modify_device; ib_dev->query_device = hns_roce_query_device; ib_dev->query_port = hns_roce_query_port; ib_dev->modify_port = hns_roce_modify_port; ib_dev->get_link_layer = hns_roce_get_link_layer; ib_dev->get_netdev = hns_roce_get_netdev; ib_dev->query_gid = hns_roce_query_gid; ib_dev->add_gid = hns_roce_add_gid; ib_dev->del_gid = hns_roce_del_gid; ib_dev->query_pkey = hns_roce_query_pkey; ib_dev->alloc_ucontext = hns_roce_alloc_ucontext; ib_dev->dealloc_ucontext = hns_roce_dealloc_ucontext; ib_dev->mmap = hns_roce_mmap; /* PD */ ib_dev->alloc_pd = hns_roce_alloc_pd; ib_dev->dealloc_pd = hns_roce_dealloc_pd; /* AH */ ib_dev->create_ah = hns_roce_create_ah; ib_dev->query_ah = hns_roce_query_ah; ib_dev->destroy_ah = hns_roce_destroy_ah; /* QP */ ib_dev->create_qp = hns_roce_create_qp; ib_dev->modify_qp = hns_roce_modify_qp; ib_dev->query_qp = hr_dev->hw->query_qp; ib_dev->destroy_qp = hr_dev->hw->destroy_qp; ib_dev->post_send = hr_dev->hw->post_send; ib_dev->post_recv = hr_dev->hw->post_recv; /* CQ */ ib_dev->create_cq = hns_roce_ib_create_cq; ib_dev->modify_cq = hr_dev->hw->modify_cq; ib_dev->destroy_cq = hns_roce_ib_destroy_cq; ib_dev->req_notify_cq = hr_dev->hw->req_notify_cq; ib_dev->poll_cq = hr_dev->hw->poll_cq; /* MR */ ib_dev->get_dma_mr = hns_roce_get_dma_mr; ib_dev->reg_user_mr = hns_roce_reg_user_mr; ib_dev->dereg_mr = hns_roce_dereg_mr; if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_REREG_MR) { ib_dev->rereg_user_mr = hns_roce_rereg_user_mr; ib_dev->uverbs_cmd_mask |= (1ULL << IB_USER_VERBS_CMD_REREG_MR); } /* OTHERS */ ib_dev->get_port_immutable = hns_roce_port_immutable; ret = ib_register_device(ib_dev, NULL); if (ret) { dev_err(dev, "ib_register_device failed!\n"); return ret; } ret = hns_roce_setup_mtu_mac(hr_dev); if (ret) { dev_err(dev, "setup_mtu_mac failed!\n"); goto error_failed_setup_mtu_mac; } iboe->nb.notifier_call = hns_roce_netdev_event; ret = register_netdevice_notifier(&iboe->nb); if (ret) { dev_err(dev, "register_netdevice_notifier failed!\n"); goto error_failed_setup_mtu_mac; } return 0; error_failed_setup_mtu_mac: ib_unregister_device(ib_dev); return ret; } static int hns_roce_init_hem(struct hns_roce_dev *hr_dev) { int ret; struct device *dev = hr_dev->dev; ret = hns_roce_init_hem_table(hr_dev, &hr_dev->mr_table.mtt_table, HEM_TYPE_MTT, hr_dev->caps.mtt_entry_sz, hr_dev->caps.num_mtt_segs, 1); if (ret) { dev_err(dev, "Failed to init MTT context memory, aborting.\n"); return ret; } if (hns_roce_check_whether_mhop(hr_dev, HEM_TYPE_CQE)) { ret = hns_roce_init_hem_table(hr_dev, &hr_dev->mr_table.mtt_cqe_table, HEM_TYPE_CQE, hr_dev->caps.mtt_entry_sz, hr_dev->caps.num_cqe_segs, 1); if (ret) { dev_err(dev, "Failed to init MTT CQE context memory, aborting.\n"); goto err_unmap_cqe; } } ret = hns_roce_init_hem_table(hr_dev, &hr_dev->mr_table.mtpt_table, HEM_TYPE_MTPT, hr_dev->caps.mtpt_entry_sz, hr_dev->caps.num_mtpts, 1); if (ret) { dev_err(dev, "Failed to init MTPT context memory, aborting.\n"); goto err_unmap_mtt; } ret = hns_roce_init_hem_table(hr_dev, &hr_dev->qp_table.qp_table, HEM_TYPE_QPC, hr_dev->caps.qpc_entry_sz, hr_dev->caps.num_qps, 1); if (ret) { dev_err(dev, "Failed to init QP context memory, aborting.\n"); goto err_unmap_dmpt; } ret = hns_roce_init_hem_table(hr_dev, &hr_dev->qp_table.irrl_table, HEM_TYPE_IRRL, hr_dev->caps.irrl_entry_sz * hr_dev->caps.max_qp_init_rdma, hr_dev->caps.num_qps, 1); if (ret) { dev_err(dev, "Failed to init irrl_table memory, aborting.\n"); goto err_unmap_qp; } if (hr_dev->caps.trrl_entry_sz) { ret = hns_roce_init_hem_table(hr_dev, &hr_dev->qp_table.trrl_table, HEM_TYPE_TRRL, hr_dev->caps.trrl_entry_sz * hr_dev->caps.max_qp_dest_rdma, hr_dev->caps.num_qps, 1); if (ret) { dev_err(dev, "Failed to init trrl_table memory, aborting.\n"); goto err_unmap_irrl; } } ret = hns_roce_init_hem_table(hr_dev, &hr_dev->cq_table.table, HEM_TYPE_CQC, hr_dev->caps.cqc_entry_sz, hr_dev->caps.num_cqs, 1); if (ret) { dev_err(dev, "Failed to init CQ context memory, aborting.\n"); goto err_unmap_trrl; } return 0; err_unmap_trrl: if (hr_dev->caps.trrl_entry_sz) hns_roce_cleanup_hem_table(hr_dev, &hr_dev->qp_table.trrl_table); err_unmap_irrl: hns_roce_cleanup_hem_table(hr_dev, &hr_dev->qp_table.irrl_table); err_unmap_qp: hns_roce_cleanup_hem_table(hr_dev, &hr_dev->qp_table.qp_table); err_unmap_dmpt: hns_roce_cleanup_hem_table(hr_dev, &hr_dev->mr_table.mtpt_table); err_unmap_mtt: if (hns_roce_check_whether_mhop(hr_dev, HEM_TYPE_CQE)) hns_roce_cleanup_hem_table(hr_dev, &hr_dev->mr_table.mtt_cqe_table); err_unmap_cqe: hns_roce_cleanup_hem_table(hr_dev, &hr_dev->mr_table.mtt_table); return ret; } /** * hns_roce_setup_hca - setup host channel adapter * @hr_dev: pointer to hns roce device * Return : int */ static int hns_roce_setup_hca(struct hns_roce_dev *hr_dev) { int ret; struct device *dev = hr_dev->dev; spin_lock_init(&hr_dev->sm_lock); spin_lock_init(&hr_dev->bt_cmd_lock); if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_RECORD_DB) { INIT_LIST_HEAD(&hr_dev->pgdir_list); mutex_init(&hr_dev->pgdir_mutex); } ret = hns_roce_init_uar_table(hr_dev); if (ret) { dev_err(dev, "Failed to initialize uar table. aborting\n"); return ret; } ret = hns_roce_uar_alloc(hr_dev, &hr_dev->priv_uar); if (ret) { dev_err(dev, "Failed to allocate priv_uar.\n"); goto err_uar_table_free; } ret = hns_roce_init_pd_table(hr_dev); if (ret) { dev_err(dev, "Failed to init protected domain table.\n"); goto err_uar_alloc_free; } ret = hns_roce_init_mr_table(hr_dev); if (ret) { dev_err(dev, "Failed to init memory region table.\n"); goto err_pd_table_free; } ret = hns_roce_init_cq_table(hr_dev); if (ret) { dev_err(dev, "Failed to init completion queue table.\n"); goto err_mr_table_free; } ret = hns_roce_init_qp_table(hr_dev); if (ret) { dev_err(dev, "Failed to init queue pair table.\n"); goto err_cq_table_free; } return 0; err_cq_table_free: hns_roce_cleanup_cq_table(hr_dev); err_mr_table_free: hns_roce_cleanup_mr_table(hr_dev); err_pd_table_free: hns_roce_cleanup_pd_table(hr_dev); err_uar_alloc_free: hns_roce_uar_free(hr_dev, &hr_dev->priv_uar); err_uar_table_free: hns_roce_cleanup_uar_table(hr_dev); return ret; } int hns_roce_init(struct hns_roce_dev *hr_dev) { int ret; struct device *dev = hr_dev->dev; if (hr_dev->hw->reset) { ret = hr_dev->hw->reset(hr_dev, true); if (ret) { dev_err(dev, "Reset RoCE engine failed!\n"); return ret; } } if (hr_dev->hw->cmq_init) { ret = hr_dev->hw->cmq_init(hr_dev); if (ret) { dev_err(dev, "Init RoCE Command Queue failed!\n"); goto error_failed_cmq_init; } } ret = hr_dev->hw->hw_profile(hr_dev); if (ret) { dev_err(dev, "Get RoCE engine profile failed!\n"); goto error_failed_cmd_init; } ret = hns_roce_cmd_init(hr_dev); if (ret) { dev_err(dev, "cmd init failed!\n"); goto error_failed_cmd_init; } ret = hr_dev->hw->init_eq(hr_dev); if (ret) { dev_err(dev, "eq init failed!\n"); goto error_failed_eq_table; } if (hr_dev->cmd_mod) { ret = hns_roce_cmd_use_events(hr_dev); if (ret) { dev_err(dev, "Switch to event-driven cmd failed!\n"); goto error_failed_use_event; } } ret = hns_roce_init_hem(hr_dev); if (ret) { dev_err(dev, "init HEM(Hardware Entry Memory) failed!\n"); goto error_failed_init_hem; } ret = hns_roce_setup_hca(hr_dev); if (ret) { dev_err(dev, "setup hca failed!\n"); goto error_failed_setup_hca; } if (hr_dev->hw->hw_init) { ret = hr_dev->hw->hw_init(hr_dev); if (ret) { dev_err(dev, "hw_init failed!\n"); goto error_failed_engine_init; } } ret = hns_roce_register_device(hr_dev); if (ret) goto error_failed_register_device; return 0; error_failed_register_device: if (hr_dev->hw->hw_exit) hr_dev->hw->hw_exit(hr_dev); error_failed_engine_init: hns_roce_cleanup_bitmap(hr_dev); error_failed_setup_hca: hns_roce_cleanup_hem(hr_dev); error_failed_init_hem: if (hr_dev->cmd_mod) hns_roce_cmd_use_polling(hr_dev); error_failed_use_event: hr_dev->hw->cleanup_eq(hr_dev); error_failed_eq_table: hns_roce_cmd_cleanup(hr_dev); error_failed_cmd_init: if (hr_dev->hw->cmq_exit) hr_dev->hw->cmq_exit(hr_dev); error_failed_cmq_init: if (hr_dev->hw->reset) { ret = hr_dev->hw->reset(hr_dev, false); if (ret) dev_err(dev, "Dereset RoCE engine failed!\n"); } return ret; } EXPORT_SYMBOL_GPL(hns_roce_init); void hns_roce_exit(struct hns_roce_dev *hr_dev) { hns_roce_unregister_device(hr_dev); if (hr_dev->hw->hw_exit) hr_dev->hw->hw_exit(hr_dev); hns_roce_cleanup_bitmap(hr_dev); hns_roce_cleanup_hem(hr_dev); if (hr_dev->cmd_mod) hns_roce_cmd_use_polling(hr_dev); hr_dev->hw->cleanup_eq(hr_dev); hns_roce_cmd_cleanup(hr_dev); if (hr_dev->hw->cmq_exit) hr_dev->hw->cmq_exit(hr_dev); if (hr_dev->hw->reset) hr_dev->hw->reset(hr_dev, false); } EXPORT_SYMBOL_GPL(hns_roce_exit); MODULE_LICENSE("Dual BSD/GPL"); MODULE_AUTHOR("Wei Hu <xavier.huwei@huawei.com>"); MODULE_AUTHOR("Nenglong Zhao <zhaonenglong@hisilicon.com>"); MODULE_AUTHOR("Lijun Ou <oulijun@huawei.com>"); MODULE_DESCRIPTION("HNS RoCE Driver");
./CrossVul/dataset_final_sorted/CWE-665/c/good_1128_0
crossvul-cpp_data_good_739_0
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2019 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // wave64.c // This module is a helper to the WavPack command-line programs to support Sony's // Wave64 WAV file variant. Note that unlike the WAV/RF64 version, this does not // fall back to conventional WAV in the < 4GB case. #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <ctype.h> #include "wavpack.h" #include "utils.h" #include "md5.h" typedef struct { char ckID [16]; int64_t ckSize; char formType [16]; } Wave64FileHeader; typedef struct { char ckID [16]; int64_t ckSize; } Wave64ChunkHeader; #define Wave64ChunkHeaderFormat "88D" static const unsigned char riff_guid [16] = { 'r','i','f','f', 0x2e,0x91,0xcf,0x11,0xa5,0xd6,0x28,0xdb,0x04,0xc1,0x00,0x00 }; static const unsigned char wave_guid [16] = { 'w','a','v','e', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a }; static const unsigned char fmt_guid [16] = { 'f','m','t',' ', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a }; static const unsigned char data_guid [16] = { 'd','a','t','a', 0xf3,0xac,0xd3,0x11,0x8c,0xd1,0x00,0xc0,0x4f,0x8e,0xdb,0x8a }; #define WAVPACK_NO_ERROR 0 #define WAVPACK_SOFT_ERROR 1 #define WAVPACK_HARD_ERROR 2 extern int debug_logging_mode; int ParseWave64HeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t total_samples = 0, infilesize; Wave64ChunkHeader chunk_header; Wave64FileHeader filehdr; WaveHeader WaveHeader; int format_chunk = 0; uint32_t bcount; CLEAR (WaveHeader); infilesize = DoGetFileSize (infile); memcpy (&filehdr, fourcc, 4); if (!DoReadFile (infile, ((char *) &filehdr) + 4, sizeof (Wave64FileHeader) - 4, &bcount) || bcount != sizeof (Wave64FileHeader) - 4 || memcmp (filehdr.ckID, riff_guid, sizeof (riff_guid)) || memcmp (filehdr.formType, wave_guid, sizeof (wave_guid))) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &filehdr, sizeof (filehdr))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackLittleEndianToNative (&filehdr, Wave64ChunkHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && filehdr.ckSize && filehdr.ckSize + 1 && filehdr.ckSize != infilesize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } #endif // loop through all elements of the wave64 header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &chunk_header, sizeof (Wave64ChunkHeader), &bcount) || bcount != sizeof (Wave64ChunkHeader)) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &chunk_header, sizeof (Wave64ChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&chunk_header, Wave64ChunkHeaderFormat); chunk_header.ckSize -= sizeof (chunk_header); // if it's the format chunk, we want to get some info out of there and // make sure it's a .wav file we can handle if (!memcmp (chunk_header.ckID, fmt_guid, sizeof (fmt_guid))) { int supported = TRUE, format; if (format_chunk++) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } chunk_header.ckSize = (chunk_header.ckSize + 7) & ~7L; if (chunk_header.ckSize < 16 || chunk_header.ckSize > sizeof (WaveHeader) || !DoReadFile (infile, &WaveHeader, (uint32_t) chunk_header.ckSize, &bcount) || bcount != chunk_header.ckSize) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &WaveHeader, (uint32_t) chunk_header.ckSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackLittleEndianToNative (&WaveHeader, WaveHeaderFormat); if (debug_logging_mode) { error_line ("format tag size = %d", chunk_header.ckSize); error_line ("FormatTag = %x, NumChannels = %d, BitsPerSample = %d", WaveHeader.FormatTag, WaveHeader.NumChannels, WaveHeader.BitsPerSample); error_line ("BlockAlign = %d, SampleRate = %d, BytesPerSecond = %d", WaveHeader.BlockAlign, WaveHeader.SampleRate, WaveHeader.BytesPerSecond); if (chunk_header.ckSize > 16) error_line ("cbSize = %d, ValidBitsPerSample = %d", WaveHeader.cbSize, WaveHeader.ValidBitsPerSample); if (chunk_header.ckSize > 20) error_line ("ChannelMask = %x, SubFormat = %d", WaveHeader.ChannelMask, WaveHeader.SubFormat); } if (chunk_header.ckSize > 16 && WaveHeader.cbSize == 2) config->qmode |= QMODE_ADOBE_MODE; format = (WaveHeader.FormatTag == 0xfffe && chunk_header.ckSize == 40) ? WaveHeader.SubFormat : WaveHeader.FormatTag; config->bits_per_sample = (chunk_header.ckSize == 40 && WaveHeader.ValidBitsPerSample) ? WaveHeader.ValidBitsPerSample : WaveHeader.BitsPerSample; if (format != 1 && format != 3) supported = FALSE; if (format == 3 && config->bits_per_sample != 32) supported = FALSE; if (!WaveHeader.NumChannels || WaveHeader.NumChannels > 256 || WaveHeader.BlockAlign / WaveHeader.NumChannels < (config->bits_per_sample + 7) / 8 || WaveHeader.BlockAlign / WaveHeader.NumChannels > 4 || WaveHeader.BlockAlign % WaveHeader.NumChannels) supported = FALSE; if (config->bits_per_sample < 1 || config->bits_per_sample > 32) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .W64 format!", infilename); return WAVPACK_SOFT_ERROR; } if (chunk_header.ckSize < 40) { if (!config->channel_mask && !(config->qmode & QMODE_CHANS_UNASSIGNED)) { if (WaveHeader.NumChannels <= 2) config->channel_mask = 0x5 - WaveHeader.NumChannels; else if (WaveHeader.NumChannels <= 18) config->channel_mask = (1 << WaveHeader.NumChannels) - 1; else config->channel_mask = 0x3ffff; } } else if (WaveHeader.ChannelMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this W64 file already has channel order information!"); return WAVPACK_SOFT_ERROR; } else if (WaveHeader.ChannelMask) config->channel_mask = WaveHeader.ChannelMask; if (format == 3) config->float_norm_exp = 127; else if ((config->qmode & QMODE_ADOBE_MODE) && WaveHeader.BlockAlign / WaveHeader.NumChannels == 4) { if (WaveHeader.BitsPerSample == 24) config->float_norm_exp = 127 + 23; else if (WaveHeader.BitsPerSample == 32) config->float_norm_exp = 127 + 15; } if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: normalized 32-bit floating point"); else error_line ("data format: %d-bit integers stored in %d byte(s)", config->bits_per_sample, WaveHeader.BlockAlign / WaveHeader.NumChannels); } } else if (!memcmp (chunk_header.ckID, data_guid, sizeof (data_guid))) { // on the data chunk, get size and exit loop if (!WaveHeader.NumChannels) { // make sure we saw "fmt" chunk error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } if ((config->qmode & QMODE_IGNORE_LENGTH) || chunk_header.ckSize <= 0) { config->qmode |= QMODE_IGNORE_LENGTH; if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / WaveHeader.BlockAlign; else total_samples = -1; } else { if (infilesize && infilesize - chunk_header.ckSize > 16777216) { error_line ("this .W64 file has over 16 MB of extra RIFF data, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } total_samples = chunk_header.ckSize / WaveHeader.BlockAlign; if (!total_samples) { error_line ("this .W64 file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } config->bytes_per_sample = WaveHeader.BlockAlign / WaveHeader.NumChannels; config->num_channels = WaveHeader.NumChannels; config->sample_rate = WaveHeader.SampleRate; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (chunk_header.ckSize + 7) & ~7L; char *buff; if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { error_line ("%s is not a valid .W64 file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", chunk_header.ckID [0], chunk_header.ckID [1], chunk_header.ckID [2], chunk_header.ckID [3], chunk_header.ckSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } int WriteWave64Header (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { Wave64ChunkHeader datahdr, fmthdr; Wave64FileHeader filehdr; WaveHeader wavhdr; uint32_t bcount; int64_t total_data_bytes, total_file_bytes; int num_channels = WavpackGetNumChannels (wpc); int32_t channel_mask = WavpackGetChannelMask (wpc); int32_t sample_rate = WavpackGetSampleRate (wpc); int bytes_per_sample = WavpackGetBytesPerSample (wpc); int bits_per_sample = WavpackGetBitsPerSample (wpc); int format = WavpackGetFloatNormExp (wpc) ? 3 : 1; int wavhdrsize = 16; if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) { error_line ("can't create valid Wave64 header for non-normalized floating data!"); return FALSE; } if (total_samples == -1) total_samples = 0x7ffff000 / (bytes_per_sample * num_channels); total_data_bytes = total_samples * bytes_per_sample * num_channels; CLEAR (wavhdr); wavhdr.FormatTag = format; wavhdr.NumChannels = num_channels; wavhdr.SampleRate = sample_rate; wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample; wavhdr.BlockAlign = bytes_per_sample * num_channels; wavhdr.BitsPerSample = bits_per_sample; if (num_channels > 2 || channel_mask != 0x5 - num_channels) { wavhdrsize = sizeof (wavhdr); wavhdr.cbSize = 22; wavhdr.ValidBitsPerSample = bits_per_sample; wavhdr.SubFormat = format; wavhdr.ChannelMask = channel_mask; wavhdr.FormatTag = 0xfffe; wavhdr.BitsPerSample = bytes_per_sample * 8; wavhdr.GUID [4] = 0x10; wavhdr.GUID [6] = 0x80; wavhdr.GUID [9] = 0xaa; wavhdr.GUID [11] = 0x38; wavhdr.GUID [12] = 0x9b; wavhdr.GUID [13] = 0x71; } total_file_bytes = sizeof (filehdr) + sizeof (fmthdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 7) & ~(int64_t)7); memcpy (filehdr.ckID, riff_guid, sizeof (riff_guid)); memcpy (filehdr.formType, wave_guid, sizeof (wave_guid)); filehdr.ckSize = total_file_bytes; memcpy (fmthdr.ckID, fmt_guid, sizeof (fmt_guid)); fmthdr.ckSize = sizeof (fmthdr) + wavhdrsize; memcpy (datahdr.ckID, data_guid, sizeof (data_guid)); datahdr.ckSize = total_data_bytes + sizeof (datahdr); // write the RIFF chunks up to just before the data starts WavpackNativeToLittleEndian (&filehdr, Wave64ChunkHeaderFormat); WavpackNativeToLittleEndian (&fmthdr, Wave64ChunkHeaderFormat); WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat); WavpackNativeToLittleEndian (&datahdr, Wave64ChunkHeaderFormat); if (!DoWriteFile (outfile, &filehdr, sizeof (filehdr), &bcount) || bcount != sizeof (filehdr) || !DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) || !DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize || !DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) { error_line ("can't write .W64 data, disk probably full!"); return FALSE; } return TRUE; }
./CrossVul/dataset_final_sorted/CWE-665/c/good_739_0
crossvul-cpp_data_bad_881_0
/* * Audible AA demuxer * Copyright (c) 2015 Vesselin Bontchev * * Header parsing is borrowed from https://github.com/jteeuwen/audible project. * Copyright (c) 2001-2014, Jim Teeuwen * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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 "avformat.h" #include "internal.h" #include "libavutil/dict.h" #include "libavutil/intreadwrite.h" #include "libavutil/tea.h" #include "libavutil/opt.h" #define AA_MAGIC 1469084982 /* this identifies an audible .aa file */ #define MAX_CODEC_SECOND_SIZE 3982 #define MAX_TOC_ENTRIES 16 #define MAX_DICTIONARY_ENTRIES 128 #define TEA_BLOCK_SIZE 8 #define CHAPTER_HEADER_SIZE 8 #define TIMEPREC 1000 #define MP3_FRAME_SIZE 104 typedef struct AADemuxContext { AVClass *class; uint8_t *aa_fixed_key; int aa_fixed_key_len; int codec_second_size; int current_codec_second_size; int chapter_idx; struct AVTEA *tea_ctx; uint8_t file_key[16]; int64_t current_chapter_size; int64_t content_start; int64_t content_end; int seek_offset; } AADemuxContext; static int get_second_size(char *codec_name) { int result = -1; if (!strcmp(codec_name, "mp332")) { result = 3982; } else if (!strcmp(codec_name, "acelp16")) { result = 2000; } else if (!strcmp(codec_name, "acelp85")) { result = 1045; } return result; } static int aa_read_header(AVFormatContext *s) { int i, j, idx, largest_idx = -1; uint32_t nkey, nval, toc_size, npairs, header_seed = 0, start; char key[128], val[128], codec_name[64] = {0}; uint8_t output[24], dst[8], src[8]; int64_t largest_size = -1, current_size = -1, chapter_pos; struct toc_entry { uint32_t offset; uint32_t size; } TOC[MAX_TOC_ENTRIES]; uint32_t header_key_part[4]; uint8_t header_key[16] = {0}; AADemuxContext *c = s->priv_data; AVIOContext *pb = s->pb; AVStream *st; /* parse .aa header */ avio_skip(pb, 4); // file size avio_skip(pb, 4); // magic string toc_size = avio_rb32(pb); // TOC size avio_skip(pb, 4); // unidentified integer if (toc_size > MAX_TOC_ENTRIES) return AVERROR_INVALIDDATA; for (i = 0; i < toc_size; i++) { // read TOC avio_skip(pb, 4); // TOC entry index TOC[i].offset = avio_rb32(pb); // block offset TOC[i].size = avio_rb32(pb); // block size } avio_skip(pb, 24); // header termination block (ignored) npairs = avio_rb32(pb); // read dictionary entries if (npairs > MAX_DICTIONARY_ENTRIES) return AVERROR_INVALIDDATA; for (i = 0; i < npairs; i++) { memset(val, 0, sizeof(val)); memset(key, 0, sizeof(key)); avio_skip(pb, 1); // unidentified integer nkey = avio_rb32(pb); // key string length nval = avio_rb32(pb); // value string length avio_get_str(pb, nkey, key, sizeof(key)); avio_get_str(pb, nval, val, sizeof(val)); if (!strcmp(key, "codec")) { av_log(s, AV_LOG_DEBUG, "Codec is <%s>\n", val); strncpy(codec_name, val, sizeof(codec_name) - 1); } else if (!strcmp(key, "HeaderSeed")) { av_log(s, AV_LOG_DEBUG, "HeaderSeed is <%s>\n", val); header_seed = atoi(val); } else if (!strcmp(key, "HeaderKey")) { // this looks like "1234567890 1234567890 1234567890 1234567890" av_log(s, AV_LOG_DEBUG, "HeaderKey is <%s>\n", val); sscanf(val, "%"SCNu32"%"SCNu32"%"SCNu32"%"SCNu32, &header_key_part[0], &header_key_part[1], &header_key_part[2], &header_key_part[3]); for (idx = 0; idx < 4; idx++) { AV_WB32(&header_key[idx * 4], header_key_part[idx]); // convert each part to BE! } av_log(s, AV_LOG_DEBUG, "Processed HeaderKey is "); for (i = 0; i < 16; i++) av_log(s, AV_LOG_DEBUG, "%02x", header_key[i]); av_log(s, AV_LOG_DEBUG, "\n"); } else { av_dict_set(&s->metadata, key, val, 0); } } /* verify fixed key */ if (c->aa_fixed_key_len != 16) { av_log(s, AV_LOG_ERROR, "aa_fixed_key value needs to be 16 bytes!\n"); return AVERROR(EINVAL); } /* verify codec */ if ((c->codec_second_size = get_second_size(codec_name)) == -1) { av_log(s, AV_LOG_ERROR, "unknown codec <%s>!\n", codec_name); return AVERROR(EINVAL); } /* decryption key derivation */ c->tea_ctx = av_tea_alloc(); if (!c->tea_ctx) return AVERROR(ENOMEM); av_tea_init(c->tea_ctx, c->aa_fixed_key, 16); output[0] = output[1] = 0; // purely for padding purposes memcpy(output + 2, header_key, 16); idx = 0; for (i = 0; i < 3; i++) { // TEA CBC with weird mixed endianness AV_WB32(src, header_seed); AV_WB32(src + 4, header_seed + 1); header_seed += 2; av_tea_crypt(c->tea_ctx, dst, src, 1, NULL, 0); // TEA ECB encrypt for (j = 0; j < TEA_BLOCK_SIZE && idx < 18; j+=1, idx+=1) { output[idx] = output[idx] ^ dst[j]; } } memcpy(c->file_key, output + 2, 16); // skip first 2 bytes of output av_log(s, AV_LOG_DEBUG, "File key is "); for (i = 0; i < 16; i++) av_log(s, AV_LOG_DEBUG, "%02x", c->file_key[i]); av_log(s, AV_LOG_DEBUG, "\n"); /* decoder setup */ st = avformat_new_stream(s, NULL); if (!st) { av_freep(&c->tea_ctx); return AVERROR(ENOMEM); } st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; if (!strcmp(codec_name, "mp332")) { st->codecpar->codec_id = AV_CODEC_ID_MP3; st->codecpar->sample_rate = 22050; st->need_parsing = AVSTREAM_PARSE_FULL_RAW; avpriv_set_pts_info(st, 64, 8, 32000 * TIMEPREC); // encoded audio frame is MP3_FRAME_SIZE bytes (+1 with padding, unlikely) } else if (!strcmp(codec_name, "acelp85")) { st->codecpar->codec_id = AV_CODEC_ID_SIPR; st->codecpar->block_align = 19; st->codecpar->channels = 1; st->codecpar->sample_rate = 8500; st->codecpar->bit_rate = 8500; st->need_parsing = AVSTREAM_PARSE_FULL_RAW; avpriv_set_pts_info(st, 64, 8, 8500 * TIMEPREC); } else if (!strcmp(codec_name, "acelp16")) { st->codecpar->codec_id = AV_CODEC_ID_SIPR; st->codecpar->block_align = 20; st->codecpar->channels = 1; st->codecpar->sample_rate = 16000; st->codecpar->bit_rate = 16000; st->need_parsing = AVSTREAM_PARSE_FULL_RAW; avpriv_set_pts_info(st, 64, 8, 16000 * TIMEPREC); } /* determine, and jump to audio start offset */ for (i = 1; i < toc_size; i++) { // skip the first entry! current_size = TOC[i].size; if (current_size > largest_size) { largest_idx = i; largest_size = current_size; } } start = TOC[largest_idx].offset; avio_seek(pb, start, SEEK_SET); // extract chapter positions. since all formats have constant bit rate, use it // as time base in bytes/s, for easy stream position <-> timestamp conversion st->start_time = 0; c->content_start = start; c->content_end = start + largest_size; while ((chapter_pos = avio_tell(pb)) >= 0 && chapter_pos < c->content_end) { int chapter_idx = s->nb_chapters; uint32_t chapter_size = avio_rb32(pb); if (chapter_size == 0) break; chapter_pos -= start + CHAPTER_HEADER_SIZE * chapter_idx; avio_skip(pb, 4 + chapter_size); if (!avpriv_new_chapter(s, chapter_idx, st->time_base, chapter_pos * TIMEPREC, (chapter_pos + chapter_size) * TIMEPREC, NULL)) return AVERROR(ENOMEM); } st->duration = (largest_size - CHAPTER_HEADER_SIZE * s->nb_chapters) * TIMEPREC; ff_update_cur_dts(s, st, 0); avio_seek(pb, start, SEEK_SET); c->current_chapter_size = 0; c->seek_offset = 0; return 0; } static int aa_read_packet(AVFormatContext *s, AVPacket *pkt) { uint8_t dst[TEA_BLOCK_SIZE]; uint8_t src[TEA_BLOCK_SIZE]; int i; int trailing_bytes; int blocks; uint8_t buf[MAX_CODEC_SECOND_SIZE * 2]; int written = 0; int ret; AADemuxContext *c = s->priv_data; uint64_t pos = avio_tell(s->pb); // are we at the end of the audio content? if (pos >= c->content_end) { return AVERROR_EOF; } // are we at the start of a chapter? if (c->current_chapter_size == 0) { c->current_chapter_size = avio_rb32(s->pb); if (c->current_chapter_size == 0) { return AVERROR_EOF; } av_log(s, AV_LOG_DEBUG, "Chapter %d (%" PRId64 " bytes)\n", c->chapter_idx, c->current_chapter_size); c->chapter_idx = c->chapter_idx + 1; avio_skip(s->pb, 4); // data start offset pos += 8; c->current_codec_second_size = c->codec_second_size; } // is this the last block in this chapter? if (c->current_chapter_size / c->current_codec_second_size == 0) { c->current_codec_second_size = c->current_chapter_size % c->current_codec_second_size; } // decrypt c->current_codec_second_size bytes blocks = c->current_codec_second_size / TEA_BLOCK_SIZE; for (i = 0; i < blocks; i++) { ret = avio_read(s->pb, src, TEA_BLOCK_SIZE); if (ret != TEA_BLOCK_SIZE) return (ret < 0) ? ret : AVERROR_EOF; av_tea_init(c->tea_ctx, c->file_key, 16); av_tea_crypt(c->tea_ctx, dst, src, 1, NULL, 1); memcpy(buf + written, dst, TEA_BLOCK_SIZE); written = written + TEA_BLOCK_SIZE; } trailing_bytes = c->current_codec_second_size % TEA_BLOCK_SIZE; if (trailing_bytes != 0) { // trailing bytes are left unencrypted! ret = avio_read(s->pb, src, trailing_bytes); if (ret != trailing_bytes) return (ret < 0) ? ret : AVERROR_EOF; memcpy(buf + written, src, trailing_bytes); written = written + trailing_bytes; } // update state c->current_chapter_size = c->current_chapter_size - c->current_codec_second_size; if (c->current_chapter_size <= 0) c->current_chapter_size = 0; if (c->seek_offset > written) c->seek_offset = 0; // ignore wrong estimate ret = av_new_packet(pkt, written - c->seek_offset); if (ret < 0) return ret; memcpy(pkt->data, buf + c->seek_offset, written - c->seek_offset); pkt->pos = pos; c->seek_offset = 0; return 0; } static int aa_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { AADemuxContext *c = s->priv_data; AVChapter *ch; int64_t chapter_pos, chapter_start, chapter_size; int chapter_idx = 0; // find chapter containing seek timestamp if (timestamp < 0) timestamp = 0; while (chapter_idx < s->nb_chapters && timestamp >= s->chapters[chapter_idx]->end) { ++chapter_idx; } if (chapter_idx >= s->nb_chapters) { chapter_idx = s->nb_chapters - 1; if (chapter_idx < 0) return -1; // there is no chapter. timestamp = s->chapters[chapter_idx]->end; } ch = s->chapters[chapter_idx]; // sync by clamping timestamp to nearest valid block position in its chapter chapter_size = ch->end / TIMEPREC - ch->start / TIMEPREC; chapter_pos = av_rescale_rnd((timestamp - ch->start) / TIMEPREC, 1, c->codec_second_size, (flags & AVSEEK_FLAG_BACKWARD) ? AV_ROUND_DOWN : AV_ROUND_UP) * c->codec_second_size; if (chapter_pos >= chapter_size) chapter_pos = chapter_size; chapter_start = c->content_start + (ch->start / TIMEPREC) + CHAPTER_HEADER_SIZE * (1 + chapter_idx); // reinit read state avio_seek(s->pb, chapter_start + chapter_pos, SEEK_SET); c->current_codec_second_size = c->codec_second_size; c->current_chapter_size = chapter_size - chapter_pos; c->chapter_idx = 1 + chapter_idx; // for unaligned frames, estimate offset of first frame in block (assume no padding) if (s->streams[0]->codecpar->codec_id == AV_CODEC_ID_MP3) { c->seek_offset = (MP3_FRAME_SIZE - chapter_pos % MP3_FRAME_SIZE) % MP3_FRAME_SIZE; } ff_update_cur_dts(s, s->streams[0], ch->start + (chapter_pos + c->seek_offset) * TIMEPREC); return 1; } static int aa_probe(const AVProbeData *p) { uint8_t *buf = p->buf; // first 4 bytes are file size, next 4 bytes are the magic if (AV_RB32(buf+4) != AA_MAGIC) return 0; return AVPROBE_SCORE_MAX / 2; } static int aa_read_close(AVFormatContext *s) { AADemuxContext *c = s->priv_data; av_freep(&c->tea_ctx); return 0; } #define OFFSET(x) offsetof(AADemuxContext, x) static const AVOption aa_options[] = { { "aa_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files! "Fixed key used for handling Audible AA files", OFFSET(aa_fixed_key), AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd2a51d673"}, .flags = AV_OPT_FLAG_DECODING_PARAM }, { NULL }, }; static const AVClass aa_class = { .class_name = "aa", .item_name = av_default_item_name, .option = aa_options, .version = LIBAVUTIL_VERSION_INT, }; AVInputFormat ff_aa_demuxer = { .name = "aa", .long_name = NULL_IF_CONFIG_SMALL("Audible AA format files"), .priv_class = &aa_class, .priv_data_size = sizeof(AADemuxContext), .extensions = "aa", .read_probe = aa_probe, .read_header = aa_read_header, .read_packet = aa_read_packet, .read_seek = aa_read_seek, .read_close = aa_read_close, .flags = AVFMT_NO_BYTE_SEEK | AVFMT_NOGENSEARCH, };
./CrossVul/dataset_final_sorted/CWE-665/c/bad_881_0
crossvul-cpp_data_good_2629_2
/***************************************************************************** * * NAGIOS.C - Core Program Code For Nagios * * Program: Nagios Core * License: GPL * * First Written: 01-28-1999 (start of development) * * Description: * * Nagios is a network monitoring tool that will check hosts and services * that you specify. It has the ability to notify contacts via email, pager, * or other user-defined methods when a service or host goes down and * recovers. Service and host monitoring is done through the use of external * plugins which can be developed independently of Nagios. * * License: * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 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. * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * *****************************************************************************/ #include "../include/config.h" #include "../include/common.h" #include "../include/objects.h" #include "../include/comments.h" #include "../include/downtime.h" #include "../include/statusdata.h" #include "../include/macros.h" #include "../include/nagios.h" #include "../include/sretention.h" #include "../include/perfdata.h" #include "../include/broker.h" #include "../include/nebmods.h" #include "../include/nebmodules.h" #include "../include/workers.h" /*#define DEBUG_MEMORY 1*/ #ifdef DEBUG_MEMORY #include <mcheck.h> #endif static int is_worker; static void set_loadctl_defaults(void) { struct rlimit rlim; /* Workers need to up 'em, master needs to know 'em */ getrlimit(RLIMIT_NOFILE, &rlim); rlim.rlim_cur = rlim.rlim_max; setrlimit(RLIMIT_NOFILE, &rlim); loadctl.nofile_limit = rlim.rlim_max; #ifdef RLIMIT_NPROC getrlimit(RLIMIT_NPROC, &rlim); rlim.rlim_cur = rlim.rlim_max; setrlimit(RLIMIT_NPROC, &rlim); loadctl.nproc_limit = rlim.rlim_max; #else loadctl.nproc_limit = loadctl.nofile_limit / 2; #endif /* * things may have been configured already. Otherwise we * set some sort of sane defaults here */ if (!loadctl.jobs_max) { loadctl.jobs_max = loadctl.nproc_limit - 100; if (!is_worker && loadctl.jobs_max > (loadctl.nofile_limit - 50) * wproc_num_workers_online) { loadctl.jobs_max = (loadctl.nofile_limit - 50) * wproc_num_workers_online; } } if (!loadctl.jobs_limit) loadctl.jobs_limit = loadctl.jobs_max; if (!loadctl.backoff_limit) loadctl.backoff_limit = online_cpus() * 2.5; if (!loadctl.rampup_limit) loadctl.rampup_limit = online_cpus() * 0.8; if (!loadctl.backoff_change) loadctl.backoff_change = loadctl.jobs_limit * 0.3; if (!loadctl.rampup_change) loadctl.rampup_change = loadctl.backoff_change * 0.25; if (!loadctl.check_interval) loadctl.check_interval = 60; if (!loadctl.jobs_min) loadctl.jobs_min = online_cpus() * 20; /* pessimistic */ } static int test_path_access(const char *program, int mode) { char *envpath, *p, *colon; int ret, our_errno = 1500; /* outside errno range */ if (program[0] == '/' || !(envpath = getenv("PATH"))) return access(program, mode); if (!(envpath = strdup(envpath))) { errno = ENOMEM; return -1; } for (p = envpath; p; p = colon + 1) { char *path; colon = strchr(p, ':'); if (colon) *colon = 0; asprintf(&path, "%s/%s", p, program); ret = access(path, mode); free(path); if (!ret) break; if (ret < 0) { if (errno == ENOENT) continue; if (our_errno > errno) our_errno = errno; } if (!colon) break; } free(envpath); if (!ret) errno = 0; else errno = our_errno; return ret; } static int nagios_core_worker(const char *path) { int sd, ret; char response[128]; is_worker = 1; set_loadctl_defaults(); sd = nsock_unix(path, NSOCK_TCP | NSOCK_CONNECT); if (sd < 0) { printf("Failed to connect to query socket '%s': %s: %s\n", path, nsock_strerror(sd), strerror(errno)); return 1; } ret = nsock_printf_nul(sd, "@wproc register name=Core Worker %ld;pid=%ld", (long)getpid(), (long)getpid()); if (ret < 0) { printf("Failed to register as worker.\n"); return 1; } ret = read(sd, response, 3); if (ret != 3) { printf("Failed to read response from wproc manager\n"); return 1; } if (memcmp(response, "OK", 3)) { read(sd, response + 3, sizeof(response) - 4); response[sizeof(response) - 2] = 0; printf("Failed to register with wproc manager: %s\n", response); return 1; } enter_worker(sd, start_cmd); return 0; } /* * only handles logfile for now, which we stash in macros to * make sure we can log *somewhere* in case the new path is * completely inaccessible. */ static int test_configured_paths(void) { FILE *fp; nagios_macros *mac; mac = get_global_macros(); fp = fopen(log_file, "a+"); if (!fp) { /* * we do some variable trashing here so logit() can * open the old logfile (if any), in case we got a * restart command or a SIGHUP */ char *value_absolute = log_file; log_file = mac->x[MACRO_LOGFILE]; logit(NSLOG_CONFIG_ERROR, TRUE, "Error: Failed to open logfile '%s' for writing: %s\n", value_absolute, strerror(errno)); return ERROR; } fclose(fp); /* save the macro */ mac->x[MACRO_LOGFILE] = log_file; return OK; } int main(int argc, char **argv) { int result; int error = FALSE; int display_license = FALSE; int display_help = FALSE; int c = 0; struct tm *tm, tm_s; time_t now; char datestring[256]; nagios_macros *mac; const char *worker_socket = NULL; int i; #ifdef HAVE_SIGACTION struct sigaction sig_action; #endif #ifdef HAVE_GETOPT_H int option_index = 0; static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'V'}, {"license", no_argument, 0, 'V'}, {"verify-config", no_argument, 0, 'v'}, {"daemon", no_argument, 0, 'd'}, {"test-scheduling", no_argument, 0, 's'}, {"precache-objects", no_argument, 0, 'p'}, {"use-precached-objects", no_argument, 0, 'u'}, {"enable-timing-point", no_argument, 0, 'T'}, {"worker", required_argument, 0, 'W'}, {0, 0, 0, 0} }; #define getopt(argc, argv, o) getopt_long(argc, argv, o, long_options, &option_index) #endif memset(&loadctl, 0, sizeof(loadctl)); mac = get_global_macros(); /* make sure we have the correct number of command line arguments */ if(argc < 2) error = TRUE; /* get all command line arguments */ while(1) { c = getopt(argc, argv, "+hVvdspuxTW"); if(c == -1 || c == EOF) break; switch(c) { case '?': /* usage */ case 'h': display_help = TRUE; break; case 'V': /* version */ display_license = TRUE; break; case 'v': /* verify */ verify_config++; break; case 's': /* scheduling check */ test_scheduling = TRUE; break; case 'd': /* daemon mode */ daemon_mode = TRUE; break; case 'p': /* precache object config */ precache_objects = TRUE; break; case 'u': /* use precached object config */ use_precached_objects = TRUE; break; case 'T': enable_timing_point = TRUE; break; case 'W': worker_socket = optarg; break; case 'x': printf("Warning: -x is deprecated and will be removed\n"); break; default: break; } } #ifdef DEBUG_MEMORY mtrace(); #endif /* if we're a worker we can skip everything below */ if(worker_socket) { exit(nagios_core_worker(worker_socket)); } /* Initialize configuration variables */ init_main_cfg_vars(1); init_shared_cfg_vars(1); if(daemon_mode == FALSE) { printf("\nNagios Core %s\n", PROGRAM_VERSION); printf("Copyright (c) 2009-present Nagios Core Development Team and Community Contributors\n"); printf("Copyright (c) 1999-2009 Ethan Galstad\n"); printf("Last Modified: %s\n", PROGRAM_MODIFICATION_DATE); printf("License: GPL\n\n"); printf("Website: https://www.nagios.org\n"); } /* just display the license */ if(display_license == TRUE) { printf("This program is free software; you can redistribute it and/or modify\n"); printf("it under the terms of the GNU General Public License version 2 as\n"); printf("published by the Free Software Foundation.\n\n"); printf("This program is distributed in the hope that it will be useful,\n"); printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"); printf("GNU General Public License for more details.\n\n"); printf("You should have received a copy of the GNU General Public License\n"); printf("along with this program; if not, write to the Free Software\n"); printf("Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n"); exit(OK); } /* make sure we got the main config file on the command line... */ if(optind >= argc) error = TRUE; /* if there are no command line options (or if we encountered an error), print usage */ if(error == TRUE || display_help == TRUE) { printf("Usage: %s [options] <main_config_file>\n", argv[0]); printf("\n"); printf("Options:\n"); printf("\n"); printf(" -v, --verify-config Verify all configuration data (-v -v for more info)\n"); printf(" -s, --test-scheduling Shows projected/recommended check scheduling and other\n"); printf(" diagnostic info based on the current configuration files.\n"); printf(" -T, --enable-timing-point Enable timed commentary on initialization\n"); printf(" -x, --dont-verify-paths Deprecated (Don't check for circular object paths)\n"); printf(" -p, --precache-objects Precache object configuration\n"); printf(" -u, --use-precached-objects Use precached object config file\n"); printf(" -d, --daemon Starts Nagios in daemon mode, instead of as a foreground process\n"); printf(" -W, --worker /path/to/socket Act as a worker for an already running daemon\n"); printf("\n"); printf("Visit the Nagios website at https://www.nagios.org/ for bug fixes, new\n"); printf("releases, online documentation, FAQs, information on subscribing to\n"); printf("the mailing lists, and commercial support options for Nagios.\n"); printf("\n"); exit(ERROR); } /* * config file is last argument specified. * Make sure it uses an absolute path */ config_file = nspath_absolute(argv[optind], NULL); if(config_file == NULL) { printf("Error allocating memory.\n"); exit(ERROR); } config_file_dir = nspath_absolute_dirname(config_file, NULL); /* * Set the signal handler for the SIGXFSZ signal here because * we may encounter this signal before the other signal handlers * are set. */ #ifdef HAVE_SIGACTION sig_action.sa_sigaction = NULL; sig_action.sa_handler = handle_sigxfsz; sigfillset(&sig_action.sa_mask); sig_action.sa_flags = SA_NODEFER|SA_RESTART; sigaction(SIGXFSZ, &sig_action, NULL); #else signal(SIGXFSZ, handle_sigxfsz); #endif /* * let's go to town. We'll be noisy if we're verifying config * or running scheduling tests. */ if(verify_config || test_scheduling || precache_objects) { reset_variables(); /* * if we don't beef up our resource limits as much as * we can, it's quite possible we'll run headlong into * EAGAIN due to too many processes when we try to * drop privileges later. */ set_loadctl_defaults(); if(verify_config) printf("Reading configuration data...\n"); /* read our config file */ result = read_main_config_file(config_file); if(result != OK) { printf(" Error processing main config file!\n\n"); exit(EXIT_FAILURE); } if(verify_config) printf(" Read main config file okay...\n"); /* drop privileges */ if((result = drop_privileges(nagios_user, nagios_group)) == ERROR) { printf(" Failed to drop privileges. Aborting."); exit(EXIT_FAILURE); } /* * this must come after dropping privileges, so we make * sure to test access permissions as the right user. */ if (!verify_config && test_configured_paths() == ERROR) { printf(" One or more path problems detected. Aborting.\n"); exit(EXIT_FAILURE); } /* read object config files */ result = read_all_object_data(config_file); if(result != OK) { printf(" Error processing object config files!\n\n"); /* if the config filename looks fishy, warn the user */ if(!strstr(config_file, "nagios.cfg")) { printf("\n***> The name of the main configuration file looks suspicious...\n"); printf("\n"); printf(" Make sure you are specifying the name of the MAIN configuration file on\n"); printf(" the command line and not the name of another configuration file. The\n"); printf(" main configuration file is typically '%s'\n", DEFAULT_CONFIG_FILE); } printf("\n***> One or more problems was encountered while processing the config files...\n"); printf("\n"); printf(" Check your configuration file(s) to ensure that they contain valid\n"); printf(" directives and data definitions. If you are upgrading from a previous\n"); printf(" version of Nagios, you should be aware that some variables/definitions\n"); printf(" may have been removed or modified in this version. Make sure to read\n"); printf(" the HTML documentation regarding the config files, as well as the\n"); printf(" 'Whats New' section to find out what has changed.\n\n"); exit(EXIT_FAILURE); } if(verify_config) { printf(" Read object config files okay...\n\n"); printf("Running pre-flight check on configuration data...\n\n"); } /* run the pre-flight check to make sure things look okay... */ result = pre_flight_check(); if(result != OK) { printf("\n***> One or more problems was encountered while running the pre-flight check...\n"); printf("\n"); printf(" Check your configuration file(s) to ensure that they contain valid\n"); printf(" directives and data definitions. If you are upgrading from a previous\n"); printf(" version of Nagios, you should be aware that some variables/definitions\n"); printf(" may have been removed or modified in this version. Make sure to read\n"); printf(" the HTML documentation regarding the config files, as well as the\n"); printf(" 'Whats New' section to find out what has changed.\n\n"); exit(EXIT_FAILURE); } if(verify_config) { printf("\nThings look okay - No serious problems were detected during the pre-flight check\n"); } /* scheduling tests need a bit more than config verifications */ if(test_scheduling == TRUE) { /* we'll need the event queue here so we can time insertions */ init_event_queue(); timing_point("Done initializing event queue\n"); /* read initial service and host state information */ initialize_retention_data(config_file); read_initial_state_information(); timing_point("Retention data and initial state parsed\n"); /* initialize the event timing loop */ init_timing_loop(); timing_point("Timing loop initialized\n"); /* display scheduling information */ display_scheduling_info(); } if(precache_objects) { result = fcache_objects(object_precache_file); timing_point("Done precaching objects\n"); if(result == OK) { printf("Object precache file created:\n%s\n", object_precache_file); } else { printf("Failed to precache objects to '%s': %s\n", object_precache_file, strerror(errno)); } } /* clean up after ourselves */ cleanup(); /* exit */ timing_point("Exiting\n"); /* make valgrind shut up about still reachable memory */ neb_free_module_list(); free(config_file_dir); free(config_file); exit(result); } /* else start to monitor things... */ else { /* * if we're called with a relative path we must make * it absolute so we can launch our workers. * If not, we needn't bother, as we're using execvp() */ if (strchr(argv[0], '/')) nagios_binary_path = nspath_absolute(argv[0], NULL); else nagios_binary_path = strdup(argv[0]); if (!nagios_binary_path) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Unable to allocate memory for nagios_binary_path\n"); exit(EXIT_FAILURE); } if (!(nagios_iobs = iobroker_create())) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Failed to create IO broker set: %s\n", strerror(errno)); exit(EXIT_FAILURE); } /* keep monitoring things until we get a shutdown command */ do { /* reset internal book-keeping (in case we're restarting) */ wproc_num_workers_spawned = wproc_num_workers_online = 0; caught_signal = sigshutdown = FALSE; sig_id = 0; /* reset program variables */ reset_variables(); timing_point("Variables reset\n"); /* get PID */ nagios_pid = (int)getpid(); /* read in the configuration files (main and resource config files) */ result = read_main_config_file(config_file); if (result != OK) { logit(NSLOG_CONFIG_ERROR, TRUE, "Error: Failed to process config file '%s'. Aborting\n", config_file); exit(EXIT_FAILURE); } timing_point("Main config file read\n"); /* NOTE 11/06/07 EG moved to after we read config files, as user may have overridden timezone offset */ /* get program (re)start time and save as macro */ program_start = time(NULL); my_free(mac->x[MACRO_PROCESSSTARTTIME]); asprintf(&mac->x[MACRO_PROCESSSTARTTIME], "%llu", (unsigned long long)program_start); /* enter daemon mode (unless we're restarting...) */ if(daemon_mode == TRUE && sigrestart == FALSE) { result = daemon_init(); /* we had an error daemonizing, so bail... */ if(result == ERROR) { logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR, TRUE, "Bailing out due to failure to daemonize. (PID=%d)", (int)getpid()); cleanup(); exit(EXIT_FAILURE); } /* get new PID */ nagios_pid = (int)getpid(); } /* drop privileges */ if(drop_privileges(nagios_user, nagios_group) == ERROR) { logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, "Failed to drop privileges. Aborting."); cleanup(); exit(ERROR); } if (test_path_access(nagios_binary_path, X_OK)) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: failed to access() %s: %s\n", nagios_binary_path, strerror(errno)); logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Spawning workers will be impossible. Aborting.\n"); exit(EXIT_FAILURE); } if (test_configured_paths() == ERROR) { /* error has already been logged */ exit(EXIT_FAILURE); } /* this must be logged after we read config data, as user may have changed location of main log file */ logit(NSLOG_PROCESS_INFO, TRUE, "Nagios %s starting... (PID=%d)\n", PROGRAM_VERSION, (int)getpid()); /* log the local time - may be different than clock time due to timezone offset */ now = time(NULL); tm = localtime_r(&now, &tm_s); strftime(datestring, sizeof(datestring), "%a %b %d %H:%M:%S %Z %Y", tm); logit(NSLOG_PROCESS_INFO, TRUE, "Local time is %s", datestring); /* write log version/info */ write_log_file_info(NULL); /* open debug log now that we're the right user */ open_debug_log(); #ifdef USE_EVENT_BROKER /* initialize modules */ neb_init_modules(); neb_init_callback_list(); #endif timing_point("NEB module API initialized\n"); /* handle signals (interrupts) before we do any socket I/O */ setup_sighandler(); /* * Initialize query handler and event subscription service. * This must be done before modules are initialized, so * the modules can use our in-core stuff properly */ if (qh_init(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET) != OK) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Error: Failed to initialize query handler. Aborting\n"); exit(EXIT_FAILURE); } timing_point("Query handler initialized\n"); nerd_init(); timing_point("NERD initialized\n"); /* initialize check workers */ if(init_workers(num_check_workers) < 0) { logit(NSLOG_RUNTIME_ERROR, TRUE, "Failed to spawn workers. Aborting\n"); exit(EXIT_FAILURE); } timing_point("%u workers spawned\n", wproc_num_workers_spawned); i = 0; while (i < 50 && wproc_num_workers_online < wproc_num_workers_spawned) { iobroker_poll(nagios_iobs, 50); i++; } timing_point("%u workers connected\n", wproc_num_workers_online); /* now that workers have arrived we can set the defaults */ set_loadctl_defaults(); #ifdef USE_EVENT_BROKER /* load modules */ if (neb_load_all_modules() != OK) { logit(NSLOG_CONFIG_ERROR, ERROR, "Error: Module loading failed. Aborting.\n"); /* if we're dumping core, we must remove all dl-files */ if (daemon_dumps_core) neb_unload_all_modules(NEBMODULE_FORCE_UNLOAD, NEBMODULE_NEB_SHUTDOWN); exit(EXIT_FAILURE); } timing_point("Modules loaded\n"); /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_PRELAUNCH, NEBFLAG_NONE, NEBATTR_NONE, NULL); timing_point("First callback made\n"); #endif /* read in all object config data */ if(result == OK) result = read_all_object_data(config_file); /* there was a problem reading the config files */ if(result != OK) logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, TRUE, "Bailing out due to one or more errors encountered in the configuration files. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)", (int)getpid()); else { /* run the pre-flight check to make sure everything looks okay*/ if((result = pre_flight_check()) != OK) logit(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_VERIFICATION_ERROR, TRUE, "Bailing out due to errors encountered while running the pre-flight check. Run Nagios from the command line with the -v option to verify your config before restarting. (PID=%d)\n", (int)getpid()); } /* an error occurred that prevented us from (re)starting */ if(result != OK) { /* if we were restarting, we need to cleanup from the previous run */ if(sigrestart == TRUE) { /* clean up the status data */ cleanup_status_data(TRUE); } #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_PROCESS_INITIATED, NEBATTR_SHUTDOWN_ABNORMAL, NULL); #endif cleanup(); exit(ERROR); } timing_point("Object configuration parsed and understood\n"); /* write the objects.cache file */ fcache_objects(object_cache_file); timing_point("Objects cached\n"); init_event_queue(); timing_point("Event queue initialized\n"); #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_START, NEBFLAG_NONE, NEBATTR_NONE, NULL); #endif /* initialize status data unless we're starting */ if(sigrestart == FALSE) { initialize_status_data(config_file); timing_point("Status data initialized\n"); } /* initialize scheduled downtime data */ initialize_downtime_data(); timing_point("Downtime data initialized\n"); /* read initial service and host state information */ initialize_retention_data(config_file); timing_point("Retention data initialized\n"); read_initial_state_information(); timing_point("Initial state information read\n"); /* initialize comment data */ initialize_comment_data(); timing_point("Comment data initialized\n"); /* initialize performance data */ initialize_performance_data(config_file); timing_point("Performance data initialized\n"); /* initialize the event timing loop */ init_timing_loop(); timing_point("Event timing loop initialized\n"); /* initialize check statistics */ init_check_stats(); timing_point("check stats initialized\n"); /* check for updates */ check_for_nagios_updates(FALSE, TRUE); timing_point("Update check concluded\n"); /* update all status data (with retained information) */ update_all_status_data(); timing_point("Status data updated\n"); /* log initial host and service state */ log_host_states(INITIAL_STATES, NULL); log_service_states(INITIAL_STATES, NULL); timing_point("Initial states logged\n"); /* reset the restart flag */ sigrestart = FALSE; /* fire up command file worker */ launch_command_file_worker(); timing_point("Command file worker launched\n"); #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_EVENTLOOPSTART, NEBFLAG_NONE, NEBATTR_NONE, NULL); #endif /* get event start time and save as macro */ event_start = time(NULL); my_free(mac->x[MACRO_EVENTSTARTTIME]); asprintf(&mac->x[MACRO_EVENTSTARTTIME], "%llu", (unsigned long long)event_start); timing_point("Entering event execution loop\n"); /***** start monitoring all services *****/ /* (doesn't return until a restart or shutdown signal is encountered) */ event_execution_loop(); /* * immediately deinitialize the query handler so it * can remove modules that have stashed data with it */ qh_deinit(qh_socket_path ? qh_socket_path : DEFAULT_QUERY_SOCKET); /* 03/01/2007 EG Moved from sighandler() to prevent FUTEX locking problems under NPTL */ /* 03/21/2007 EG SIGSEGV signals are still logged in sighandler() so we don't loose them */ /* did we catch a signal? */ if(caught_signal == TRUE) { if(sig_id == SIGHUP) logit(NSLOG_PROCESS_INFO, TRUE, "Caught SIGHUP, restarting...\n"); } #ifdef USE_EVENT_BROKER /* send program data to broker */ broker_program_state(NEBTYPE_PROCESS_EVENTLOOPEND, NEBFLAG_NONE, NEBATTR_NONE, NULL); if(sigshutdown == TRUE) broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_USER_INITIATED, NEBATTR_SHUTDOWN_NORMAL, NULL); else if(sigrestart == TRUE) broker_program_state(NEBTYPE_PROCESS_RESTART, NEBFLAG_USER_INITIATED, NEBATTR_RESTART_NORMAL, NULL); #endif /* save service and host state information */ save_state_information(FALSE); cleanup_retention_data(); /* clean up performance data */ cleanup_performance_data(); /* clean up the scheduled downtime data */ cleanup_downtime_data(); /* clean up the status data unless we're restarting */ if(sigrestart == FALSE) { cleanup_status_data(TRUE); } free_worker_memory(WPROC_FORCE); /* shutdown stuff... */ if(sigshutdown == TRUE) { iobroker_destroy(nagios_iobs, IOBROKER_CLOSE_SOCKETS); nagios_iobs = NULL; /* log a shutdown message */ logit(NSLOG_PROCESS_INFO, TRUE, "Successfully shutdown... (PID=%d)\n", (int)getpid()); } /* clean up after ourselves */ cleanup(); /* close debug log */ close_debug_log(); } while(sigrestart == TRUE && sigshutdown == FALSE); if(daemon_mode == TRUE) unlink(lock_file); /* free misc memory */ my_free(lock_file); my_free(config_file); my_free(config_file_dir); my_free(nagios_binary_path); } return OK; }
./CrossVul/dataset_final_sorted/CWE-665/c/good_2629_2
crossvul-cpp_data_good_738_0
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2019 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // caff.c // This module is a helper to the WavPack command-line programs to support CAF files. #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <ctype.h> #include "wavpack.h" #include "utils.h" #include "md5.h" #ifdef _WIN32 #define strdup(x) _strdup(x) #endif #define WAVPACK_NO_ERROR 0 #define WAVPACK_SOFT_ERROR 1 #define WAVPACK_HARD_ERROR 2 extern int debug_logging_mode; typedef struct { char mFileType [4]; uint16_t mFileVersion; uint16_t mFileFlags; } CAFFileHeader; #define CAFFileHeaderFormat "4SS" #pragma pack(push,4) typedef struct { char mChunkType [4]; int64_t mChunkSize; } CAFChunkHeader; #pragma pack(pop) #define CAFChunkHeaderFormat "4D" typedef struct { double mSampleRate; char mFormatID [4]; uint32_t mFormatFlags; uint32_t mBytesPerPacket; uint32_t mFramesPerPacket; uint32_t mChannelsPerFrame; uint32_t mBitsPerChannel; } CAFAudioFormat; #define CAFAudioFormatFormat "D4LLLLL" #define CAF_FORMAT_FLOAT 0x1 #define CAF_FORMAT_LITTLE_ENDIAN 0x2 typedef struct { uint32_t mChannelLayoutTag; uint32_t mChannelBitmap; uint32_t mNumberChannelDescriptions; } CAFChannelLayout; #define CAFChannelLayoutFormat "LLL" enum { kCAFChannelLayoutTag_UseChannelDescriptions = (0<<16) | 0, // use the array of AudioChannelDescriptions to define the mapping. kCAFChannelLayoutTag_UseChannelBitmap = (1<<16) | 0, // use the bitmap to define the mapping. }; typedef struct { uint32_t mChannelLabel; uint32_t mChannelFlags; float mCoordinates [3]; } CAFChannelDescription; #define CAFChannelDescriptionFormat "LLLLL" static const char TMH_full [] = { 1,2,3,13,9,10,5,6,12,14,15,16,17,9,4,18,7,8,19,20,21,0 }; static const char TMH_std [] = { 1,2,3,11,8,9,5,6,10,12,13,14,15,7,4,16,0 }; static struct { uint32_t mChannelLayoutTag; // Core Audio layout, 100 - 146 in high word, num channels in low word uint32_t mChannelBitmap; // Microsoft standard mask (for those channels that appear) const char *mChannelReorder; // reorder string if layout is NOT in Microsoft standard order const char *mChannelIdentities; // identities of any channels NOT in Microsoft standard } layouts [] = { { (100<<16) | 1, 0x004, NULL, NULL }, // FC { (101<<16) | 2, 0x003, NULL, NULL }, // FL, FR { (102<<16) | 2, 0x003, NULL, NULL }, // FL, FR (headphones) { (103<<16) | 2, 0x000, NULL, "\46\47" }, // [Lt, Rt] (matrix encoded) { (104<<16) | 2, 0x000, NULL, "\314\315" }, // [Mid, Side] { (105<<16) | 2, 0x000, NULL, "\316\317" }, // [X, Y] { (106<<16) | 2, 0x003, NULL, NULL }, // FL, FR (binaural) { (107<<16) | 4, 0x000, NULL, "\310\311\312\313" }, // [W, X, Y, Z] (ambisonics) { (108<<16) | 4, 0x033, NULL, NULL }, // FL, FR, BL, BR (quad) { (109<<16) | 5, 0x037, "12453", NULL }, // FL, FR, BL, BR, FC (pentagonal) { (110<<16) | 6, 0x137, "124536", NULL }, // FL, FR, BL, BR, FC, BC (hexagonal) { (111<<16) | 8, 0x737, "12453678", NULL }, // FL, FR, BL, BR, FC, BC, SL, SR (octagonal) { (112<<16) | 8, 0x2d033, NULL, NULL }, // FL, FR, BL, BR, TFL, TFR, TBL, TBR (cubic) { (113<<16) | 3, 0x007, NULL, NULL }, // FL, FR, FC { (114<<16) | 3, 0x007, "312", NULL }, // FC, FL, FR { (115<<16) | 4, 0x107, NULL, NULL }, // FL, FR, FC, BC { (116<<16) | 4, 0x107, "3124", NULL }, // FC, FL, FR, BC { (117<<16) | 5, 0x037, NULL, NULL }, // FL, FR, FC, BL, BR { (118<<16) | 5, 0x037, "12453", NULL }, // FL, FR, BL, BR, FC { (119<<16) | 5, 0x037, "13245", NULL }, // FL, FC, FR, BL, BR { (120<<16) | 5, 0x037, "31245", NULL }, // FC, FL, FR, BL, BR { (121<<16) | 6, 0x03f, NULL, NULL }, // FL, FR, FC, LFE, BL, BR { (122<<16) | 6, 0x03f, "125634", NULL }, // FL, FR, BL, BR, FC, LFE { (123<<16) | 6, 0x03f, "132564", NULL }, // FL, FC, FR, BL, BR, LFE { (124<<16) | 6, 0x03f, "312564", NULL }, // FC, FL, FR, BL, BR, LFE { (125<<16) | 7, 0x13f, NULL, NULL }, // FL, FR, FC, LFE, BL, BR, BC { (126<<16) | 8, 0x0ff, NULL, NULL }, // FL, FR, FC, LFE, BL, BR, FLC, FRC { (127<<16) | 8, 0x0ff, "37812564", NULL }, // FC, FLC, FRC, FL, FR, BL, BR, LFE { (128<<16) | 8, 0x03f, NULL, "\41\42" }, // FL, FR, FC, LFE, BL, BR, [Rls, Rrs] { (129<<16) | 8, 0x0ff, "12563478", NULL }, // FL, FR, BL, BR, FC, LFE, FLC, FRC { (130<<16) | 8, 0x03f, NULL, "\46\47" }, // FL, FR, FC, LFE, BL, BR, [Lt, Rt] { (131<<16) | 3, 0x103, NULL, NULL }, // FL, FR, BC { (132<<16) | 4, 0x033, NULL, NULL }, // FL, FR, BL, BR { (133<<16) | 3, 0x00B, NULL, NULL }, // FL, FR, LFE { (134<<16) | 4, 0x10B, NULL, NULL }, // FL, FR, LFE, BC { (135<<16) | 5, 0x03B, NULL, NULL }, // FL, FR, LFE, BL, BR { (136<<16) | 4, 0x00F, NULL, NULL }, // FL, FR, FC, LFE { (137<<16) | 5, 0x10f, NULL, NULL }, // FL, FR, FC, LFE, BC { (138<<16) | 5, 0x03b, "12453", NULL }, // FL, FR, BL, BR, LFE { (139<<16) | 6, 0x137, "124536", NULL }, // FL, FR, BL, BR, FC, BC { (140<<16) | 7, 0x037, "1245367", "\41\42" }, // FL, FR, BL, BR, FC, [Rls, Rrs] { (141<<16) | 6, 0x137, "312456", NULL }, // FC, FL, FR, BL, BR, BC { (142<<16) | 7, 0x13f, "3125674", NULL }, // FC, FL, FR, BL, BR, BC, LFE { (143<<16) | 7, 0x037, "3124567", "\41\42" }, // FC, FL, FR, BL, BR, [Rls, Rrs] { (144<<16) | 8, 0x137, "31245786", "\41\42" }, // FC, FL, FR, BL, BR, [Rls, Rrs], BC { (145<<16) | 16, 0x773f, TMH_std, "\43\44\54\45" }, // FL, FR, FC, TFC, SL, SR, BL, BR, TFL, TFR, [Lw, Rw, Csd], BC, LFE, [LFE2] { (146<<16) | 21, 0x77ff, TMH_full, "\43\44\54\45" }, // FL, FR, FC, TFC, SL, SR, BL, BR, TFL, TFR, [Lw, Rw, Csd], BC, LFE, [LFE2], // FLC, FRC, [HI, VI, Haptic] }; #define NUM_LAYOUTS (sizeof (layouts) / sizeof (layouts [0])) int ParseCaffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { uint32_t chan_chunk = 0, desc_chunk = 0, channel_layout = 0, bcount; unsigned char *channel_identities = NULL; unsigned char *channel_reorder = NULL; int64_t total_samples = 0, infilesize; CAFFileHeader caf_file_header; CAFChunkHeader caf_chunk_header; CAFAudioFormat caf_audio_format; int i; infilesize = DoGetFileSize (infile); memcpy (&caf_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &caf_file_header) + 4, sizeof (CAFFileHeader) - 4, &bcount) || bcount != sizeof (CAFFileHeader) - 4)) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &caf_file_header, sizeof (CAFFileHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&caf_file_header, CAFFileHeaderFormat); if (caf_file_header.mFileVersion != 1) { error_line ("%s: can't handle version %d .CAF files!", infilename, caf_file_header.mFileVersion); return WAVPACK_SOFT_ERROR; } // loop through all elements of the RIFF wav header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &caf_chunk_header, sizeof (CAFChunkHeader), &bcount) || bcount != sizeof (CAFChunkHeader)) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &caf_chunk_header, sizeof (CAFChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&caf_chunk_header, CAFChunkHeaderFormat); // if it's the format chunk, we want to get some info out of there and // make sure it's a .caf file we can handle if (!strncmp (caf_chunk_header.mChunkType, "desc", 4)) { int supported = TRUE; if (caf_chunk_header.mChunkSize != sizeof (CAFAudioFormat) || !DoReadFile (infile, &caf_audio_format, (uint32_t) caf_chunk_header.mChunkSize, &bcount) || bcount != caf_chunk_header.mChunkSize) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &caf_audio_format, (uint32_t) caf_chunk_header.mChunkSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&caf_audio_format, CAFAudioFormatFormat); desc_chunk = 1; if (debug_logging_mode) { char formatstr [5]; memcpy (formatstr, caf_audio_format.mFormatID, 4); formatstr [4] = 0; error_line ("format = %s, flags = %x, sampling rate = %g", formatstr, caf_audio_format.mFormatFlags, caf_audio_format.mSampleRate); error_line ("packet = %d bytes and %d frames", caf_audio_format.mBytesPerPacket, caf_audio_format.mFramesPerPacket); error_line ("channels per frame = %d, bits per channel = %d", caf_audio_format.mChannelsPerFrame, caf_audio_format.mBitsPerChannel); } if (strncmp (caf_audio_format.mFormatID, "lpcm", 4) || (caf_audio_format.mFormatFlags & ~3)) supported = FALSE; else if (caf_audio_format.mSampleRate < 1.0 || caf_audio_format.mSampleRate > 16777215.0 || caf_audio_format.mSampleRate != floor (caf_audio_format.mSampleRate)) supported = FALSE; else if (!caf_audio_format.mChannelsPerFrame || caf_audio_format.mChannelsPerFrame > 256) supported = FALSE; else if (caf_audio_format.mBitsPerChannel < 1 || caf_audio_format.mBitsPerChannel > 32 || ((caf_audio_format.mFormatFlags & CAF_FORMAT_FLOAT) && caf_audio_format.mBitsPerChannel != 32)) supported = FALSE; else if (caf_audio_format.mFramesPerPacket != 1 || caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame < (caf_audio_format.mBitsPerChannel + 7) / 8 || caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame > 4 || caf_audio_format.mBytesPerPacket % caf_audio_format.mChannelsPerFrame) supported = FALSE; if (!supported) { error_line ("%s is an unsupported .CAF format!", infilename); return WAVPACK_SOFT_ERROR; } config->bytes_per_sample = caf_audio_format.mBytesPerPacket / caf_audio_format.mChannelsPerFrame; config->float_norm_exp = (caf_audio_format.mFormatFlags & CAF_FORMAT_FLOAT) ? 127 : 0; config->bits_per_sample = caf_audio_format.mBitsPerChannel; config->num_channels = caf_audio_format.mChannelsPerFrame; config->sample_rate = (int) caf_audio_format.mSampleRate; if (!(caf_audio_format.mFormatFlags & CAF_FORMAT_LITTLE_ENDIAN) && config->bytes_per_sample > 1) config->qmode |= QMODE_BIG_ENDIAN; if (config->bytes_per_sample == 1) config->qmode |= QMODE_SIGNED_BYTES; if (debug_logging_mode) { if (config->float_norm_exp == 127) error_line ("data format: 32-bit %s-endian floating point", (config->qmode & QMODE_BIG_ENDIAN) ? "big" : "little"); else error_line ("data format: %d-bit %s-endian integers stored in %d byte(s)", config->bits_per_sample, (config->qmode & QMODE_BIG_ENDIAN) ? "big" : "little", config->bytes_per_sample); } } else if (!strncmp (caf_chunk_header.mChunkType, "chan", 4)) { CAFChannelLayout *caf_channel_layout; if (caf_chunk_header.mChunkSize < 0 || caf_chunk_header.mChunkSize > 1024 || caf_chunk_header.mChunkSize < sizeof (CAFChannelLayout)) { error_line ("this .CAF file has an invalid 'chan' chunk!"); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("'chan' chunk is %d bytes", (int) caf_chunk_header.mChunkSize); caf_channel_layout = malloc ((size_t) caf_chunk_header.mChunkSize); if (!DoReadFile (infile, caf_channel_layout, (uint32_t) caf_chunk_header.mChunkSize, &bcount) || bcount != caf_chunk_header.mChunkSize) { error_line ("%s is not a valid .CAF file!", infilename); free (caf_channel_layout); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, caf_channel_layout, (uint32_t) caf_chunk_header.mChunkSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (caf_channel_layout); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (caf_channel_layout, CAFChannelLayoutFormat); chan_chunk = 1; if (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED)) { error_line ("this CAF file already has channel order information!"); free (caf_channel_layout); return WAVPACK_SOFT_ERROR; } switch (caf_channel_layout->mChannelLayoutTag) { case kCAFChannelLayoutTag_UseChannelDescriptions: { CAFChannelDescription *descriptions = (CAFChannelDescription *) (caf_channel_layout + 1); int num_descriptions = caf_channel_layout->mNumberChannelDescriptions; int label, cindex = 0, idents = 0; if (caf_chunk_header.mChunkSize != sizeof (CAFChannelLayout) + sizeof (CAFChannelDescription) * num_descriptions || num_descriptions != config->num_channels) { error_line ("channel descriptions in 'chan' chunk are the wrong size!"); free (caf_channel_layout); return WAVPACK_SOFT_ERROR; } if (num_descriptions >= 256) { error_line ("%d channel descriptions is more than we can handle...ignoring!"); break; } // we allocate (and initialize to invalid values) a channel reorder array // (even though we might not end up doing any reordering) and a string for // any non-Microsoft channels we encounter channel_reorder = malloc (num_descriptions); memset (channel_reorder, -1, num_descriptions); channel_identities = malloc (num_descriptions+1); // convert the descriptions array to our native endian so it's easy to access for (i = 0; i < num_descriptions; ++i) { WavpackBigEndianToNative (descriptions + i, CAFChannelDescriptionFormat); if (debug_logging_mode) error_line ("chan %d --> %d", i + 1, descriptions [i].mChannelLabel); } // first, we go though and find any MS channels present, and move those to the beginning for (label = 1; label <= 18; ++label) for (i = 0; i < num_descriptions; ++i) if (descriptions [i].mChannelLabel == label) { config->channel_mask |= 1 << (label - 1); channel_reorder [i] = cindex++; break; } // next, we go though the channels again assigning any we haven't done for (i = 0; i < num_descriptions; ++i) if (channel_reorder [i] == (unsigned char) -1) { uint32_t clabel = descriptions [i].mChannelLabel; if (clabel == 0 || clabel == 0xffffffff || clabel == 100) channel_identities [idents++] = 0xff; else if ((clabel >= 33 && clabel <= 44) || (clabel >= 200 && clabel <= 207) || (clabel >= 301 && clabel <= 305)) channel_identities [idents++] = clabel >= 301 ? clabel - 80 : clabel; else { error_line ("warning: unknown channel descriptions label: %d", clabel); channel_identities [idents++] = 0xff; } channel_reorder [i] = cindex++; } // then, go through the reordering array and see if we really have to reorder for (i = 0; i < num_descriptions; ++i) if (channel_reorder [i] != i) break; if (i == num_descriptions) { free (channel_reorder); // no reordering required, so don't channel_reorder = NULL; } else { config->qmode |= QMODE_REORDERED_CHANS; // reordering required, put channel count into layout channel_layout = num_descriptions; } if (!idents) { // if no non-MS channels, free the identities string free (channel_identities); channel_identities = NULL; } else channel_identities [idents] = 0; // otherwise NULL terminate it if (debug_logging_mode) { error_line ("layout_tag = 0x%08x, so generated bitmap of 0x%08x from %d descriptions, %d non-MS", caf_channel_layout->mChannelLayoutTag, config->channel_mask, caf_channel_layout->mNumberChannelDescriptions, idents); // if debugging, display the reordering as a string (but only little ones) if (channel_reorder && num_descriptions <= 8) { char reorder_string [] = "12345678"; for (i = 0; i < num_descriptions; ++i) reorder_string [i] = channel_reorder [i] + '1'; reorder_string [i] = 0; error_line ("reordering string = \"%s\"\n", reorder_string); } } } break; case kCAFChannelLayoutTag_UseChannelBitmap: config->channel_mask = caf_channel_layout->mChannelBitmap; if (debug_logging_mode) error_line ("layout_tag = 0x%08x, so using supplied bitmap of 0x%08x", caf_channel_layout->mChannelLayoutTag, caf_channel_layout->mChannelBitmap); break; default: for (i = 0; i < NUM_LAYOUTS; ++i) if (caf_channel_layout->mChannelLayoutTag == layouts [i].mChannelLayoutTag) { config->channel_mask = layouts [i].mChannelBitmap; channel_layout = layouts [i].mChannelLayoutTag; if (layouts [i].mChannelReorder) { channel_reorder = (unsigned char *) strdup (layouts [i].mChannelReorder); config->qmode |= QMODE_REORDERED_CHANS; } if (layouts [i].mChannelIdentities) channel_identities = (unsigned char *) strdup (layouts [i].mChannelIdentities); if (debug_logging_mode) error_line ("layout_tag 0x%08x found in table, bitmap = 0x%08x, reorder = %s, identities = %s", channel_layout, config->channel_mask, channel_reorder ? "yes" : "no", channel_identities ? "yes" : "no"); break; } if (i == NUM_LAYOUTS && debug_logging_mode) error_line ("layout_tag 0x%08x not found in table...all channels unassigned", caf_channel_layout->mChannelLayoutTag); break; } free (caf_channel_layout); } else if (!strncmp (caf_chunk_header.mChunkType, "data", 4)) { // on the data chunk, get size and exit loop uint32_t mEditCount; if (!desc_chunk || !DoReadFile (infile, &mEditCount, sizeof (mEditCount), &bcount) || bcount != sizeof (mEditCount)) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &mEditCount, sizeof (mEditCount))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } if ((config->qmode & QMODE_IGNORE_LENGTH) || caf_chunk_header.mChunkSize == -1) { config->qmode |= QMODE_IGNORE_LENGTH; if (infilesize && DoGetFilePosition (infile) != -1) total_samples = (infilesize - DoGetFilePosition (infile)) / caf_audio_format.mBytesPerPacket; else total_samples = -1; } else { if (infilesize && infilesize - caf_chunk_header.mChunkSize > 16777216) { error_line (".CAF file %s has over 16 MB of extra CAFF data, probably is corrupt!", infilename); return WAVPACK_SOFT_ERROR; } if ((caf_chunk_header.mChunkSize - 4) % caf_audio_format.mBytesPerPacket) { error_line (".CAF file %s has an invalid data chunk size, probably is corrupt!", infilename); return WAVPACK_SOFT_ERROR; } total_samples = (caf_chunk_header.mChunkSize - 4) / caf_audio_format.mBytesPerPacket; if (!total_samples) { error_line ("this .CAF file has no audio samples, probably is corrupt!"); return WAVPACK_SOFT_ERROR; } if (total_samples > MAX_WAVPACK_SAMPLES) { error_line ("%s has too many samples for WavPack!", infilename); return WAVPACK_SOFT_ERROR; } } break; } else { // just copy unknown chunks to output file uint32_t bytes_to_copy = (uint32_t) caf_chunk_header.mChunkSize; char *buff; if (caf_chunk_header.mChunkSize < 0 || caf_chunk_header.mChunkSize > 1048576) { error_line ("%s is not a valid .CAF file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", caf_chunk_header.mChunkType [0], caf_chunk_header.mChunkType [1], caf_chunk_header.mChunkType [2], caf_chunk_header.mChunkType [3], caf_chunk_header.mChunkSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (!chan_chunk && !config->channel_mask && config->num_channels <= 2 && !(config->qmode & QMODE_CHANS_UNASSIGNED)) config->channel_mask = 0x5 - config->num_channels; if (!WavpackSetConfiguration64 (wpc, config, total_samples, channel_identities)) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } if (channel_identities) free (channel_identities); if (channel_layout || channel_reorder) { if (!WavpackSetChannelLayout (wpc, channel_layout, channel_reorder)) { error_line ("problem with setting channel layout (should not happen)"); return WAVPACK_SOFT_ERROR; } if (channel_reorder) free (channel_reorder); } return WAVPACK_NO_ERROR; } int WriteCaffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { CAFChunkHeader caf_desc_chunk_header, caf_chan_chunk_header, caf_data_chunk_header; CAFChannelLayout caf_channel_layout; CAFAudioFormat caf_audio_format; CAFFileHeader caf_file_header; uint32_t mEditCount, bcount; int num_channels = WavpackGetNumChannels (wpc); int32_t channel_mask = WavpackGetChannelMask (wpc); int32_t sample_rate = WavpackGetSampleRate (wpc); int bytes_per_sample = WavpackGetBytesPerSample (wpc); int bits_per_sample = WavpackGetBitsPerSample (wpc); int float_norm_exp = WavpackGetFloatNormExp (wpc); uint32_t channel_layout_tag = WavpackGetChannelLayout (wpc, NULL); unsigned char *channel_identities = malloc (num_channels + 1); int num_identified_chans, i; if (float_norm_exp && float_norm_exp != 127) { error_line ("can't create valid CAFF header for non-normalized floating data!"); free (channel_identities); return FALSE; } // get the channel identities (including Microsoft) and count up the defined ones WavpackGetChannelIdentities (wpc, channel_identities); for (num_identified_chans = i = 0; i < num_channels; ++i) if (channel_identities [i] != 0xff) num_identified_chans++; // format and write the CAF File Header strncpy (caf_file_header.mFileType, "caff", sizeof (caf_file_header.mFileType)); caf_file_header.mFileVersion = 1; caf_file_header.mFileFlags = 0; WavpackNativeToBigEndian (&caf_file_header, CAFFileHeaderFormat); if (!DoWriteFile (outfile, &caf_file_header, sizeof (caf_file_header), &bcount) || bcount != sizeof (caf_file_header)) return FALSE; // format and write the Audio Description Chunk strncpy (caf_desc_chunk_header.mChunkType, "desc", sizeof (caf_desc_chunk_header.mChunkType)); caf_desc_chunk_header.mChunkSize = sizeof (caf_audio_format); WavpackNativeToBigEndian (&caf_desc_chunk_header, CAFChunkHeaderFormat); if (!DoWriteFile (outfile, &caf_desc_chunk_header, sizeof (caf_desc_chunk_header), &bcount) || bcount != sizeof (caf_desc_chunk_header)) return FALSE; caf_audio_format.mSampleRate = (double) sample_rate; strncpy (caf_audio_format.mFormatID, "lpcm", sizeof (caf_audio_format.mFormatID)); caf_audio_format.mFormatFlags = float_norm_exp ? CAF_FORMAT_FLOAT : 0; if (!(qmode & QMODE_BIG_ENDIAN)) caf_audio_format.mFormatFlags |= CAF_FORMAT_LITTLE_ENDIAN; caf_audio_format.mBytesPerPacket = bytes_per_sample * num_channels; caf_audio_format.mFramesPerPacket = 1; caf_audio_format.mChannelsPerFrame = num_channels; caf_audio_format.mBitsPerChannel = bits_per_sample; WavpackNativeToBigEndian (&caf_audio_format, CAFAudioFormatFormat); if (!DoWriteFile (outfile, &caf_audio_format, sizeof (caf_audio_format), &bcount) || bcount != sizeof (caf_audio_format)) return FALSE; // we write the Channel Layout Chunk if any of these are true: // 1. a specific CAF layout was specified (100 - 147) // 2. there are more than 2 channels and ANY are defined // 3. there are 1 or 2 channels and NOT regular mono/stereo if (channel_layout_tag || (num_channels > 2 ? num_identified_chans : channel_mask != 5 - num_channels)) { int bits = 0, bmask; for (bmask = 1; bmask; bmask <<= 1) // count the set bits in the channel mask if (bmask & channel_mask) ++bits; // we use a layout tag if there is a specific CAF layout (100 - 147) or // all the channels are MS defined and in MS order...otherwise we have to // write a full channel description array if ((channel_layout_tag & 0xff0000) || (bits == num_channels && !(qmode & QMODE_REORDERED_CHANS))) { strncpy (caf_chan_chunk_header.mChunkType, "chan", sizeof (caf_chan_chunk_header.mChunkType)); caf_chan_chunk_header.mChunkSize = sizeof (caf_channel_layout); WavpackNativeToBigEndian (&caf_chan_chunk_header, CAFChunkHeaderFormat); if (!DoWriteFile (outfile, &caf_chan_chunk_header, sizeof (caf_chan_chunk_header), &bcount) || bcount != sizeof (caf_chan_chunk_header)) return FALSE; if (channel_layout_tag) { if (debug_logging_mode) error_line ("writing \"chan\" chunk with layout tag 0x%08x", channel_layout_tag); caf_channel_layout.mChannelLayoutTag = channel_layout_tag; caf_channel_layout.mChannelBitmap = 0; } else { if (debug_logging_mode) error_line ("writing \"chan\" chunk with UseChannelBitmap tag, bitmap = 0x%08x", channel_mask); caf_channel_layout.mChannelLayoutTag = kCAFChannelLayoutTag_UseChannelBitmap; caf_channel_layout.mChannelBitmap = channel_mask; } caf_channel_layout.mNumberChannelDescriptions = 0; WavpackNativeToBigEndian (&caf_channel_layout, CAFChannelLayoutFormat); if (!DoWriteFile (outfile, &caf_channel_layout, sizeof (caf_channel_layout), &bcount) || bcount != sizeof (caf_channel_layout)) return FALSE; } else { // write a channel description array because a single layout or bitmap won't do it... CAFChannelDescription caf_channel_description; unsigned char *new_channel_order = NULL; int i; if (debug_logging_mode) error_line ("writing \"chan\" chunk with UseChannelDescriptions tag, bitmap = 0x%08x, reordered = %s", channel_mask, (qmode & QMODE_REORDERED_CHANS) ? "yes" : "no"); if (qmode & QMODE_REORDERED_CHANS) { if ((int)(channel_layout_tag & 0xff) <= num_channels) { new_channel_order = malloc (num_channels); for (i = 0; i < num_channels; ++i) new_channel_order [i] = i; WavpackGetChannelLayout (wpc, new_channel_order); } } strncpy (caf_chan_chunk_header.mChunkType, "chan", sizeof (caf_chan_chunk_header.mChunkType)); caf_chan_chunk_header.mChunkSize = sizeof (caf_channel_layout) + sizeof (caf_channel_description) * num_channels; WavpackNativeToBigEndian (&caf_chan_chunk_header, CAFChunkHeaderFormat); if (!DoWriteFile (outfile, &caf_chan_chunk_header, sizeof (caf_chan_chunk_header), &bcount) || bcount != sizeof (caf_chan_chunk_header)) return FALSE; caf_channel_layout.mChannelLayoutTag = kCAFChannelLayoutTag_UseChannelDescriptions; caf_channel_layout.mChannelBitmap = 0; caf_channel_layout.mNumberChannelDescriptions = num_channels; WavpackNativeToBigEndian (&caf_channel_layout, CAFChannelLayoutFormat); if (!DoWriteFile (outfile, &caf_channel_layout, sizeof (caf_channel_layout), &bcount) || bcount != sizeof (caf_channel_layout)) return FALSE; for (i = 0; i < num_channels; ++i) { unsigned char chan_id = new_channel_order ? channel_identities [new_channel_order [i]] : channel_identities [i]; CLEAR (caf_channel_description); if ((chan_id >= 1 && chan_id <= 18) || (chan_id >= 33 && chan_id <= 44) || (chan_id >= 200 && chan_id <= 207)) caf_channel_description.mChannelLabel = chan_id; else if (chan_id >= 221 && chan_id <= 225) caf_channel_description.mChannelLabel = chan_id + 80; if (debug_logging_mode) error_line ("chan %d --> %d", i + 1, caf_channel_description.mChannelLabel); WavpackNativeToBigEndian (&caf_channel_description, CAFChannelDescriptionFormat); if (!DoWriteFile (outfile, &caf_channel_description, sizeof (caf_channel_description), &bcount) || bcount != sizeof (caf_channel_description)) return FALSE; } if (new_channel_order) free (new_channel_order); } } // format and write the Audio Data Chunk strncpy (caf_data_chunk_header.mChunkType, "data", sizeof (caf_data_chunk_header.mChunkType)); if (total_samples == -1) caf_data_chunk_header.mChunkSize = -1; else caf_data_chunk_header.mChunkSize = (total_samples * bytes_per_sample * num_channels) + sizeof (mEditCount); WavpackNativeToBigEndian (&caf_data_chunk_header, CAFChunkHeaderFormat); if (!DoWriteFile (outfile, &caf_data_chunk_header, sizeof (caf_data_chunk_header), &bcount) || bcount != sizeof (caf_data_chunk_header)) return FALSE; mEditCount = 0; WavpackNativeToBigEndian (&mEditCount, "L"); if (!DoWriteFile (outfile, &mEditCount, sizeof (mEditCount), &bcount) || bcount != sizeof (mEditCount)) return FALSE; free (channel_identities); return TRUE; }
./CrossVul/dataset_final_sorted/CWE-665/c/good_738_0
crossvul-cpp_data_good_3092_0
/* * * (C) 2013-17 - ntop.org * * * 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, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include "ntop_includes.h" #ifndef _GETOPT_H #define _GETOPT_H #endif #ifndef LIB_VERSION #define LIB_VERSION "1.4.7" #endif extern "C" { #include "rrd.h" #ifdef HAVE_GEOIP extern const char * GeoIP_lib_version(void); #endif #include "../third-party/snmp/snmp.c" #include "../third-party/snmp/asn1.c" #include "../third-party/snmp/net.c" }; #include "../third-party/lsqlite3/lsqlite3.c" struct keyval string_to_replace[MAX_NUM_HTTP_REPLACEMENTS] = { { NULL, NULL } }; /* ******************************* */ Lua::Lua() { L = luaL_newstate(); if(L == NULL) { ntop->getTrace()->traceEvent(TRACE_ERROR, "Unable to create Lua interpreter"); return; } } /* ******************************* */ Lua::~Lua() { if(L) lua_close(L); } /* ******************************* */ /** * @brief Check the expected type of lua function. * @details Find in the lua stack the function and check the function parameters types. * * @param vm The lua state. * @param func The function name. * @param pos Index of lua stack. * @param expected_type Index of expected type. * @return @ref CONST_LUA_ERROR if the expected type is equal to function type, @ref CONST_LUA_PARAM_ERROR otherwise. */ int ntop_lua_check(lua_State* vm, const char* func, int pos, int expected_type) { if(lua_type(vm, pos) != expected_type) { ntop->getTrace()->traceEvent(TRACE_ERROR, "%s : expected %s, got %s", func, lua_typename(vm, expected_type), lua_typename(vm, lua_type(vm,pos))); return(CONST_LUA_PARAM_ERROR); } return(CONST_LUA_ERROR); } /* ****************************************** */ static NetworkInterface* handle_null_interface(lua_State* vm) { char allowed_ifname[MAX_INTERFACE_NAME_LEN]; ntop->getTrace()->traceEvent(TRACE_INFO, "NULL interface: did you restart ntopng in the meantime?"); if(ntop->getInterfaceAllowed(vm, allowed_ifname)) { return ntop->getNetworkInterface(allowed_ifname); } return(ntop->getInterfaceAtId(0)); } /* ****************************************** */ static int ntop_dump_file(lua_State* vm) { char *fname; FILE *fd; struct mg_connection *conn; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_getglobal(vm, CONST_HTTP_CONN); if((conn = (struct mg_connection*)lua_touserdata(vm, lua_gettop(vm))) == NULL) { ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: null HTTP connection"); return(CONST_LUA_ERROR); } if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((fname = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); ntop->fixPath(fname); if((fd = fopen(fname, "r")) != NULL) { char tmp[1024]; ntop->getTrace()->traceEvent(TRACE_INFO, "[HTTP] Serving file %s", fname); while((fgets(tmp, sizeof(tmp)-256 /* To make sure we have room for replacements */, fd)) != NULL) { for(int i=0; string_to_replace[i].key != NULL; i++) Utils::replacestr(tmp, string_to_replace[i].key, string_to_replace[i].val); mg_printf(conn, "%s", tmp); } fclose(fd); return(CONST_LUA_OK); } else { ntop->getTrace()->traceEvent(TRACE_INFO, "Unable to read file %s", fname); return(CONST_LUA_ERROR); } } /* ****************************************** */ /** * @brief Get default interface name. * @details Push the default interface name of ntop into the lua stack. * * @param vm The lua state. * @return @ref CONST_LUA_OK. */ static int ntop_get_default_interface_name(lua_State* vm) { char ifname[MAX_INTERFACE_NAME_LEN]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop->getInterfaceAllowed(vm, ifname)) { // if there is an allowed interface for the user // we return that interface lua_pushstring(vm, ntop->getNetworkInterface(ifname)->get_name()); } else { lua_pushstring(vm, ntop->getInterfaceAtId(NULL, /* no need to check as there is no constaint */ 0)->get_name()); } return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Set the name of active interface id into lua stack. * * @param vm The lua stack. * @return @ref CONST_LUA_OK. */ static int ntop_set_active_interface_id(lua_State* vm) { NetworkInterface *iface; int id; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); id = (u_int32_t)lua_tonumber(vm, 1); iface = ntop->getNetworkInterface(vm, id); ntop->getTrace()->traceEvent(TRACE_INFO, "Index: %d, Name: %s", id, iface ? iface->get_name() : "<unknown>"); if(iface != NULL) lua_pushstring(vm, iface->get_name()); else lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the ntopng interface names. * * @param vm The lua state. * @return @ref CONST_LUA_OK. */ static int ntop_get_interface_names(lua_State* vm) { lua_newtable(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); for(int i=0; i<ntop->get_num_interfaces(); i++) { NetworkInterface *iface; if((iface = ntop->getInterfaceAtId(vm, i)) != NULL) { char num[8]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "Returning name %s", iface->get_name()); snprintf(num, sizeof(num), "%d", i); lua_push_str_table_entry(vm, num, iface->get_name()); } } return(CONST_LUA_OK); } /* ****************************************** */ static AddressTree* get_allowed_nets(lua_State* vm) { AddressTree *ptree; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_getglobal(vm, CONST_ALLOWED_NETS); ptree = (AddressTree*)lua_touserdata(vm, lua_gettop(vm)); //ntop->getTrace()->traceEvent(TRACE_WARNING, "GET %p", ptree); return(ptree); } /* ****************************************** */ static NetworkInterface* getCurrentInterface(lua_State* vm) { NetworkInterface *ntop_interface; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_getglobal(vm, "ntop_interface"); if((ntop_interface = (NetworkInterface*)lua_touserdata(vm, lua_gettop(vm))) == NULL) { ntop_interface = handle_null_interface(vm); } return(ntop_interface); } /* ****************************************** */ /** * @brief Find the network interface and set it as global variable to lua. * * @param vm The lua state. * @return @ref CONST_LUA_OK */ static int ntop_select_interface(lua_State* vm) { char *ifname; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TNIL) ifname = (char*)"any"; else { if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); ifname = (char*)lua_tostring(vm, 1); } lua_pushlightuserdata(vm, (char*)ntop->getNetworkInterface(vm, ifname)); lua_setglobal(vm, "ntop_interface"); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the nDPI statistics of interface. * @details Get the ntop interface global variable of lua, get nDpistats of interface and push it into lua stack. * * @param vm The lua state. * @return @ref CONST_LUA_OK */ static int ntop_get_ndpi_interface_stats(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); nDPIStats stats; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) { ntop_interface->getnDPIStats(&stats); lua_newtable(vm); stats.lua(ntop_interface, vm); } return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the ndpi flows count of interface. * @details Get the ntop interface global variable of lua, get nDpi flow count of interface and push it into lua stack. * * @param vm The lua state. * @return @ref CONST_LUA_OK */ static int ntop_get_ndpi_interface_flows_count(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) { lua_newtable(vm); ntop_interface->getnDPIFlowsCount(vm); } return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the flow status for flows in cache * @details Get the ntop interface global variable of lua, get flow stats of interface and push it into lua stack. * * @param vm The lua state. * @return @ref CONST_LUA_OK */ static int ntop_get_ndpi_interface_flows_status(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) { lua_newtable(vm); ntop_interface->getFlowsStatus(vm); } return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the ndpi protocol name of protocol id of network interface. * @details Get the ntop interface global variable of lua. Once do that, get the protocol id of lua stack and return into lua stack "Host-to-Host Contact" if protocol id is equal to host family id; the protocol name or null otherwise. * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise. */ static int ntop_get_ndpi_protocol_name(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); nDPIStats stats; int proto; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); proto = (u_int32_t)lua_tonumber(vm, 1); if(proto == HOST_FAMILY_ID) lua_pushstring(vm, "Host-to-Host Contact"); else { if(ntop_interface) lua_pushstring(vm, ntop_interface->get_ndpi_proto_name(proto)); else lua_pushnil(vm); } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_ndpi_protocol_id(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); nDPIStats stats; char *proto; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); proto = (char*)lua_tostring(vm, 1); if(ntop_interface && proto) lua_pushnumber(vm, ntop_interface->get_ndpi_proto_id(proto)); else lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_ndpi_protocol_category(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); u_int proto; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); proto = (u_int)lua_tonumber(vm, 1); if(ntop_interface) { ndpi_protocol_category_t category = ntop_interface->get_ndpi_proto_category(proto); lua_newtable(vm); lua_push_int32_table_entry(vm, "id", category); lua_push_str_table_entry(vm, "name", (char*)ndpi_category_str(category)); } else lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Same as ntop_get_ndpi_protocol_name() with the exception that the protocol breed is returned * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise. */ static int ntop_get_ndpi_protocol_breed(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); nDPIStats stats; int proto; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); proto = (u_int32_t)lua_tonumber(vm, 1); if(proto == HOST_FAMILY_ID) lua_pushstring(vm, "Unrated-to-Host Contact"); else { if(ntop_interface) lua_pushstring(vm, ntop_interface->get_ndpi_proto_breed_name(proto)); else lua_pushnil(vm); } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_hosts(lua_State* vm, LocationPolicy location) { NetworkInterface *ntop_interface = getCurrentInterface(vm); bool show_details = true; char *sortColumn = (char*)"column_ip", *country = NULL, *os_filter = NULL, *mac_filter = NULL; bool a2zSortOrder = true; u_int16_t vlan_filter, *vlan_filter_ptr = NULL; u_int32_t asn_filter, *asn_filter_ptr = NULL; int16_t network_filter, *network_filter_ptr = NULL; u_int32_t toSkip = 0, maxHits = CONST_MAX_NUM_HITS; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TBOOLEAN) show_details = lua_toboolean(vm, 1) ? true : false; if(lua_type(vm, 2) == LUA_TSTRING) sortColumn = (char*)lua_tostring(vm, 2); if(lua_type(vm, 3) == LUA_TNUMBER) maxHits = (u_int16_t)lua_tonumber(vm, 3); if(lua_type(vm, 4) == LUA_TNUMBER) toSkip = (u_int16_t)lua_tonumber(vm, 4); if(lua_type(vm, 5) == LUA_TBOOLEAN) a2zSortOrder = lua_toboolean(vm, 5) ? true : false; if(lua_type(vm, 6) == LUA_TSTRING) country = (char*)lua_tostring(vm, 6); if(lua_type(vm, 7) == LUA_TSTRING) os_filter = (char*)lua_tostring(vm, 7); if(lua_type(vm, 8) == LUA_TNUMBER) vlan_filter = (u_int16_t)lua_tonumber(vm, 8), vlan_filter_ptr = &vlan_filter; if(lua_type(vm, 9) == LUA_TNUMBER) asn_filter = (u_int32_t)lua_tonumber(vm, 9), asn_filter_ptr = &asn_filter; if(lua_type(vm,10) == LUA_TNUMBER) network_filter = (int16_t)lua_tonumber(vm, 10), network_filter_ptr = &network_filter; if(lua_type(vm,11) == LUA_TSTRING) mac_filter = (char*)lua_tostring(vm, 11); if(!ntop_interface || ntop_interface->getActiveHostsList(vm, get_allowed_nets(vm), show_details, location, country, mac_filter, vlan_filter_ptr, os_filter, asn_filter_ptr, network_filter_ptr, sortColumn, maxHits, toSkip, a2zSortOrder) < 0) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_latest_activity_hosts_info(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->getLatestActivityHostsList(vm, get_allowed_nets(vm)); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the host information of network interface grouped according to the criteria. * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null or the host is null, CONST_LUA_OK otherwise. */ static int ntop_get_grouped_interface_hosts(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); bool show_details = true, hostsOnly = true; char *country = NULL, *os_filter = NULL; char *groupBy = (char*)"column_ip"; u_int16_t vlan_filter, *vlan_filter_ptr = NULL; u_int32_t asn_filter, *asn_filter_ptr = NULL; int16_t network_filter, *network_filter_ptr = NULL; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TBOOLEAN) show_details = lua_toboolean(vm, 1) ? true : false; if(lua_type(vm, 2) == LUA_TSTRING) groupBy = (char*)lua_tostring(vm, 2); if(lua_type(vm, 3) == LUA_TSTRING) country = (char*)lua_tostring(vm, 3); if(lua_type(vm, 4) == LUA_TSTRING) os_filter = (char*)lua_tostring(vm, 4); if(lua_type(vm, 5) == LUA_TNUMBER) vlan_filter = (u_int16_t)lua_tonumber(vm, 5), vlan_filter_ptr = &vlan_filter; if(lua_type(vm, 6) == LUA_TNUMBER) asn_filter = (u_int32_t)lua_tonumber(vm, 6), asn_filter_ptr = &asn_filter; if(lua_type(vm, 7) == LUA_TNUMBER) network_filter = (int16_t)lua_tonumber(vm, 7), network_filter_ptr = &network_filter; if(lua_type(vm, 8) == LUA_TBOOLEAN) hostsOnly = lua_toboolean(vm, 8) ? true : false; if((!ntop_interface) || ntop_interface->getActiveHostsGroup(vm, get_allowed_nets(vm), show_details, location_all, country, vlan_filter_ptr, os_filter, asn_filter_ptr, network_filter_ptr, hostsOnly, groupBy) < 0) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the hosts information of network interface. * @details Get the ntop interface global variable of lua and return into lua stack a new hash table of hash tables containing the host information. * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise. */ static int ntop_get_interface_hosts_info(lua_State* vm) { return(ntop_get_interface_hosts(vm, location_all)); } /* ****************************************** */ static int ntop_get_interface_macs_info(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *sortColumn = (char*)"column_mac"; u_int32_t toSkip = 0, maxHits = CONST_MAX_NUM_HITS; u_int16_t vlan_id = 0; bool a2zSortOrder = true, skipSpecialMacs = false, hostMacsOnly = false; if(lua_type(vm, 1) == LUA_TSTRING) { sortColumn = (char*)lua_tostring(vm, 1); if(lua_type(vm, 2) == LUA_TNUMBER) { maxHits = (u_int16_t)lua_tonumber(vm, 2); if(lua_type(vm, 3) == LUA_TNUMBER) { toSkip = (u_int16_t)lua_tonumber(vm, 3); if(lua_type(vm, 4) == LUA_TBOOLEAN) { a2zSortOrder = lua_toboolean(vm, 4) ? true : false; if(lua_type(vm, 5) == LUA_TNUMBER) { vlan_id = (u_int16_t)lua_tonumber(vm, 5); if(lua_type(vm, 6) == LUA_TBOOLEAN) { skipSpecialMacs = lua_toboolean(vm, 6) ? true : false; } if(lua_type(vm, 7) == LUA_TBOOLEAN) { hostMacsOnly = lua_toboolean(vm, 7) ? true : false; } } } } } } if(!ntop_interface || ntop_interface->getActiveMacList(vm, vlan_id, skipSpecialMacs, hostMacsOnly, sortColumn, maxHits, toSkip, a2zSortOrder) < 0) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_mac_info(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *mac = NULL; u_int16_t vlan_id = 0; if(lua_type(vm, 1) == LUA_TSTRING) { mac = (char*)lua_tostring(vm, 1); if(lua_type(vm, 2) == LUA_TNUMBER) { vlan_id = (u_int16_t)lua_tonumber(vm, 2); } } if((!ntop_interface) || (!mac) || (!ntop_interface->getMacInfo(vm, mac, vlan_id))) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get local hosts information of network interface. * @details Get the ntop interface global variable of lua and return into lua stack a new hash table of hash tables containing the local host information. * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise. */ static int ntop_get_interface_local_hosts_info(lua_State* vm) { return(ntop_get_interface_hosts(vm, location_local_only)); } /* ****************************************** */ /** * @brief Get remote hosts information of network interface. * @details Get the ntop interface global variable of lua and return into lua stack a new hash table of hash tables containing the remote host information. * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise. */ static int ntop_get_interface_remote_hosts_info(lua_State* vm) { return(ntop_get_interface_hosts(vm, location_remote_only)); } /* ****************************************** */ /** * @brief Get local hosts activity information. * @details Get the ntop interface global variable of lua and return into lua stack a new hash table of hash tables containing the local host activities. * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null or host is null, CONST_LUA_OK otherwise. */ static int ntop_get_interface_host_activity(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); const char * host = NULL; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if (lua_type(vm, 1) == LUA_TSTRING) host = lua_tostring(vm, 1); if (ntop_interface == NULL || host == NULL) return CONST_LUA_ERROR; ntop_interface->getLocalHostActivity(vm, host); return CONST_LUA_OK; } /* ****************************************** */ /** * @brief Check if the specified path is a directory and it exists. * @details True if if the specified path is a directory and it exists, false otherwise. * * @param vm The lua state. * @return CONST_LUA_OK */ static int ntop_is_dir(lua_State* vm) { char *path; struct stat buf; int rc; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); path = (char*)lua_tostring(vm, 1); rc = ((stat(path, &buf) != 0) || (!S_ISDIR(buf.st_mode))) ? 0 : 1; lua_pushboolean(vm, rc); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Check if the file is exists and is not empty * @details Simple check for existance + non empty file * * @param vm The lua state. * @return CONST_LUA_OK */ static int ntop_is_not_empty_file(lua_State* vm) { char *path; struct stat buf; int rc; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); path = (char*)lua_tostring(vm, 1); rc = (stat(path, &buf) != 0) ? 0 : 1; if(rc && (buf.st_size == 0)) rc = 0; lua_pushboolean(vm, rc); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Check if the file or directory exists. * @details Get the path of file/directory from to lua stack and push true into lua stack if it exists, false otherwise. * * @param vm The lua state. * @return CONST_LUA_OK */ static int ntop_get_file_dir_exists(lua_State* vm) { char *path; struct stat buf; int rc; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); path = (char*)lua_tostring(vm, 1); rc = (stat(path, &buf) != 0) ? 0 : 1; // ntop->getTrace()->traceEvent(TRACE_ERROR, "%s: %d", path, rc); lua_pushboolean(vm, rc); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Return the epoch of the file last change * @details This function return that time (epoch) of the last chnge on a file, or -1 if the file does not exist. * * @param vm The lua state. * @return CONST_LUA_OK */ static int ntop_get_file_last_change(lua_State* vm) { char *path; struct stat buf; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); path = (char*)lua_tostring(vm, 1); if(stat(path, &buf) == 0) lua_pushnumber(vm, (lua_Number)buf.st_mtime); else lua_pushnumber(vm, -1); /* not found */ return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Check if ntop has seen VLAN tagged packets on this interface. * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_has_vlans(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) lua_pushboolean(vm, ntop_interface->hasSeenVlanTaggedPackets()); else lua_pushboolean(vm, 0); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Check if ntop has loaded ASN information (via GeoIP) * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_has_geoip(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_pushboolean(vm, ntop->getGeolocation() ? 1 : 0); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Check if ntop is running on windows. * @details Push into lua stack 1 if ntop is running on windows, 0 otherwise. * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_is_windows(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_pushboolean(vm, #ifdef WIN32 1 #else 0 #endif ); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_allocHostBlacklist(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); ntop->allocHostBlacklist(); lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_swapHostBlacklist(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); ntop->swapHostBlacklist(); lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_addToHostBlacklist(lua_State* vm) { char *net; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); net = (char*)lua_tostring(vm, 1); ntop->addToHostBlacklist(net); lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Wrapper for the libc call getservbyport() * @details Wrapper for the libc call getservbyport() * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_getservbyport(lua_State* vm) { int port; char *proto; struct servent *s = NULL; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); port = (int)lua_tonumber(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); proto = (char*)lua_tostring(vm, 2); if((port > 0) && (proto != NULL)) s = getservbyport(htons(port), proto); if(s && s->s_name) lua_pushstring(vm, s->s_name); else { char buf[32]; snprintf(buf, sizeof(buf), "%d", port); lua_pushstring(vm, buf); } return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Scan the input directory and return the list of files. * @details Get the path from the lua stack and push into a new hashtable the files name existing in the directory. * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_list_dir_files(lua_State* vm) { char *path; DIR *dirp; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); path = (char*)lua_tostring(vm, 1); ntop->fixPath(path); lua_newtable(vm); if((dirp = opendir(path)) != NULL) { struct dirent *dp; while ((dp = readdir(dirp)) != NULL) if((dp->d_name[0] != '\0') && (dp->d_name[0] != '.')) { lua_push_str_table_entry(vm, dp->d_name, dp->d_name); } (void)closedir(dirp); } return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the system time and push it into the lua stack. * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_gettimemsec(lua_State* vm) { struct timeval tp; double ret; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); gettimeofday(&tp, NULL); ret = (((double)tp.tv_usec) / (double)1000) + tp.tv_sec; lua_pushnumber(vm, ret); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Lua-equivaled ot C inet_ntoa * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_inet_ntoa(lua_State* vm) { u_int32_t ip; struct in_addr in; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TSTRING) ip = atol((char*)lua_tostring(vm, 1)); else if(lua_type(vm, 1) == LUA_TNUMBER) ip = (u_int32_t)lua_tonumber(vm, 1); else return(CONST_LUA_ERROR); in.s_addr = htonl(ip); lua_pushstring(vm, inet_ntoa(in)); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_zmq_connect(lua_State* vm) { char *endpoint, *topic; void *context, *subscriber; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((endpoint = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((topic = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); context = zmq_ctx_new(), subscriber = zmq_socket(context, ZMQ_SUB); if(zmq_connect(subscriber, endpoint) != 0) { zmq_close(subscriber); zmq_ctx_destroy(context); return(CONST_LUA_PARAM_ERROR); } if(zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, topic, strlen(topic)) != 0) { zmq_close(subscriber); zmq_ctx_destroy(context); return -1; } lua_pushlightuserdata(vm, context); lua_setglobal(vm, "zmq_context"); lua_pushlightuserdata(vm, subscriber); lua_setglobal(vm, "zmq_subscriber"); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Delete the specified member(field) from the redis hash stored at key. * @details Get the key parameter from the lua stack and delete it from redis. * * @param vm The lua stack. * @return CONST_LUA_OK. */ static int ntop_delete_redis_key(lua_State* vm) { char *key; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); ntop->getRedis()->delKey(key); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the members of a redis set. * @details Get the set key form the lua stack and push the mambers name into lua stack. * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_get_set_members_redis(lua_State* vm) { char *key; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); ntop->getRedis()->smembers(vm, key); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Delete the specified member(field) from the redis hash stored at key. * @details Get the member name and the hash key form the lua stack and remove the specified member. * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_delete_hash_redis_key(lua_State* vm) { char *key, *member; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((member = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); ntop->getRedis()->hashDel(key, member); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_zmq_disconnect(lua_State* vm) { void *context, *subscriber; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_getglobal(vm, "zmq_context"); if((context = (void*)lua_touserdata(vm, lua_gettop(vm))) == NULL) { ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: NULL context"); return(CONST_LUA_ERROR); } lua_getglobal(vm, "zmq_subscriber"); if((subscriber = (void*)lua_touserdata(vm, lua_gettop(vm))) == NULL) { ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: NULL subscriber"); return(CONST_LUA_ERROR); } zmq_close(subscriber); zmq_ctx_destroy(context); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_zmq_receive(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); void *subscriber; int size; struct zmq_msg_hdr h; char *payload; int payload_len; zmq_pollitem_t item; int rc; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_getglobal(vm, "zmq_subscriber"); if((subscriber = (void*)lua_touserdata(vm, lua_gettop(vm))) == NULL) { ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: NULL subscriber"); return(CONST_LUA_ERROR); } item.socket = subscriber; item.events = ZMQ_POLLIN; do { rc = zmq_poll(&item, 1, 1000); if(rc < 0 || !ntop_interface->isRunning()) /* CHECK */ return(CONST_LUA_PARAM_ERROR); } while (rc == 0); size = zmq_recv(subscriber, &h, sizeof(h), 0); if(size != sizeof(h) || h.version != ZMQ_MSG_VERSION) { ntop->getTrace()->traceEvent(TRACE_WARNING, "Unsupported publisher version [%d]", h.version); return -1; } payload_len = h.size + 1; if((payload = (char*)malloc(payload_len)) != NULL) { size = zmq_recv(subscriber, payload, payload_len, 0); payload[h.size] = '\0'; if(size > 0) { enum json_tokener_error jerr = json_tokener_success; json_object *o = json_tokener_parse_verbose(payload, &jerr); if(o != NULL) { struct json_object_iterator it = json_object_iter_begin(o); struct json_object_iterator itEnd = json_object_iter_end(o); while (!json_object_iter_equal(&it, &itEnd)) { char *key = (char*)json_object_iter_peek_name(&it); const char *value = json_object_get_string(json_object_iter_peek_value(&it)); ntop->getTrace()->traceEvent(TRACE_NORMAL, "[%s]=[%s]", key, value); json_object_iter_next(&it); } json_object_put(o); } else ntop->getTrace()->traceEvent(TRACE_WARNING, "JSON Parse error [%s]: %s", json_tokener_error_desc(jerr), payload); lua_pushfstring(vm, "%s", payload); ntop->getTrace()->traceEvent(TRACE_INFO, "[%u] %s", h.size, payload); free(payload); return(CONST_LUA_OK); } else { free(payload); return(CONST_LUA_PARAM_ERROR); } } else return(CONST_LUA_PARAM_ERROR); } /* ****************************************** */ static int ntop_get_local_networks(lua_State* vm) { lua_newtable(vm); ntop->getLocalNetworks(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_reload_preferences(lua_State* vm) { lua_newtable(vm); ntop->getPrefs()->reloadPrefsFromRedis(); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Check if the trace level of ntop is verbose. * @details Push true into the lua stack if the trace level of ntop is set to MAX_TRACE_LEVEL, false otherwise. * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_verbose_trace(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_pushboolean(vm, (ntop->getTrace()->get_trace_level() == MAX_TRACE_LEVEL) ? true : false); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_send_udp_data(lua_State* vm) { int rc, port, sockfd = ntop->getUdpSock(); char *host, *data; if(sockfd == -1) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); host = (char*)lua_tostring(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); port = (u_int16_t)lua_tonumber(vm, 2); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR); data = (char*)lua_tostring(vm, 3); if(strchr(host, ':') != NULL) { struct sockaddr_in6 server_addr; memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin6_family = AF_INET6; inet_pton(AF_INET6, host, &server_addr.sin6_addr); server_addr.sin6_port = htons(port); rc = sendto(sockfd, data, strlen(data),0, (struct sockaddr *)&server_addr, sizeof(server_addr)); } else { struct sockaddr_in server_addr; memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(host); /* FIX: add IPv6 support */ server_addr.sin_port = htons(port); rc = sendto(sockfd, data, strlen(data),0, (struct sockaddr *)&server_addr, sizeof(server_addr)); } if(rc == -1) return(CONST_LUA_ERROR); else return(CONST_LUA_OK); } /* ****************************************** */ static void get_host_vlan_info(char* lua_ip, char** host_ip, u_int16_t* vlan_id, char *buf, u_int buf_len) { char *where, *vlan = NULL; snprintf(buf, buf_len, "%s", lua_ip); if(((*host_ip) = strtok_r(buf, "@", &where)) != NULL) vlan = strtok_r(NULL, "@", &where); if(vlan) (*vlan_id) = (u_int16_t)atoi(vlan); } /* ****************************************** */ static int ntop_get_interface_flows(lua_State* vm, LocationPolicy location) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char buf[64]; char *host_ip = NULL; u_int16_t vlan_id = 0; Host *host = NULL; Paginator *p = NULL; int numFlows = -1; if(!ntop_interface) return(CONST_LUA_ERROR); if((p = new(std::nothrow) Paginator()) == NULL) return(CONST_LUA_ERROR); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TSTRING) { get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); host = ntop_interface->getHost(host_ip, vlan_id); } if(lua_type(vm, 2) == LUA_TTABLE) p->readOptions(vm, 2); if(ntop_interface) numFlows = ntop_interface->getFlows(vm, get_allowed_nets(vm), location, host, p); if(p) delete p; return numFlows < 0 ? CONST_LUA_ERROR : CONST_LUA_OK; } static int ntop_get_interface_flows_info(lua_State* vm) { return(ntop_get_interface_flows(vm, location_all)); } static int ntop_get_interface_local_flows_info(lua_State* vm) { return(ntop_get_interface_flows(vm, location_local_only)); } static int ntop_get_interface_remote_flows_info(lua_State* vm) { return(ntop_get_interface_flows(vm, location_remote_only)); } /* ****************************************** */ /** * @brief Get nDPI stats for flows * @details Compute nDPI flow statistics * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_get_interface_flows_stats(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) ntop_interface->getFlowsStats(vm); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get interface stats for local networks * @details Returns traffic statistics per local network * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_get_interface_networks_stats(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) ntop_interface->getNetworksStats(vm); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the host information of network interface. * @details Get the ntop interface global variable of lua, the host ip and optional the VLAN id form the lua stack and push a new hash table of hash tables containing the host information into lua stack. * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null or the host is null, CONST_LUA_OK otherwise. */ static int ntop_get_interface_host_info(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((!ntop_interface) || !ntop_interface->getHostInfo(vm, get_allowed_nets(vm), host_ip, vlan_id)) return(CONST_LUA_ERROR); else return(CONST_LUA_OK); } /* ****************************************** */ #ifdef NOTUSED static int ntop_get_grouped_interface_host(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *country_s = NULL, *os_s = NULL; u_int16_t vlan_n, *vlan_ptr = NULL; u_int32_t as_n, *as_ptr = NULL; int16_t network_n, *network_ptr = NULL; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TNUMBER) vlan_n = (u_int16_t)lua_tonumber(vm, 1), vlan_ptr = &vlan_n; if(lua_type(vm, 2) == LUA_TNUMBER) as_n = (u_int32_t)lua_tonumber(vm, 2), as_ptr = &as_n; if(lua_type(vm, 3) == LUA_TNUMBER) network_n = (int16_t)lua_tonumber(vm, 3), network_ptr = &network_n; if(lua_type(vm, 4) == LUA_TSTRING) country_s = (char*)lua_tostring(vm, 4); if(lua_type(vm, 5) == LUA_TSTRING) os_s = (char*)lua_tostring(vm, 5); if(!ntop_interface || ntop_interface->getActiveHostsGroup(vm, get_allowed_nets(vm), false, false, country_s, vlan_ptr, os_s, as_ptr, network_ptr, (char*)"column_ip", (char*)"country", CONST_MAX_NUM_HITS, 0 /* toSkip */, true /* a2zSortOrder */) < 0) return(CONST_LUA_ERROR); else return(CONST_LUA_OK); } #endif /* ****************************************** */ static int ntop_getflowdevices(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); else { ntop_interface->getFlowDevices(vm); return(CONST_LUA_OK); } } /* ****************************************** */ static int ntop_getflowdeviceinfo(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *device_ip; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); device_ip = (char*)lua_tostring(vm, 1); if(!ntop_interface) return(CONST_LUA_ERROR); else { in_addr_t addr = inet_addr(device_ip); ntop_interface->getFlowDeviceInfo(vm, ntohl(addr)); return(CONST_LUA_OK); } } /* ****************************************** */ static int ntop_interface_load_host_alert_prefs(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((!ntop_interface) || !ntop_interface->loadHostAlertPrefs(vm, get_allowed_nets(vm), host_ip, vlan_id)) return(CONST_LUA_ERROR); else return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_host_reset_periodic_stats(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; Host *h; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((!ntop_interface) || ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL)) return(CONST_LUA_ERROR); h->resetPeriodicStats(); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_host_trigger_alerts(lua_State* vm, bool trigger) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; Host *h; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((!ntop_interface) || ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL)) return(CONST_LUA_ERROR); if(trigger) h->enableAlerts(); else h->disableAlerts(); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_host_enable_alerts(lua_State* vm) { return ntop_interface_host_trigger_alerts(vm, true); } /* ****************************************** */ static int ntop_interface_host_disable_alerts(lua_State* vm) { return ntop_interface_host_trigger_alerts(vm, false); } /* ****************************************** */ static int ntop_interface_refresh_num_alerts(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); AlertsManager *am; Host *h; char *host_ip; u_int16_t vlan_id = 0; u_int32_t num_alerts; char buf[128]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if((!ntop_interface)) return(CONST_LUA_ERROR); if(lua_type(vm, 1) == LUA_TSTRING) { get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((h = ntop_interface->getHost(host_ip, vlan_id))) { if(lua_type(vm, 3) == LUA_TNUMBER) { num_alerts = (u_int32_t)lua_tonumber(vm, 3); h->setNumAlerts(num_alerts); } else { h->getNumAlerts(true /* From AlertsManager re-reads the values */); } } } else { if((am = ntop_interface->getAlertsManager()) == NULL) return(CONST_LUA_ERROR); am->refreshCachedNumAlerts(); } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_correalate_host_activity(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((!ntop_interface) || !ntop_interface->correlateHostActivity(vm, get_allowed_nets(vm), host_ip, vlan_id)) return(CONST_LUA_ERROR); else return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_similar_host_activity(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((!ntop_interface) || !ntop_interface->similarHostActivity(vm, get_allowed_nets(vm), host_ip, vlan_id)) return(CONST_LUA_ERROR); else return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_host_activitymap(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; GenericHost *h; u_int16_t vlan_id = 0; char buf[64]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); h = ntop_interface->getHost(host_ip, vlan_id); if(h == NULL) return(CONST_LUA_ERROR); else { if(h->match(get_allowed_nets(vm))) { char *json = h->getJsonActivityMap(); lua_pushfstring(vm, "%s", json); free(json); } return(CONST_LUA_OK); } } /* ****************************************** */ /** * @brief Restore the host of network interface. * @details Get the ntop interface global variable of lua and the IP address of host form the lua stack and restore the host into hash host of network interface. * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null or if is impossible to restore the host, CONST_LUA_OK otherwise. */ static int ntop_restore_interface_host(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; bool skip_privileges_check = false; char buf[64]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* make sure skip privileges check cannot be set from the web interface */ if(lua_type(vm, 2) == LUA_TBOOLEAN) skip_privileges_check = lua_toboolean(vm, 2); if(!skip_privileges_check && !Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if((!ntop_interface) || !ntop_interface->restoreHost(host_ip, vlan_id)) return(CONST_LUA_ERROR); else return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_flows_peers(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_name; u_int16_t vlan_id = 0; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TSTRING) { char buf[64]; get_host_vlan_info((char*)lua_tostring(vm, 1), &host_name, &vlan_id, buf, sizeof(buf)); } else host_name = NULL; /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if(ntop_interface) ntop_interface->getFlowPeersList(vm, get_allowed_nets(vm), host_name, vlan_id); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_flow_key(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); Host *cli, *srv; char *cli_name = NULL; u_int16_t cli_vlan = 0; u_int16_t cli_port = 0; char *srv_name = NULL; u_int16_t srv_vlan = 0; u_int16_t srv_port = 0; u_int16_t protocol; char cli_buf[256], srv_buf[256]; if(!ntop_interface) return(CONST_LUA_ERROR); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING) /* cli_host@cli_vlan */ || ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER) /* cli port */ || ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING) /* srv_host@srv_vlan */ || ntop_lua_check(vm, __FUNCTION__, 4, LUA_TNUMBER) /* srv port */ || ntop_lua_check(vm, __FUNCTION__, 5, LUA_TNUMBER) /* protocol */ ) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &cli_name, &cli_vlan, cli_buf, sizeof(cli_buf)); cli_port = htons((u_int16_t)lua_tonumber(vm, 2)); get_host_vlan_info((char*)lua_tostring(vm, 3), &srv_name, &srv_vlan, srv_buf, sizeof(srv_buf)); srv_port = htons((u_int16_t)lua_tonumber(vm, 4)); protocol = (u_int16_t)lua_tonumber(vm, 5); if(cli_vlan != srv_vlan) { ntop->getTrace()->traceEvent(TRACE_ERROR, "Client and Server vlans don't match."); return(CONST_LUA_ERROR); } if(cli_name == NULL || srv_name == NULL ||(cli = ntop_interface->getHost(cli_name, cli_vlan)) == NULL ||(srv = ntop_interface->getHost(srv_name, srv_vlan)) == NULL) { lua_pushnil(vm); } else { lua_pushnumber(vm, Flow::key(cli, cli_port, srv, srv_port, cli_vlan, protocol)); } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_find_flow_by_key(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); u_int32_t key; Flow *f; AddressTree *ptree = get_allowed_nets(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); key = (u_int32_t)lua_tonumber(vm, 1); if(!ntop_interface) return(false); f = ntop_interface->findFlowByKey(key, ptree); if(f == NULL) return(CONST_LUA_ERROR); else { f->lua(vm, ptree, details_high, false); return(CONST_LUA_OK); } } /* ****************************************** */ static int ntop_drop_flow_traffic(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); u_int32_t key; Flow *f; AddressTree *ptree = get_allowed_nets(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); key = (u_int32_t)lua_tonumber(vm, 1); if(!ntop_interface) return(false); f = ntop_interface->findFlowByKey(key, ptree); if(f == NULL) return(CONST_LUA_ERROR); else { f->setDropVerdict(); return(CONST_LUA_OK); } } /* ****************************************** */ static int ntop_dump_flow_traffic(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); u_int32_t key, what; Flow *f; AddressTree *ptree = get_allowed_nets(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); key = (u_int32_t)lua_tonumber(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); what = (u_int32_t)lua_tonumber(vm, 2); if(!ntop_interface) return(false); f = ntop_interface->findFlowByKey(key, ptree); if(f == NULL) return(CONST_LUA_ERROR); else { f->setDumpFlowTraffic(what ? true : false); return(CONST_LUA_OK); } } /* ****************************************** */ static int ntop_dump_local_hosts_2_redis(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->dumpLocalHosts2redis(true /* must disable purge as we are called from lua */); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_find_user_flows(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *key; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); key = (char*)lua_tostring(vm, 1); if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->findUserFlows(vm, key); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_find_pid_flows(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); u_int32_t pid; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); pid = (u_int32_t)lua_tonumber(vm, 1); if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->findPidFlows(vm, pid); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_find_father_pid_flows(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); u_int32_t father_pid; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); father_pid = (u_int32_t)lua_tonumber(vm, 1); if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->findFatherPidFlows(vm, father_pid); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_find_proc_name_flows(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *proc_name; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); proc_name = (char*)lua_tostring(vm, 1); if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->findProcNameFlows(vm, proc_name); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_list_http_hosts(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *key; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); if(lua_type(vm, 1) != LUA_TSTRING) /* Optional */ key = NULL; else key = (char*)lua_tostring(vm, 1); ntop_interface->listHTTPHosts(vm, key); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_find_host(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *key; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); key = (char*)lua_tostring(vm, 1); if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->findHostsByName(vm, get_allowed_nets(vm), key); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_update_host_traffic_policy(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; Host *h; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((!ntop_interface) || ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL)) return(CONST_LUA_ERROR); h->updateHostTrafficPolicy(host_ip); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_update_host_alert_policy(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; Host *h; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((!ntop_interface) || ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL)) return(CONST_LUA_ERROR); h->readAlertPrefs(); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_set_second_traffic(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->updateSecondTraffic(time(NULL)); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_set_host_dump_policy(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; Host *h; bool dump_traffic_to_disk; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TBOOLEAN)) return(CONST_LUA_ERROR); dump_traffic_to_disk = lua_toboolean(vm, 1) ? true : false; if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 2), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 3) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 3); if((!ntop_interface) || ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL)) return(CONST_LUA_ERROR); h->setDumpTrafficPolicy(dump_traffic_to_disk); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_host_hit_rate(lua_State* vm) { #ifdef NOTUSED NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; Host *h; u_int32_t peer_key; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); peer_key = (u_int32_t)lua_tonumber(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 2), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 3) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 3); if((!ntop_interface) || ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL)) return(CONST_LUA_ERROR); h->getPeerBytes(vm, peer_key); return(CONST_LUA_OK); #else return(CONST_LUA_ERROR); // not supported #endif } /* ****************************************** */ static int ntop_set_host_quota(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; Host *h; u_int32_t quota; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); quota = (u_int32_t)lua_tonumber(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 2), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 3) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 3); if((!ntop_interface) || ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL)) return(CONST_LUA_ERROR); h->setQuota(quota); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_dump_tap_policy(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); bool dump_traffic_to_tap; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); dump_traffic_to_tap = ntop_interface->getDumpTrafficTapPolicy(); lua_pushboolean(vm, dump_traffic_to_tap ? 1 : 0); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_dump_tap_name(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); lua_pushstring(vm, ntop_interface->getDumpTrafficTapName()); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_dump_disk_policy(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); bool dump_traffic_to_disk; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); dump_traffic_to_disk = ntop_interface->getDumpTrafficDiskPolicy(); lua_pushboolean(vm, dump_traffic_to_disk ? 1 : 0); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_dump_max_pkts(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); int max_pkts; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); max_pkts = ntop_interface->getDumpTrafficMaxPktsPerFile(); lua_pushnumber(vm, max_pkts); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_dump_max_sec(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); int max_sec; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); max_sec = ntop_interface->getDumpTrafficMaxSecPerFile(); lua_pushnumber(vm, max_sec); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_dump_max_files(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); int max_files; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); max_files = ntop_interface->getDumpTrafficMaxFiles(); lua_pushnumber(vm, max_files); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_pkts_dumped_file(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); int num_pkts; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); PacketDumper *dumper = ntop_interface->getPacketDumper(); if(!dumper) return(CONST_LUA_ERROR); num_pkts = dumper->get_num_dumped_packets(); lua_pushnumber(vm, num_pkts); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_pkts_dumped_tap(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); int num_pkts; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); PacketDumperTuntap *dumper = ntop_interface->getPacketDumperTap(); if(!dumper) return(CONST_LUA_ERROR); num_pkts = dumper->get_num_dumped_packets(); lua_pushnumber(vm, num_pkts); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_endpoint(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); u_int8_t id; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) != LUA_TNUMBER) /* Optional */ id = 0; else id = (u_int8_t)lua_tonumber(vm, 1); if(ntop_interface) { char *endpoint = ntop_interface->getEndpoint(id); /* CHECK */ lua_pushfstring(vm, "%s", endpoint ? endpoint : ""); } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_is_packet_interface(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); lua_pushboolean(vm, ntop_interface->isPacketInterface()); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_is_bridge_interface(lua_State* vm) { int ifid; NetworkInterface *iface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if((lua_type(vm, 1) == LUA_TNUMBER)) { ifid = lua_tointeger(vm, 1); if(ifid < 0 || !(iface = ntop->getNetworkInterface(ifid))) return (CONST_LUA_ERROR); } lua_pushboolean(vm, iface->is_bridge_interface()); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_is_pcap_dump_interface(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); const char *interface_type; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface || ((interface_type = ntop_interface->get_type()) == NULL)) return(CONST_LUA_ERROR); lua_pushboolean(vm, strcmp(interface_type, CONST_INTERFACE_TYPE_PCAP_DUMP) == 0); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_is_running(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); return(ntop_interface->isRunning()); } /* ****************************************** */ static int ntop_interface_is_idle(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); return(ntop_interface->idle()); } /* ****************************************** */ static int ntop_interface_set_idle(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); bool state; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TBOOLEAN)) return(CONST_LUA_ERROR); state = lua_toboolean(vm, 1) ? true : false; ntop_interface->setIdleState(state); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_name2id(lua_State* vm) { char *if_name; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TNIL) if_name = NULL; else { if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if_name = (char*)lua_tostring(vm, 1); } lua_pushinteger(vm, ntop->getInterfaceIdByName(if_name)); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_ndpi_protocols(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ndpi_protocol_category_t category_filter; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if((lua_type(vm, 1) == LUA_TNUMBER)) { category_filter = (ndpi_protocol_category_t)lua_tointeger(vm, 1); if(category_filter >= NDPI_PROTOCOL_NUM_CATEGORIES) return (CONST_LUA_ERROR); ntop_interface->getnDPIProtocols(vm, category_filter); } else ntop_interface->getnDPIProtocols(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_ndpi_categories(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_newtable(vm); for (int i=0; i < NDPI_PROTOCOL_NUM_CATEGORIES; i++) { char buf[8]; snprintf(buf, sizeof(buf), "%d", i); lua_push_str_table_entry(vm, ndpi_category_str((ndpi_protocol_category_t)i), buf); } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_load_dump_prefs(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); ntop_interface->loadDumpPrefs(); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_load_scaling_factor_prefs(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); ntop_interface->loadScalingFactorPrefs(); return(CONST_LUA_OK); } /* ****************************************** */ /* Code partially taken from third-party/rrdtool-1.4.7/bindings/lua/rrdlua.c and made reentrant */ static void reset_rrd_state(void) { optind = 0; opterr = 0; rrd_clear_error(); } /* ****************************************** */ static const char **make_argv(lua_State * vm, u_int offset) { const char **argv; int i; int argc = lua_gettop(vm) - offset; if(!(argv = (const char**)calloc(argc, sizeof (char *)))) /* raise an error and never return */ luaL_error(vm, "Can't allocate memory for arguments array"); /* fprintf(stderr, "%s\n", argv[0]); */ for(i=0; i<argc; i++) { u_int idx = i + offset; /* accepts string or number */ if(lua_isstring(vm, idx) || lua_isnumber(vm, idx)) { if(!(argv[i] = (char*)lua_tostring (vm, idx))) { /* raise an error and never return */ luaL_error(vm, "Error duplicating string area for arg #%d", i); } } else { /* raise an error and never return */ luaL_error(vm, "Invalid arg #%d: args must be strings or numbers", i); } // ntop->getTrace()->traceEvent(TRACE_NORMAL, "[%d] %s", i, argv[i]); } return(argv); } /* ****************************************** */ static int ntop_rrd_create(lua_State* vm) { const char *filename; unsigned long pdp_step; const char **argv; int argc, status, offset = 3; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((filename = (const char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); pdp_step = (unsigned long)lua_tonumber(vm, 2); ntop->getTrace()->traceEvent(TRACE_INFO, "%s(%s)", __FUNCTION__, filename); argc = lua_gettop(vm) - offset; argv = make_argv(vm, offset); reset_rrd_state(); status = rrd_create_r(filename, pdp_step, time(NULL)-86400 /* 1 day */, argc, argv); free(argv); if(status != 0) { char *err = rrd_get_error(); if(err != NULL) { luaL_error(vm, err); return(CONST_LUA_ERROR); } } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_rrd_update(lua_State* vm) { const char *filename, *update_arg; int status; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((filename = (const char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((update_arg = (const char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s(%s) %s", __FUNCTION__, filename, update_arg); reset_rrd_state(); status = rrd_update_r(filename, NULL, 1, &update_arg); if(status != 0) { char *err = rrd_get_error(); if(err != NULL) { luaL_error(vm, err); return(CONST_LUA_ERROR); } } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_rrd_lastupdate(lua_State* vm) { const char *filename; time_t last_update; char **ds_names; char **last_ds; unsigned long ds_count, i; int status; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((filename = (const char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); status = rrd_lastupdate_r(filename, &last_update, &ds_count, &ds_names, &last_ds); if(status != 0) { return(CONST_LUA_ERROR); } else { for(i = 0; i < ds_count; i++) free(last_ds[i]), free(ds_names[i]); free(last_ds), free(ds_names); lua_pushnumber(vm, last_update); lua_pushnumber(vm, ds_count); return(2 /* 2 values returned */); } } /* ****************************************** */ /* positional 1:4 parameters for ntop_rrd_fetch */ static int __ntop_rrd_args (lua_State* vm, char **filename, char **cf, time_t *start, time_t *end) { char *start_s, *end_s, *err; rrd_time_value_t start_tv, end_tv; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((*filename = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((*cf = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if((lua_type(vm, 3) == LUA_TNUMBER) && (lua_type(vm, 4) == LUA_TNUMBER)) *start = (time_t)lua_tonumber(vm, 3), *end = (time_t)lua_tonumber(vm, 4); else { if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((start_s = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR); if((err = rrd_parsetime(start_s, &start_tv)) != NULL) { luaL_error(vm, err); return(CONST_LUA_PARAM_ERROR); } if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((end_s = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR); if((err = rrd_parsetime(end_s, &end_tv)) != NULL) { luaL_error(vm, err); return(CONST_LUA_PARAM_ERROR); } if(rrd_proc_start_end(&start_tv, &end_tv, start, end) == -1) return(CONST_LUA_PARAM_ERROR); } return(CONST_LUA_OK); } static int __ntop_rrd_status(lua_State* vm, int status, char *filename, char *cf) { char * err; if(status != 0) { err = rrd_get_error(); if(err != NULL) { ntop->getTrace()->traceEvent(TRACE_ERROR, "Error '%s' while calling rrd_fetch_r(%s, %s): is the RRD corrupted perhaps?", err, filename, cf); lua_pushnil(vm); lua_pushnil(vm); lua_pushnil(vm); lua_pushnil(vm); return(CONST_LUA_ERROR); } } return(CONST_LUA_OK); } /* Fetches data from RRD by rows */ static int ntop_rrd_fetch(lua_State* vm) { unsigned long i, j, step = 0, ds_cnt = 0; rrd_value_t *data, *p; char **names; char *filename, *cf; time_t t, start, end; int status; if ((status = __ntop_rrd_args(vm, &filename, &cf, &start, &end)) != CONST_LUA_OK) return status; ntop->getTrace()->traceEvent(TRACE_INFO, "%s(%s)", __FUNCTION__, filename); reset_rrd_state(); if ((status = __ntop_rrd_status(vm, rrd_fetch_r(filename, cf, &start, &end, &step, &ds_cnt, &names, &data), filename, cf)) != CONST_LUA_OK) return status; lua_pushnumber(vm, (lua_Number) start); lua_pushnumber(vm, (lua_Number) step); /* fprintf(stderr, "%lu, %lu, %lu, %lu\n", start, end, step, num_points); */ /* create the ds names array */ lua_newtable(vm); for(i=0; i<ds_cnt; i++) { lua_pushstring(vm, names[i]); lua_rawseti(vm, -2, i+1); rrd_freemem(names[i]); } rrd_freemem(names); /* create the data points array */ lua_newtable(vm); p = data; for(t=start+1, i=0; t<end; t+=step, i++) { lua_newtable(vm); for(j=0; j<ds_cnt; j++) { rrd_value_t value = *p++; if(value != DNAN /* Skip NaN */) { lua_pushnumber(vm, (lua_Number)value); lua_rawseti(vm, -2, j+1); // ntop->getTrace()->traceEvent(TRACE_NORMAL, "%u / %.f", t, value); } } lua_rawseti(vm, -2, i+1); } rrd_freemem(data); /* return the end as the last value */ lua_pushnumber(vm, (lua_Number) end); /* number of return values: start, step, names, data, end */ return(5); } /* ****************************************** */ /* * Similar to ntop_rrd_fetch, but data series oriented (reads RRD by columns) * * Positional parameters: * filename: RRD file path * cf: RRD cf * start: the start time you wish to query * end: the end time you wish to query * * Positional return values: * start: the time of the first data in the series * step: the fetched data step * data: a table, where each key is an RRD name, and the value is its series data * end: the time of the last data in each series * npoints: the number of points in each series */ static int ntop_rrd_fetch_columns(lua_State* vm) { char *filename, *cf; time_t start, end; int status; unsigned int npoints = 0, i, j; char **names; unsigned long step = 0, ds_cnt = 0; rrd_value_t *data, *p; if ((status = __ntop_rrd_args(vm, &filename, &cf, &start, &end)) != CONST_LUA_OK) return status; ntop->getTrace()->traceEvent(TRACE_INFO, "%s(%s)", __FUNCTION__, filename); reset_rrd_state(); if ((status = __ntop_rrd_status(vm, rrd_fetch_r(filename, cf, &start, &end, &step, &ds_cnt, &names, &data), filename, cf)) != CONST_LUA_OK) return status; npoints = (end - start) / step; lua_pushnumber(vm, (lua_Number) start); lua_pushnumber(vm, (lua_Number) step); /* create the data series table */ lua_createtable(vm, 0, ds_cnt); for(i=0; i<ds_cnt; i++) { /* a single serie table, preallocated */ lua_createtable(vm, npoints, 0); p = data + i; for(j=0; j<npoints; j++) { rrd_value_t value = *p; /* we are accessing data table by columns */ p = p + ds_cnt; lua_pushnumber(vm, (lua_Number)value); lua_rawseti(vm, -2, j+1); } /* add the single serie to the series table */ lua_setfield(vm, -2, names[i]); rrd_freemem(names[i]); } rrd_freemem(names); rrd_freemem(data); /* end and npoints as last values */ lua_pushnumber(vm, (lua_Number) end); lua_pushnumber(vm, (lua_Number) npoints); /* number of return values */ return(5); } /* ****************************************** */ static int ntop_http_redirect(lua_State* vm) { char *url, str[512]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((url = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); snprintf(str, sizeof(str), "HTTP/1.1 302 Found\r\n" "Location: %s\r\n\r\n" "<html>\n" "<head>\n" "<title>Moved</title>\n" "</head>\n" "<body>\n" "<h1>Moved</h1>\n" "<p>This page has moved to <a href=\"%s\">%s</a>.</p>\n" "</body>\n" "</html>\n", url, url, url); lua_pushstring(vm, str); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_http_get(lua_State* vm) { char *url, *username = NULL, *pwd = NULL; int timeout = 30; bool return_content = true; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((url = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(lua_type(vm, 2) == LUA_TSTRING) { username = (char*)lua_tostring(vm, 2); if(lua_type(vm, 3) == LUA_TSTRING) { pwd = (char*)lua_tostring(vm, 3); if(lua_type(vm, 4) == LUA_TNUMBER) { timeout = lua_tointeger(vm, 4); if(timeout < 1) timeout = 1; /* This optional parameter specifies if the result of HTTP GET has to be returned to LUA or not. Usually the content has to be returned, but in some causes it just matters to time (for instance when use for testing HTTP services) */ if(lua_type(vm, 4) == LUA_TBOOLEAN) { return_content = lua_toboolean(vm, 5) ? true : false; } } } } if(Utils::httpGet(vm, url, username, pwd, timeout, return_content)) return(CONST_LUA_OK); else return(CONST_LUA_ERROR); } /* ****************************************** */ static int ntop_http_get_prefix(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_pushstring(vm, ntop->getPrefs()->get_http_prefix()); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_prefs(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); ntop->getPrefs()->lua(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_nologin_username(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_pushstring(vm, NTOP_NOLOGIN_USER); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_users(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); ntop->getUsers(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_user_group(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); ntop->getUserGroup(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_allowed_networks(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); ntop->getAllowedNetworks(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_reset_user_password(lua_State* vm) { char *who, *username, *old_password, *new_password; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); /* Username who requested the password change */ if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((who = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((username = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((old_password = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((new_password = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR); if((!Utils::isUserAdministrator(vm)) && (strcmp(who, username))) return(CONST_LUA_ERROR); return(ntop->resetUserPassword(username, old_password, new_password)); } /* ****************************************** */ static int ntop_change_user_role(lua_State* vm) { char *username, *user_role; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((user_role = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); return ntop->changeUserRole(username, user_role); } /* ****************************************** */ static int ntop_change_allowed_nets(lua_State* vm) { char *username, *allowed_nets; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((allowed_nets = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); return ntop->changeAllowedNets(username, allowed_nets); } /* ****************************************** */ static int ntop_change_allowed_ifname(lua_State* vm) { char *username, *allowed_ifname; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((allowed_ifname = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); return ntop->changeAllowedIfname(username, allowed_ifname); } /* ****************************************** */ static int ntop_post_http_json_data(lua_State* vm) { char *username, *password, *url, *json; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((password = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((url = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((json = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR); if(Utils::postHTTPJsonData(username, password, url, json)) return(CONST_LUA_OK); else return(CONST_LUA_ERROR); } /* ****************************************** */ static int ntop_add_user(lua_State* vm) { char *username, *full_name, *password, *host_role, *allowed_networks, *allowed_interface; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((full_name = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((password = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((host_role = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 5, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((allowed_networks = (char*)lua_tostring(vm, 5)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 6, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((allowed_interface = (char*)lua_tostring(vm, 6)) == NULL) return(CONST_LUA_PARAM_ERROR); return ntop->addUser(username, full_name, password, host_role, allowed_networks, allowed_interface); } /* ****************************************** */ static int ntop_delete_user(lua_State* vm) { char *username; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); return ntop->deleteUser(username); } /* ****************************************** */ static int ntop_resolve_address(lua_State* vm) { char *numIP, symIP[64]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((numIP = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); ntop->resolveHostName(numIP, symIP, sizeof(symIP)); lua_pushstring(vm, symIP); return(CONST_LUA_OK); } /* ****************************************** */ void lua_push_str_table_entry(lua_State *L, const char *key, char *value) { if(L) { lua_pushstring(L, key); lua_pushstring(L, value); lua_settable(L, -3); } } /* ****************************************** */ void lua_push_nil_table_entry(lua_State *L, const char *key) { if(L) { lua_pushstring(L, key); lua_pushnil(L); lua_settable(L, -3); } } /* ****************************************** */ void lua_push_bool_table_entry(lua_State *L, const char *key, bool value) { if(L) { lua_pushstring(L, key); lua_pushboolean(L, value ? 1 : 0); lua_settable(L, -3); } } /* ****************************************** */ void lua_push_int_table_entry(lua_State *L, const char *key, u_int64_t value) { if(L) { lua_pushstring(L, key); /* using LUA_NUMBER (double: 64 bit) in place of LUA_INTEGER (ptrdiff_t: 32 or 64 bit * according to the platform, as defined in luaconf.h) to handle big counters */ lua_pushnumber(L, (lua_Number)value); lua_settable(L, -3); } } /* ****************************************** */ void lua_push_int32_table_entry(lua_State *L, const char *key, int32_t value) { if(L) { lua_pushstring(L, key); lua_pushnumber(L, (lua_Number)value); lua_settable(L, -3); } } /* ****************************************** */ void lua_push_float_table_entry(lua_State *L, const char *key, float value) { if(L) { lua_pushstring(L, key); lua_pushnumber(L, value); lua_settable(L, -3); } } /* ****************************************** */ static int ntop_get_interface_stats(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); /* ntop_interface->getAlertsManager()->engageAlert(alert_entity_host, "127.0.0.1", "min_bytes", alert_threshold_exceeded, alert_level_warning, "miao"); ntop_interface->getAlertsManager()->releaseAlert(alert_entity_host, "127.0.0.1", "min_bytes", alert_threshold_exceeded, alert_level_warning, "miao"); */ ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) ntop_interface->lua(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_reset_counters(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); bool only_drops = true; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TBOOLEAN) only_drops = lua_toboolean(vm, 1) ? true : false; if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->checkPointCounters(only_drops); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_is_pro(lua_State *vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_pushboolean(vm, ntop->getPrefs()->is_pro_edition()); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_is_enterprise(lua_State *vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_pushboolean(vm, ntop->getPrefs()->is_enterprise_edition()); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_reload_l7_rules(lua_State *vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) { char *net; AddressTree ptree; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((net = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); #ifdef SHAPER_DEBUG ntop->getTrace()->traceEvent(TRACE_NORMAL, "%s(%s)", __FUNCTION__, net); #endif ptree.addAddresses(net); #ifdef NTOPNG_PRO ntop_interface->refreshL7Rules(&ptree); #endif return(CONST_LUA_OK); } else return(CONST_LUA_ERROR); } /* ****************************************** */ static int ntop_reload_shapers(lua_State *vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) { #ifdef NTOPNG_PRO ntop_interface->refreshShapers(); #endif return(CONST_LUA_OK); } else return(CONST_LUA_ERROR); } /* ****************************************** */ static int ntop_interface_exec_sql_query(lua_State *vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); bool limit_rows = true; // honour the limit by default bool wait_for_db_created = true; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); else { char *sql; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((sql = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(lua_type(vm, 2) == LUA_TBOOLEAN) { limit_rows = lua_toboolean(vm, 2) ? true : false; } if(lua_type(vm, 3) == LUA_TBOOLEAN) { wait_for_db_created = lua_toboolean(vm, 3) ? true : false; } if(ntop_interface->exec_sql_query(vm, sql, limit_rows, wait_for_db_created) < 0) lua_pushnil(vm); return(CONST_LUA_OK); } } /* ****************************************** */ static int ntop_get_dirs(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_newtable(vm); lua_push_str_table_entry(vm, "installdir", ntop->get_install_dir()); lua_push_str_table_entry(vm, "workingdir", ntop->get_working_dir()); lua_push_str_table_entry(vm, "scriptdir", ntop->getPrefs()->get_scripts_dir()); lua_push_str_table_entry(vm, "httpdocsdir", ntop->getPrefs()->get_docs_dir()); lua_push_str_table_entry(vm, "callbacksdir", ntop->getPrefs()->get_callbacks_dir()); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_uptime(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_pushinteger(vm, ntop->getGlobals()->getUptime()); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_check_license(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); #ifdef NTOPNG_PRO ntop->getPro()->check_license(); #endif lua_pushinteger(vm,1); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_info(lua_State* vm) { char rsp[256]; int major, minor, patch; bool verbose = true; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TBOOLEAN) verbose = lua_toboolean(vm, 1) ? true : false; lua_newtable(vm); lua_push_str_table_entry(vm, "product", (char*)"ntopng"); lua_push_str_table_entry(vm, "copyright", (char*)"&copy; 1998-17 - ntop.org"); lua_push_str_table_entry(vm, "authors", (char*)"The ntop.org team"); lua_push_str_table_entry(vm, "license", (char*)"GNU GPLv3"); lua_push_str_table_entry(vm, "version", (char*)PACKAGE_VERSION); lua_push_str_table_entry(vm, "git", (char*)NTOPNG_GIT_RELEASE); snprintf(rsp, sizeof(rsp), "%s [%s][%s]", PACKAGE_OSNAME, PACKAGE_MACHINE, PACKAGE_OS); lua_push_str_table_entry(vm, "platform", rsp); lua_push_str_table_entry(vm, "OS", #ifdef WIN32 (char*)"Windows" #else (char*)PACKAGE_OS #endif ); lua_push_int_table_entry(vm, "bits", (sizeof(void*) == 4) ? 32 : 64); lua_push_int_table_entry(vm, "uptime", ntop->getGlobals()->getUptime()); lua_push_str_table_entry(vm, "command_line", ntop->getPrefs()->get_command_line()); if(verbose) { lua_push_str_table_entry(vm, "version.rrd", rrd_strversion()); lua_push_str_table_entry(vm, "version.redis", ntop->getRedis()->getVersion(rsp, sizeof(rsp))); lua_push_str_table_entry(vm, "version.httpd", (char*)mg_version()); lua_push_str_table_entry(vm, "version.git", (char*)NTOPNG_GIT_RELEASE); lua_push_str_table_entry(vm, "version.luajit", (char*)LUAJIT_VERSION); #ifdef HAVE_GEOIP lua_push_str_table_entry(vm, "version.geoip", (char*)GeoIP_lib_version()); #endif lua_push_str_table_entry(vm, "version.ndpi", ndpi_revision()); lua_push_bool_table_entry(vm, "version.enterprise_edition", ntop->getPrefs()->is_enterprise_edition()); lua_push_bool_table_entry(vm, "version.embedded_edition", ntop->getPrefs()->is_embedded_edition()); lua_push_bool_table_entry(vm, "pro.release", ntop->getPrefs()->is_pro_edition()); lua_push_int_table_entry(vm, "pro.demo_ends_at", ntop->getPrefs()->pro_edition_demo_ends_at()); #ifdef NTOPNG_PRO lua_push_str_table_entry(vm, "pro.license", ntop->getPro()->get_license()); lua_push_bool_table_entry(vm, "pro.use_redis_license", ntop->getPro()->use_redis_license()); lua_push_str_table_entry(vm, "pro.systemid", ntop->getPro()->get_system_id()); #endif #if 0 ntop->getRedis()->get((char*)CONST_STR_NTOPNG_LICENSE, rsp, sizeof(rsp)); lua_push_str_table_entry(vm, "ntopng.license", rsp); #endif zmq_version(&major, &minor, &patch); snprintf(rsp, sizeof(rsp), "%d.%d.%d", major, minor, patch); lua_push_str_table_entry(vm, "version.zmq", rsp); } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_resolved_address(lua_State* vm) { char *key, *tmp,rsp[256],value[64]; Redis *redis = ntop->getRedis(); u_int16_t vlan_id = 0; char buf[64]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &key, &vlan_id, buf, sizeof(buf)); if(key == NULL) return(CONST_LUA_ERROR); if(redis->getAddress(key, rsp, sizeof(rsp), true) == 0) tmp = rsp; else tmp = key; if(vlan_id != 0) snprintf(value, sizeof(value), "%s@%u", tmp, vlan_id); else snprintf(value, sizeof(value), "%s", tmp); #if 0 if(!strcmp(value, key)) { char rsp[64]; if((ntop->getRedis()->hashGet((char*)HOST_LABEL_NAMES, key, rsp, sizeof(rsp)) == 0) && (rsp[0] !='\0')) lua_pushfstring(vm, "%s", rsp); else lua_pushfstring(vm, "%s", value); } else lua_pushfstring(vm, "%s", value); #else lua_pushfstring(vm, "%s", value); #endif return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_snmp_get_fctn(lua_State* vm, int operation) { char *agent_host, *oid, *community; u_int agent_port = 161, timeout = 5, request_id = (u_int)time(NULL); int sock, i = 0, rc = CONST_LUA_OK; SNMPMessage *message; int len; unsigned char *buf; bool debug = false; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); agent_host = (char*)lua_tostring(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); community = (char*)lua_tostring(vm, 2); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR); oid = (char*)lua_tostring(vm, 3); sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(sock < 0) return(CONST_LUA_ERROR); message = snmp_create_message(); snmp_set_version(message, 0); snmp_set_community(message, community); snmp_set_pdu_type(message, operation); snmp_set_request_id(message, request_id); snmp_set_error(message, 0); snmp_set_error_index(message, 0); snmp_add_varbind_null(message, oid); /* Add additional OIDs */ i = 4; while(lua_type(vm, i) == LUA_TSTRING) { snmp_add_varbind_null(message, (char*)lua_tostring(vm, i)); i++; } len = snmp_message_length(message); buf = (unsigned char*)malloc(len); snmp_render_message(message, buf); snmp_destroy_message(message); send_udp_datagram(buf, len, sock, agent_host, agent_port); free(buf); if(debug) ntop->getTrace()->traceEvent(TRACE_NORMAL, "SNMP %s %s@%s %s", (operation == SNMP_GET_REQUEST_TYPE) ? "Get" : "GetNext", agent_host, community, oid); if(input_timeout(sock, timeout) == 0) { /* Timeout */ if(debug) ntop->getTrace()->traceEvent(TRACE_NORMAL, "SNMP Timeout %s@%s %s", agent_host, community, oid); rc = CONST_LUA_ERROR; lua_pushnil(vm); } else { char buf[BUFLEN]; SNMPMessage *message; char *sender_host, *oid_str, *value_str; int sender_port, added = 0, len; len = receive_udp_datagram(buf, BUFLEN, sock, &sender_host, &sender_port); message = snmp_parse_message(buf, len); i = 0; while(snmp_get_varbind_as_string(message, i, &oid_str, NULL, &value_str)) { if(!added) lua_newtable(vm), added = 1; lua_push_str_table_entry(vm, oid_str, value_str); if(debug) ntop->getTrace()->traceEvent(TRACE_NORMAL, "SNMP OK %s@%s %s=%s", agent_host, community, oid_str, value_str); i++; } snmp_destroy_message(message); if(!added) { ntop->getTrace()->traceEvent(TRACE_ERROR, "SNMP Error %s@%s", agent_host, community); lua_pushnil(vm), rc = CONST_LUA_ERROR; } } closesocket(sock); return(rc); } /* ****************************************** */ static int ntop_snmpget(lua_State* vm) { return(ntop_snmp_get_fctn(vm, SNMP_GET_REQUEST_TYPE)); } static int ntop_snmpgetnext(lua_State* vm) { return(ntop_snmp_get_fctn(vm, SNMP_GETNEXT_REQUEST_TYPE)); } /* ****************************************** */ /** * @brief Send a message to the system syslog * @details Send a message to the syslog syslog: callers can specify if it is an error or informational message * * @param vm The lua state. * @return @ref CONST_LUA_ERROR if the expected type is equal to function type, @ref CONST_LUA_PARAM_ERROR otherwise. */ static int ntop_syslog(lua_State* vm) { #ifndef WIN32 char *msg; bool is_error; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TBOOLEAN)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); is_error = lua_toboolean(vm, 1) ? true : false; msg = (char*)lua_tostring(vm, 2); syslog(is_error ? LOG_ERR : LOG_INFO, "%s", msg); #endif return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Generate a random value to prevent CSRF and XSRF attacks * @details See http://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/ * * @param vm The lua state. * @return The random value just generated */ static int ntop_generate_csrf_value(lua_State* vm) { char random_a[32], random_b[32], csrf[33], user[64] = { '\0' }; Redis *redis = ntop->getRedis(); struct mg_connection *conn; lua_getglobal(vm, CONST_HTTP_CONN); if((conn = (struct mg_connection*)lua_touserdata(vm, lua_gettop(vm))) == NULL) { ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: null HTTP connection"); return(CONST_LUA_OK); } ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); #ifdef __OpenBSD__ snprintf(random_a, sizeof(random_a), "%d", arc4random()); snprintf(random_b, sizeof(random_b), "%lu", time(NULL)*arc4random()); #else snprintf(random_a, sizeof(random_a), "%d", rand()); snprintf(random_b, sizeof(random_b), "%lu", time(NULL)*rand()); #endif mg_get_cookie(conn, "user", user, sizeof(user)); mg_md5(csrf, random_a, random_b, NULL); redis->set(csrf, (char*)user, MAX_CSRF_DURATION); lua_pushfstring(vm, "%s", csrf); return(CONST_LUA_OK); } /* ****************************************** */ struct ntopng_sqlite_state { lua_State* vm; u_int num_rows; }; static int sqlite_callback(void *data, int argc, char **argv, char **azColName) { struct ntopng_sqlite_state *s = (struct ntopng_sqlite_state*)data; lua_newtable(s->vm); for(int i=0; i<argc; i++) lua_push_str_table_entry(s->vm, (const char*)azColName[i], (char*)(argv[i] ? argv[i] : "NULL")); lua_pushinteger(s->vm, ++s->num_rows); lua_insert(s->vm, -2); lua_settable(s->vm, -3); return(0); } /* ****************************************** */ /** * @brief Exec SQL query * @details Execute the specified query and return the results * * @param vm The lua state. * @return @ref CONST_LUA_ERROR in case of error, CONST_LUA_OK otherwise. */ static int ntop_sqlite_exec_query(lua_State* vm) { char *db_path, *db_query; sqlite3 *db; char *zErrMsg = 0; struct ntopng_sqlite_state state; struct stat buf; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); db_path = (char*)lua_tostring(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); db_query = (char*)lua_tostring(vm, 2); if(stat(db_path, &buf) != 0) { ntop->getTrace()->traceEvent(TRACE_INFO, "Not found database %s", db_path); return(CONST_LUA_ERROR); } if(sqlite3_open(db_path, &db)) { ntop->getTrace()->traceEvent(TRACE_INFO, "Unable to open %s: %s", db_path, sqlite3_errmsg(db)); return(CONST_LUA_ERROR); } state.vm = vm, state.num_rows = 0; lua_newtable(vm); if(sqlite3_exec(db, db_query, sqlite_callback, (void*)&state, &zErrMsg)) { ntop->getTrace()->traceEvent(TRACE_INFO, "SQL Error: %s", zErrMsg); sqlite3_free(zErrMsg); } sqlite3_close(db); return(CONST_LUA_OK); } /** * @brief Insert a new minute sampling in the historical database * @details Given a certain sampling point, store statistics for said * sampling point. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_insert_minute_sampling(lua_State *vm) { char *sampling; time_t rawtime; int ifid; NetworkInterface* iface; StatsManager *sm; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); if((sampling = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); time(&rawtime); if(sm->insertMinuteSampling(rawtime, sampling)) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /** * @brief Insert a new hour sampling in the historical database * @details Given a certain sampling point, store statistics for said * sampling point. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_insert_hour_sampling(lua_State *vm) { char *sampling; time_t rawtime; int ifid; NetworkInterface* iface; StatsManager *sm; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); if((sampling = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); time(&rawtime); rawtime -= (rawtime % 60); if(sm->insertHourSampling(rawtime, sampling)) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /** * @brief Insert a new day sampling in the historical database * @details Given a certain sampling point, store statistics for said * sampling point. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_insert_day_sampling(lua_State *vm) { char *sampling; time_t rawtime; int ifid; NetworkInterface* iface; StatsManager *sm; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); if((sampling = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); time(&rawtime); rawtime -= (rawtime % 60); if(sm->insertDaySampling(rawtime, sampling)) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /** * @brief Get a minute sampling from the historical database * @details Given a certain sampling point, get statistics for said * sampling point. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_get_minute_sampling(lua_State *vm) { time_t epoch; string sampling; int ifid; NetworkInterface* iface; StatsManager *sm; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); epoch = (time_t)lua_tointeger(vm, 2); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); if(sm->getMinuteSampling(epoch, &sampling)) return(CONST_LUA_ERROR); lua_pushstring(vm, sampling.c_str()); return(CONST_LUA_OK); } /** * @brief Delete minute stats older than a certain number of days. * @details Given a number of days, delete stats for the current interface that * are older than a certain number of days. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_delete_minute_older_than(lua_State *vm) { int num_days; int ifid; NetworkInterface* iface; StatsManager *sm; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); num_days = lua_tointeger(vm, 2); if(num_days < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); if(sm->deleteMinuteStatsOlderThan(num_days)) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /** * @brief Delete hour stats older than a certain number of days. * @details Given a number of days, delete stats for the current interface that * are older than a certain number of days. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_delete_hour_older_than(lua_State *vm) { int num_days; int ifid; NetworkInterface* iface; StatsManager *sm; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); num_days = lua_tointeger(vm, 2); if(num_days < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); if(sm->deleteHourStatsOlderThan(num_days)) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /** * @brief Delete day stats older than a certain number of days. * @details Given a number of days, delete stats for the current interface that * are older than a certain number of days. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_delete_day_older_than(lua_State *vm) { int num_days; int ifid; NetworkInterface* iface; StatsManager *sm; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); num_days = lua_tointeger(vm, 2); if(num_days < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); if(sm->deleteDayStatsOlderThan(num_days)) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /** * @brief Get an interval of minute stats samplings from the historical database * @details Given a certain interval of sampling points, get statistics for said * sampling points. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_get_minute_samplings_interval(lua_State *vm) { time_t epoch_start, epoch_end; int ifid; NetworkInterface* iface; StatsManager *sm; struct statsManagerRetrieval retvals; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); epoch_start = lua_tointeger(vm, 2); if(epoch_start < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR); epoch_end = lua_tointeger(vm, 3); if(epoch_end < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); if(sm->retrieveMinuteStatsInterval(epoch_start, epoch_end, &retvals)) return(CONST_LUA_ERROR); lua_newtable(vm); for (unsigned i = 0 ; i < retvals.rows.size() ; i++) lua_push_str_table_entry(vm, retvals.rows[i].c_str(), (char*)""); return(CONST_LUA_OK); } /** * @brief Given an epoch, get minute stats for the latest n minutes * @details Given a certain sampling point, get statistics for that point and * for all timepoints spanning an interval of a given number of * minutes. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_get_samplings_of_minutes_from_epoch(lua_State *vm) { time_t epoch_start, epoch_end; int num_minutes; int ifid; NetworkInterface* iface; StatsManager *sm; struct statsManagerRetrieval retvals; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); epoch_end = lua_tointeger(vm, 2); epoch_end -= (epoch_end % 60); if(epoch_end < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR); num_minutes = lua_tointeger(vm, 3); if(num_minutes < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); epoch_start = epoch_end - (60 * num_minutes); if(sm->retrieveMinuteStatsInterval(epoch_start, epoch_end, &retvals)) return(CONST_LUA_ERROR); lua_newtable(vm); for (unsigned i = 0 ; i < retvals.rows.size() ; i++) lua_push_str_table_entry(vm, retvals.rows[i].c_str(), (char*)""); return(CONST_LUA_OK); } /** * @brief Given an epoch, get hour stats for the latest n hours * @details Given a certain sampling point, get statistics for that point and * for all timepoints spanning an interval of a given number of * hours. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_get_samplings_of_hours_from_epoch(lua_State *vm) { time_t epoch_start, epoch_end; int num_hours; int ifid; NetworkInterface* iface; StatsManager *sm; struct statsManagerRetrieval retvals; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); epoch_end = lua_tointeger(vm, 2); epoch_end -= (epoch_end % 60); if(epoch_end < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR); num_hours = lua_tointeger(vm, 3); if(num_hours < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); epoch_start = epoch_end - (num_hours * 60 * 60); if(sm->retrieveHourStatsInterval(epoch_start, epoch_end, &retvals)) return(CONST_LUA_ERROR); lua_newtable(vm); for (unsigned i = 0 ; i < retvals.rows.size() ; i++) lua_push_str_table_entry(vm, retvals.rows[i].c_str(), (char*)""); return(CONST_LUA_OK); } /** * @brief Given an epoch, get hour stats for the latest n days * @details Given a certain sampling point, get statistics for that point and * for all timepoints spanning an interval of a given number of * days. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_get_samplings_of_days_from_epoch(lua_State *vm) { time_t epoch_start, epoch_end; int num_days; int ifid; NetworkInterface* iface; StatsManager *sm; struct statsManagerRetrieval retvals; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); epoch_end = lua_tointeger(vm, 2); epoch_end -= (epoch_end % 60); if(epoch_end < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR); num_days = lua_tointeger(vm, 3); if(num_days < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); epoch_start = epoch_end - (num_days * 24 * 60 * 60); if(sm->retrieveDayStatsInterval(epoch_start, epoch_end, &retvals)) return(CONST_LUA_ERROR); lua_newtable(vm); for (unsigned i = 0 ; i < retvals.rows.size() ; i++) lua_push_str_table_entry(vm, retvals.rows[i].c_str(), (char*)""); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_delete_dump_files(lua_State *vm) { int ifid; char pcap_path[MAX_PATH]; NetworkInterface *iface; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); if((ifid = lua_tointeger(vm, 1)) < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(ifid))) return(CONST_LUA_ERROR); snprintf(pcap_path, sizeof(pcap_path), "%s/%d/pcap/", ntop->get_working_dir(), ifid); ntop->fixPath(pcap_path); if(Utils::discardOldFilesExceeding(pcap_path, iface->getDumpTrafficMaxFiles())) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_mkdir_tree(lua_State* vm) { char *dir; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((dir = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(dir[0] == '\0') return(CONST_LUA_OK); /* Nothing to do */ return(Utils::mkdir_tree(dir)); } /* ****************************************** */ static int ntop_list_reports(lua_State* vm) { DIR *dir; char fullpath[MAX_PATH]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_newtable(vm); snprintf(fullpath, sizeof(fullpath), "%s/%s", ntop->get_working_dir(), "reports"); ntop->fixPath(fullpath); if((dir = opendir(fullpath)) != NULL) { struct dirent *ent; while ((ent = readdir(dir)) != NULL) { char filepath[MAX_PATH]; snprintf(filepath, sizeof(filepath), "%s/%s", fullpath, ent->d_name); ntop->fixPath(filepath); struct stat buf; if(!stat(filepath, &buf) && !S_ISDIR(buf.st_mode)) lua_push_str_table_entry(vm, ent->d_name, (char*)""); } closedir(dir); } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_redis(lua_State* vm) { char *key, *rsp; u_int rsp_len = 32768; Redis *redis = ntop->getRedis(); bool cache_it = false; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); /* Optional cache_it */ if(lua_type(vm, 2) == LUA_TBOOLEAN) cache_it = lua_toboolean(vm, 2); if((rsp = (char*)malloc(rsp_len)) != NULL) { lua_pushfstring(vm, "%s", (redis->get(key, rsp, rsp_len, cache_it) == 0) ? rsp : (char*)""); free(rsp); return(CONST_LUA_OK); } else return(CONST_LUA_ERROR); } /* ****************************************** */ static int ntop_get_hash_redis(lua_State* vm) { char *key, *member, rsp[CONST_MAX_LEN_REDIS_VALUE]; Redis *redis = ntop->getRedis(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if((member = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); lua_pushfstring(vm, "%s", (redis->hashGet(key, member, rsp, sizeof(rsp)) == 0) ? rsp : (char*)""); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_set_hash_redis(lua_State* vm) { char *key, *member, *value; Redis *redis = ntop->getRedis(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if((member = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if((value = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR); redis->hashSet(key, member, value); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_del_hash_redis(lua_State* vm) { char *key, *member; Redis *redis = ntop->getRedis(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if((member = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); redis->hashDel(key, member); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_hash_keys_redis(lua_State* vm) { char *key, **vals; Redis *redis = ntop->getRedis(); int rc; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); rc = redis->hashKeys(key, &vals); if(rc > 0) { lua_newtable(vm); for(int i = 0; i < rc; i++) { lua_push_str_table_entry(vm, vals[i] ? vals[i] : "", (char*)""); if(vals[i]) free(vals[i]); } free(vals); } else lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_keys_redis(lua_State* vm) { char *pattern, **keys; Redis *redis = ntop->getRedis(); int rc; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((pattern = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); rc = redis->keys(pattern, &keys); if(rc > 0) { lua_newtable(vm); for(int i = 0; i < rc; i++) { lua_push_str_table_entry(vm, keys[i] ? keys[i] : "", (char*)""); if(keys[i]) free(keys[i]); } free(keys); } else lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_lrange_redis(lua_State* vm) { char *l_name, **l_elements; Redis *redis = ntop->getRedis(); int start_offset = 0, end_offset = -1; int rc; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((l_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(lua_type(vm, 2) == LUA_TNUMBER) { start_offset = lua_tointeger(vm, 2); } if(lua_type(vm, 3) == LUA_TNUMBER) { end_offset = lua_tointeger(vm, 3); } rc = redis->lrange(l_name, &l_elements, start_offset, end_offset); if(rc > 0) { lua_newtable(vm); for(int i = 0; i < rc; i++) { lua_push_str_table_entry(vm, l_elements[i] ? l_elements[i] : "", (char*)""); if(l_elements[i]) free(l_elements[i]); } free(l_elements); } else lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_redis_set_pop(lua_State* vm) { char *set_name, rsp[CONST_MAX_LEN_REDIS_VALUE]; Redis *redis = ntop->getRedis(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((set_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); lua_pushfstring(vm, "%s", redis->popSet(set_name, rsp, sizeof(rsp))); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_list_index_redis(lua_State* vm) { char *index_name, rsp[CONST_MAX_LEN_REDIS_VALUE]; Redis *redis = ntop->getRedis(); int idx; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((index_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); idx = lua_tointeger(vm, 2); if(redis->lindex(index_name, idx, rsp, sizeof(rsp)) != 0) return(CONST_LUA_ERROR); lua_pushfstring(vm, "%s", rsp); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_lpop_redis(lua_State* vm) { char msg[1024], *list_name; Redis *redis = ntop->getRedis(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((list_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(redis->lpop(list_name, msg, sizeof(msg)) == 0) { lua_pushfstring(vm, "%s", msg); return(CONST_LUA_OK); } else return(CONST_LUA_ERROR); } /* ****************************************** */ static int ntop_lpush_redis(lua_State* vm) { char *list_name, *value; u_int list_trim_size = 0; // default 0 = no trim Redis *redis = ntop->getRedis(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((list_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); if((value = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); /* Optional trim list up to the specified number of elements */ if(lua_type(vm, 3) == LUA_TNUMBER) list_trim_size = (u_int)lua_tonumber(vm, 3); if(redis->lpush(list_name, value, list_trim_size) == 0) { return(CONST_LUA_OK); }else return(CONST_LUA_ERROR); } /* ****************************************** */ static int ntop_redis_get_host_id(lua_State* vm) { char *host_name; Redis *redis = ntop->getRedis(); char daybuf[32]; time_t when = time(NULL); bool new_key; NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((host_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); strftime(daybuf, sizeof(daybuf), CONST_DB_DAY_FORMAT, localtime(&when)); lua_pushinteger(vm, redis->host_to_id(ntop_interface, daybuf, host_name, &new_key)); /* CHECK */ return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_redis_get_id_to_host(lua_State* vm) { char *host_idx, rsp[CONST_MAX_LEN_REDIS_VALUE]; Redis *redis = ntop->getRedis(); char daybuf[32]; time_t when = time(NULL); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((host_idx = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); strftime(daybuf, sizeof(daybuf), CONST_DB_DAY_FORMAT, localtime(&when)); lua_pushfstring(vm, "%d", redis->id_to_host(daybuf, host_idx, rsp, sizeof(rsp))); return(CONST_LUA_OK); } /* ****************************************** */ #ifdef NOTUSED static int ntop_interface_store_alert(lua_State* vm) { int ifid; NetworkInterface* iface; AlertsManager *am; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TTABLE)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(vm, ifid)) || !(am = iface->getAlertsManager())) return (CONST_LUA_ERROR); return am->storeAlert(vm, 2) ? CONST_LUA_ERROR : CONST_LUA_OK; } #endif /* ****************************************** */ static int ntop_interface_engage_release_host_alert(lua_State* vm, bool engage) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; Host *h; int alert_severity; int alert_type; char *alert_json, *engaged_alert_id; AlertsManager *am; int ret; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); engaged_alert_id = (char*)lua_tostring(vm, 2); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR); alert_type = (int)lua_tonumber(vm, 3); if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TNUMBER)) return(CONST_LUA_ERROR); alert_severity = (int)lua_tonumber(vm, 4); if(ntop_lua_check(vm, __FUNCTION__, 5, LUA_TSTRING)) return(CONST_LUA_ERROR); alert_json = (char*)lua_tostring(vm, 5); if((!ntop_interface) || ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL) || ((am = ntop_interface->getAlertsManager()) == NULL)) return(CONST_LUA_ERROR); if(engage) ret = am->engageHostAlert(h, engaged_alert_id, (AlertType)alert_type, (AlertLevel)alert_severity, alert_json); else ret = am->releaseHostAlert(h, engaged_alert_id, (AlertType)alert_type, (AlertLevel)alert_severity, alert_json); return ret >= 0 ? CONST_LUA_OK : CONST_LUA_ERROR; } /* ****************************************** */ static int ntop_interface_engage_release_network_alert(lua_State* vm, bool engage) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *cidr; int alert_severity; int alert_type; char *alert_json, *engaged_alert_id; AlertsManager *am; int ret; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); cidr = (char*)lua_tostring(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); engaged_alert_id = (char*)lua_tostring(vm, 2); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR); alert_type = (int)lua_tonumber(vm, 3); if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TNUMBER)) return(CONST_LUA_ERROR); alert_severity = (int)lua_tonumber(vm, 4); if(ntop_lua_check(vm, __FUNCTION__, 5, LUA_TSTRING)) return(CONST_LUA_ERROR); alert_json = (char*)lua_tostring(vm, 5); if((!ntop_interface) || ((am = ntop_interface->getAlertsManager()) == NULL)) return(CONST_LUA_ERROR); if(engage) ret = am->engageNetworkAlert(cidr, engaged_alert_id, (AlertType)alert_type, (AlertLevel)alert_severity, alert_json); else ret = am->releaseNetworkAlert(cidr, engaged_alert_id, (AlertType)alert_type, (AlertLevel)alert_severity, alert_json); return ret >= 0 ? CONST_LUA_OK : CONST_LUA_ERROR; } /* ****************************************** */ static int ntop_interface_engage_release_interface_alert(lua_State* vm, bool engage) { NetworkInterface *ntop_interface = getCurrentInterface(vm); int alert_severity; int alert_type; char *alert_json, *engaged_alert_id; AlertsManager *am; int ret; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); engaged_alert_id = (char*)lua_tostring(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); alert_type = (int)lua_tonumber(vm, 2); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR); alert_severity = (int)lua_tonumber(vm, 3); if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_ERROR); alert_json = (char*)lua_tostring(vm, 4); if((!ntop_interface) || ((am = ntop_interface->getAlertsManager()) == NULL)) return(CONST_LUA_ERROR); if(engage) ret = am->engageInterfaceAlert(ntop_interface, engaged_alert_id, (AlertType)alert_type, (AlertLevel)alert_severity, alert_json); else ret = am->releaseInterfaceAlert(ntop_interface, engaged_alert_id, (AlertType)alert_type, (AlertLevel)alert_severity, alert_json); return ret >= 0 ? CONST_LUA_OK : CONST_LUA_ERROR; } /* ****************************************** */ static int ntop_interface_engage_host_alert(lua_State* vm) { return ntop_interface_engage_release_host_alert(vm, true /* engage */); } /* ****************************************** */ static int ntop_interface_release_host_alert(lua_State* vm) { return ntop_interface_engage_release_host_alert(vm, false /* release */); } /* ****************************************** */ static int ntop_interface_engage_network_alert(lua_State* vm) { return ntop_interface_engage_release_network_alert(vm, true /* engage */); } /* ****************************************** */ static int ntop_interface_release_network_alert(lua_State* vm) { return ntop_interface_engage_release_network_alert(vm, false /* release */); } /* ****************************************** */ static int ntop_interface_engage_interface_alert(lua_State* vm) { return ntop_interface_engage_release_interface_alert(vm, true /* engage */); } /* ****************************************** */ static int ntop_interface_release_interface_alert(lua_State* vm) { return ntop_interface_engage_release_interface_alert(vm, false /* release */); } /* ****************************************** */ static int ntop_interface_get_cached_num_alerts(lua_State* vm) { NetworkInterface *iface = getCurrentInterface(vm); AlertsManager *am; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!iface || !(am = iface->getAlertsManager())) return (CONST_LUA_ERROR); return (!am->getCachedNumAlerts(vm)) ? CONST_LUA_OK : CONST_LUA_ERROR; } /* ****************************************** */ static int ntop_interface_query_alerts_raw(lua_State* vm) { NetworkInterface *iface = getCurrentInterface(vm); AlertsManager *am; bool engaged = false; char *selection = NULL, *clauses = NULL; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!iface || !(am = iface->getAlertsManager())) return (CONST_LUA_ERROR); if(lua_type(vm, 1) == LUA_TBOOLEAN) engaged = lua_toboolean(vm, 1); if(lua_type(vm, 2) == LUA_TSTRING) if((selection = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(lua_type(vm, 3) == LUA_TSTRING) if((clauses = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR); if(am->queryAlertsRaw(vm, engaged, selection, clauses)) return(CONST_LUA_ERROR); return (CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_query_flow_alerts_raw(lua_State* vm) { NetworkInterface *iface = getCurrentInterface(vm); AlertsManager *am; char *selection = NULL, *clauses = NULL; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!iface || !(am = iface->getAlertsManager())) return (CONST_LUA_ERROR); if(lua_type(vm, 1) == LUA_TSTRING) if((selection = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(lua_type(vm, 2) == LUA_TSTRING) if((clauses = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(am->queryFlowAlertsRaw(vm, selection, clauses)) return(CONST_LUA_ERROR); return (CONST_LUA_OK); } /* ****************************************** */ #if NTOPNG_PRO static int ntop_nagios_reload_config(lua_State* vm) { NagiosManager *nagios = ntop->getNagios(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!nagios) { ntop->getTrace()->traceEvent(TRACE_ERROR, "%s(): unable to get the nagios manager", __FUNCTION__); return(CONST_LUA_ERROR); } nagios->loadConfig(); lua_pushnil(vm); return(CONST_LUA_OK); } static int ntop_nagios_send_alert(lua_State* vm) { NagiosManager *nagios = ntop->getNagios(); char *alert_source; char *timespan; char *alarmed_metric; char *alert_msg; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); alert_source = (char*)lua_tostring(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); timespan = (char*)lua_tostring(vm, 2); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR); alarmed_metric = (char*)lua_tostring(vm, 3); if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_ERROR); alert_msg = (char*)lua_tostring(vm, 4); nagios->sendAlert(alert_source, timespan, alarmed_metric, alert_msg); lua_pushnil(vm); return(CONST_LUA_OK); } static int ntop_nagios_withdraw_alert(lua_State* vm) { NagiosManager *nagios = ntop->getNagios(); char *alert_source; char *timespan; char *alarmed_metric; char *alert_msg; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); alert_source = (char*)lua_tostring(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); timespan = (char*)lua_tostring(vm, 2); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR); alarmed_metric = (char*)lua_tostring(vm, 3); if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_ERROR); alert_msg = (char*)lua_tostring(vm, 4); nagios->withdrawAlert(alert_source, timespan, alarmed_metric, alert_msg); lua_pushnil(vm); return(CONST_LUA_OK); } #endif /* ****************************************** */ #ifdef NTOPNG_PRO static int ntop_check_profile_syntax(lua_State* vm) { char *filter; NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); filter = (char*)lua_tostring(vm, 1); lua_pushboolean(vm, ntop_interface ? ntop_interface->checkProfileSyntax(filter) : false); return(CONST_LUA_OK); } #endif /* ****************************************** */ #ifdef NTOPNG_PRO static int ntop_reload_traffic_profiles(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) ntop_interface->updateFlowProfiles(); /* Reload profiles in memory */ lua_pushnil(vm); return(CONST_LUA_OK); } #endif /* ****************************************** */ static int ntop_set_redis(lua_State* vm) { char *key, *value; u_int expire_secs = 0; // default 0 = no expiration Redis *redis = ntop->getRedis(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); if((value = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); /* Optional key expiration in SECONDS */ if(lua_type(vm, 3) == LUA_TNUMBER) expire_secs = (u_int)lua_tonumber(vm, 3); if(redis->set(key, value, expire_secs) == 0) { return(CONST_LUA_OK); }else return(CONST_LUA_ERROR); } /* ****************************************** */ static int ntop_set_redis_preference(lua_State* vm) { char *key, *value; Redis *redis = ntop->getRedis(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); if((value = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(redis->set(key, value) || ntop->getPrefs()->refresh(key, value)) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_lua_http_print(lua_State* vm) { struct mg_connection *conn; char *printtype; int t; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_getglobal(vm, CONST_HTTP_CONN); if((conn = (struct mg_connection*)lua_touserdata(vm, lua_gettop(vm))) == NULL) { ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: null HTTP connection"); return(CONST_LUA_OK); } /* Handle binary blob */ if(lua_type(vm, 2) == LUA_TSTRING && (printtype = (char*)lua_tostring(vm, 2)) != NULL) if(!strncmp(printtype, "blob", 4)) { char *str = NULL; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return (CONST_LUA_ERROR); if((str = (char*)lua_tostring(vm, 1)) != NULL) { int len = strlen(str); if(len <= 1) mg_printf(conn, "%c", str[0]); else return (CONST_LUA_PARAM_ERROR); } return (CONST_LUA_OK); } switch(t = lua_type(vm, 1)) { case LUA_TNIL: mg_printf(conn, "%s", "nil"); break; case LUA_TBOOLEAN: { int v = lua_toboolean(vm, 1); mg_printf(conn, "%s", v ? "true" : "false"); } break; case LUA_TSTRING: { char *str = (char*)lua_tostring(vm, 1); if(str && (strlen(str) > 0)) mg_printf(conn, "%s", str); } break; case LUA_TNUMBER: { char str[64]; snprintf(str, sizeof(str), "%f", (float)lua_tonumber(vm, 1)); mg_printf(conn, "%s", str); } break; default: ntop->getTrace()->traceEvent(TRACE_WARNING, "%s(): Lua type %d is not handled", __FUNCTION__, t); return(CONST_LUA_ERROR); } return(CONST_LUA_OK); } /* ****************************************** */ int ntop_lua_cli_print(lua_State* vm) { int t; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); switch(t = lua_type(vm, 1)) { case LUA_TSTRING: { char *str = (char*)lua_tostring(vm, 1); if(str && (strlen(str) > 0)) ntop->getTrace()->traceEvent(TRACE_NORMAL, "%s", str); } break; case LUA_TNUMBER: ntop->getTrace()->traceEvent(TRACE_NORMAL, "%f", (float)lua_tonumber(vm, 1)); break; default: ntop->getTrace()->traceEvent(TRACE_WARNING, "%s(): Lua type %d is not handled", __FUNCTION__, t); return(CONST_LUA_ERROR); } return(CONST_LUA_OK); } /* ****************************************** */ #ifdef NTOPNG_PRO static int __ntop_lua_handlefile(lua_State* L, char *script_path, bool ex) { int rc; LuaHandler *lh = new LuaHandler(L, script_path); rc = lh->luaL_dofileM(ex); delete lh; return rc; } /* This function is called by Lua scripts when the call require(...) */ static int ntop_lua_require(lua_State* L) { char *script_name; if(lua_type(L, 1) != LUA_TSTRING || (script_name = (char*)lua_tostring(L, 1)) == NULL) return 0; lua_getglobal( L, "package" ); lua_getfield( L, -1, "path" ); string cur_path = lua_tostring( L, -1 ), parsed, script_path = ""; stringstream input_stringstream(cur_path); while(getline(input_stringstream, parsed, ';')) { /* Example: package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path */ unsigned found = parsed.find_last_of("?"); if(found) { string s = parsed.substr(0, found) + script_name + ".lua"; if(Utils::file_exists(s.c_str())) { script_path = s; break; } } } if(script_path == "" || __ntop_lua_handlefile(L, (char *)script_path.c_str(), false)) return 0; return 1; } static int ntop_lua_dofile(lua_State* L) { char *script_path; if(lua_type(L, 1) != LUA_TSTRING || (script_path = (char*)lua_tostring(L, 1)) == NULL || __ntop_lua_handlefile(L, script_path, true)) return 0; return 1; } #endif /* ****************************************** */ /** * @brief Return true if login has been disabled * * @param vm The lua state. * @return @ref CONST_LUA_OK and push the return code into the Lua stack */ static int ntop_is_login_disabled(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); bool ret = ntop->getPrefs()->is_localhost_users_login_disabled() || !ntop->getPrefs()->is_users_login_enabled(); lua_pushboolean(vm, ret); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Convert the network Id to a symbolic name (network/mask) * * @param vm The lua state. * @return @ref CONST_LUA_OK and push the return code into the Lua stack */ static int ntop_network_name_by_id(lua_State* vm) { int id; char *name; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); id = (u_int32_t)lua_tonumber(vm, 1); name = ntop->getLocalNetworkName(id); lua_pushstring(vm, name ? name : ""); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_set_logging_level(lua_State* vm) { char *lvlStr; ntop->getTrace()->traceEvent(TRACE_INFO, "%s() called", __FUNCTION__); if(ntop->getPrefs()->hasCmdlTraceLevel()) return(CONST_LUA_OK); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); lvlStr = (char*)lua_tostring(vm, 1); if(!strcmp(lvlStr, "trace")){ ntop->getTrace()->set_trace_level(TRACE_LEVEL_TRACE); } else if(!strcmp(lvlStr, "debug")){ ntop->getTrace()->set_trace_level(TRACE_LEVEL_DEBUG); } else if(!strcmp(lvlStr, "info")){ ntop->getTrace()->set_trace_level(TRACE_LEVEL_INFO); } else if(!strcmp(lvlStr, "normal")){ ntop->getTrace()->set_trace_level(TRACE_LEVEL_NORMAL); } else if(!strcmp(lvlStr, "warning")){ ntop->getTrace()->set_trace_level(TRACE_LEVEL_WARNING); } else if(!strcmp(lvlStr, "error")){ ntop->getTrace()->set_trace_level(TRACE_LEVEL_ERROR); } else{ return(CONST_LUA_ERROR); } return(CONST_LUA_OK); } /* ****************************************** */ static const luaL_Reg ntop_interface_reg[] = { { "getDefaultIfName", ntop_get_default_interface_name }, { "setActiveInterfaceId", ntop_set_active_interface_id }, { "getIfNames", ntop_get_interface_names }, { "select", ntop_select_interface }, { "getStats", ntop_get_interface_stats }, { "resetCounters", ntop_interface_reset_counters }, { "getnDPIStats", ntop_get_ndpi_interface_stats }, { "getnDPIProtoName", ntop_get_ndpi_protocol_name }, { "getnDPIProtoId", ntop_get_ndpi_protocol_id }, { "getnDPIProtoCategory", ntop_get_ndpi_protocol_category }, { "getnDPIFlowsCount", ntop_get_ndpi_interface_flows_count }, { "getFlowsStatus", ntop_get_ndpi_interface_flows_status }, { "getnDPIProtoBreed", ntop_get_ndpi_protocol_breed }, { "getnDPIProtocols", ntop_get_ndpi_protocols }, { "getnDPICategories", ntop_get_ndpi_categories }, { "getHostsInfo", ntop_get_interface_hosts_info }, { "getLocalHostsInfo", ntop_get_interface_local_hosts_info }, { "getRemoteHostsInfo", ntop_get_interface_remote_hosts_info }, { "getHostActivity", ntop_get_interface_host_activity }, { "getHostInfo", ntop_get_interface_host_info }, { "getGroupedHosts", ntop_get_grouped_interface_hosts }, { "getNetworksStats", ntop_get_interface_networks_stats }, { "resetPeriodicStats", ntop_host_reset_periodic_stats }, { "correlateHostActivity", ntop_correalate_host_activity }, { "similarHostActivity", ntop_similar_host_activity }, { "getHostActivityMap", ntop_get_interface_host_activitymap }, { "restoreHost", ntop_restore_interface_host }, { "getFlowsInfo", ntop_get_interface_flows_info }, { "getLocalFlowsInfo", ntop_get_interface_local_flows_info }, { "getRemoteFlowsInfo", ntop_get_interface_remote_flows_info }, { "getFlowsStats", ntop_get_interface_flows_stats }, { "getFlowPeers", ntop_get_interface_flows_peers }, { "getFlowKey", ntop_get_interface_flow_key }, { "findFlowByKey", ntop_get_interface_find_flow_by_key }, { "dropFlowTraffic", ntop_drop_flow_traffic }, { "dumpFlowTraffic", ntop_dump_flow_traffic }, { "dumpLocalHosts2redis", ntop_dump_local_hosts_2_redis }, { "findUserFlows", ntop_get_interface_find_user_flows }, { "findPidFlows", ntop_get_interface_find_pid_flows }, { "findFatherPidFlows", ntop_get_interface_find_father_pid_flows }, { "findNameFlows", ntop_get_interface_find_proc_name_flows }, { "listHTTPhosts", ntop_list_http_hosts }, { "findHost", ntop_get_interface_find_host }, { "updateHostTrafficPolicy", ntop_update_host_traffic_policy }, { "updateHostAlertPolicy", ntop_update_host_alert_policy }, { "setSecondTraffic", ntop_set_second_traffic }, { "setHostDumpPolicy", ntop_set_host_dump_policy }, { "setHostQuota", ntop_set_host_quota }, { "getPeerHitRate", ntop_get_host_hit_rate }, { "getLatestActivityHostsInfo", ntop_get_interface_latest_activity_hosts_info }, { "getInterfaceDumpDiskPolicy", ntop_get_interface_dump_disk_policy }, { "getInterfaceDumpTapPolicy", ntop_get_interface_dump_tap_policy }, { "getInterfaceDumpTapName", ntop_get_interface_dump_tap_name }, { "getInterfaceDumpMaxPkts", ntop_get_interface_dump_max_pkts }, { "getInterfaceDumpMaxSec", ntop_get_interface_dump_max_sec }, { "getInterfaceDumpMaxFiles", ntop_get_interface_dump_max_files }, { "getInterfacePacketsDumpedFile", ntop_get_interface_pkts_dumped_file }, { "getInterfacePacketsDumpedTap", ntop_get_interface_pkts_dumped_tap }, { "getEndpoint", ntop_get_interface_endpoint }, { "isPacketInterface", ntop_interface_is_packet_interface }, { "isBridgeInterface", ntop_interface_is_bridge_interface }, { "isPcapDumpInterface", ntop_interface_is_pcap_dump_interface }, { "isRunning", ntop_interface_is_running }, { "isIdle", ntop_interface_is_idle }, { "setInterfaceIdleState", ntop_interface_set_idle }, { "name2id", ntop_interface_name2id }, { "loadDumpPrefs", ntop_load_dump_prefs }, { "loadScalingFactorPrefs", ntop_load_scaling_factor_prefs }, { "loadHostAlertPrefs", ntop_interface_load_host_alert_prefs }, /* Mac */ { "getMacsInfo", ntop_get_interface_macs_info }, { "getMacInfo", ntop_get_interface_mac_info }, /* L7 */ { "reloadL7Rules", ntop_reload_l7_rules }, { "reloadShapers", ntop_reload_shapers }, /* DB */ { "execSQLQuery", ntop_interface_exec_sql_query }, /* Flows */ { "getFlowDevices", ntop_getflowdevices }, { "getFlowDeviceInfo", ntop_getflowdeviceinfo }, /* New generation alerts */ { "getCachedNumAlerts", ntop_interface_get_cached_num_alerts }, { "queryAlertsRaw", ntop_interface_query_alerts_raw }, { "queryFlowAlertsRaw", ntop_interface_query_flow_alerts_raw }, { "engageHostAlert", ntop_interface_engage_host_alert }, { "releaseHostAlert", ntop_interface_release_host_alert }, { "engageNetworkAlert", ntop_interface_engage_network_alert }, { "releaseNetworkAlert", ntop_interface_release_network_alert }, { "engageInterfaceAlert", ntop_interface_engage_interface_alert }, { "releaseInterfaceAlert",ntop_interface_release_interface_alert }, { "enableHostAlerts", ntop_interface_host_enable_alerts }, { "disableHostAlerts", ntop_interface_host_disable_alerts }, { "refreshNumAlerts", ntop_interface_refresh_num_alerts }, { NULL, NULL } }; /* **************************************************************** */ static const luaL_Reg ntop_reg[] = { { "getDirs", ntop_get_dirs }, { "getInfo", ntop_get_info }, { "getUptime", ntop_get_uptime }, { "dumpFile", ntop_dump_file }, { "checkLicense", ntop_check_license }, /* Redis */ { "getCache", ntop_get_redis }, { "setCache", ntop_set_redis }, { "delCache", ntop_delete_redis_key }, { "listIndexCache", ntop_list_index_redis }, { "lpushCache", ntop_lpush_redis }, { "lpopCache", ntop_lpop_redis }, { "lrangeCache", ntop_lrange_redis }, { "getMembersCache", ntop_get_set_members_redis }, { "getHashCache", ntop_get_hash_redis }, { "setHashCache", ntop_set_hash_redis }, { "delHashCache", ntop_del_hash_redis }, { "getHashKeysCache",ntop_get_hash_keys_redis }, { "getKeysCache", ntop_get_keys_redis }, { "delHashCache", ntop_delete_hash_redis_key }, { "setPopCache", ntop_get_redis_set_pop }, { "getHostId", ntop_redis_get_host_id }, { "getIdToHost", ntop_redis_get_id_to_host }, /* Redis Preferences */ { "setPref", ntop_set_redis_preference }, { "getPref", ntop_get_redis }, { "isdir", ntop_is_dir }, { "mkdir", ntop_mkdir_tree }, { "notEmptyFile", ntop_is_not_empty_file }, { "exists", ntop_get_file_dir_exists }, { "listReports", ntop_list_reports }, { "fileLastChange", ntop_get_file_last_change }, { "readdir", ntop_list_dir_files }, { "zmq_connect", ntop_zmq_connect }, { "zmq_disconnect", ntop_zmq_disconnect }, { "zmq_receive", ntop_zmq_receive }, { "getLocalNetworks", ntop_get_local_networks }, { "reloadPreferences", ntop_reload_preferences }, #ifdef NTOPNG_PRO { "sendNagiosAlert", ntop_nagios_send_alert }, { "withdrawNagiosAlert", ntop_nagios_withdraw_alert }, { "reloadNagiosConfig", ntop_nagios_reload_config }, { "checkProfileSyntax", ntop_check_profile_syntax }, { "reloadProfiles", ntop_reload_traffic_profiles }, #endif /* Pro */ { "isPro", ntop_is_pro }, { "isEnterprise", ntop_is_enterprise }, /* Historical database */ { "insertMinuteSampling", ntop_stats_insert_minute_sampling }, { "insertHourSampling", ntop_stats_insert_hour_sampling }, { "insertDaySampling", ntop_stats_insert_day_sampling }, { "getMinuteSampling", ntop_stats_get_minute_sampling }, { "deleteMinuteStatsOlderThan", ntop_stats_delete_minute_older_than }, { "deleteHourStatsOlderThan", ntop_stats_delete_hour_older_than }, { "deleteDayStatsOlderThan", ntop_stats_delete_day_older_than }, { "getMinuteSamplingsFromEpoch", ntop_stats_get_samplings_of_minutes_from_epoch }, { "getHourSamplingsFromEpoch", ntop_stats_get_samplings_of_hours_from_epoch }, { "getDaySamplingsFromEpoch", ntop_stats_get_samplings_of_days_from_epoch }, { "getMinuteSamplingsInterval", ntop_stats_get_minute_samplings_interval }, { "deleteDumpFiles", ntop_delete_dump_files }, /* Time */ { "gettimemsec", ntop_gettimemsec }, /* Trace */ { "verboseTrace", ntop_verbose_trace }, /* UDP */ { "send_udp_data", ntop_send_udp_data }, /* IP */ { "inet_ntoa", ntop_inet_ntoa }, /* RRD */ { "rrd_create", ntop_rrd_create }, { "rrd_update", ntop_rrd_update }, { "rrd_fetch", ntop_rrd_fetch }, { "rrd_fetch_columns", ntop_rrd_fetch_columns }, { "rrd_lastupdate", ntop_rrd_lastupdate }, /* Prefs */ { "getPrefs", ntop_get_prefs }, /* HTTP */ { "httpRedirect", ntop_http_redirect }, { "httpGet", ntop_http_get }, { "getHttpPrefix", ntop_http_get_prefix }, /* Admin */ { "getNologinUser", ntop_get_nologin_username }, { "getUsers", ntop_get_users }, { "getUserGroup", ntop_get_user_group }, { "getAllowedNetworks", ntop_get_allowed_networks }, { "resetUserPassword", ntop_reset_user_password }, { "changeUserRole", ntop_change_user_role }, { "changeAllowedNets", ntop_change_allowed_nets }, { "changeAllowedIfname",ntop_change_allowed_ifname }, { "addUser", ntop_add_user }, { "deleteUser", ntop_delete_user }, { "isLoginDisabled", ntop_is_login_disabled }, { "getNetworkNameById", ntop_network_name_by_id }, /* Security */ { "getRandomCSRFValue", ntop_generate_csrf_value }, /* HTTP */ { "postHTTPJsonData", ntop_post_http_json_data }, /* Address Resolution */ { "resolveAddress", ntop_resolve_address }, { "getResolvedAddress", ntop_get_resolved_address }, /* Logging */ { "syslog", ntop_syslog }, { "setLoggingLevel",ntop_set_logging_level }, /* SNMP */ { "snmpget", ntop_snmpget }, { "snmpgetnext", ntop_snmpgetnext }, /* SQLite */ { "execQuery", ntop_sqlite_exec_query }, /* Runtime */ { "hasVLANs", ntop_has_vlans }, { "hasGeoIP", ntop_has_geoip }, { "isWindows", ntop_is_windows }, /* Host Blacklist */ { "allocHostBlacklist", ntop_allocHostBlacklist }, { "swapHostBlacklist", ntop_swapHostBlacklist }, { "addToHostBlacklist", ntop_addToHostBlacklist }, /* Misc */ { "getservbyport", ntop_getservbyport }, { NULL, NULL} }; /* ****************************************** */ void Lua::lua_register_classes(lua_State *L, bool http_mode) { static const luaL_Reg _meta[] = { { NULL, NULL } }; int i; ntop_class_reg ntop_lua_reg[] = { { "interface", ntop_interface_reg }, { "ntop", ntop_reg }, {NULL, NULL} }; if(!L) return; luaopen_lsqlite3(L); for(i=0; ntop_lua_reg[i].class_name != NULL; i++) { int lib_id, meta_id; /* newclass = {} */ lua_createtable(L, 0, 0); lib_id = lua_gettop(L); /* metatable = {} */ luaL_newmetatable(L, ntop_lua_reg[i].class_name); meta_id = lua_gettop(L); luaL_register(L, NULL, _meta); /* metatable.__index = class_methods */ lua_newtable(L), luaL_register(L, NULL, ntop_lua_reg[i].class_methods); lua_setfield(L, meta_id, "__index"); /* class.__metatable = metatable */ lua_setmetatable(L, lib_id); /* _G["Foo"] = newclass */ lua_setglobal(L, ntop_lua_reg[i].class_name); } if(http_mode) { /* Overload the standard Lua print() with ntop_lua_http_print that dumps data on HTTP server */ lua_register(L, "print", ntop_lua_http_print); } else lua_register(L, "print", ntop_lua_cli_print); #ifdef NTOPNG_PRO if(ntop->getPro()->has_valid_license()) { lua_register(L, "ntopRequire", ntop_lua_require); luaL_dostring(L, "table.insert(package.loaders, 1, ntopRequire)"); lua_register(L, "dofile", ntop_lua_dofile); } #endif } /* ****************************************** */ #if 0 /** * Iterator over key-value pairs where the value * maybe made available in increments and/or may * not be zero-terminated. Used for processing * POST data. * * @param cls user-specified closure * @param kind type of the value * @param key 0-terminated key for the value * @param filename name of the uploaded file, NULL if not known * @param content_type mime-type of the data, NULL if not known * @param transfer_encoding encoding of the data, NULL if not known * @param data pointer to size bytes of data at the * specified offset * @param off offset of data in the overall value * @param size number of bytes in data available * @return MHD_YES to continue iterating, * MHD_NO to abort the iteration */ static int post_iterator(void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct Request *request = cls; char tmp[1024]; u_int len = min(size, sizeof(tmp)-1); memcpy(tmp, &data[off], len); tmp[len] = '\0'; fprintf(stdout, "[POST] [%s][%s]\n", key, tmp); return MHD_YES; } #endif /* ****************************************** */ /* Run a Lua script from within ntopng (no HTTP GUI) */ int Lua::run_script(char *script_path) { int rc = 0; if(!L) return(-1); try { luaL_openlibs(L); /* Load base libraries */ lua_register_classes(L, false); /* Load custom classes */ #ifndef NTOPNG_PRO rc = luaL_dofile(L, script_path); #else if(ntop->getPro()->has_valid_license()) rc = __ntop_lua_handlefile(L, script_path, true); else rc = luaL_dofile(L, script_path); #endif if(rc != 0) { const char *err = lua_tostring(L, -1); ntop->getTrace()->traceEvent(TRACE_WARNING, "Script failure [%s][%s]", script_path, err); rc = -1; } } catch(...) { ntop->getTrace()->traceEvent(TRACE_WARNING, "Script failure [%s]", script_path); rc = -2; } return(rc); } /* ****************************************** */ /* http://www.geekhideout.com/downloads/urlcode.c */ #if 0 /* Converts an integer value to its hex character*/ static char to_hex(char code) { static char hex[] = "0123456789abcdef"; return hex[code & 15]; } /* ****************************************** */ /* Returns a url-encoded version of str */ /* IMPORTANT: be sure to free() the returned string after use */ static char* http_encode(char *str) { char *pstr = str, *buf = (char*)malloc(strlen(str) * 3 + 1), *pbuf = buf; while (*pstr) { if(isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~') *pbuf++ = *pstr; else if(*pstr == ' ') *pbuf++ = '+'; else *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15); pstr++; } *pbuf = '\0'; return buf; } #endif /* ****************************************** */ /* Converts a hex character to its integer value */ static char from_hex(char ch) { return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10; } /* ****************************************** */ /* Returns a url-decoded version of str */ /* IMPORTANT: be sure to free() the returned string after use */ static char* http_decode(char *str) { char *pstr = str, *buf = (char*)malloc(strlen(str) + 1), *pbuf = buf; while (*pstr) { if(*pstr == '%') { if(pstr[1] && pstr[2]) { *pbuf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]); pstr += 2; } } else if(*pstr == '+') { *pbuf++ = ' '; } else { *pbuf++ = *pstr; } pstr++; } *pbuf = '\0'; return buf; } /* ****************************************** */ void Lua::purifyHTTPParameter(char *param) { char *ampercent; if((ampercent = strchr(param, '%')) != NULL) { /* We allow only a few chars, removing all the others */ if((ampercent[1] != 0) && (ampercent[2] != 0)) { char c; char b = ampercent[3]; ampercent[3] = '\0'; c = (char)strtol(&ampercent[1], NULL, 16); ampercent[3] = b; switch(c) { case '/': case ':': case '(': case ')': case '{': case '}': case '[': case ']': case '?': case '!': case '$': case ',': case '^': case '*': case '_': case '&': case ' ': case '=': case '<': case '>': case '@': case '#': break; default: if(!Utils::isPrintableChar(c)) { ntop->getTrace()->traceEvent(TRACE_WARNING, "Discarded char '%c' in URI [%s]", c, param); ampercent[0] = '\0'; return; } } purifyHTTPParameter(&ampercent[3]); } else ampercent[0] = '\0'; } } /* ****************************************** */ void Lua::setInterface(const char *user) { char key[64], ifname[MAX_INTERFACE_NAME_LEN]; bool enforce_allowed_interface = false; if(user[0] != '\0') { // check if the user is restricted to browse only a given interface if(snprintf(key, sizeof(key), CONST_STR_USER_ALLOWED_IFNAME, user) && !ntop->getRedis()->get(key, ifname, sizeof(ifname))) { // there is only one allowed interface for the user enforce_allowed_interface = true; goto set_preferred_interface; } else if(snprintf(key, sizeof(key), "ntopng.prefs.%s.ifname", user) && ntop->getRedis()->get(key, ifname, sizeof(ifname)) < 0) { // no allowed interface and no default set interface set_default_if_name_in_session: snprintf(ifname, sizeof(ifname), "%s", ntop->getInterfaceAtId(NULL /* allowed user interface check already enforced */, 0)->get_name()); lua_push_str_table_entry(L, "ifname", ifname); ntop->getRedis()->set(key, ifname, 3600 /* 1h */); } else { goto set_preferred_interface; } } else { // We need to check if ntopng is running with the option --disable-login snprintf(key, sizeof(key), "ntopng.prefs.ifname"); if(ntop->getRedis()->get(key, ifname, sizeof(ifname)) < 0) { goto set_preferred_interface; } set_preferred_interface: NetworkInterface *iface; if((iface = ntop->getNetworkInterface(NULL /* allowed user interface check already enforced */, ifname)) != NULL) { /* The specified interface still exists */ lua_push_str_table_entry(L, "ifname", iface->get_name()); } else if(!enforce_allowed_interface) { goto set_default_if_name_in_session; } else { // TODO: handle the case where the user has // an allowed interface that is not presently available // (e.g., not running?) } } } /* ****************************************** */ int Lua::handle_script_request(struct mg_connection *conn, const struct mg_request_info *request_info, char *script_path) { char buf[64], key[64], ifname[MAX_INTERFACE_NAME_LEN]; char *_cookies, user[64] = { '\0' }, outbuf[FILENAME_MAX]; AddressTree ptree; int rc; bool csrf_found = false; if(!L) return(-1); luaL_openlibs(L); /* Load base libraries */ lua_register_classes(L, true); /* Load custom classes */ lua_pushlightuserdata(L, (char*)conn); lua_setglobal(L, CONST_HTTP_CONN); /* Put the GET params into the environment */ lua_newtable(L); if(request_info->query_string != NULL) { char *query_string = strdup(request_info->query_string); if(query_string) { char *where; char *tok; // ntop->getTrace()->traceEvent(TRACE_WARNING, "[HTTP] %s", query_string); tok = strtok_r(query_string, "&", &where); while(tok != NULL) { /* key=val */ char *_equal = strchr(tok, '='); if(_equal) { char *equal; int len; _equal[0] = '\0'; _equal = &_equal[1]; len = strlen(_equal); purifyHTTPParameter(tok), purifyHTTPParameter(_equal); // ntop->getTrace()->traceEvent(TRACE_WARNING, "%s = %s", tok, _equal); if((equal = (char*)malloc(len+1)) != NULL) { char *decoded_buf; Utils::urlDecode(_equal, equal, len+1); if((decoded_buf = http_decode(equal)) != NULL) { FILE *fd; Utils::purifyHTTPparam(tok, true, false); Utils::purifyHTTPparam(decoded_buf, false, false); /* Now make sure that decoded_buf is not a file path */ if((decoded_buf[0] == '.') && ((fd = fopen(decoded_buf, "r")) || (fd = fopen(realpath(decoded_buf, outbuf), "r")))) { ntop->getTrace()->traceEvent(TRACE_WARNING, "Discarded '%s'='%s' as argument is a valid file path", tok, decoded_buf); decoded_buf[0] = '\0'; fclose(fd); } /* ntop->getTrace()->traceEvent(TRACE_WARNING, "'%s'='%s'", tok, decoded_buf); */ if(strcmp(tok, "csrf") == 0) { char rsp[32], user[64] = { '\0' }; mg_get_cookie(conn, "user", user, sizeof(user)); if((ntop->getRedis()->get(decoded_buf, rsp, sizeof(rsp)) == -1) || (strcmp(rsp, user) != 0)) { const char *msg = "The submitted form is expired. Please reload the page and try again"; ntop->getTrace()->traceEvent(TRACE_WARNING, "Invalid CSRF parameter specified [%s][%s][%s][%s]: page expired?", decoded_buf, rsp, user, tok); free(equal); return(send_error(conn, 500 /* Internal server error */, msg, PAGE_ERROR, query_string, msg)); } else ntop->getRedis()->delKey(decoded_buf); csrf_found = true; } lua_push_str_table_entry(L, tok, decoded_buf); free(decoded_buf); } free(equal); } else ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory"); } tok = strtok_r(NULL, "&", &where); } /* while */ free(query_string); } else ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory"); } if(strstr(request_info->uri, "/admin/") && (!csrf_found)) { const char *msg = "Missing CSRF parameter"; return(send_error(conn, 500 /* Internal server error */, msg, PAGE_ERROR, request_info->uri, msg)); } lua_setglobal(L, "_GET"); /* Like in php */ /* _SERVER */ lua_newtable(L); lua_push_str_table_entry(L, "HTTP_REFERER", (char*)mg_get_header(conn, "Referer")); lua_push_str_table_entry(L, "HTTP_USER_AGENT", (char*)mg_get_header(conn, "User-Agent")); lua_push_str_table_entry(L, "SERVER_NAME", (char*)mg_get_header(conn, "Host")); lua_setglobal(L, "_SERVER"); /* Like in php */ /* Cookies */ lua_newtable(L); if((_cookies = (char*)mg_get_header(conn, "Cookie")) != NULL) { char *cookies = strdup(_cookies); char *tok, *where; // ntop->getTrace()->traceEvent(TRACE_WARNING, "=> '%s'", cookies); tok = strtok_r(cookies, "=", &where); while(tok != NULL) { char *val; while(tok[0] == ' ') tok++; if((val = strtok_r(NULL, ";", &where)) != NULL) { lua_push_str_table_entry(L, tok, val); // ntop->getTrace()->traceEvent(TRACE_WARNING, "'%s'='%s'", tok, val); } else break; tok = strtok_r(NULL, "=", &where); } free(cookies); } lua_setglobal(L, "_COOKIE"); /* Like in php */ /* Put the _SESSION params into the environment */ lua_newtable(L); mg_get_cookie(conn, "user", user, sizeof(user)); lua_push_str_table_entry(L, "user", user); mg_get_cookie(conn, "session", buf, sizeof(buf)); lua_push_str_table_entry(L, "session", buf); // now it's time to set the interface. setInterface(user); lua_setglobal(L, "_SESSION"); /* Like in php */ if(user[0] != '\0') { char val[255]; lua_pushlightuserdata(L, user); lua_setglobal(L, "user"); snprintf(key, sizeof(key), "ntopng.user.%s.allowed_nets", user); if((ntop->getRedis()->get(key, val, sizeof(val)) != -1) && (val[0] != '\0')) { ptree.addAddresses(val); lua_pushlightuserdata(L, &ptree); lua_setglobal(L, CONST_ALLOWED_NETS); // ntop->getTrace()->traceEvent(TRACE_WARNING, "SET %p", ptree); } snprintf(key, sizeof(key), CONST_STR_USER_ALLOWED_IFNAME, user); if(snprintf(key, sizeof(key), CONST_STR_USER_ALLOWED_IFNAME, user) && !ntop->getRedis()->get(key, ifname, sizeof(ifname))) { lua_pushlightuserdata(L, ifname); lua_setglobal(L, CONST_ALLOWED_IFNAME); } } #ifndef NTOPNG_PRO rc = luaL_dofile(L, script_path); #else if(ntop->getPro()->has_valid_license()) rc = __ntop_lua_handlefile(L, script_path, true); else rc = luaL_dofile(L, script_path); #endif if(rc != 0) { const char *err = lua_tostring(L, -1); ntop->getTrace()->traceEvent(TRACE_WARNING, "Script failure [%s][%s]", script_path, err); return(send_error(conn, 500 /* Internal server error */, "Internal server error", PAGE_ERROR, script_path, err)); } return(CONST_LUA_OK); }
./CrossVul/dataset_final_sorted/CWE-352/cpp/good_3092_0
crossvul-cpp_data_bad_3092_0
/* * * (C) 2013-17 - ntop.org * * * 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, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include "ntop_includes.h" #ifndef _GETOPT_H #define _GETOPT_H #endif #ifndef LIB_VERSION #define LIB_VERSION "1.4.7" #endif extern "C" { #include "rrd.h" #ifdef HAVE_GEOIP extern const char * GeoIP_lib_version(void); #endif #include "../third-party/snmp/snmp.c" #include "../third-party/snmp/asn1.c" #include "../third-party/snmp/net.c" }; #include "../third-party/lsqlite3/lsqlite3.c" struct keyval string_to_replace[MAX_NUM_HTTP_REPLACEMENTS] = { { NULL, NULL } }; /* ******************************* */ Lua::Lua() { L = luaL_newstate(); if(L == NULL) { ntop->getTrace()->traceEvent(TRACE_ERROR, "Unable to create Lua interpreter"); return; } } /* ******************************* */ Lua::~Lua() { if(L) lua_close(L); } /* ******************************* */ /** * @brief Check the expected type of lua function. * @details Find in the lua stack the function and check the function parameters types. * * @param vm The lua state. * @param func The function name. * @param pos Index of lua stack. * @param expected_type Index of expected type. * @return @ref CONST_LUA_ERROR if the expected type is equal to function type, @ref CONST_LUA_PARAM_ERROR otherwise. */ int ntop_lua_check(lua_State* vm, const char* func, int pos, int expected_type) { if(lua_type(vm, pos) != expected_type) { ntop->getTrace()->traceEvent(TRACE_ERROR, "%s : expected %s, got %s", func, lua_typename(vm, expected_type), lua_typename(vm, lua_type(vm,pos))); return(CONST_LUA_PARAM_ERROR); } return(CONST_LUA_ERROR); } /* ****************************************** */ static NetworkInterface* handle_null_interface(lua_State* vm) { char allowed_ifname[MAX_INTERFACE_NAME_LEN]; ntop->getTrace()->traceEvent(TRACE_INFO, "NULL interface: did you restart ntopng in the meantime?"); if(ntop->getInterfaceAllowed(vm, allowed_ifname)) { return ntop->getNetworkInterface(allowed_ifname); } return(ntop->getInterfaceAtId(0)); } /* ****************************************** */ static int ntop_dump_file(lua_State* vm) { char *fname; FILE *fd; struct mg_connection *conn; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_getglobal(vm, CONST_HTTP_CONN); if((conn = (struct mg_connection*)lua_touserdata(vm, lua_gettop(vm))) == NULL) { ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: null HTTP connection"); return(CONST_LUA_ERROR); } if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((fname = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); ntop->fixPath(fname); if((fd = fopen(fname, "r")) != NULL) { char tmp[1024]; ntop->getTrace()->traceEvent(TRACE_INFO, "[HTTP] Serving file %s", fname); while((fgets(tmp, sizeof(tmp)-256 /* To make sure we have room for replacements */, fd)) != NULL) { for(int i=0; string_to_replace[i].key != NULL; i++) Utils::replacestr(tmp, string_to_replace[i].key, string_to_replace[i].val); mg_printf(conn, "%s", tmp); } fclose(fd); return(CONST_LUA_OK); } else { ntop->getTrace()->traceEvent(TRACE_INFO, "Unable to read file %s", fname); return(CONST_LUA_ERROR); } } /* ****************************************** */ /** * @brief Get default interface name. * @details Push the default interface name of ntop into the lua stack. * * @param vm The lua state. * @return @ref CONST_LUA_OK. */ static int ntop_get_default_interface_name(lua_State* vm) { char ifname[MAX_INTERFACE_NAME_LEN]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop->getInterfaceAllowed(vm, ifname)) { // if there is an allowed interface for the user // we return that interface lua_pushstring(vm, ntop->getNetworkInterface(ifname)->get_name()); } else { lua_pushstring(vm, ntop->getInterfaceAtId(NULL, /* no need to check as there is no constaint */ 0)->get_name()); } return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Set the name of active interface id into lua stack. * * @param vm The lua stack. * @return @ref CONST_LUA_OK. */ static int ntop_set_active_interface_id(lua_State* vm) { NetworkInterface *iface; int id; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); id = (u_int32_t)lua_tonumber(vm, 1); iface = ntop->getNetworkInterface(vm, id); ntop->getTrace()->traceEvent(TRACE_INFO, "Index: %d, Name: %s", id, iface ? iface->get_name() : "<unknown>"); if(iface != NULL) lua_pushstring(vm, iface->get_name()); else lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the ntopng interface names. * * @param vm The lua state. * @return @ref CONST_LUA_OK. */ static int ntop_get_interface_names(lua_State* vm) { lua_newtable(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); for(int i=0; i<ntop->get_num_interfaces(); i++) { NetworkInterface *iface; if((iface = ntop->getInterfaceAtId(vm, i)) != NULL) { char num[8]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "Returning name %s", iface->get_name()); snprintf(num, sizeof(num), "%d", i); lua_push_str_table_entry(vm, num, iface->get_name()); } } return(CONST_LUA_OK); } /* ****************************************** */ static AddressTree* get_allowed_nets(lua_State* vm) { AddressTree *ptree; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_getglobal(vm, CONST_ALLOWED_NETS); ptree = (AddressTree*)lua_touserdata(vm, lua_gettop(vm)); //ntop->getTrace()->traceEvent(TRACE_WARNING, "GET %p", ptree); return(ptree); } /* ****************************************** */ static NetworkInterface* getCurrentInterface(lua_State* vm) { NetworkInterface *ntop_interface; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_getglobal(vm, "ntop_interface"); if((ntop_interface = (NetworkInterface*)lua_touserdata(vm, lua_gettop(vm))) == NULL) { ntop_interface = handle_null_interface(vm); } return(ntop_interface); } /* ****************************************** */ /** * @brief Find the network interface and set it as global variable to lua. * * @param vm The lua state. * @return @ref CONST_LUA_OK */ static int ntop_select_interface(lua_State* vm) { char *ifname; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TNIL) ifname = (char*)"any"; else { if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); ifname = (char*)lua_tostring(vm, 1); } lua_pushlightuserdata(vm, (char*)ntop->getNetworkInterface(vm, ifname)); lua_setglobal(vm, "ntop_interface"); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the nDPI statistics of interface. * @details Get the ntop interface global variable of lua, get nDpistats of interface and push it into lua stack. * * @param vm The lua state. * @return @ref CONST_LUA_OK */ static int ntop_get_ndpi_interface_stats(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); nDPIStats stats; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) { ntop_interface->getnDPIStats(&stats); lua_newtable(vm); stats.lua(ntop_interface, vm); } return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the ndpi flows count of interface. * @details Get the ntop interface global variable of lua, get nDpi flow count of interface and push it into lua stack. * * @param vm The lua state. * @return @ref CONST_LUA_OK */ static int ntop_get_ndpi_interface_flows_count(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) { lua_newtable(vm); ntop_interface->getnDPIFlowsCount(vm); } return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the flow status for flows in cache * @details Get the ntop interface global variable of lua, get flow stats of interface and push it into lua stack. * * @param vm The lua state. * @return @ref CONST_LUA_OK */ static int ntop_get_ndpi_interface_flows_status(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) { lua_newtable(vm); ntop_interface->getFlowsStatus(vm); } return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the ndpi protocol name of protocol id of network interface. * @details Get the ntop interface global variable of lua. Once do that, get the protocol id of lua stack and return into lua stack "Host-to-Host Contact" if protocol id is equal to host family id; the protocol name or null otherwise. * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise. */ static int ntop_get_ndpi_protocol_name(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); nDPIStats stats; int proto; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); proto = (u_int32_t)lua_tonumber(vm, 1); if(proto == HOST_FAMILY_ID) lua_pushstring(vm, "Host-to-Host Contact"); else { if(ntop_interface) lua_pushstring(vm, ntop_interface->get_ndpi_proto_name(proto)); else lua_pushnil(vm); } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_ndpi_protocol_id(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); nDPIStats stats; char *proto; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); proto = (char*)lua_tostring(vm, 1); if(ntop_interface && proto) lua_pushnumber(vm, ntop_interface->get_ndpi_proto_id(proto)); else lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_ndpi_protocol_category(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); u_int proto; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); proto = (u_int)lua_tonumber(vm, 1); if(ntop_interface) { ndpi_protocol_category_t category = ntop_interface->get_ndpi_proto_category(proto); lua_newtable(vm); lua_push_int32_table_entry(vm, "id", category); lua_push_str_table_entry(vm, "name", (char*)ndpi_category_str(category)); } else lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Same as ntop_get_ndpi_protocol_name() with the exception that the protocol breed is returned * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise. */ static int ntop_get_ndpi_protocol_breed(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); nDPIStats stats; int proto; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); proto = (u_int32_t)lua_tonumber(vm, 1); if(proto == HOST_FAMILY_ID) lua_pushstring(vm, "Unrated-to-Host Contact"); else { if(ntop_interface) lua_pushstring(vm, ntop_interface->get_ndpi_proto_breed_name(proto)); else lua_pushnil(vm); } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_hosts(lua_State* vm, LocationPolicy location) { NetworkInterface *ntop_interface = getCurrentInterface(vm); bool show_details = true; char *sortColumn = (char*)"column_ip", *country = NULL, *os_filter = NULL, *mac_filter = NULL; bool a2zSortOrder = true; u_int16_t vlan_filter, *vlan_filter_ptr = NULL; u_int32_t asn_filter, *asn_filter_ptr = NULL; int16_t network_filter, *network_filter_ptr = NULL; u_int32_t toSkip = 0, maxHits = CONST_MAX_NUM_HITS; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TBOOLEAN) show_details = lua_toboolean(vm, 1) ? true : false; if(lua_type(vm, 2) == LUA_TSTRING) sortColumn = (char*)lua_tostring(vm, 2); if(lua_type(vm, 3) == LUA_TNUMBER) maxHits = (u_int16_t)lua_tonumber(vm, 3); if(lua_type(vm, 4) == LUA_TNUMBER) toSkip = (u_int16_t)lua_tonumber(vm, 4); if(lua_type(vm, 5) == LUA_TBOOLEAN) a2zSortOrder = lua_toboolean(vm, 5) ? true : false; if(lua_type(vm, 6) == LUA_TSTRING) country = (char*)lua_tostring(vm, 6); if(lua_type(vm, 7) == LUA_TSTRING) os_filter = (char*)lua_tostring(vm, 7); if(lua_type(vm, 8) == LUA_TNUMBER) vlan_filter = (u_int16_t)lua_tonumber(vm, 8), vlan_filter_ptr = &vlan_filter; if(lua_type(vm, 9) == LUA_TNUMBER) asn_filter = (u_int32_t)lua_tonumber(vm, 9), asn_filter_ptr = &asn_filter; if(lua_type(vm,10) == LUA_TNUMBER) network_filter = (int16_t)lua_tonumber(vm, 10), network_filter_ptr = &network_filter; if(lua_type(vm,11) == LUA_TSTRING) mac_filter = (char*)lua_tostring(vm, 11); if(!ntop_interface || ntop_interface->getActiveHostsList(vm, get_allowed_nets(vm), show_details, location, country, mac_filter, vlan_filter_ptr, os_filter, asn_filter_ptr, network_filter_ptr, sortColumn, maxHits, toSkip, a2zSortOrder) < 0) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_latest_activity_hosts_info(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->getLatestActivityHostsList(vm, get_allowed_nets(vm)); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the host information of network interface grouped according to the criteria. * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null or the host is null, CONST_LUA_OK otherwise. */ static int ntop_get_grouped_interface_hosts(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); bool show_details = true, hostsOnly = true; char *country = NULL, *os_filter = NULL; char *groupBy = (char*)"column_ip"; u_int16_t vlan_filter, *vlan_filter_ptr = NULL; u_int32_t asn_filter, *asn_filter_ptr = NULL; int16_t network_filter, *network_filter_ptr = NULL; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TBOOLEAN) show_details = lua_toboolean(vm, 1) ? true : false; if(lua_type(vm, 2) == LUA_TSTRING) groupBy = (char*)lua_tostring(vm, 2); if(lua_type(vm, 3) == LUA_TSTRING) country = (char*)lua_tostring(vm, 3); if(lua_type(vm, 4) == LUA_TSTRING) os_filter = (char*)lua_tostring(vm, 4); if(lua_type(vm, 5) == LUA_TNUMBER) vlan_filter = (u_int16_t)lua_tonumber(vm, 5), vlan_filter_ptr = &vlan_filter; if(lua_type(vm, 6) == LUA_TNUMBER) asn_filter = (u_int32_t)lua_tonumber(vm, 6), asn_filter_ptr = &asn_filter; if(lua_type(vm, 7) == LUA_TNUMBER) network_filter = (int16_t)lua_tonumber(vm, 7), network_filter_ptr = &network_filter; if(lua_type(vm, 8) == LUA_TBOOLEAN) hostsOnly = lua_toboolean(vm, 8) ? true : false; if((!ntop_interface) || ntop_interface->getActiveHostsGroup(vm, get_allowed_nets(vm), show_details, location_all, country, vlan_filter_ptr, os_filter, asn_filter_ptr, network_filter_ptr, hostsOnly, groupBy) < 0) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the hosts information of network interface. * @details Get the ntop interface global variable of lua and return into lua stack a new hash table of hash tables containing the host information. * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise. */ static int ntop_get_interface_hosts_info(lua_State* vm) { return(ntop_get_interface_hosts(vm, location_all)); } /* ****************************************** */ static int ntop_get_interface_macs_info(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *sortColumn = (char*)"column_mac"; u_int32_t toSkip = 0, maxHits = CONST_MAX_NUM_HITS; u_int16_t vlan_id = 0; bool a2zSortOrder = true, skipSpecialMacs = false, hostMacsOnly = false; if(lua_type(vm, 1) == LUA_TSTRING) { sortColumn = (char*)lua_tostring(vm, 1); if(lua_type(vm, 2) == LUA_TNUMBER) { maxHits = (u_int16_t)lua_tonumber(vm, 2); if(lua_type(vm, 3) == LUA_TNUMBER) { toSkip = (u_int16_t)lua_tonumber(vm, 3); if(lua_type(vm, 4) == LUA_TBOOLEAN) { a2zSortOrder = lua_toboolean(vm, 4) ? true : false; if(lua_type(vm, 5) == LUA_TNUMBER) { vlan_id = (u_int16_t)lua_tonumber(vm, 5); if(lua_type(vm, 6) == LUA_TBOOLEAN) { skipSpecialMacs = lua_toboolean(vm, 6) ? true : false; } if(lua_type(vm, 7) == LUA_TBOOLEAN) { hostMacsOnly = lua_toboolean(vm, 7) ? true : false; } } } } } } if(!ntop_interface || ntop_interface->getActiveMacList(vm, vlan_id, skipSpecialMacs, hostMacsOnly, sortColumn, maxHits, toSkip, a2zSortOrder) < 0) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_mac_info(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *mac = NULL; u_int16_t vlan_id = 0; if(lua_type(vm, 1) == LUA_TSTRING) { mac = (char*)lua_tostring(vm, 1); if(lua_type(vm, 2) == LUA_TNUMBER) { vlan_id = (u_int16_t)lua_tonumber(vm, 2); } } if((!ntop_interface) || (!mac) || (!ntop_interface->getMacInfo(vm, mac, vlan_id))) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get local hosts information of network interface. * @details Get the ntop interface global variable of lua and return into lua stack a new hash table of hash tables containing the local host information. * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise. */ static int ntop_get_interface_local_hosts_info(lua_State* vm) { return(ntop_get_interface_hosts(vm, location_local_only)); } /* ****************************************** */ /** * @brief Get remote hosts information of network interface. * @details Get the ntop interface global variable of lua and return into lua stack a new hash table of hash tables containing the remote host information. * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null, CONST_LUA_OK otherwise. */ static int ntop_get_interface_remote_hosts_info(lua_State* vm) { return(ntop_get_interface_hosts(vm, location_remote_only)); } /* ****************************************** */ /** * @brief Get local hosts activity information. * @details Get the ntop interface global variable of lua and return into lua stack a new hash table of hash tables containing the local host activities. * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null or host is null, CONST_LUA_OK otherwise. */ static int ntop_get_interface_host_activity(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); const char * host = NULL; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if (lua_type(vm, 1) == LUA_TSTRING) host = lua_tostring(vm, 1); if (ntop_interface == NULL || host == NULL) return CONST_LUA_ERROR; ntop_interface->getLocalHostActivity(vm, host); return CONST_LUA_OK; } /* ****************************************** */ /** * @brief Check if the specified path is a directory and it exists. * @details True if if the specified path is a directory and it exists, false otherwise. * * @param vm The lua state. * @return CONST_LUA_OK */ static int ntop_is_dir(lua_State* vm) { char *path; struct stat buf; int rc; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); path = (char*)lua_tostring(vm, 1); rc = ((stat(path, &buf) != 0) || (!S_ISDIR(buf.st_mode))) ? 0 : 1; lua_pushboolean(vm, rc); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Check if the file is exists and is not empty * @details Simple check for existance + non empty file * * @param vm The lua state. * @return CONST_LUA_OK */ static int ntop_is_not_empty_file(lua_State* vm) { char *path; struct stat buf; int rc; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); path = (char*)lua_tostring(vm, 1); rc = (stat(path, &buf) != 0) ? 0 : 1; if(rc && (buf.st_size == 0)) rc = 0; lua_pushboolean(vm, rc); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Check if the file or directory exists. * @details Get the path of file/directory from to lua stack and push true into lua stack if it exists, false otherwise. * * @param vm The lua state. * @return CONST_LUA_OK */ static int ntop_get_file_dir_exists(lua_State* vm) { char *path; struct stat buf; int rc; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); path = (char*)lua_tostring(vm, 1); rc = (stat(path, &buf) != 0) ? 0 : 1; // ntop->getTrace()->traceEvent(TRACE_ERROR, "%s: %d", path, rc); lua_pushboolean(vm, rc); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Return the epoch of the file last change * @details This function return that time (epoch) of the last chnge on a file, or -1 if the file does not exist. * * @param vm The lua state. * @return CONST_LUA_OK */ static int ntop_get_file_last_change(lua_State* vm) { char *path; struct stat buf; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); path = (char*)lua_tostring(vm, 1); if(stat(path, &buf) == 0) lua_pushnumber(vm, (lua_Number)buf.st_mtime); else lua_pushnumber(vm, -1); /* not found */ return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Check if ntop has seen VLAN tagged packets on this interface. * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_has_vlans(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) lua_pushboolean(vm, ntop_interface->hasSeenVlanTaggedPackets()); else lua_pushboolean(vm, 0); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Check if ntop has loaded ASN information (via GeoIP) * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_has_geoip(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_pushboolean(vm, ntop->getGeolocation() ? 1 : 0); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Check if ntop is running on windows. * @details Push into lua stack 1 if ntop is running on windows, 0 otherwise. * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_is_windows(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_pushboolean(vm, #ifdef WIN32 1 #else 0 #endif ); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_allocHostBlacklist(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); ntop->allocHostBlacklist(); lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_swapHostBlacklist(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); ntop->swapHostBlacklist(); lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_addToHostBlacklist(lua_State* vm) { char *net; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); net = (char*)lua_tostring(vm, 1); ntop->addToHostBlacklist(net); lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Wrapper for the libc call getservbyport() * @details Wrapper for the libc call getservbyport() * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_getservbyport(lua_State* vm) { int port; char *proto; struct servent *s = NULL; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); port = (int)lua_tonumber(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); proto = (char*)lua_tostring(vm, 2); if((port > 0) && (proto != NULL)) s = getservbyport(htons(port), proto); if(s && s->s_name) lua_pushstring(vm, s->s_name); else { char buf[32]; snprintf(buf, sizeof(buf), "%d", port); lua_pushstring(vm, buf); } return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Scan the input directory and return the list of files. * @details Get the path from the lua stack and push into a new hashtable the files name existing in the directory. * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_list_dir_files(lua_State* vm) { char *path; DIR *dirp; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); path = (char*)lua_tostring(vm, 1); ntop->fixPath(path); lua_newtable(vm); if((dirp = opendir(path)) != NULL) { struct dirent *dp; while ((dp = readdir(dirp)) != NULL) if((dp->d_name[0] != '\0') && (dp->d_name[0] != '.')) { lua_push_str_table_entry(vm, dp->d_name, dp->d_name); } (void)closedir(dirp); } return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the system time and push it into the lua stack. * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_gettimemsec(lua_State* vm) { struct timeval tp; double ret; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); gettimeofday(&tp, NULL); ret = (((double)tp.tv_usec) / (double)1000) + tp.tv_sec; lua_pushnumber(vm, ret); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Lua-equivaled ot C inet_ntoa * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_inet_ntoa(lua_State* vm) { u_int32_t ip; struct in_addr in; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TSTRING) ip = atol((char*)lua_tostring(vm, 1)); else if(lua_type(vm, 1) == LUA_TNUMBER) ip = (u_int32_t)lua_tonumber(vm, 1); else return(CONST_LUA_ERROR); in.s_addr = htonl(ip); lua_pushstring(vm, inet_ntoa(in)); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_zmq_connect(lua_State* vm) { char *endpoint, *topic; void *context, *subscriber; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((endpoint = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((topic = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); context = zmq_ctx_new(), subscriber = zmq_socket(context, ZMQ_SUB); if(zmq_connect(subscriber, endpoint) != 0) { zmq_close(subscriber); zmq_ctx_destroy(context); return(CONST_LUA_PARAM_ERROR); } if(zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, topic, strlen(topic)) != 0) { zmq_close(subscriber); zmq_ctx_destroy(context); return -1; } lua_pushlightuserdata(vm, context); lua_setglobal(vm, "zmq_context"); lua_pushlightuserdata(vm, subscriber); lua_setglobal(vm, "zmq_subscriber"); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Delete the specified member(field) from the redis hash stored at key. * @details Get the key parameter from the lua stack and delete it from redis. * * @param vm The lua stack. * @return CONST_LUA_OK. */ static int ntop_delete_redis_key(lua_State* vm) { char *key; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); ntop->getRedis()->delKey(key); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the members of a redis set. * @details Get the set key form the lua stack and push the mambers name into lua stack. * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_get_set_members_redis(lua_State* vm) { char *key; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); ntop->getRedis()->smembers(vm, key); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Delete the specified member(field) from the redis hash stored at key. * @details Get the member name and the hash key form the lua stack and remove the specified member. * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_delete_hash_redis_key(lua_State* vm) { char *key, *member; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((member = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); ntop->getRedis()->hashDel(key, member); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_zmq_disconnect(lua_State* vm) { void *context, *subscriber; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_getglobal(vm, "zmq_context"); if((context = (void*)lua_touserdata(vm, lua_gettop(vm))) == NULL) { ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: NULL context"); return(CONST_LUA_ERROR); } lua_getglobal(vm, "zmq_subscriber"); if((subscriber = (void*)lua_touserdata(vm, lua_gettop(vm))) == NULL) { ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: NULL subscriber"); return(CONST_LUA_ERROR); } zmq_close(subscriber); zmq_ctx_destroy(context); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_zmq_receive(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); void *subscriber; int size; struct zmq_msg_hdr h; char *payload; int payload_len; zmq_pollitem_t item; int rc; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_getglobal(vm, "zmq_subscriber"); if((subscriber = (void*)lua_touserdata(vm, lua_gettop(vm))) == NULL) { ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: NULL subscriber"); return(CONST_LUA_ERROR); } item.socket = subscriber; item.events = ZMQ_POLLIN; do { rc = zmq_poll(&item, 1, 1000); if(rc < 0 || !ntop_interface->isRunning()) /* CHECK */ return(CONST_LUA_PARAM_ERROR); } while (rc == 0); size = zmq_recv(subscriber, &h, sizeof(h), 0); if(size != sizeof(h) || h.version != ZMQ_MSG_VERSION) { ntop->getTrace()->traceEvent(TRACE_WARNING, "Unsupported publisher version [%d]", h.version); return -1; } payload_len = h.size + 1; if((payload = (char*)malloc(payload_len)) != NULL) { size = zmq_recv(subscriber, payload, payload_len, 0); payload[h.size] = '\0'; if(size > 0) { enum json_tokener_error jerr = json_tokener_success; json_object *o = json_tokener_parse_verbose(payload, &jerr); if(o != NULL) { struct json_object_iterator it = json_object_iter_begin(o); struct json_object_iterator itEnd = json_object_iter_end(o); while (!json_object_iter_equal(&it, &itEnd)) { char *key = (char*)json_object_iter_peek_name(&it); const char *value = json_object_get_string(json_object_iter_peek_value(&it)); ntop->getTrace()->traceEvent(TRACE_NORMAL, "[%s]=[%s]", key, value); json_object_iter_next(&it); } json_object_put(o); } else ntop->getTrace()->traceEvent(TRACE_WARNING, "JSON Parse error [%s]: %s", json_tokener_error_desc(jerr), payload); lua_pushfstring(vm, "%s", payload); ntop->getTrace()->traceEvent(TRACE_INFO, "[%u] %s", h.size, payload); free(payload); return(CONST_LUA_OK); } else { free(payload); return(CONST_LUA_PARAM_ERROR); } } else return(CONST_LUA_PARAM_ERROR); } /* ****************************************** */ static int ntop_get_local_networks(lua_State* vm) { lua_newtable(vm); ntop->getLocalNetworks(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_reload_preferences(lua_State* vm) { lua_newtable(vm); ntop->getPrefs()->reloadPrefsFromRedis(); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Check if the trace level of ntop is verbose. * @details Push true into the lua stack if the trace level of ntop is set to MAX_TRACE_LEVEL, false otherwise. * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_verbose_trace(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_pushboolean(vm, (ntop->getTrace()->get_trace_level() == MAX_TRACE_LEVEL) ? true : false); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_send_udp_data(lua_State* vm) { int rc, port, sockfd = ntop->getUdpSock(); char *host, *data; if(sockfd == -1) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); host = (char*)lua_tostring(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); port = (u_int16_t)lua_tonumber(vm, 2); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR); data = (char*)lua_tostring(vm, 3); if(strchr(host, ':') != NULL) { struct sockaddr_in6 server_addr; memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin6_family = AF_INET6; inet_pton(AF_INET6, host, &server_addr.sin6_addr); server_addr.sin6_port = htons(port); rc = sendto(sockfd, data, strlen(data),0, (struct sockaddr *)&server_addr, sizeof(server_addr)); } else { struct sockaddr_in server_addr; memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(host); /* FIX: add IPv6 support */ server_addr.sin_port = htons(port); rc = sendto(sockfd, data, strlen(data),0, (struct sockaddr *)&server_addr, sizeof(server_addr)); } if(rc == -1) return(CONST_LUA_ERROR); else return(CONST_LUA_OK); } /* ****************************************** */ static void get_host_vlan_info(char* lua_ip, char** host_ip, u_int16_t* vlan_id, char *buf, u_int buf_len) { char *where, *vlan = NULL; snprintf(buf, buf_len, "%s", lua_ip); if(((*host_ip) = strtok_r(buf, "@", &where)) != NULL) vlan = strtok_r(NULL, "@", &where); if(vlan) (*vlan_id) = (u_int16_t)atoi(vlan); } /* ****************************************** */ static int ntop_get_interface_flows(lua_State* vm, LocationPolicy location) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char buf[64]; char *host_ip = NULL; u_int16_t vlan_id = 0; Host *host = NULL; Paginator *p = NULL; int numFlows = -1; if(!ntop_interface) return(CONST_LUA_ERROR); if((p = new(std::nothrow) Paginator()) == NULL) return(CONST_LUA_ERROR); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TSTRING) { get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); host = ntop_interface->getHost(host_ip, vlan_id); } if(lua_type(vm, 2) == LUA_TTABLE) p->readOptions(vm, 2); if(ntop_interface) numFlows = ntop_interface->getFlows(vm, get_allowed_nets(vm), location, host, p); if(p) delete p; return numFlows < 0 ? CONST_LUA_ERROR : CONST_LUA_OK; } static int ntop_get_interface_flows_info(lua_State* vm) { return(ntop_get_interface_flows(vm, location_all)); } static int ntop_get_interface_local_flows_info(lua_State* vm) { return(ntop_get_interface_flows(vm, location_local_only)); } static int ntop_get_interface_remote_flows_info(lua_State* vm) { return(ntop_get_interface_flows(vm, location_remote_only)); } /* ****************************************** */ /** * @brief Get nDPI stats for flows * @details Compute nDPI flow statistics * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_get_interface_flows_stats(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) ntop_interface->getFlowsStats(vm); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get interface stats for local networks * @details Returns traffic statistics per local network * * @param vm The lua state. * @return CONST_LUA_OK. */ static int ntop_get_interface_networks_stats(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) ntop_interface->getNetworksStats(vm); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Get the host information of network interface. * @details Get the ntop interface global variable of lua, the host ip and optional the VLAN id form the lua stack and push a new hash table of hash tables containing the host information into lua stack. * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null or the host is null, CONST_LUA_OK otherwise. */ static int ntop_get_interface_host_info(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((!ntop_interface) || !ntop_interface->getHostInfo(vm, get_allowed_nets(vm), host_ip, vlan_id)) return(CONST_LUA_ERROR); else return(CONST_LUA_OK); } /* ****************************************** */ #ifdef NOTUSED static int ntop_get_grouped_interface_host(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *country_s = NULL, *os_s = NULL; u_int16_t vlan_n, *vlan_ptr = NULL; u_int32_t as_n, *as_ptr = NULL; int16_t network_n, *network_ptr = NULL; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TNUMBER) vlan_n = (u_int16_t)lua_tonumber(vm, 1), vlan_ptr = &vlan_n; if(lua_type(vm, 2) == LUA_TNUMBER) as_n = (u_int32_t)lua_tonumber(vm, 2), as_ptr = &as_n; if(lua_type(vm, 3) == LUA_TNUMBER) network_n = (int16_t)lua_tonumber(vm, 3), network_ptr = &network_n; if(lua_type(vm, 4) == LUA_TSTRING) country_s = (char*)lua_tostring(vm, 4); if(lua_type(vm, 5) == LUA_TSTRING) os_s = (char*)lua_tostring(vm, 5); if(!ntop_interface || ntop_interface->getActiveHostsGroup(vm, get_allowed_nets(vm), false, false, country_s, vlan_ptr, os_s, as_ptr, network_ptr, (char*)"column_ip", (char*)"country", CONST_MAX_NUM_HITS, 0 /* toSkip */, true /* a2zSortOrder */) < 0) return(CONST_LUA_ERROR); else return(CONST_LUA_OK); } #endif /* ****************************************** */ static int ntop_getflowdevices(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); else { ntop_interface->getFlowDevices(vm); return(CONST_LUA_OK); } } /* ****************************************** */ static int ntop_getflowdeviceinfo(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *device_ip; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); device_ip = (char*)lua_tostring(vm, 1); if(!ntop_interface) return(CONST_LUA_ERROR); else { in_addr_t addr = inet_addr(device_ip); ntop_interface->getFlowDeviceInfo(vm, ntohl(addr)); return(CONST_LUA_OK); } } /* ****************************************** */ static int ntop_interface_load_host_alert_prefs(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((!ntop_interface) || !ntop_interface->loadHostAlertPrefs(vm, get_allowed_nets(vm), host_ip, vlan_id)) return(CONST_LUA_ERROR); else return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_host_reset_periodic_stats(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; Host *h; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((!ntop_interface) || ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL)) return(CONST_LUA_ERROR); h->resetPeriodicStats(); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_host_trigger_alerts(lua_State* vm, bool trigger) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; Host *h; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((!ntop_interface) || ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL)) return(CONST_LUA_ERROR); if(trigger) h->enableAlerts(); else h->disableAlerts(); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_host_enable_alerts(lua_State* vm) { return ntop_interface_host_trigger_alerts(vm, true); } /* ****************************************** */ static int ntop_interface_host_disable_alerts(lua_State* vm) { return ntop_interface_host_trigger_alerts(vm, false); } /* ****************************************** */ static int ntop_interface_refresh_num_alerts(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); AlertsManager *am; Host *h; char *host_ip; u_int16_t vlan_id = 0; u_int32_t num_alerts; char buf[128]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if((!ntop_interface)) return(CONST_LUA_ERROR); if(lua_type(vm, 1) == LUA_TSTRING) { get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((h = ntop_interface->getHost(host_ip, vlan_id))) { if(lua_type(vm, 3) == LUA_TNUMBER) { num_alerts = (u_int32_t)lua_tonumber(vm, 3); h->setNumAlerts(num_alerts); } else { h->getNumAlerts(true /* From AlertsManager re-reads the values */); } } } else { if((am = ntop_interface->getAlertsManager()) == NULL) return(CONST_LUA_ERROR); am->refreshCachedNumAlerts(); } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_correalate_host_activity(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((!ntop_interface) || !ntop_interface->correlateHostActivity(vm, get_allowed_nets(vm), host_ip, vlan_id)) return(CONST_LUA_ERROR); else return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_similar_host_activity(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((!ntop_interface) || !ntop_interface->similarHostActivity(vm, get_allowed_nets(vm), host_ip, vlan_id)) return(CONST_LUA_ERROR); else return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_host_activitymap(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; GenericHost *h; u_int16_t vlan_id = 0; char buf[64]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); h = ntop_interface->getHost(host_ip, vlan_id); if(h == NULL) return(CONST_LUA_ERROR); else { if(h->match(get_allowed_nets(vm))) { char *json = h->getJsonActivityMap(); lua_pushfstring(vm, "%s", json); free(json); } return(CONST_LUA_OK); } } /* ****************************************** */ /** * @brief Restore the host of network interface. * @details Get the ntop interface global variable of lua and the IP address of host form the lua stack and restore the host into hash host of network interface. * * @param vm The lua state. * @return CONST_LUA_ERROR if ntop_interface is null or if is impossible to restore the host, CONST_LUA_OK otherwise. */ static int ntop_restore_interface_host(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; bool skip_privileges_check = false; char buf[64]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* make sure skip privileges check cannot be set from the web interface */ if(lua_type(vm, 2) == LUA_TBOOLEAN) skip_privileges_check = lua_toboolean(vm, 2); if(!skip_privileges_check && !Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if((!ntop_interface) || !ntop_interface->restoreHost(host_ip, vlan_id)) return(CONST_LUA_ERROR); else return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_flows_peers(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_name; u_int16_t vlan_id = 0; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TSTRING) { char buf[64]; get_host_vlan_info((char*)lua_tostring(vm, 1), &host_name, &vlan_id, buf, sizeof(buf)); } else host_name = NULL; /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if(ntop_interface) ntop_interface->getFlowPeersList(vm, get_allowed_nets(vm), host_name, vlan_id); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_flow_key(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); Host *cli, *srv; char *cli_name = NULL; u_int16_t cli_vlan = 0; u_int16_t cli_port = 0; char *srv_name = NULL; u_int16_t srv_vlan = 0; u_int16_t srv_port = 0; u_int16_t protocol; char cli_buf[256], srv_buf[256]; if(!ntop_interface) return(CONST_LUA_ERROR); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING) /* cli_host@cli_vlan */ || ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER) /* cli port */ || ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING) /* srv_host@srv_vlan */ || ntop_lua_check(vm, __FUNCTION__, 4, LUA_TNUMBER) /* srv port */ || ntop_lua_check(vm, __FUNCTION__, 5, LUA_TNUMBER) /* protocol */ ) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &cli_name, &cli_vlan, cli_buf, sizeof(cli_buf)); cli_port = htons((u_int16_t)lua_tonumber(vm, 2)); get_host_vlan_info((char*)lua_tostring(vm, 3), &srv_name, &srv_vlan, srv_buf, sizeof(srv_buf)); srv_port = htons((u_int16_t)lua_tonumber(vm, 4)); protocol = (u_int16_t)lua_tonumber(vm, 5); if(cli_vlan != srv_vlan) { ntop->getTrace()->traceEvent(TRACE_ERROR, "Client and Server vlans don't match."); return(CONST_LUA_ERROR); } if(cli_name == NULL || srv_name == NULL ||(cli = ntop_interface->getHost(cli_name, cli_vlan)) == NULL ||(srv = ntop_interface->getHost(srv_name, srv_vlan)) == NULL) { lua_pushnil(vm); } else { lua_pushnumber(vm, Flow::key(cli, cli_port, srv, srv_port, cli_vlan, protocol)); } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_find_flow_by_key(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); u_int32_t key; Flow *f; AddressTree *ptree = get_allowed_nets(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); key = (u_int32_t)lua_tonumber(vm, 1); if(!ntop_interface) return(false); f = ntop_interface->findFlowByKey(key, ptree); if(f == NULL) return(CONST_LUA_ERROR); else { f->lua(vm, ptree, details_high, false); return(CONST_LUA_OK); } } /* ****************************************** */ static int ntop_drop_flow_traffic(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); u_int32_t key; Flow *f; AddressTree *ptree = get_allowed_nets(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); key = (u_int32_t)lua_tonumber(vm, 1); if(!ntop_interface) return(false); f = ntop_interface->findFlowByKey(key, ptree); if(f == NULL) return(CONST_LUA_ERROR); else { f->setDropVerdict(); return(CONST_LUA_OK); } } /* ****************************************** */ static int ntop_dump_flow_traffic(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); u_int32_t key, what; Flow *f; AddressTree *ptree = get_allowed_nets(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); key = (u_int32_t)lua_tonumber(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); what = (u_int32_t)lua_tonumber(vm, 2); if(!ntop_interface) return(false); f = ntop_interface->findFlowByKey(key, ptree); if(f == NULL) return(CONST_LUA_ERROR); else { f->setDumpFlowTraffic(what ? true : false); return(CONST_LUA_OK); } } /* ****************************************** */ static int ntop_dump_local_hosts_2_redis(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->dumpLocalHosts2redis(true /* must disable purge as we are called from lua */); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_find_user_flows(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *key; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); key = (char*)lua_tostring(vm, 1); if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->findUserFlows(vm, key); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_find_pid_flows(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); u_int32_t pid; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); pid = (u_int32_t)lua_tonumber(vm, 1); if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->findPidFlows(vm, pid); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_find_father_pid_flows(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); u_int32_t father_pid; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); father_pid = (u_int32_t)lua_tonumber(vm, 1); if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->findFatherPidFlows(vm, father_pid); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_find_proc_name_flows(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *proc_name; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); proc_name = (char*)lua_tostring(vm, 1); if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->findProcNameFlows(vm, proc_name); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_list_http_hosts(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *key; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); if(lua_type(vm, 1) != LUA_TSTRING) /* Optional */ key = NULL; else key = (char*)lua_tostring(vm, 1); ntop_interface->listHTTPHosts(vm, key); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_find_host(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *key; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); key = (char*)lua_tostring(vm, 1); if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->findHostsByName(vm, get_allowed_nets(vm), key); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_update_host_traffic_policy(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; Host *h; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((!ntop_interface) || ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL)) return(CONST_LUA_ERROR); h->updateHostTrafficPolicy(host_ip); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_update_host_alert_policy(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; Host *h; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 2) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 2); if((!ntop_interface) || ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL)) return(CONST_LUA_ERROR); h->readAlertPrefs(); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_set_second_traffic(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->updateSecondTraffic(time(NULL)); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_set_host_dump_policy(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; Host *h; bool dump_traffic_to_disk; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TBOOLEAN)) return(CONST_LUA_ERROR); dump_traffic_to_disk = lua_toboolean(vm, 1) ? true : false; if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 2), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 3) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 3); if((!ntop_interface) || ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL)) return(CONST_LUA_ERROR); h->setDumpTrafficPolicy(dump_traffic_to_disk); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_host_hit_rate(lua_State* vm) { #ifdef NOTUSED NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; Host *h; u_int32_t peer_key; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); peer_key = (u_int32_t)lua_tonumber(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 2), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 3) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 3); if((!ntop_interface) || ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL)) return(CONST_LUA_ERROR); h->getPeerBytes(vm, peer_key); return(CONST_LUA_OK); #else return(CONST_LUA_ERROR); // not supported #endif } /* ****************************************** */ static int ntop_set_host_quota(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; Host *h; u_int32_t quota; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); quota = (u_int32_t)lua_tonumber(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 2), &host_ip, &vlan_id, buf, sizeof(buf)); /* Optional VLAN id */ if(lua_type(vm, 3) == LUA_TNUMBER) vlan_id = (u_int16_t)lua_tonumber(vm, 3); if((!ntop_interface) || ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL)) return(CONST_LUA_ERROR); h->setQuota(quota); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_dump_tap_policy(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); bool dump_traffic_to_tap; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); dump_traffic_to_tap = ntop_interface->getDumpTrafficTapPolicy(); lua_pushboolean(vm, dump_traffic_to_tap ? 1 : 0); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_dump_tap_name(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); lua_pushstring(vm, ntop_interface->getDumpTrafficTapName()); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_dump_disk_policy(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); bool dump_traffic_to_disk; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); dump_traffic_to_disk = ntop_interface->getDumpTrafficDiskPolicy(); lua_pushboolean(vm, dump_traffic_to_disk ? 1 : 0); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_dump_max_pkts(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); int max_pkts; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); max_pkts = ntop_interface->getDumpTrafficMaxPktsPerFile(); lua_pushnumber(vm, max_pkts); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_dump_max_sec(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); int max_sec; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); max_sec = ntop_interface->getDumpTrafficMaxSecPerFile(); lua_pushnumber(vm, max_sec); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_dump_max_files(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); int max_files; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); max_files = ntop_interface->getDumpTrafficMaxFiles(); lua_pushnumber(vm, max_files); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_pkts_dumped_file(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); int num_pkts; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); PacketDumper *dumper = ntop_interface->getPacketDumper(); if(!dumper) return(CONST_LUA_ERROR); num_pkts = dumper->get_num_dumped_packets(); lua_pushnumber(vm, num_pkts); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_pkts_dumped_tap(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); int num_pkts; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); PacketDumperTuntap *dumper = ntop_interface->getPacketDumperTap(); if(!dumper) return(CONST_LUA_ERROR); num_pkts = dumper->get_num_dumped_packets(); lua_pushnumber(vm, num_pkts); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_interface_endpoint(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); u_int8_t id; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) != LUA_TNUMBER) /* Optional */ id = 0; else id = (u_int8_t)lua_tonumber(vm, 1); if(ntop_interface) { char *endpoint = ntop_interface->getEndpoint(id); /* CHECK */ lua_pushfstring(vm, "%s", endpoint ? endpoint : ""); } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_is_packet_interface(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); lua_pushboolean(vm, ntop_interface->isPacketInterface()); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_is_bridge_interface(lua_State* vm) { int ifid; NetworkInterface *iface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if((lua_type(vm, 1) == LUA_TNUMBER)) { ifid = lua_tointeger(vm, 1); if(ifid < 0 || !(iface = ntop->getNetworkInterface(ifid))) return (CONST_LUA_ERROR); } lua_pushboolean(vm, iface->is_bridge_interface()); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_is_pcap_dump_interface(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); const char *interface_type; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface || ((interface_type = ntop_interface->get_type()) == NULL)) return(CONST_LUA_ERROR); lua_pushboolean(vm, strcmp(interface_type, CONST_INTERFACE_TYPE_PCAP_DUMP) == 0); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_is_running(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); return(ntop_interface->isRunning()); } /* ****************************************** */ static int ntop_interface_is_idle(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); return(ntop_interface->idle()); } /* ****************************************** */ static int ntop_interface_set_idle(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); bool state; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TBOOLEAN)) return(CONST_LUA_ERROR); state = lua_toboolean(vm, 1) ? true : false; ntop_interface->setIdleState(state); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_name2id(lua_State* vm) { char *if_name; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TNIL) if_name = NULL; else { if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if_name = (char*)lua_tostring(vm, 1); } lua_pushinteger(vm, ntop->getInterfaceIdByName(if_name)); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_ndpi_protocols(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ndpi_protocol_category_t category_filter; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if((lua_type(vm, 1) == LUA_TNUMBER)) { category_filter = (ndpi_protocol_category_t)lua_tointeger(vm, 1); if(category_filter >= NDPI_PROTOCOL_NUM_CATEGORIES) return (CONST_LUA_ERROR); ntop_interface->getnDPIProtocols(vm, category_filter); } else ntop_interface->getnDPIProtocols(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_ndpi_categories(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_newtable(vm); for (int i=0; i < NDPI_PROTOCOL_NUM_CATEGORIES; i++) { char buf[8]; snprintf(buf, sizeof(buf), "%d", i); lua_push_str_table_entry(vm, ndpi_category_str((ndpi_protocol_category_t)i), buf); } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_load_dump_prefs(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); ntop_interface->loadDumpPrefs(); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_load_scaling_factor_prefs(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); ntop_interface->loadScalingFactorPrefs(); return(CONST_LUA_OK); } /* ****************************************** */ /* Code partially taken from third-party/rrdtool-1.4.7/bindings/lua/rrdlua.c and made reentrant */ static void reset_rrd_state(void) { optind = 0; opterr = 0; rrd_clear_error(); } /* ****************************************** */ static const char **make_argv(lua_State * vm, u_int offset) { const char **argv; int i; int argc = lua_gettop(vm) - offset; if(!(argv = (const char**)calloc(argc, sizeof (char *)))) /* raise an error and never return */ luaL_error(vm, "Can't allocate memory for arguments array"); /* fprintf(stderr, "%s\n", argv[0]); */ for(i=0; i<argc; i++) { u_int idx = i + offset; /* accepts string or number */ if(lua_isstring(vm, idx) || lua_isnumber(vm, idx)) { if(!(argv[i] = (char*)lua_tostring (vm, idx))) { /* raise an error and never return */ luaL_error(vm, "Error duplicating string area for arg #%d", i); } } else { /* raise an error and never return */ luaL_error(vm, "Invalid arg #%d: args must be strings or numbers", i); } // ntop->getTrace()->traceEvent(TRACE_NORMAL, "[%d] %s", i, argv[i]); } return(argv); } /* ****************************************** */ static int ntop_rrd_create(lua_State* vm) { const char *filename; unsigned long pdp_step; const char **argv; int argc, status, offset = 3; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((filename = (const char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); pdp_step = (unsigned long)lua_tonumber(vm, 2); ntop->getTrace()->traceEvent(TRACE_INFO, "%s(%s)", __FUNCTION__, filename); argc = lua_gettop(vm) - offset; argv = make_argv(vm, offset); reset_rrd_state(); status = rrd_create_r(filename, pdp_step, time(NULL)-86400 /* 1 day */, argc, argv); free(argv); if(status != 0) { char *err = rrd_get_error(); if(err != NULL) { luaL_error(vm, err); return(CONST_LUA_ERROR); } } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_rrd_update(lua_State* vm) { const char *filename, *update_arg; int status; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((filename = (const char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((update_arg = (const char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s(%s) %s", __FUNCTION__, filename, update_arg); reset_rrd_state(); status = rrd_update_r(filename, NULL, 1, &update_arg); if(status != 0) { char *err = rrd_get_error(); if(err != NULL) { luaL_error(vm, err); return(CONST_LUA_ERROR); } } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_rrd_lastupdate(lua_State* vm) { const char *filename; time_t last_update; char **ds_names; char **last_ds; unsigned long ds_count, i; int status; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((filename = (const char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); status = rrd_lastupdate_r(filename, &last_update, &ds_count, &ds_names, &last_ds); if(status != 0) { return(CONST_LUA_ERROR); } else { for(i = 0; i < ds_count; i++) free(last_ds[i]), free(ds_names[i]); free(last_ds), free(ds_names); lua_pushnumber(vm, last_update); lua_pushnumber(vm, ds_count); return(2 /* 2 values returned */); } } /* ****************************************** */ /* positional 1:4 parameters for ntop_rrd_fetch */ static int __ntop_rrd_args (lua_State* vm, char **filename, char **cf, time_t *start, time_t *end) { char *start_s, *end_s, *err; rrd_time_value_t start_tv, end_tv; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((*filename = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((*cf = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if((lua_type(vm, 3) == LUA_TNUMBER) && (lua_type(vm, 4) == LUA_TNUMBER)) *start = (time_t)lua_tonumber(vm, 3), *end = (time_t)lua_tonumber(vm, 4); else { if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((start_s = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR); if((err = rrd_parsetime(start_s, &start_tv)) != NULL) { luaL_error(vm, err); return(CONST_LUA_PARAM_ERROR); } if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((end_s = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR); if((err = rrd_parsetime(end_s, &end_tv)) != NULL) { luaL_error(vm, err); return(CONST_LUA_PARAM_ERROR); } if(rrd_proc_start_end(&start_tv, &end_tv, start, end) == -1) return(CONST_LUA_PARAM_ERROR); } return(CONST_LUA_OK); } static int __ntop_rrd_status(lua_State* vm, int status, char *filename, char *cf) { char * err; if(status != 0) { err = rrd_get_error(); if(err != NULL) { ntop->getTrace()->traceEvent(TRACE_ERROR, "Error '%s' while calling rrd_fetch_r(%s, %s): is the RRD corrupted perhaps?", err, filename, cf); lua_pushnil(vm); lua_pushnil(vm); lua_pushnil(vm); lua_pushnil(vm); return(CONST_LUA_ERROR); } } return(CONST_LUA_OK); } /* Fetches data from RRD by rows */ static int ntop_rrd_fetch(lua_State* vm) { unsigned long i, j, step = 0, ds_cnt = 0; rrd_value_t *data, *p; char **names; char *filename, *cf; time_t t, start, end; int status; if ((status = __ntop_rrd_args(vm, &filename, &cf, &start, &end)) != CONST_LUA_OK) return status; ntop->getTrace()->traceEvent(TRACE_INFO, "%s(%s)", __FUNCTION__, filename); reset_rrd_state(); if ((status = __ntop_rrd_status(vm, rrd_fetch_r(filename, cf, &start, &end, &step, &ds_cnt, &names, &data), filename, cf)) != CONST_LUA_OK) return status; lua_pushnumber(vm, (lua_Number) start); lua_pushnumber(vm, (lua_Number) step); /* fprintf(stderr, "%lu, %lu, %lu, %lu\n", start, end, step, num_points); */ /* create the ds names array */ lua_newtable(vm); for(i=0; i<ds_cnt; i++) { lua_pushstring(vm, names[i]); lua_rawseti(vm, -2, i+1); rrd_freemem(names[i]); } rrd_freemem(names); /* create the data points array */ lua_newtable(vm); p = data; for(t=start+1, i=0; t<end; t+=step, i++) { lua_newtable(vm); for(j=0; j<ds_cnt; j++) { rrd_value_t value = *p++; if(value != DNAN /* Skip NaN */) { lua_pushnumber(vm, (lua_Number)value); lua_rawseti(vm, -2, j+1); // ntop->getTrace()->traceEvent(TRACE_NORMAL, "%u / %.f", t, value); } } lua_rawseti(vm, -2, i+1); } rrd_freemem(data); /* return the end as the last value */ lua_pushnumber(vm, (lua_Number) end); /* number of return values: start, step, names, data, end */ return(5); } /* ****************************************** */ /* * Similar to ntop_rrd_fetch, but data series oriented (reads RRD by columns) * * Positional parameters: * filename: RRD file path * cf: RRD cf * start: the start time you wish to query * end: the end time you wish to query * * Positional return values: * start: the time of the first data in the series * step: the fetched data step * data: a table, where each key is an RRD name, and the value is its series data * end: the time of the last data in each series * npoints: the number of points in each series */ static int ntop_rrd_fetch_columns(lua_State* vm) { char *filename, *cf; time_t start, end; int status; unsigned int npoints = 0, i, j; char **names; unsigned long step = 0, ds_cnt = 0; rrd_value_t *data, *p; if ((status = __ntop_rrd_args(vm, &filename, &cf, &start, &end)) != CONST_LUA_OK) return status; ntop->getTrace()->traceEvent(TRACE_INFO, "%s(%s)", __FUNCTION__, filename); reset_rrd_state(); if ((status = __ntop_rrd_status(vm, rrd_fetch_r(filename, cf, &start, &end, &step, &ds_cnt, &names, &data), filename, cf)) != CONST_LUA_OK) return status; npoints = (end - start) / step; lua_pushnumber(vm, (lua_Number) start); lua_pushnumber(vm, (lua_Number) step); /* create the data series table */ lua_createtable(vm, 0, ds_cnt); for(i=0; i<ds_cnt; i++) { /* a single serie table, preallocated */ lua_createtable(vm, npoints, 0); p = data + i; for(j=0; j<npoints; j++) { rrd_value_t value = *p; /* we are accessing data table by columns */ p = p + ds_cnt; lua_pushnumber(vm, (lua_Number)value); lua_rawseti(vm, -2, j+1); } /* add the single serie to the series table */ lua_setfield(vm, -2, names[i]); rrd_freemem(names[i]); } rrd_freemem(names); rrd_freemem(data); /* end and npoints as last values */ lua_pushnumber(vm, (lua_Number) end); lua_pushnumber(vm, (lua_Number) npoints); /* number of return values */ return(5); } /* ****************************************** */ static int ntop_http_redirect(lua_State* vm) { char *url, str[512]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((url = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); snprintf(str, sizeof(str), "HTTP/1.1 302 Found\r\n" "Location: %s\r\n\r\n" "<html>\n" "<head>\n" "<title>Moved</title>\n" "</head>\n" "<body>\n" "<h1>Moved</h1>\n" "<p>This page has moved to <a href=\"%s\">%s</a>.</p>\n" "</body>\n" "</html>\n", url, url, url); lua_pushstring(vm, str); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_http_get(lua_State* vm) { char *url, *username = NULL, *pwd = NULL; int timeout = 30; bool return_content = true; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((url = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(lua_type(vm, 2) == LUA_TSTRING) { username = (char*)lua_tostring(vm, 2); if(lua_type(vm, 3) == LUA_TSTRING) { pwd = (char*)lua_tostring(vm, 3); if(lua_type(vm, 4) == LUA_TNUMBER) { timeout = lua_tointeger(vm, 4); if(timeout < 1) timeout = 1; /* This optional parameter specifies if the result of HTTP GET has to be returned to LUA or not. Usually the content has to be returned, but in some causes it just matters to time (for instance when use for testing HTTP services) */ if(lua_type(vm, 4) == LUA_TBOOLEAN) { return_content = lua_toboolean(vm, 5) ? true : false; } } } } if(Utils::httpGet(vm, url, username, pwd, timeout, return_content)) return(CONST_LUA_OK); else return(CONST_LUA_ERROR); } /* ****************************************** */ static int ntop_http_get_prefix(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_pushstring(vm, ntop->getPrefs()->get_http_prefix()); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_prefs(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); ntop->getPrefs()->lua(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_nologin_username(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_pushstring(vm, NTOP_NOLOGIN_USER); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_users(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); ntop->getUsers(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_user_group(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); ntop->getUserGroup(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_allowed_networks(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); ntop->getAllowedNetworks(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_reset_user_password(lua_State* vm) { char *who, *username, *old_password, *new_password; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); /* Username who requested the password change */ if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((who = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((username = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((old_password = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((new_password = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR); if((!Utils::isUserAdministrator(vm)) && (strcmp(who, username))) return(CONST_LUA_ERROR); return(ntop->resetUserPassword(username, old_password, new_password)); } /* ****************************************** */ static int ntop_change_user_role(lua_State* vm) { char *username, *user_role; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((user_role = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); return ntop->changeUserRole(username, user_role); } /* ****************************************** */ static int ntop_change_allowed_nets(lua_State* vm) { char *username, *allowed_nets; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((allowed_nets = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); return ntop->changeAllowedNets(username, allowed_nets); } /* ****************************************** */ static int ntop_change_allowed_ifname(lua_State* vm) { char *username, *allowed_ifname; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((allowed_ifname = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); return ntop->changeAllowedIfname(username, allowed_ifname); } /* ****************************************** */ static int ntop_post_http_json_data(lua_State* vm) { char *username, *password, *url, *json; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((password = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((url = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((json = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR); if(Utils::postHTTPJsonData(username, password, url, json)) return(CONST_LUA_OK); else return(CONST_LUA_ERROR); } /* ****************************************** */ static int ntop_add_user(lua_State* vm) { char *username, *full_name, *password, *host_role, *allowed_networks, *allowed_interface; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((full_name = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((password = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((host_role = (char*)lua_tostring(vm, 4)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 5, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((allowed_networks = (char*)lua_tostring(vm, 5)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 6, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((allowed_interface = (char*)lua_tostring(vm, 6)) == NULL) return(CONST_LUA_PARAM_ERROR); return ntop->addUser(username, full_name, password, host_role, allowed_networks, allowed_interface); } /* ****************************************** */ static int ntop_delete_user(lua_State* vm) { char *username; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((username = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); return ntop->deleteUser(username); } /* ****************************************** */ static int ntop_resolve_address(lua_State* vm) { char *numIP, symIP[64]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((numIP = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); ntop->resolveHostName(numIP, symIP, sizeof(symIP)); lua_pushstring(vm, symIP); return(CONST_LUA_OK); } /* ****************************************** */ void lua_push_str_table_entry(lua_State *L, const char *key, char *value) { if(L) { lua_pushstring(L, key); lua_pushstring(L, value); lua_settable(L, -3); } } /* ****************************************** */ void lua_push_nil_table_entry(lua_State *L, const char *key) { if(L) { lua_pushstring(L, key); lua_pushnil(L); lua_settable(L, -3); } } /* ****************************************** */ void lua_push_bool_table_entry(lua_State *L, const char *key, bool value) { if(L) { lua_pushstring(L, key); lua_pushboolean(L, value ? 1 : 0); lua_settable(L, -3); } } /* ****************************************** */ void lua_push_int_table_entry(lua_State *L, const char *key, u_int64_t value) { if(L) { lua_pushstring(L, key); /* using LUA_NUMBER (double: 64 bit) in place of LUA_INTEGER (ptrdiff_t: 32 or 64 bit * according to the platform, as defined in luaconf.h) to handle big counters */ lua_pushnumber(L, (lua_Number)value); lua_settable(L, -3); } } /* ****************************************** */ void lua_push_int32_table_entry(lua_State *L, const char *key, int32_t value) { if(L) { lua_pushstring(L, key); lua_pushnumber(L, (lua_Number)value); lua_settable(L, -3); } } /* ****************************************** */ void lua_push_float_table_entry(lua_State *L, const char *key, float value) { if(L) { lua_pushstring(L, key); lua_pushnumber(L, value); lua_settable(L, -3); } } /* ****************************************** */ static int ntop_get_interface_stats(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); /* ntop_interface->getAlertsManager()->engageAlert(alert_entity_host, "127.0.0.1", "min_bytes", alert_threshold_exceeded, alert_level_warning, "miao"); ntop_interface->getAlertsManager()->releaseAlert(alert_entity_host, "127.0.0.1", "min_bytes", alert_threshold_exceeded, alert_level_warning, "miao"); */ ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) ntop_interface->lua(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_reset_counters(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); bool only_drops = true; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TBOOLEAN) only_drops = lua_toboolean(vm, 1) ? true : false; if(!ntop_interface) return(CONST_LUA_ERROR); ntop_interface->checkPointCounters(only_drops); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_is_pro(lua_State *vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_pushboolean(vm, ntop->getPrefs()->is_pro_edition()); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_is_enterprise(lua_State *vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_pushboolean(vm, ntop->getPrefs()->is_enterprise_edition()); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_reload_l7_rules(lua_State *vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) { char *net; AddressTree ptree; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((net = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); #ifdef SHAPER_DEBUG ntop->getTrace()->traceEvent(TRACE_NORMAL, "%s(%s)", __FUNCTION__, net); #endif ptree.addAddresses(net); #ifdef NTOPNG_PRO ntop_interface->refreshL7Rules(&ptree); #endif return(CONST_LUA_OK); } else return(CONST_LUA_ERROR); } /* ****************************************** */ static int ntop_reload_shapers(lua_State *vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) { #ifdef NTOPNG_PRO ntop_interface->refreshShapers(); #endif return(CONST_LUA_OK); } else return(CONST_LUA_ERROR); } /* ****************************************** */ static int ntop_interface_exec_sql_query(lua_State *vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); bool limit_rows = true; // honour the limit by default bool wait_for_db_created = true; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!ntop_interface) return(CONST_LUA_ERROR); else { char *sql; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_PARAM_ERROR); if((sql = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(lua_type(vm, 2) == LUA_TBOOLEAN) { limit_rows = lua_toboolean(vm, 2) ? true : false; } if(lua_type(vm, 3) == LUA_TBOOLEAN) { wait_for_db_created = lua_toboolean(vm, 3) ? true : false; } if(ntop_interface->exec_sql_query(vm, sql, limit_rows, wait_for_db_created) < 0) lua_pushnil(vm); return(CONST_LUA_OK); } } /* ****************************************** */ static int ntop_get_dirs(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_newtable(vm); lua_push_str_table_entry(vm, "installdir", ntop->get_install_dir()); lua_push_str_table_entry(vm, "workingdir", ntop->get_working_dir()); lua_push_str_table_entry(vm, "scriptdir", ntop->getPrefs()->get_scripts_dir()); lua_push_str_table_entry(vm, "httpdocsdir", ntop->getPrefs()->get_docs_dir()); lua_push_str_table_entry(vm, "callbacksdir", ntop->getPrefs()->get_callbacks_dir()); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_uptime(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_pushinteger(vm, ntop->getGlobals()->getUptime()); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_check_license(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); #ifdef NTOPNG_PRO ntop->getPro()->check_license(); #endif lua_pushinteger(vm,1); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_info(lua_State* vm) { char rsp[256]; int major, minor, patch; bool verbose = true; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(lua_type(vm, 1) == LUA_TBOOLEAN) verbose = lua_toboolean(vm, 1) ? true : false; lua_newtable(vm); lua_push_str_table_entry(vm, "product", (char*)"ntopng"); lua_push_str_table_entry(vm, "copyright", (char*)"&copy; 1998-17 - ntop.org"); lua_push_str_table_entry(vm, "authors", (char*)"The ntop.org team"); lua_push_str_table_entry(vm, "license", (char*)"GNU GPLv3"); lua_push_str_table_entry(vm, "version", (char*)PACKAGE_VERSION); lua_push_str_table_entry(vm, "git", (char*)NTOPNG_GIT_RELEASE); snprintf(rsp, sizeof(rsp), "%s [%s][%s]", PACKAGE_OSNAME, PACKAGE_MACHINE, PACKAGE_OS); lua_push_str_table_entry(vm, "platform", rsp); lua_push_str_table_entry(vm, "OS", #ifdef WIN32 (char*)"Windows" #else (char*)PACKAGE_OS #endif ); lua_push_int_table_entry(vm, "bits", (sizeof(void*) == 4) ? 32 : 64); lua_push_int_table_entry(vm, "uptime", ntop->getGlobals()->getUptime()); lua_push_str_table_entry(vm, "command_line", ntop->getPrefs()->get_command_line()); if(verbose) { lua_push_str_table_entry(vm, "version.rrd", rrd_strversion()); lua_push_str_table_entry(vm, "version.redis", ntop->getRedis()->getVersion(rsp, sizeof(rsp))); lua_push_str_table_entry(vm, "version.httpd", (char*)mg_version()); lua_push_str_table_entry(vm, "version.git", (char*)NTOPNG_GIT_RELEASE); lua_push_str_table_entry(vm, "version.luajit", (char*)LUAJIT_VERSION); #ifdef HAVE_GEOIP lua_push_str_table_entry(vm, "version.geoip", (char*)GeoIP_lib_version()); #endif lua_push_str_table_entry(vm, "version.ndpi", ndpi_revision()); lua_push_bool_table_entry(vm, "version.enterprise_edition", ntop->getPrefs()->is_enterprise_edition()); lua_push_bool_table_entry(vm, "version.embedded_edition", ntop->getPrefs()->is_embedded_edition()); lua_push_bool_table_entry(vm, "pro.release", ntop->getPrefs()->is_pro_edition()); lua_push_int_table_entry(vm, "pro.demo_ends_at", ntop->getPrefs()->pro_edition_demo_ends_at()); #ifdef NTOPNG_PRO lua_push_str_table_entry(vm, "pro.license", ntop->getPro()->get_license()); lua_push_bool_table_entry(vm, "pro.use_redis_license", ntop->getPro()->use_redis_license()); lua_push_str_table_entry(vm, "pro.systemid", ntop->getPro()->get_system_id()); #endif #if 0 ntop->getRedis()->get((char*)CONST_STR_NTOPNG_LICENSE, rsp, sizeof(rsp)); lua_push_str_table_entry(vm, "ntopng.license", rsp); #endif zmq_version(&major, &minor, &patch); snprintf(rsp, sizeof(rsp), "%d.%d.%d", major, minor, patch); lua_push_str_table_entry(vm, "version.zmq", rsp); } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_resolved_address(lua_State* vm) { char *key, *tmp,rsp[256],value[64]; Redis *redis = ntop->getRedis(); u_int16_t vlan_id = 0; char buf[64]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &key, &vlan_id, buf, sizeof(buf)); if(key == NULL) return(CONST_LUA_ERROR); if(redis->getAddress(key, rsp, sizeof(rsp), true) == 0) tmp = rsp; else tmp = key; if(vlan_id != 0) snprintf(value, sizeof(value), "%s@%u", tmp, vlan_id); else snprintf(value, sizeof(value), "%s", tmp); #if 0 if(!strcmp(value, key)) { char rsp[64]; if((ntop->getRedis()->hashGet((char*)HOST_LABEL_NAMES, key, rsp, sizeof(rsp)) == 0) && (rsp[0] !='\0')) lua_pushfstring(vm, "%s", rsp); else lua_pushfstring(vm, "%s", value); } else lua_pushfstring(vm, "%s", value); #else lua_pushfstring(vm, "%s", value); #endif return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_snmp_get_fctn(lua_State* vm, int operation) { char *agent_host, *oid, *community; u_int agent_port = 161, timeout = 5, request_id = (u_int)time(NULL); int sock, i = 0, rc = CONST_LUA_OK; SNMPMessage *message; int len; unsigned char *buf; bool debug = false; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); agent_host = (char*)lua_tostring(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); community = (char*)lua_tostring(vm, 2); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR); oid = (char*)lua_tostring(vm, 3); sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if(sock < 0) return(CONST_LUA_ERROR); message = snmp_create_message(); snmp_set_version(message, 0); snmp_set_community(message, community); snmp_set_pdu_type(message, operation); snmp_set_request_id(message, request_id); snmp_set_error(message, 0); snmp_set_error_index(message, 0); snmp_add_varbind_null(message, oid); /* Add additional OIDs */ i = 4; while(lua_type(vm, i) == LUA_TSTRING) { snmp_add_varbind_null(message, (char*)lua_tostring(vm, i)); i++; } len = snmp_message_length(message); buf = (unsigned char*)malloc(len); snmp_render_message(message, buf); snmp_destroy_message(message); send_udp_datagram(buf, len, sock, agent_host, agent_port); free(buf); if(debug) ntop->getTrace()->traceEvent(TRACE_NORMAL, "SNMP %s %s@%s %s", (operation == SNMP_GET_REQUEST_TYPE) ? "Get" : "GetNext", agent_host, community, oid); if(input_timeout(sock, timeout) == 0) { /* Timeout */ if(debug) ntop->getTrace()->traceEvent(TRACE_NORMAL, "SNMP Timeout %s@%s %s", agent_host, community, oid); rc = CONST_LUA_ERROR; lua_pushnil(vm); } else { char buf[BUFLEN]; SNMPMessage *message; char *sender_host, *oid_str, *value_str; int sender_port, added = 0, len; len = receive_udp_datagram(buf, BUFLEN, sock, &sender_host, &sender_port); message = snmp_parse_message(buf, len); i = 0; while(snmp_get_varbind_as_string(message, i, &oid_str, NULL, &value_str)) { if(!added) lua_newtable(vm), added = 1; lua_push_str_table_entry(vm, oid_str, value_str); if(debug) ntop->getTrace()->traceEvent(TRACE_NORMAL, "SNMP OK %s@%s %s=%s", agent_host, community, oid_str, value_str); i++; } snmp_destroy_message(message); if(!added) { ntop->getTrace()->traceEvent(TRACE_ERROR, "SNMP Error %s@%s", agent_host, community); lua_pushnil(vm), rc = CONST_LUA_ERROR; } } closesocket(sock); return(rc); } /* ****************************************** */ static int ntop_snmpget(lua_State* vm) { return(ntop_snmp_get_fctn(vm, SNMP_GET_REQUEST_TYPE)); } static int ntop_snmpgetnext(lua_State* vm) { return(ntop_snmp_get_fctn(vm, SNMP_GETNEXT_REQUEST_TYPE)); } /* ****************************************** */ /** * @brief Send a message to the system syslog * @details Send a message to the syslog syslog: callers can specify if it is an error or informational message * * @param vm The lua state. * @return @ref CONST_LUA_ERROR if the expected type is equal to function type, @ref CONST_LUA_PARAM_ERROR otherwise. */ static int ntop_syslog(lua_State* vm) { #ifndef WIN32 char *msg; bool is_error; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TBOOLEAN)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); is_error = lua_toboolean(vm, 1) ? true : false; msg = (char*)lua_tostring(vm, 2); syslog(is_error ? LOG_ERR : LOG_INFO, "%s", msg); #endif return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Generate a random value to prevent CSRF and XSRF attacks * @details See http://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/ * * @param vm The lua state. * @return The random value just generated */ static int ntop_generate_csrf_value(lua_State* vm) { char random_a[32], random_b[32], csrf[33], user[64] = { '\0' }; Redis *redis = ntop->getRedis(); struct mg_connection *conn; lua_getglobal(vm, CONST_HTTP_CONN); if((conn = (struct mg_connection*)lua_touserdata(vm, lua_gettop(vm))) == NULL) { ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: null HTTP connection"); return(CONST_LUA_OK); } ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); #ifdef __OpenBSD__ snprintf(random_a, sizeof(random_a), "%d", arc4random()); snprintf(random_b, sizeof(random_b), "%lu", time(NULL)*arc4random()); #else snprintf(random_a, sizeof(random_a), "%d", rand()); snprintf(random_b, sizeof(random_b), "%lu", time(NULL)*rand()); #endif mg_get_cookie(conn, "user", user, sizeof(user)); mg_md5(csrf, random_a, random_b, NULL); redis->set(csrf, (char*)user, MAX_CSRF_DURATION); lua_pushfstring(vm, "%s", csrf); return(CONST_LUA_OK); } /* ****************************************** */ struct ntopng_sqlite_state { lua_State* vm; u_int num_rows; }; static int sqlite_callback(void *data, int argc, char **argv, char **azColName) { struct ntopng_sqlite_state *s = (struct ntopng_sqlite_state*)data; lua_newtable(s->vm); for(int i=0; i<argc; i++) lua_push_str_table_entry(s->vm, (const char*)azColName[i], (char*)(argv[i] ? argv[i] : "NULL")); lua_pushinteger(s->vm, ++s->num_rows); lua_insert(s->vm, -2); lua_settable(s->vm, -3); return(0); } /* ****************************************** */ /** * @brief Exec SQL query * @details Execute the specified query and return the results * * @param vm The lua state. * @return @ref CONST_LUA_ERROR in case of error, CONST_LUA_OK otherwise. */ static int ntop_sqlite_exec_query(lua_State* vm) { char *db_path, *db_query; sqlite3 *db; char *zErrMsg = 0; struct ntopng_sqlite_state state; struct stat buf; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); db_path = (char*)lua_tostring(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); db_query = (char*)lua_tostring(vm, 2); if(stat(db_path, &buf) != 0) { ntop->getTrace()->traceEvent(TRACE_INFO, "Not found database %s", db_path); return(CONST_LUA_ERROR); } if(sqlite3_open(db_path, &db)) { ntop->getTrace()->traceEvent(TRACE_INFO, "Unable to open %s: %s", db_path, sqlite3_errmsg(db)); return(CONST_LUA_ERROR); } state.vm = vm, state.num_rows = 0; lua_newtable(vm); if(sqlite3_exec(db, db_query, sqlite_callback, (void*)&state, &zErrMsg)) { ntop->getTrace()->traceEvent(TRACE_INFO, "SQL Error: %s", zErrMsg); sqlite3_free(zErrMsg); } sqlite3_close(db); return(CONST_LUA_OK); } /** * @brief Insert a new minute sampling in the historical database * @details Given a certain sampling point, store statistics for said * sampling point. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_insert_minute_sampling(lua_State *vm) { char *sampling; time_t rawtime; int ifid; NetworkInterface* iface; StatsManager *sm; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); if((sampling = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); time(&rawtime); if(sm->insertMinuteSampling(rawtime, sampling)) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /** * @brief Insert a new hour sampling in the historical database * @details Given a certain sampling point, store statistics for said * sampling point. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_insert_hour_sampling(lua_State *vm) { char *sampling; time_t rawtime; int ifid; NetworkInterface* iface; StatsManager *sm; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); if((sampling = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); time(&rawtime); rawtime -= (rawtime % 60); if(sm->insertHourSampling(rawtime, sampling)) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /** * @brief Insert a new day sampling in the historical database * @details Given a certain sampling point, store statistics for said * sampling point. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_insert_day_sampling(lua_State *vm) { char *sampling; time_t rawtime; int ifid; NetworkInterface* iface; StatsManager *sm; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); if((sampling = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); time(&rawtime); rawtime -= (rawtime % 60); if(sm->insertDaySampling(rawtime, sampling)) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /** * @brief Get a minute sampling from the historical database * @details Given a certain sampling point, get statistics for said * sampling point. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_get_minute_sampling(lua_State *vm) { time_t epoch; string sampling; int ifid; NetworkInterface* iface; StatsManager *sm; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); epoch = (time_t)lua_tointeger(vm, 2); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); if(sm->getMinuteSampling(epoch, &sampling)) return(CONST_LUA_ERROR); lua_pushstring(vm, sampling.c_str()); return(CONST_LUA_OK); } /** * @brief Delete minute stats older than a certain number of days. * @details Given a number of days, delete stats for the current interface that * are older than a certain number of days. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_delete_minute_older_than(lua_State *vm) { int num_days; int ifid; NetworkInterface* iface; StatsManager *sm; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); num_days = lua_tointeger(vm, 2); if(num_days < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); if(sm->deleteMinuteStatsOlderThan(num_days)) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /** * @brief Delete hour stats older than a certain number of days. * @details Given a number of days, delete stats for the current interface that * are older than a certain number of days. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_delete_hour_older_than(lua_State *vm) { int num_days; int ifid; NetworkInterface* iface; StatsManager *sm; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); num_days = lua_tointeger(vm, 2); if(num_days < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); if(sm->deleteHourStatsOlderThan(num_days)) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /** * @brief Delete day stats older than a certain number of days. * @details Given a number of days, delete stats for the current interface that * are older than a certain number of days. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_delete_day_older_than(lua_State *vm) { int num_days; int ifid; NetworkInterface* iface; StatsManager *sm; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!Utils::isUserAdministrator(vm)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); num_days = lua_tointeger(vm, 2); if(num_days < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); if(sm->deleteDayStatsOlderThan(num_days)) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /** * @brief Get an interval of minute stats samplings from the historical database * @details Given a certain interval of sampling points, get statistics for said * sampling points. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_get_minute_samplings_interval(lua_State *vm) { time_t epoch_start, epoch_end; int ifid; NetworkInterface* iface; StatsManager *sm; struct statsManagerRetrieval retvals; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); epoch_start = lua_tointeger(vm, 2); if(epoch_start < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR); epoch_end = lua_tointeger(vm, 3); if(epoch_end < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); if(sm->retrieveMinuteStatsInterval(epoch_start, epoch_end, &retvals)) return(CONST_LUA_ERROR); lua_newtable(vm); for (unsigned i = 0 ; i < retvals.rows.size() ; i++) lua_push_str_table_entry(vm, retvals.rows[i].c_str(), (char*)""); return(CONST_LUA_OK); } /** * @brief Given an epoch, get minute stats for the latest n minutes * @details Given a certain sampling point, get statistics for that point and * for all timepoints spanning an interval of a given number of * minutes. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_get_samplings_of_minutes_from_epoch(lua_State *vm) { time_t epoch_start, epoch_end; int num_minutes; int ifid; NetworkInterface* iface; StatsManager *sm; struct statsManagerRetrieval retvals; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); epoch_end = lua_tointeger(vm, 2); epoch_end -= (epoch_end % 60); if(epoch_end < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR); num_minutes = lua_tointeger(vm, 3); if(num_minutes < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); epoch_start = epoch_end - (60 * num_minutes); if(sm->retrieveMinuteStatsInterval(epoch_start, epoch_end, &retvals)) return(CONST_LUA_ERROR); lua_newtable(vm); for (unsigned i = 0 ; i < retvals.rows.size() ; i++) lua_push_str_table_entry(vm, retvals.rows[i].c_str(), (char*)""); return(CONST_LUA_OK); } /** * @brief Given an epoch, get hour stats for the latest n hours * @details Given a certain sampling point, get statistics for that point and * for all timepoints spanning an interval of a given number of * hours. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_get_samplings_of_hours_from_epoch(lua_State *vm) { time_t epoch_start, epoch_end; int num_hours; int ifid; NetworkInterface* iface; StatsManager *sm; struct statsManagerRetrieval retvals; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); epoch_end = lua_tointeger(vm, 2); epoch_end -= (epoch_end % 60); if(epoch_end < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR); num_hours = lua_tointeger(vm, 3); if(num_hours < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); epoch_start = epoch_end - (num_hours * 60 * 60); if(sm->retrieveHourStatsInterval(epoch_start, epoch_end, &retvals)) return(CONST_LUA_ERROR); lua_newtable(vm); for (unsigned i = 0 ; i < retvals.rows.size() ; i++) lua_push_str_table_entry(vm, retvals.rows[i].c_str(), (char*)""); return(CONST_LUA_OK); } /** * @brief Given an epoch, get hour stats for the latest n days * @details Given a certain sampling point, get statistics for that point and * for all timepoints spanning an interval of a given number of * days. * * @param vm The lua state. * @return @ref CONST_LUA_PARAM_ERROR in case of wrong parameter, * CONST_LUA_ERROR in case of generic error, CONST_LUA_OK otherwise. */ static int ntop_stats_get_samplings_of_days_from_epoch(lua_State *vm) { time_t epoch_start, epoch_end; int num_days; int ifid; NetworkInterface* iface; StatsManager *sm; struct statsManagerRetrieval retvals; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); epoch_end = lua_tointeger(vm, 2); epoch_end -= (epoch_end % 60); if(epoch_end < 0) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR); num_days = lua_tointeger(vm, 3); if(num_days < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(ifid)) || !(sm = iface->getStatsManager())) return (CONST_LUA_ERROR); epoch_start = epoch_end - (num_days * 24 * 60 * 60); if(sm->retrieveDayStatsInterval(epoch_start, epoch_end, &retvals)) return(CONST_LUA_ERROR); lua_newtable(vm); for (unsigned i = 0 ; i < retvals.rows.size() ; i++) lua_push_str_table_entry(vm, retvals.rows[i].c_str(), (char*)""); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_delete_dump_files(lua_State *vm) { int ifid; char pcap_path[MAX_PATH]; NetworkInterface *iface; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); if((ifid = lua_tointeger(vm, 1)) < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(ifid))) return(CONST_LUA_ERROR); snprintf(pcap_path, sizeof(pcap_path), "%s/%d/pcap/", ntop->get_working_dir(), ifid); ntop->fixPath(pcap_path); if(Utils::discardOldFilesExceeding(pcap_path, iface->getDumpTrafficMaxFiles())) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_mkdir_tree(lua_State* vm) { char *dir; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((dir = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(dir[0] == '\0') return(CONST_LUA_OK); /* Nothing to do */ return(Utils::mkdir_tree(dir)); } /* ****************************************** */ static int ntop_list_reports(lua_State* vm) { DIR *dir; char fullpath[MAX_PATH]; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_newtable(vm); snprintf(fullpath, sizeof(fullpath), "%s/%s", ntop->get_working_dir(), "reports"); ntop->fixPath(fullpath); if((dir = opendir(fullpath)) != NULL) { struct dirent *ent; while ((ent = readdir(dir)) != NULL) { char filepath[MAX_PATH]; snprintf(filepath, sizeof(filepath), "%s/%s", fullpath, ent->d_name); ntop->fixPath(filepath); struct stat buf; if(!stat(filepath, &buf) && !S_ISDIR(buf.st_mode)) lua_push_str_table_entry(vm, ent->d_name, (char*)""); } closedir(dir); } return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_redis(lua_State* vm) { char *key, *rsp; u_int rsp_len = 32768; Redis *redis = ntop->getRedis(); bool cache_it = false; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); /* Optional cache_it */ if(lua_type(vm, 2) == LUA_TBOOLEAN) cache_it = lua_toboolean(vm, 2); if((rsp = (char*)malloc(rsp_len)) != NULL) { lua_pushfstring(vm, "%s", (redis->get(key, rsp, rsp_len, cache_it) == 0) ? rsp : (char*)""); free(rsp); return(CONST_LUA_OK); } else return(CONST_LUA_ERROR); } /* ****************************************** */ static int ntop_get_hash_redis(lua_State* vm) { char *key, *member, rsp[CONST_MAX_LEN_REDIS_VALUE]; Redis *redis = ntop->getRedis(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if((member = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); lua_pushfstring(vm, "%s", (redis->hashGet(key, member, rsp, sizeof(rsp)) == 0) ? rsp : (char*)""); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_set_hash_redis(lua_State* vm) { char *key, *member, *value; Redis *redis = ntop->getRedis(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if((member = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if((value = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR); redis->hashSet(key, member, value); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_del_hash_redis(lua_State* vm) { char *key, *member; Redis *redis = ntop->getRedis(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if((member = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); redis->hashDel(key, member); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_hash_keys_redis(lua_State* vm) { char *key, **vals; Redis *redis = ntop->getRedis(); int rc; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); rc = redis->hashKeys(key, &vals); if(rc > 0) { lua_newtable(vm); for(int i = 0; i < rc; i++) { lua_push_str_table_entry(vm, vals[i] ? vals[i] : "", (char*)""); if(vals[i]) free(vals[i]); } free(vals); } else lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_keys_redis(lua_State* vm) { char *pattern, **keys; Redis *redis = ntop->getRedis(); int rc; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((pattern = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); rc = redis->keys(pattern, &keys); if(rc > 0) { lua_newtable(vm); for(int i = 0; i < rc; i++) { lua_push_str_table_entry(vm, keys[i] ? keys[i] : "", (char*)""); if(keys[i]) free(keys[i]); } free(keys); } else lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_lrange_redis(lua_State* vm) { char *l_name, **l_elements; Redis *redis = ntop->getRedis(); int start_offset = 0, end_offset = -1; int rc; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((l_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(lua_type(vm, 2) == LUA_TNUMBER) { start_offset = lua_tointeger(vm, 2); } if(lua_type(vm, 3) == LUA_TNUMBER) { end_offset = lua_tointeger(vm, 3); } rc = redis->lrange(l_name, &l_elements, start_offset, end_offset); if(rc > 0) { lua_newtable(vm); for(int i = 0; i < rc; i++) { lua_push_str_table_entry(vm, l_elements[i] ? l_elements[i] : "", (char*)""); if(l_elements[i]) free(l_elements[i]); } free(l_elements); } else lua_pushnil(vm); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_get_redis_set_pop(lua_State* vm) { char *set_name, rsp[CONST_MAX_LEN_REDIS_VALUE]; Redis *redis = ntop->getRedis(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((set_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); lua_pushfstring(vm, "%s", redis->popSet(set_name, rsp, sizeof(rsp))); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_list_index_redis(lua_State* vm) { char *index_name, rsp[CONST_MAX_LEN_REDIS_VALUE]; Redis *redis = ntop->getRedis(); int idx; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((index_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); idx = lua_tointeger(vm, 2); if(redis->lindex(index_name, idx, rsp, sizeof(rsp)) != 0) return(CONST_LUA_ERROR); lua_pushfstring(vm, "%s", rsp); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_lpop_redis(lua_State* vm) { char msg[1024], *list_name; Redis *redis = ntop->getRedis(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((list_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(redis->lpop(list_name, msg, sizeof(msg)) == 0) { lua_pushfstring(vm, "%s", msg); return(CONST_LUA_OK); } else return(CONST_LUA_ERROR); } /* ****************************************** */ static int ntop_lpush_redis(lua_State* vm) { char *list_name, *value; u_int list_trim_size = 0; // default 0 = no trim Redis *redis = ntop->getRedis(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((list_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); if((value = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); /* Optional trim list up to the specified number of elements */ if(lua_type(vm, 3) == LUA_TNUMBER) list_trim_size = (u_int)lua_tonumber(vm, 3); if(redis->lpush(list_name, value, list_trim_size) == 0) { return(CONST_LUA_OK); }else return(CONST_LUA_ERROR); } /* ****************************************** */ static int ntop_redis_get_host_id(lua_State* vm) { char *host_name; Redis *redis = ntop->getRedis(); char daybuf[32]; time_t when = time(NULL); bool new_key; NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((host_name = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); strftime(daybuf, sizeof(daybuf), CONST_DB_DAY_FORMAT, localtime(&when)); lua_pushinteger(vm, redis->host_to_id(ntop_interface, daybuf, host_name, &new_key)); /* CHECK */ return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_redis_get_id_to_host(lua_State* vm) { char *host_idx, rsp[CONST_MAX_LEN_REDIS_VALUE]; Redis *redis = ntop->getRedis(); char daybuf[32]; time_t when = time(NULL); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((host_idx = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); strftime(daybuf, sizeof(daybuf), CONST_DB_DAY_FORMAT, localtime(&when)); lua_pushfstring(vm, "%d", redis->id_to_host(daybuf, host_idx, rsp, sizeof(rsp))); return(CONST_LUA_OK); } /* ****************************************** */ #ifdef NOTUSED static int ntop_interface_store_alert(lua_State* vm) { int ifid; NetworkInterface* iface; AlertsManager *am; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TTABLE)) return(CONST_LUA_ERROR); ifid = lua_tointeger(vm, 1); if(ifid < 0) return(CONST_LUA_ERROR); if(!(iface = ntop->getNetworkInterface(vm, ifid)) || !(am = iface->getAlertsManager())) return (CONST_LUA_ERROR); return am->storeAlert(vm, 2) ? CONST_LUA_ERROR : CONST_LUA_OK; } #endif /* ****************************************** */ static int ntop_interface_engage_release_host_alert(lua_State* vm, bool engage) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *host_ip; u_int16_t vlan_id = 0; char buf[64]; Host *h; int alert_severity; int alert_type; char *alert_json, *engaged_alert_id; AlertsManager *am; int ret; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); get_host_vlan_info((char*)lua_tostring(vm, 1), &host_ip, &vlan_id, buf, sizeof(buf)); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); engaged_alert_id = (char*)lua_tostring(vm, 2); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR); alert_type = (int)lua_tonumber(vm, 3); if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TNUMBER)) return(CONST_LUA_ERROR); alert_severity = (int)lua_tonumber(vm, 4); if(ntop_lua_check(vm, __FUNCTION__, 5, LUA_TSTRING)) return(CONST_LUA_ERROR); alert_json = (char*)lua_tostring(vm, 5); if((!ntop_interface) || ((h = ntop_interface->findHostsByIP(get_allowed_nets(vm), host_ip, vlan_id)) == NULL) || ((am = ntop_interface->getAlertsManager()) == NULL)) return(CONST_LUA_ERROR); if(engage) ret = am->engageHostAlert(h, engaged_alert_id, (AlertType)alert_type, (AlertLevel)alert_severity, alert_json); else ret = am->releaseHostAlert(h, engaged_alert_id, (AlertType)alert_type, (AlertLevel)alert_severity, alert_json); return ret >= 0 ? CONST_LUA_OK : CONST_LUA_ERROR; } /* ****************************************** */ static int ntop_interface_engage_release_network_alert(lua_State* vm, bool engage) { NetworkInterface *ntop_interface = getCurrentInterface(vm); char *cidr; int alert_severity; int alert_type; char *alert_json, *engaged_alert_id; AlertsManager *am; int ret; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); cidr = (char*)lua_tostring(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); engaged_alert_id = (char*)lua_tostring(vm, 2); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR); alert_type = (int)lua_tonumber(vm, 3); if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TNUMBER)) return(CONST_LUA_ERROR); alert_severity = (int)lua_tonumber(vm, 4); if(ntop_lua_check(vm, __FUNCTION__, 5, LUA_TSTRING)) return(CONST_LUA_ERROR); alert_json = (char*)lua_tostring(vm, 5); if((!ntop_interface) || ((am = ntop_interface->getAlertsManager()) == NULL)) return(CONST_LUA_ERROR); if(engage) ret = am->engageNetworkAlert(cidr, engaged_alert_id, (AlertType)alert_type, (AlertLevel)alert_severity, alert_json); else ret = am->releaseNetworkAlert(cidr, engaged_alert_id, (AlertType)alert_type, (AlertLevel)alert_severity, alert_json); return ret >= 0 ? CONST_LUA_OK : CONST_LUA_ERROR; } /* ****************************************** */ static int ntop_interface_engage_release_interface_alert(lua_State* vm, bool engage) { NetworkInterface *ntop_interface = getCurrentInterface(vm); int alert_severity; int alert_type; char *alert_json, *engaged_alert_id; AlertsManager *am; int ret; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); engaged_alert_id = (char*)lua_tostring(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TNUMBER)) return(CONST_LUA_ERROR); alert_type = (int)lua_tonumber(vm, 2); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TNUMBER)) return(CONST_LUA_ERROR); alert_severity = (int)lua_tonumber(vm, 3); if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_ERROR); alert_json = (char*)lua_tostring(vm, 4); if((!ntop_interface) || ((am = ntop_interface->getAlertsManager()) == NULL)) return(CONST_LUA_ERROR); if(engage) ret = am->engageInterfaceAlert(ntop_interface, engaged_alert_id, (AlertType)alert_type, (AlertLevel)alert_severity, alert_json); else ret = am->releaseInterfaceAlert(ntop_interface, engaged_alert_id, (AlertType)alert_type, (AlertLevel)alert_severity, alert_json); return ret >= 0 ? CONST_LUA_OK : CONST_LUA_ERROR; } /* ****************************************** */ static int ntop_interface_engage_host_alert(lua_State* vm) { return ntop_interface_engage_release_host_alert(vm, true /* engage */); } /* ****************************************** */ static int ntop_interface_release_host_alert(lua_State* vm) { return ntop_interface_engage_release_host_alert(vm, false /* release */); } /* ****************************************** */ static int ntop_interface_engage_network_alert(lua_State* vm) { return ntop_interface_engage_release_network_alert(vm, true /* engage */); } /* ****************************************** */ static int ntop_interface_release_network_alert(lua_State* vm) { return ntop_interface_engage_release_network_alert(vm, false /* release */); } /* ****************************************** */ static int ntop_interface_engage_interface_alert(lua_State* vm) { return ntop_interface_engage_release_interface_alert(vm, true /* engage */); } /* ****************************************** */ static int ntop_interface_release_interface_alert(lua_State* vm) { return ntop_interface_engage_release_interface_alert(vm, false /* release */); } /* ****************************************** */ static int ntop_interface_get_cached_num_alerts(lua_State* vm) { NetworkInterface *iface = getCurrentInterface(vm); AlertsManager *am; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!iface || !(am = iface->getAlertsManager())) return (CONST_LUA_ERROR); return (!am->getCachedNumAlerts(vm)) ? CONST_LUA_OK : CONST_LUA_ERROR; } /* ****************************************** */ static int ntop_interface_query_alerts_raw(lua_State* vm) { NetworkInterface *iface = getCurrentInterface(vm); AlertsManager *am; bool engaged = false; char *selection = NULL, *clauses = NULL; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!iface || !(am = iface->getAlertsManager())) return (CONST_LUA_ERROR); if(lua_type(vm, 1) == LUA_TBOOLEAN) engaged = lua_toboolean(vm, 1); if(lua_type(vm, 2) == LUA_TSTRING) if((selection = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(lua_type(vm, 3) == LUA_TSTRING) if((clauses = (char*)lua_tostring(vm, 3)) == NULL) return(CONST_LUA_PARAM_ERROR); if(am->queryAlertsRaw(vm, engaged, selection, clauses)) return(CONST_LUA_ERROR); return (CONST_LUA_OK); } /* ****************************************** */ static int ntop_interface_query_flow_alerts_raw(lua_State* vm) { NetworkInterface *iface = getCurrentInterface(vm); AlertsManager *am; char *selection = NULL, *clauses = NULL; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!iface || !(am = iface->getAlertsManager())) return (CONST_LUA_ERROR); if(lua_type(vm, 1) == LUA_TSTRING) if((selection = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(lua_type(vm, 2) == LUA_TSTRING) if((clauses = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(am->queryFlowAlertsRaw(vm, selection, clauses)) return(CONST_LUA_ERROR); return (CONST_LUA_OK); } /* ****************************************** */ #if NTOPNG_PRO static int ntop_nagios_reload_config(lua_State* vm) { NagiosManager *nagios = ntop->getNagios(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(!nagios) { ntop->getTrace()->traceEvent(TRACE_ERROR, "%s(): unable to get the nagios manager", __FUNCTION__); return(CONST_LUA_ERROR); } nagios->loadConfig(); lua_pushnil(vm); return(CONST_LUA_OK); } static int ntop_nagios_send_alert(lua_State* vm) { NagiosManager *nagios = ntop->getNagios(); char *alert_source; char *timespan; char *alarmed_metric; char *alert_msg; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); alert_source = (char*)lua_tostring(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); timespan = (char*)lua_tostring(vm, 2); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR); alarmed_metric = (char*)lua_tostring(vm, 3); if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_ERROR); alert_msg = (char*)lua_tostring(vm, 4); nagios->sendAlert(alert_source, timespan, alarmed_metric, alert_msg); lua_pushnil(vm); return(CONST_LUA_OK); } static int ntop_nagios_withdraw_alert(lua_State* vm) { NagiosManager *nagios = ntop->getNagios(); char *alert_source; char *timespan; char *alarmed_metric; char *alert_msg; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); alert_source = (char*)lua_tostring(vm, 1); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); timespan = (char*)lua_tostring(vm, 2); if(ntop_lua_check(vm, __FUNCTION__, 3, LUA_TSTRING)) return(CONST_LUA_ERROR); alarmed_metric = (char*)lua_tostring(vm, 3); if(ntop_lua_check(vm, __FUNCTION__, 4, LUA_TSTRING)) return(CONST_LUA_ERROR); alert_msg = (char*)lua_tostring(vm, 4); nagios->withdrawAlert(alert_source, timespan, alarmed_metric, alert_msg); lua_pushnil(vm); return(CONST_LUA_OK); } #endif /* ****************************************** */ #ifdef NTOPNG_PRO static int ntop_check_profile_syntax(lua_State* vm) { char *filter; NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); filter = (char*)lua_tostring(vm, 1); lua_pushboolean(vm, ntop_interface ? ntop_interface->checkProfileSyntax(filter) : false); return(CONST_LUA_OK); } #endif /* ****************************************** */ #ifdef NTOPNG_PRO static int ntop_reload_traffic_profiles(lua_State* vm) { NetworkInterface *ntop_interface = getCurrentInterface(vm); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_interface) ntop_interface->updateFlowProfiles(); /* Reload profiles in memory */ lua_pushnil(vm); return(CONST_LUA_OK); } #endif /* ****************************************** */ static int ntop_set_redis(lua_State* vm) { char *key, *value; u_int expire_secs = 0; // default 0 = no expiration Redis *redis = ntop->getRedis(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); if((value = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); /* Optional key expiration in SECONDS */ if(lua_type(vm, 3) == LUA_TNUMBER) expire_secs = (u_int)lua_tonumber(vm, 3); if(redis->set(key, value, expire_secs) == 0) { return(CONST_LUA_OK); }else return(CONST_LUA_ERROR); } /* ****************************************** */ static int ntop_set_redis_preference(lua_State* vm) { char *key, *value; Redis *redis = ntop->getRedis(); ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); if((key = (char*)lua_tostring(vm, 1)) == NULL) return(CONST_LUA_PARAM_ERROR); if(ntop_lua_check(vm, __FUNCTION__, 2, LUA_TSTRING)) return(CONST_LUA_ERROR); if((value = (char*)lua_tostring(vm, 2)) == NULL) return(CONST_LUA_PARAM_ERROR); if(redis->set(key, value) || ntop->getPrefs()->refresh(key, value)) return(CONST_LUA_ERROR); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_lua_http_print(lua_State* vm) { struct mg_connection *conn; char *printtype; int t; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); lua_getglobal(vm, CONST_HTTP_CONN); if((conn = (struct mg_connection*)lua_touserdata(vm, lua_gettop(vm))) == NULL) { ntop->getTrace()->traceEvent(TRACE_ERROR, "INTERNAL ERROR: null HTTP connection"); return(CONST_LUA_OK); } /* Handle binary blob */ if(lua_type(vm, 2) == LUA_TSTRING && (printtype = (char*)lua_tostring(vm, 2)) != NULL) if(!strncmp(printtype, "blob", 4)) { char *str = NULL; if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return (CONST_LUA_ERROR); if((str = (char*)lua_tostring(vm, 1)) != NULL) { int len = strlen(str); if(len <= 1) mg_printf(conn, "%c", str[0]); else return (CONST_LUA_PARAM_ERROR); } return (CONST_LUA_OK); } switch(t = lua_type(vm, 1)) { case LUA_TNIL: mg_printf(conn, "%s", "nil"); break; case LUA_TBOOLEAN: { int v = lua_toboolean(vm, 1); mg_printf(conn, "%s", v ? "true" : "false"); } break; case LUA_TSTRING: { char *str = (char*)lua_tostring(vm, 1); if(str && (strlen(str) > 0)) mg_printf(conn, "%s", str); } break; case LUA_TNUMBER: { char str[64]; snprintf(str, sizeof(str), "%f", (float)lua_tonumber(vm, 1)); mg_printf(conn, "%s", str); } break; default: ntop->getTrace()->traceEvent(TRACE_WARNING, "%s(): Lua type %d is not handled", __FUNCTION__, t); return(CONST_LUA_ERROR); } return(CONST_LUA_OK); } /* ****************************************** */ int ntop_lua_cli_print(lua_State* vm) { int t; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); switch(t = lua_type(vm, 1)) { case LUA_TSTRING: { char *str = (char*)lua_tostring(vm, 1); if(str && (strlen(str) > 0)) ntop->getTrace()->traceEvent(TRACE_NORMAL, "%s", str); } break; case LUA_TNUMBER: ntop->getTrace()->traceEvent(TRACE_NORMAL, "%f", (float)lua_tonumber(vm, 1)); break; default: ntop->getTrace()->traceEvent(TRACE_WARNING, "%s(): Lua type %d is not handled", __FUNCTION__, t); return(CONST_LUA_ERROR); } return(CONST_LUA_OK); } /* ****************************************** */ #ifdef NTOPNG_PRO static int __ntop_lua_handlefile(lua_State* L, char *script_path, bool ex) { int rc; LuaHandler *lh = new LuaHandler(L, script_path); rc = lh->luaL_dofileM(ex); delete lh; return rc; } /* This function is called by Lua scripts when the call require(...) */ static int ntop_lua_require(lua_State* L) { char *script_name; if(lua_type(L, 1) != LUA_TSTRING || (script_name = (char*)lua_tostring(L, 1)) == NULL) return 0; lua_getglobal( L, "package" ); lua_getfield( L, -1, "path" ); string cur_path = lua_tostring( L, -1 ), parsed, script_path = ""; stringstream input_stringstream(cur_path); while(getline(input_stringstream, parsed, ';')) { /* Example: package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path */ unsigned found = parsed.find_last_of("?"); if(found) { string s = parsed.substr(0, found) + script_name + ".lua"; if(Utils::file_exists(s.c_str())) { script_path = s; break; } } } if(script_path == "" || __ntop_lua_handlefile(L, (char *)script_path.c_str(), false)) return 0; return 1; } static int ntop_lua_dofile(lua_State* L) { char *script_path; if(lua_type(L, 1) != LUA_TSTRING || (script_path = (char*)lua_tostring(L, 1)) == NULL || __ntop_lua_handlefile(L, script_path, true)) return 0; return 1; } #endif /* ****************************************** */ /** * @brief Return true if login has been disabled * * @param vm The lua state. * @return @ref CONST_LUA_OK and push the return code into the Lua stack */ static int ntop_is_login_disabled(lua_State* vm) { ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); bool ret = ntop->getPrefs()->is_localhost_users_login_disabled() || !ntop->getPrefs()->is_users_login_enabled(); lua_pushboolean(vm, ret); return(CONST_LUA_OK); } /* ****************************************** */ /** * @brief Convert the network Id to a symbolic name (network/mask) * * @param vm The lua state. * @return @ref CONST_LUA_OK and push the return code into the Lua stack */ static int ntop_network_name_by_id(lua_State* vm) { int id; char *name; ntop->getTrace()->traceEvent(TRACE_DEBUG, "%s() called", __FUNCTION__); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TNUMBER)) return(CONST_LUA_ERROR); id = (u_int32_t)lua_tonumber(vm, 1); name = ntop->getLocalNetworkName(id); lua_pushstring(vm, name ? name : ""); return(CONST_LUA_OK); } /* ****************************************** */ static int ntop_set_logging_level(lua_State* vm) { char *lvlStr; ntop->getTrace()->traceEvent(TRACE_INFO, "%s() called", __FUNCTION__); if(ntop->getPrefs()->hasCmdlTraceLevel()) return(CONST_LUA_OK); if(ntop_lua_check(vm, __FUNCTION__, 1, LUA_TSTRING)) return(CONST_LUA_ERROR); lvlStr = (char*)lua_tostring(vm, 1); if(!strcmp(lvlStr, "trace")){ ntop->getTrace()->set_trace_level(TRACE_LEVEL_TRACE); } else if(!strcmp(lvlStr, "debug")){ ntop->getTrace()->set_trace_level(TRACE_LEVEL_DEBUG); } else if(!strcmp(lvlStr, "info")){ ntop->getTrace()->set_trace_level(TRACE_LEVEL_INFO); } else if(!strcmp(lvlStr, "normal")){ ntop->getTrace()->set_trace_level(TRACE_LEVEL_NORMAL); } else if(!strcmp(lvlStr, "warning")){ ntop->getTrace()->set_trace_level(TRACE_LEVEL_WARNING); } else if(!strcmp(lvlStr, "error")){ ntop->getTrace()->set_trace_level(TRACE_LEVEL_ERROR); } else{ return(CONST_LUA_ERROR); } return(CONST_LUA_OK); } /* ****************************************** */ static const luaL_Reg ntop_interface_reg[] = { { "getDefaultIfName", ntop_get_default_interface_name }, { "setActiveInterfaceId", ntop_set_active_interface_id }, { "getIfNames", ntop_get_interface_names }, { "select", ntop_select_interface }, { "getStats", ntop_get_interface_stats }, { "resetCounters", ntop_interface_reset_counters }, { "getnDPIStats", ntop_get_ndpi_interface_stats }, { "getnDPIProtoName", ntop_get_ndpi_protocol_name }, { "getnDPIProtoId", ntop_get_ndpi_protocol_id }, { "getnDPIProtoCategory", ntop_get_ndpi_protocol_category }, { "getnDPIFlowsCount", ntop_get_ndpi_interface_flows_count }, { "getFlowsStatus", ntop_get_ndpi_interface_flows_status }, { "getnDPIProtoBreed", ntop_get_ndpi_protocol_breed }, { "getnDPIProtocols", ntop_get_ndpi_protocols }, { "getnDPICategories", ntop_get_ndpi_categories }, { "getHostsInfo", ntop_get_interface_hosts_info }, { "getLocalHostsInfo", ntop_get_interface_local_hosts_info }, { "getRemoteHostsInfo", ntop_get_interface_remote_hosts_info }, { "getHostActivity", ntop_get_interface_host_activity }, { "getHostInfo", ntop_get_interface_host_info }, { "getGroupedHosts", ntop_get_grouped_interface_hosts }, { "getNetworksStats", ntop_get_interface_networks_stats }, { "resetPeriodicStats", ntop_host_reset_periodic_stats }, { "correlateHostActivity", ntop_correalate_host_activity }, { "similarHostActivity", ntop_similar_host_activity }, { "getHostActivityMap", ntop_get_interface_host_activitymap }, { "restoreHost", ntop_restore_interface_host }, { "getFlowsInfo", ntop_get_interface_flows_info }, { "getLocalFlowsInfo", ntop_get_interface_local_flows_info }, { "getRemoteFlowsInfo", ntop_get_interface_remote_flows_info }, { "getFlowsStats", ntop_get_interface_flows_stats }, { "getFlowPeers", ntop_get_interface_flows_peers }, { "getFlowKey", ntop_get_interface_flow_key }, { "findFlowByKey", ntop_get_interface_find_flow_by_key }, { "dropFlowTraffic", ntop_drop_flow_traffic }, { "dumpFlowTraffic", ntop_dump_flow_traffic }, { "dumpLocalHosts2redis", ntop_dump_local_hosts_2_redis }, { "findUserFlows", ntop_get_interface_find_user_flows }, { "findPidFlows", ntop_get_interface_find_pid_flows }, { "findFatherPidFlows", ntop_get_interface_find_father_pid_flows }, { "findNameFlows", ntop_get_interface_find_proc_name_flows }, { "listHTTPhosts", ntop_list_http_hosts }, { "findHost", ntop_get_interface_find_host }, { "updateHostTrafficPolicy", ntop_update_host_traffic_policy }, { "updateHostAlertPolicy", ntop_update_host_alert_policy }, { "setSecondTraffic", ntop_set_second_traffic }, { "setHostDumpPolicy", ntop_set_host_dump_policy }, { "setHostQuota", ntop_set_host_quota }, { "getPeerHitRate", ntop_get_host_hit_rate }, { "getLatestActivityHostsInfo", ntop_get_interface_latest_activity_hosts_info }, { "getInterfaceDumpDiskPolicy", ntop_get_interface_dump_disk_policy }, { "getInterfaceDumpTapPolicy", ntop_get_interface_dump_tap_policy }, { "getInterfaceDumpTapName", ntop_get_interface_dump_tap_name }, { "getInterfaceDumpMaxPkts", ntop_get_interface_dump_max_pkts }, { "getInterfaceDumpMaxSec", ntop_get_interface_dump_max_sec }, { "getInterfaceDumpMaxFiles", ntop_get_interface_dump_max_files }, { "getInterfacePacketsDumpedFile", ntop_get_interface_pkts_dumped_file }, { "getInterfacePacketsDumpedTap", ntop_get_interface_pkts_dumped_tap }, { "getEndpoint", ntop_get_interface_endpoint }, { "isPacketInterface", ntop_interface_is_packet_interface }, { "isBridgeInterface", ntop_interface_is_bridge_interface }, { "isPcapDumpInterface", ntop_interface_is_pcap_dump_interface }, { "isRunning", ntop_interface_is_running }, { "isIdle", ntop_interface_is_idle }, { "setInterfaceIdleState", ntop_interface_set_idle }, { "name2id", ntop_interface_name2id }, { "loadDumpPrefs", ntop_load_dump_prefs }, { "loadScalingFactorPrefs", ntop_load_scaling_factor_prefs }, { "loadHostAlertPrefs", ntop_interface_load_host_alert_prefs }, /* Mac */ { "getMacsInfo", ntop_get_interface_macs_info }, { "getMacInfo", ntop_get_interface_mac_info }, /* L7 */ { "reloadL7Rules", ntop_reload_l7_rules }, { "reloadShapers", ntop_reload_shapers }, /* DB */ { "execSQLQuery", ntop_interface_exec_sql_query }, /* Flows */ { "getFlowDevices", ntop_getflowdevices }, { "getFlowDeviceInfo", ntop_getflowdeviceinfo }, /* New generation alerts */ { "getCachedNumAlerts", ntop_interface_get_cached_num_alerts }, { "queryAlertsRaw", ntop_interface_query_alerts_raw }, { "queryFlowAlertsRaw", ntop_interface_query_flow_alerts_raw }, { "engageHostAlert", ntop_interface_engage_host_alert }, { "releaseHostAlert", ntop_interface_release_host_alert }, { "engageNetworkAlert", ntop_interface_engage_network_alert }, { "releaseNetworkAlert", ntop_interface_release_network_alert }, { "engageInterfaceAlert", ntop_interface_engage_interface_alert }, { "releaseInterfaceAlert",ntop_interface_release_interface_alert }, { "enableHostAlerts", ntop_interface_host_enable_alerts }, { "disableHostAlerts", ntop_interface_host_disable_alerts }, { "refreshNumAlerts", ntop_interface_refresh_num_alerts }, { NULL, NULL } }; /* **************************************************************** */ static const luaL_Reg ntop_reg[] = { { "getDirs", ntop_get_dirs }, { "getInfo", ntop_get_info }, { "getUptime", ntop_get_uptime }, { "dumpFile", ntop_dump_file }, { "checkLicense", ntop_check_license }, /* Redis */ { "getCache", ntop_get_redis }, { "setCache", ntop_set_redis }, { "delCache", ntop_delete_redis_key }, { "listIndexCache", ntop_list_index_redis }, { "lpushCache", ntop_lpush_redis }, { "lpopCache", ntop_lpop_redis }, { "lrangeCache", ntop_lrange_redis }, { "getMembersCache", ntop_get_set_members_redis }, { "getHashCache", ntop_get_hash_redis }, { "setHashCache", ntop_set_hash_redis }, { "delHashCache", ntop_del_hash_redis }, { "getHashKeysCache",ntop_get_hash_keys_redis }, { "getKeysCache", ntop_get_keys_redis }, { "delHashCache", ntop_delete_hash_redis_key }, { "setPopCache", ntop_get_redis_set_pop }, { "getHostId", ntop_redis_get_host_id }, { "getIdToHost", ntop_redis_get_id_to_host }, /* Redis Preferences */ { "setPref", ntop_set_redis_preference }, { "getPref", ntop_get_redis }, { "isdir", ntop_is_dir }, { "mkdir", ntop_mkdir_tree }, { "notEmptyFile", ntop_is_not_empty_file }, { "exists", ntop_get_file_dir_exists }, { "listReports", ntop_list_reports }, { "fileLastChange", ntop_get_file_last_change }, { "readdir", ntop_list_dir_files }, { "zmq_connect", ntop_zmq_connect }, { "zmq_disconnect", ntop_zmq_disconnect }, { "zmq_receive", ntop_zmq_receive }, { "getLocalNetworks", ntop_get_local_networks }, { "reloadPreferences", ntop_reload_preferences }, #ifdef NTOPNG_PRO { "sendNagiosAlert", ntop_nagios_send_alert }, { "withdrawNagiosAlert", ntop_nagios_withdraw_alert }, { "reloadNagiosConfig", ntop_nagios_reload_config }, { "checkProfileSyntax", ntop_check_profile_syntax }, { "reloadProfiles", ntop_reload_traffic_profiles }, #endif /* Pro */ { "isPro", ntop_is_pro }, { "isEnterprise", ntop_is_enterprise }, /* Historical database */ { "insertMinuteSampling", ntop_stats_insert_minute_sampling }, { "insertHourSampling", ntop_stats_insert_hour_sampling }, { "insertDaySampling", ntop_stats_insert_day_sampling }, { "getMinuteSampling", ntop_stats_get_minute_sampling }, { "deleteMinuteStatsOlderThan", ntop_stats_delete_minute_older_than }, { "deleteHourStatsOlderThan", ntop_stats_delete_hour_older_than }, { "deleteDayStatsOlderThan", ntop_stats_delete_day_older_than }, { "getMinuteSamplingsFromEpoch", ntop_stats_get_samplings_of_minutes_from_epoch }, { "getHourSamplingsFromEpoch", ntop_stats_get_samplings_of_hours_from_epoch }, { "getDaySamplingsFromEpoch", ntop_stats_get_samplings_of_days_from_epoch }, { "getMinuteSamplingsInterval", ntop_stats_get_minute_samplings_interval }, { "deleteDumpFiles", ntop_delete_dump_files }, /* Time */ { "gettimemsec", ntop_gettimemsec }, /* Trace */ { "verboseTrace", ntop_verbose_trace }, /* UDP */ { "send_udp_data", ntop_send_udp_data }, /* IP */ { "inet_ntoa", ntop_inet_ntoa }, /* RRD */ { "rrd_create", ntop_rrd_create }, { "rrd_update", ntop_rrd_update }, { "rrd_fetch", ntop_rrd_fetch }, { "rrd_fetch_columns", ntop_rrd_fetch_columns }, { "rrd_lastupdate", ntop_rrd_lastupdate }, /* Prefs */ { "getPrefs", ntop_get_prefs }, /* HTTP */ { "httpRedirect", ntop_http_redirect }, { "httpGet", ntop_http_get }, { "getHttpPrefix", ntop_http_get_prefix }, /* Admin */ { "getNologinUser", ntop_get_nologin_username }, { "getUsers", ntop_get_users }, { "getUserGroup", ntop_get_user_group }, { "getAllowedNetworks", ntop_get_allowed_networks }, { "resetUserPassword", ntop_reset_user_password }, { "changeUserRole", ntop_change_user_role }, { "changeAllowedNets", ntop_change_allowed_nets }, { "changeAllowedIfname",ntop_change_allowed_ifname }, { "addUser", ntop_add_user }, { "deleteUser", ntop_delete_user }, { "isLoginDisabled", ntop_is_login_disabled }, { "getNetworkNameById", ntop_network_name_by_id }, /* Security */ { "getRandomCSRFValue", ntop_generate_csrf_value }, /* HTTP */ { "postHTTPJsonData", ntop_post_http_json_data }, /* Address Resolution */ { "resolveAddress", ntop_resolve_address }, { "getResolvedAddress", ntop_get_resolved_address }, /* Logging */ { "syslog", ntop_syslog }, { "setLoggingLevel",ntop_set_logging_level }, /* SNMP */ { "snmpget", ntop_snmpget }, { "snmpgetnext", ntop_snmpgetnext }, /* SQLite */ { "execQuery", ntop_sqlite_exec_query }, /* Runtime */ { "hasVLANs", ntop_has_vlans }, { "hasGeoIP", ntop_has_geoip }, { "isWindows", ntop_is_windows }, /* Host Blacklist */ { "allocHostBlacklist", ntop_allocHostBlacklist }, { "swapHostBlacklist", ntop_swapHostBlacklist }, { "addToHostBlacklist", ntop_addToHostBlacklist }, /* Misc */ { "getservbyport", ntop_getservbyport }, { NULL, NULL} }; /* ****************************************** */ void Lua::lua_register_classes(lua_State *L, bool http_mode) { static const luaL_Reg _meta[] = { { NULL, NULL } }; int i; ntop_class_reg ntop_lua_reg[] = { { "interface", ntop_interface_reg }, { "ntop", ntop_reg }, {NULL, NULL} }; if(!L) return; luaopen_lsqlite3(L); for(i=0; ntop_lua_reg[i].class_name != NULL; i++) { int lib_id, meta_id; /* newclass = {} */ lua_createtable(L, 0, 0); lib_id = lua_gettop(L); /* metatable = {} */ luaL_newmetatable(L, ntop_lua_reg[i].class_name); meta_id = lua_gettop(L); luaL_register(L, NULL, _meta); /* metatable.__index = class_methods */ lua_newtable(L), luaL_register(L, NULL, ntop_lua_reg[i].class_methods); lua_setfield(L, meta_id, "__index"); /* class.__metatable = metatable */ lua_setmetatable(L, lib_id); /* _G["Foo"] = newclass */ lua_setglobal(L, ntop_lua_reg[i].class_name); } if(http_mode) { /* Overload the standard Lua print() with ntop_lua_http_print that dumps data on HTTP server */ lua_register(L, "print", ntop_lua_http_print); } else lua_register(L, "print", ntop_lua_cli_print); #ifdef NTOPNG_PRO if(ntop->getPro()->has_valid_license()) { lua_register(L, "ntopRequire", ntop_lua_require); luaL_dostring(L, "table.insert(package.loaders, 1, ntopRequire)"); lua_register(L, "dofile", ntop_lua_dofile); } #endif } /* ****************************************** */ #if 0 /** * Iterator over key-value pairs where the value * maybe made available in increments and/or may * not be zero-terminated. Used for processing * POST data. * * @param cls user-specified closure * @param kind type of the value * @param key 0-terminated key for the value * @param filename name of the uploaded file, NULL if not known * @param content_type mime-type of the data, NULL if not known * @param transfer_encoding encoding of the data, NULL if not known * @param data pointer to size bytes of data at the * specified offset * @param off offset of data in the overall value * @param size number of bytes in data available * @return MHD_YES to continue iterating, * MHD_NO to abort the iteration */ static int post_iterator(void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct Request *request = cls; char tmp[1024]; u_int len = min(size, sizeof(tmp)-1); memcpy(tmp, &data[off], len); tmp[len] = '\0'; fprintf(stdout, "[POST] [%s][%s]\n", key, tmp); return MHD_YES; } #endif /* ****************************************** */ /* Run a Lua script from within ntopng (no HTTP GUI) */ int Lua::run_script(char *script_path) { int rc = 0; if(!L) return(-1); try { luaL_openlibs(L); /* Load base libraries */ lua_register_classes(L, false); /* Load custom classes */ #ifndef NTOPNG_PRO rc = luaL_dofile(L, script_path); #else if(ntop->getPro()->has_valid_license()) rc = __ntop_lua_handlefile(L, script_path, true); else rc = luaL_dofile(L, script_path); #endif if(rc != 0) { const char *err = lua_tostring(L, -1); ntop->getTrace()->traceEvent(TRACE_WARNING, "Script failure [%s][%s]", script_path, err); rc = -1; } } catch(...) { ntop->getTrace()->traceEvent(TRACE_WARNING, "Script failure [%s]", script_path); rc = -2; } return(rc); } /* ****************************************** */ /* http://www.geekhideout.com/downloads/urlcode.c */ #if 0 /* Converts an integer value to its hex character*/ static char to_hex(char code) { static char hex[] = "0123456789abcdef"; return hex[code & 15]; } /* ****************************************** */ /* Returns a url-encoded version of str */ /* IMPORTANT: be sure to free() the returned string after use */ static char* http_encode(char *str) { char *pstr = str, *buf = (char*)malloc(strlen(str) * 3 + 1), *pbuf = buf; while (*pstr) { if(isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~') *pbuf++ = *pstr; else if(*pstr == ' ') *pbuf++ = '+'; else *pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15); pstr++; } *pbuf = '\0'; return buf; } #endif /* ****************************************** */ /* Converts a hex character to its integer value */ static char from_hex(char ch) { return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10; } /* ****************************************** */ /* Returns a url-decoded version of str */ /* IMPORTANT: be sure to free() the returned string after use */ static char* http_decode(char *str) { char *pstr = str, *buf = (char*)malloc(strlen(str) + 1), *pbuf = buf; while (*pstr) { if(*pstr == '%') { if(pstr[1] && pstr[2]) { *pbuf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]); pstr += 2; } } else if(*pstr == '+') { *pbuf++ = ' '; } else { *pbuf++ = *pstr; } pstr++; } *pbuf = '\0'; return buf; } /* ****************************************** */ void Lua::purifyHTTPParameter(char *param) { char *ampercent; if((ampercent = strchr(param, '%')) != NULL) { /* We allow only a few chars, removing all the others */ if((ampercent[1] != 0) && (ampercent[2] != 0)) { char c; char b = ampercent[3]; ampercent[3] = '\0'; c = (char)strtol(&ampercent[1], NULL, 16); ampercent[3] = b; switch(c) { case '/': case ':': case '(': case ')': case '{': case '}': case '[': case ']': case '?': case '!': case '$': case ',': case '^': case '*': case '_': case '&': case ' ': case '=': case '<': case '>': case '@': case '#': break; default: if(!Utils::isPrintableChar(c)) { ntop->getTrace()->traceEvent(TRACE_WARNING, "Discarded char '%c' in URI [%s]", c, param); ampercent[0] = '\0'; return; } } purifyHTTPParameter(&ampercent[3]); } else ampercent[0] = '\0'; } } /* ****************************************** */ void Lua::setInterface(const char *user) { char key[64], ifname[MAX_INTERFACE_NAME_LEN]; bool enforce_allowed_interface = false; if(user[0] != '\0') { // check if the user is restricted to browse only a given interface if(snprintf(key, sizeof(key), CONST_STR_USER_ALLOWED_IFNAME, user) && !ntop->getRedis()->get(key, ifname, sizeof(ifname))) { // there is only one allowed interface for the user enforce_allowed_interface = true; goto set_preferred_interface; } else if(snprintf(key, sizeof(key), "ntopng.prefs.%s.ifname", user) && ntop->getRedis()->get(key, ifname, sizeof(ifname)) < 0) { // no allowed interface and no default set interface set_default_if_name_in_session: snprintf(ifname, sizeof(ifname), "%s", ntop->getInterfaceAtId(NULL /* allowed user interface check already enforced */, 0)->get_name()); lua_push_str_table_entry(L, "ifname", ifname); ntop->getRedis()->set(key, ifname, 3600 /* 1h */); } else { goto set_preferred_interface; } } else { // We need to check if ntopng is running with the option --disable-login snprintf(key, sizeof(key), "ntopng.prefs.ifname"); if(ntop->getRedis()->get(key, ifname, sizeof(ifname)) < 0) { goto set_preferred_interface; } set_preferred_interface: NetworkInterface *iface; if((iface = ntop->getNetworkInterface(NULL /* allowed user interface check already enforced */, ifname)) != NULL) { /* The specified interface still exists */ lua_push_str_table_entry(L, "ifname", iface->get_name()); } else if(!enforce_allowed_interface) { goto set_default_if_name_in_session; } else { // TODO: handle the case where the user has // an allowed interface that is not presently available // (e.g., not running?) } } } /* ****************************************** */ int Lua::handle_script_request(struct mg_connection *conn, const struct mg_request_info *request_info, char *script_path) { char buf[64], key[64], ifname[MAX_INTERFACE_NAME_LEN]; char *_cookies, user[64] = { '\0' }, outbuf[FILENAME_MAX]; AddressTree ptree; int rc; if(!L) return(-1); luaL_openlibs(L); /* Load base libraries */ lua_register_classes(L, true); /* Load custom classes */ lua_pushlightuserdata(L, (char*)conn); lua_setglobal(L, CONST_HTTP_CONN); /* Put the GET params into the environment */ lua_newtable(L); if(request_info->query_string != NULL) { char *query_string = strdup(request_info->query_string); if(query_string) { char *where; char *tok; // ntop->getTrace()->traceEvent(TRACE_WARNING, "[HTTP] %s", query_string); tok = strtok_r(query_string, "&", &where); while(tok != NULL) { /* key=val */ char *_equal = strchr(tok, '='); if(_equal) { char *equal; int len; _equal[0] = '\0'; _equal = &_equal[1]; len = strlen(_equal); purifyHTTPParameter(tok), purifyHTTPParameter(_equal); // ntop->getTrace()->traceEvent(TRACE_WARNING, "%s = %s", tok, _equal); if((equal = (char*)malloc(len+1)) != NULL) { char *decoded_buf; Utils::urlDecode(_equal, equal, len+1); if((decoded_buf = http_decode(equal)) != NULL) { FILE *fd; Utils::purifyHTTPparam(tok, true, false); Utils::purifyHTTPparam(decoded_buf, false, false); /* Now make sure that decoded_buf is not a file path */ if((decoded_buf[0] == '.') && ((fd = fopen(decoded_buf, "r")) || (fd = fopen(realpath(decoded_buf, outbuf), "r")))) { ntop->getTrace()->traceEvent(TRACE_WARNING, "Discarded '%s'='%s' as argument is a valid file path", tok, decoded_buf); decoded_buf[0] = '\0'; fclose(fd); } /* ntop->getTrace()->traceEvent(TRACE_WARNING, "'%s'='%s'", tok, decoded_buf); */ if(strcmp(tok, "csrf") == 0) { char rsp[32], user[64] = { '\0' }; mg_get_cookie(conn, "user", user, sizeof(user)); if((ntop->getRedis()->get(decoded_buf, rsp, sizeof(rsp)) == -1) || (strcmp(rsp, user) != 0)) { const char *msg = "The submitted form is expired. Please reload the page and try again"; ntop->getTrace()->traceEvent(TRACE_WARNING, "Invalid CSRF parameter specified [%s][%s][%s][%s]: page expired?", decoded_buf, rsp, user, tok); free(equal); return(send_error(conn, 500 /* Internal server error */, msg, PAGE_ERROR, query_string, msg)); } else ntop->getRedis()->delKey(decoded_buf); } lua_push_str_table_entry(L, tok, decoded_buf); free(decoded_buf); } free(equal); } else ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory"); } tok = strtok_r(NULL, "&", &where); } /* while */ free(query_string); } else ntop->getTrace()->traceEvent(TRACE_WARNING, "Not enough memory"); } lua_setglobal(L, "_GET"); /* Like in php */ /* _SERVER */ lua_newtable(L); lua_push_str_table_entry(L, "HTTP_REFERER", (char*)mg_get_header(conn, "Referer")); lua_push_str_table_entry(L, "HTTP_USER_AGENT", (char*)mg_get_header(conn, "User-Agent")); lua_push_str_table_entry(L, "SERVER_NAME", (char*)mg_get_header(conn, "Host")); lua_setglobal(L, "_SERVER"); /* Like in php */ /* Cookies */ lua_newtable(L); if((_cookies = (char*)mg_get_header(conn, "Cookie")) != NULL) { char *cookies = strdup(_cookies); char *tok, *where; // ntop->getTrace()->traceEvent(TRACE_WARNING, "=> '%s'", cookies); tok = strtok_r(cookies, "=", &where); while(tok != NULL) { char *val; while(tok[0] == ' ') tok++; if((val = strtok_r(NULL, ";", &where)) != NULL) { lua_push_str_table_entry(L, tok, val); // ntop->getTrace()->traceEvent(TRACE_WARNING, "'%s'='%s'", tok, val); } else break; tok = strtok_r(NULL, "=", &where); } free(cookies); } lua_setglobal(L, "_COOKIE"); /* Like in php */ /* Put the _SESSION params into the environment */ lua_newtable(L); mg_get_cookie(conn, "user", user, sizeof(user)); lua_push_str_table_entry(L, "user", user); mg_get_cookie(conn, "session", buf, sizeof(buf)); lua_push_str_table_entry(L, "session", buf); // now it's time to set the interface. setInterface(user); lua_setglobal(L, "_SESSION"); /* Like in php */ if(user[0] != '\0') { char val[255]; lua_pushlightuserdata(L, user); lua_setglobal(L, "user"); snprintf(key, sizeof(key), "ntopng.user.%s.allowed_nets", user); if((ntop->getRedis()->get(key, val, sizeof(val)) != -1) && (val[0] != '\0')) { ptree.addAddresses(val); lua_pushlightuserdata(L, &ptree); lua_setglobal(L, CONST_ALLOWED_NETS); // ntop->getTrace()->traceEvent(TRACE_WARNING, "SET %p", ptree); } snprintf(key, sizeof(key), CONST_STR_USER_ALLOWED_IFNAME, user); if(snprintf(key, sizeof(key), CONST_STR_USER_ALLOWED_IFNAME, user) && !ntop->getRedis()->get(key, ifname, sizeof(ifname))) { lua_pushlightuserdata(L, ifname); lua_setglobal(L, CONST_ALLOWED_IFNAME); } } #ifndef NTOPNG_PRO rc = luaL_dofile(L, script_path); #else if(ntop->getPro()->has_valid_license()) rc = __ntop_lua_handlefile(L, script_path, true); else rc = luaL_dofile(L, script_path); #endif if(rc != 0) { const char *err = lua_tostring(L, -1); ntop->getTrace()->traceEvent(TRACE_WARNING, "Script failure [%s][%s]", script_path, err); return(send_error(conn, 500 /* Internal server error */, "Internal server error", PAGE_ERROR, script_path, err)); } return(CONST_LUA_OK); }
./CrossVul/dataset_final_sorted/CWE-352/cpp/bad_3092_0
crossvul-cpp_data_good_612_0
#include "uncurl/uncurl.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include "net.h" #include "tls.h" #include "http.h" #include "ws.h" #define LEN_IP4 16 #define LEN_CHUNK 64 #define LEN_ORIGIN 512 #if defined(__WINDOWS__) #include <winsock2.h> #define strdup(a) _strdup(a) #else #include <arpa/inet.h> #endif struct uncurl_opts { uint32_t max_header; uint32_t max_body; }; struct uncurl_tls_ctx { struct tls_state *tlss; }; struct uncurl_conn { struct uncurl_opts opts; struct net_opts nopts; struct tls_opts topts; char *hout; struct http_header *hin; struct net_context *net; struct tls_context *tls; void *ctx; int32_t (*read)(void *ctx, char *buf, uint32_t buf_size); int32_t (*write)(void *ctx, char *buf, uint32_t buf_size); char *host; uint16_t port; uint32_t seed; uint8_t ws_mask; char *netbuf; uint64_t netbuf_size; }; /*** TLS CONTEXT ***/ UNCURL_EXPORT void uncurl_free_tls_ctx(struct uncurl_tls_ctx *uc_tls) { if (!uc_tls) return; tlss_free(uc_tls->tlss); free(uc_tls); } UNCURL_EXPORT int32_t uncurl_new_tls_ctx(struct uncurl_tls_ctx **uc_tls_in) { int32_t e; struct uncurl_tls_ctx *uc_tls = *uc_tls_in = calloc(1, sizeof(struct uncurl_tls_ctx)); e = tlss_alloc(&uc_tls->tlss); if (e == UNCURL_OK) return e; uncurl_free_tls_ctx(uc_tls); *uc_tls_in = NULL; return e; } UNCURL_EXPORT int32_t uncurl_set_cacert(struct uncurl_tls_ctx *uc_tls, char *cacert, size_t size) { return tlss_load_cacert(uc_tls->tlss, cacert, size); } UNCURL_EXPORT int32_t uncurl_set_cacert_file(struct uncurl_tls_ctx *uc_tls, char *cacert_file) { return tlss_load_cacert_file(uc_tls->tlss, cacert_file); } UNCURL_EXPORT int32_t uncurl_set_cert_and_key_file(struct uncurl_tls_ctx *uc_tls, char *cert_file, char *key_file) { return tlss_load_cert_and_key_file(uc_tls->tlss, cert_file, key_file); } /*** CONNECTION ***/ static void uncurl_default_opts(struct uncurl_opts *opts) { opts->max_header = 1024; opts->max_body = 128 * 1024 * 1024; } UNCURL_EXPORT struct uncurl_conn *uncurl_new_conn(struct uncurl_conn *parent) { struct uncurl_conn *ucc = calloc(1, sizeof(struct uncurl_conn)); if (parent) { memcpy(&ucc->opts, &parent->opts, sizeof(struct uncurl_opts)); memcpy(&ucc->nopts, &parent->nopts, sizeof(struct net_opts)); memcpy(&ucc->topts, &parent->topts, sizeof(struct tls_opts)); } else { uncurl_default_opts(&ucc->opts); net_default_opts(&ucc->nopts); tls_default_opts(&ucc->topts); } ucc->seed = ws_rand(&ucc->seed); return ucc; } static void uncurl_attach_net(struct uncurl_conn *ucc) { ucc->ctx = ucc->net; ucc->read = net_read; ucc->write = net_write; } static void uncurl_attach_tls(struct uncurl_conn *ucc) { ucc->ctx = ucc->tls; ucc->read = tls_read; ucc->write = tls_write; } UNCURL_EXPORT int32_t uncurl_connect(struct uncurl_tls_ctx *uc_tls, struct uncurl_conn *ucc, int32_t scheme, char *host, uint16_t port) { int32_t e; //set state ucc->host = strdup(host); ucc->port = port; //resolve the hostname into an ip4 address char ip4[LEN_IP4]; e = net_getip4(ucc->host, ip4, LEN_IP4); if (e != UNCURL_OK) return e; //make the net connection e = net_connect(&ucc->net, ip4, ucc->port, &ucc->nopts); if (e != UNCURL_OK) return e; //default read/write callbacks uncurl_attach_net(ucc); if (scheme == UNCURL_HTTPS || scheme == UNCURL_WSS) { if (!uc_tls) return UNCURL_TLS_ERR_CONTEXT; e = tls_connect(&ucc->tls, uc_tls->tlss, ucc->net, ucc->host, &ucc->topts); if (e != UNCURL_OK) return e; //tls read/write callbacks uncurl_attach_tls(ucc); } return UNCURL_OK; } UNCURL_EXPORT int32_t uncurl_listen(struct uncurl_conn *ucc, char *bind_ip4, uint16_t port) { int32_t e; ucc->port = port; e = net_listen(&ucc->net, bind_ip4, ucc->port, &ucc->nopts); if (e != UNCURL_OK) return e; return UNCURL_OK; } UNCURL_EXPORT int32_t uncurl_accept(struct uncurl_tls_ctx *uc_tls, struct uncurl_conn *ucc, struct uncurl_conn **ucc_new_in, int32_t scheme) { int32_t r = UNCURL_ERR_DEFAULT; int32_t e; struct uncurl_conn *ucc_new = *ucc_new_in = uncurl_new_conn(ucc); struct net_context *new_net = NULL; e = net_accept(ucc->net, &new_net); if (e != UNCURL_OK) {r = e; goto uncurl_accept_end;} ucc_new->net = new_net; uncurl_attach_net(ucc_new); if (scheme == UNCURL_HTTPS || scheme == UNCURL_WSS) { if (!uc_tls) return UNCURL_TLS_ERR_CONTEXT; e = tls_accept(&ucc_new->tls, uc_tls->tlss, ucc_new->net, &ucc_new->topts); if (e != UNCURL_OK) {r = e; goto uncurl_accept_end;} //tls read/write callbacks uncurl_attach_tls(ucc_new); } return UNCURL_OK; uncurl_accept_end: free(ucc_new); *ucc_new_in = NULL; return r; } UNCURL_EXPORT int32_t uncurl_poll(struct uncurl_conn *ucc, int32_t timeout_ms) { return net_poll(ucc->net, NET_POLLIN, timeout_ms); } UNCURL_EXPORT void uncurl_get_socket(struct uncurl_conn *ucc, void *socket) { net_get_socket(ucc->net, socket); } UNCURL_EXPORT void uncurl_close(struct uncurl_conn *ucc) { if (!ucc) return; tls_close(ucc->tls); net_close(ucc->net); free(ucc->host); http_free_header(ucc->hin); free(ucc->hout); free(ucc->netbuf); free(ucc); } UNCURL_EXPORT void uncurl_set_option(struct uncurl_conn *ucc, int32_t opt, int32_t val) { switch (opt) { //uncurl options case UNCURL_OPT_MAX_HEADER: ucc->opts.max_header = (uint32_t) val; break; case UNCURL_OPT_MAX_BODY: ucc->opts.max_body = (uint32_t) val; break; //net options case UNCURL_NOPT_READ_TIMEOUT: ucc->nopts.read_timeout = val; break; case UNCURL_NOPT_CONNECT_TIMEOUT: ucc->nopts.connect_timeout = val; break; case UNCURL_NOPT_ACCEPT_TIMEOUT: ucc->nopts.accept_timeout = val; break; case UNCURL_NOPT_READ_BUF: ucc->nopts.read_buf = val; break; case UNCURL_NOPT_WRITE_BUF: ucc->nopts.write_buf = val; break; case UNCURL_NOPT_KEEPALIVE: ucc->nopts.keepalive = val; break; case UNCURL_NOPT_TCP_NODELAY: ucc->nopts.tcp_nodelay = val; break; case UNCURL_NOPT_REUSEADDR: ucc->nopts.reuseaddr = val; break; //tls options case UNCURL_TOPT_VERIFY_HOST: ucc->topts.verify_host = val; break; } } /*** REQUEST ***/ UNCURL_EXPORT void uncurl_set_header_str(struct uncurl_conn *ucc, char *name, char *value) { ucc->hout = http_set_header(ucc->hout, name, HTTP_STRING, value); } UNCURL_EXPORT void uncurl_set_header_int(struct uncurl_conn *ucc, char *name, int32_t value) { ucc->hout = http_set_header(ucc->hout, name, HTTP_INT, &value); } UNCURL_EXPORT void uncurl_free_header(struct uncurl_conn *ucc) { free(ucc->hout); ucc->hout = NULL; } UNCURL_EXPORT int32_t uncurl_write_header(struct uncurl_conn *ucc, char *str0, char *str1, int32_t type) { int32_t e; //generate the HTTP request/response header char *h = (type == UNCURL_REQUEST) ? http_request(str0, ucc->host, str1, ucc->hout) : http_response(str0, str1, ucc->hout); //write the header to the HTTP client/server e = ucc->write(ucc->ctx, h, (uint32_t) strlen(h)); free(h); return e; } UNCURL_EXPORT int32_t uncurl_write_body(struct uncurl_conn *ucc, char *body, uint32_t body_len) { int32_t e; e = ucc->write(ucc->ctx, body, body_len); return e; } /*** RESPONSE ***/ static int32_t uncurl_read_header_(struct uncurl_conn *ucc, char **header) { int32_t r = UNCURL_ERR_MAX_HEADER; uint32_t max_header = ucc->opts.max_header; char *h = *header = calloc(max_header, 1); uint32_t x = 0; for (; x < max_header - 1; x++) { int32_t e; e = ucc->read(ucc->ctx, h + x, 1); if (e != UNCURL_OK) {r = e; break;} if (x > 2 && h[x - 3] == '\r' && h[x - 2] == '\n' && h[x - 1] == '\r' && h[x] == '\n') return UNCURL_OK; } free(h); *header = NULL; return r; } UNCURL_EXPORT int32_t uncurl_read_header(struct uncurl_conn *ucc) { int32_t e; //free any exiting response headers if (ucc->hin) http_free_header(ucc->hin); ucc->hin = NULL; //read the HTTP response header char *header = NULL; e = uncurl_read_header_(ucc, &header); if (e == UNCURL_OK) { //parse the header into the http_header struct ucc->hin = http_parse_header(header); free(header); } return e; } static int32_t uncurl_read_chunk_len(struct uncurl_conn *ucc, uint32_t *len) { int32_t r = UNCURL_ERR_MAX_CHUNK; char chunk_len[LEN_CHUNK]; memset(chunk_len, 0, LEN_CHUNK); for (uint32_t x = 0; x < LEN_CHUNK - 1; x++) { int32_t e; e = ucc->read(ucc->ctx, chunk_len + x, 1); if (e != UNCURL_OK) {r = e; break;} if (x > 0 && chunk_len[x - 1] == '\r' && chunk_len[x] == '\n') { chunk_len[x - 1] = '\0'; *len = strtoul(chunk_len, NULL, 16); return UNCURL_OK; } } *len = 0; return r; } static int32_t uncurl_response_body_chunked(struct uncurl_conn *ucc, char **body, uint32_t *body_len) { uint32_t offset = 0; uint32_t chunk_len = 0; do { int32_t e; //read the chunk size one byte at a time e = uncurl_read_chunk_len(ucc, &chunk_len); if (e != UNCURL_OK) return e; if (offset + chunk_len > ucc->opts.max_body) return UNCURL_ERR_MAX_BODY; //make room for chunk and "\r\n" after chunk *body = realloc(*body, offset + chunk_len + 2); //read chunk into buffer with extra 2 bytes for "\r\n" e = ucc->read(ucc->ctx, *body + offset, chunk_len + 2); if (e != UNCURL_OK) return e; offset += chunk_len; } while (chunk_len > 0); (*body)[offset] = '\0'; *body_len = offset; return UNCURL_OK; } UNCURL_EXPORT int32_t uncurl_read_body_all(struct uncurl_conn *ucc, char **body, uint32_t *body_len) { int32_t r = UNCURL_ERR_DEFAULT; int32_t e; *body = NULL; *body_len = 0; //look for chunked response if (uncurl_check_header(ucc, "Transfer-Encoding", "chunked")) { e = uncurl_response_body_chunked(ucc, body, body_len); if (e != UNCURL_OK) {r = e; goto uncurl_response_body_end;} r = UNCURL_OK; } //fall through to using Content-Length if (r != UNCURL_OK) { e = uncurl_get_header_int(ucc, "Content-Length", (int32_t *) body_len); if (e != UNCURL_OK) {r = e; goto uncurl_response_body_end;} if (*body_len == 0) {r = UNCURL_ERR_NO_BODY; goto uncurl_response_body_end;} if (*body_len > ucc->opts.max_body) {r = UNCURL_ERR_MAX_BODY; goto uncurl_response_body_end;} *body = calloc(*body_len + 1, 1); e = ucc->read(ucc->ctx, *body, *body_len); if (e != UNCURL_OK) {r = e; goto uncurl_response_body_end;} r = UNCURL_OK; } uncurl_response_body_end: if (r != UNCURL_OK) { free(*body); *body = NULL; } return r; } /*** WEBSOCKETS ***/ UNCURL_EXPORT int32_t uncurl_ws_connect(struct uncurl_conn *ucc, char *path, char *origin) { int32_t e; int32_t r = UNCURL_ERR_DEFAULT; //obligatory websocket headers char *sec_key = ws_create_key(&ucc->seed); uncurl_set_header_str(ucc, "Upgrade", "websocket"); uncurl_set_header_str(ucc, "Connection", "Upgrade"); uncurl_set_header_str(ucc, "Sec-WebSocket-Key", sec_key); uncurl_set_header_str(ucc, "Sec-WebSocket-Version", "13"); //optional origin header if (origin) uncurl_set_header_str(ucc, "Origin", origin); //write the header e = uncurl_write_header(ucc, "GET", path, UNCURL_REQUEST); if (e != UNCURL_OK) {r = e; goto uncurl_ws_connect_end;} //we expect a 101 response code from the server e = uncurl_read_header(ucc); if (e != UNCURL_OK) {r = e; goto uncurl_ws_connect_end;} //make sure we have a 101 from the server int32_t status_code = 0; e = uncurl_get_status_code(ucc, &status_code); if (e != UNCURL_OK) {r = e; goto uncurl_ws_connect_end;} if (status_code != 101) {r = UNCURL_WS_ERR_STATUS; goto uncurl_ws_connect_end;} //validate the security key response char *server_sec_key = NULL; e = uncurl_get_header_str(ucc, "Sec-WebSocket-Accept", &server_sec_key); if (e != UNCURL_OK) {r = e; goto uncurl_ws_connect_end;} if (!ws_validate_key(sec_key, server_sec_key)) {r = UNCURL_WS_ERR_KEY; goto uncurl_ws_connect_end;} //client must send masked messages ucc->ws_mask = 1; r = UNCURL_OK; uncurl_ws_connect_end: free(sec_key); return r; } UNCURL_EXPORT int32_t uncurl_ws_accept(struct uncurl_conn *ucc, char **origins, int32_t n_origins) { int32_t e; //wait for the client's request header e = uncurl_read_header(ucc); if (e != UNCURL_OK) return e; //set obligatory headers uncurl_set_header_str(ucc, "Upgrade", "websocket"); uncurl_set_header_str(ucc, "Connection", "Upgrade"); //check the origin header against our whitelist char *origin = NULL; e = uncurl_get_header_str(ucc, "Origin", &origin); if (e != UNCURL_OK) return e; //the substring MUST came at the end of the origin header, thus a strstr AND a strcmp bool origin_ok = false; for (int32_t x = 0; x < n_origins; x++) { char *match = strstr(origin, origins[x]); if (match && !strcmp(match, origins[x])) {origin_ok = true; break;} } if (!origin_ok) return UNCURL_WS_ERR_ORIGIN; //read the key and set a compliant response header char *sec_key = NULL; e = uncurl_get_header_str(ucc, "Sec-WebSocket-Key", &sec_key); if (e != UNCURL_OK) return e; char *accept_key = ws_create_accept_key(sec_key); uncurl_set_header_str(ucc, "Sec-WebSocket-Accept", accept_key); free(accept_key); //write the response header e = uncurl_write_header(ucc, "101", "Switching Protocols", UNCURL_RESPONSE); if (e != UNCURL_OK) return e; //server does not send masked messages ucc->ws_mask = 0; return UNCURL_OK; } UNCURL_EXPORT int32_t uncurl_ws_write(struct uncurl_conn *ucc, char *buf, uint32_t buf_len, uint8_t opcode) { struct ws_header h; memset(&h, 0, sizeof(struct ws_header)); h.fin = 1; h.mask = ucc->ws_mask; h.opcode = opcode; h.payload_len = buf_len; //resize the serialized buffer if (h.payload_len + WS_HEADER_SIZE > ucc->netbuf_size) { free(ucc->netbuf); ucc->netbuf_size = h.payload_len + WS_HEADER_SIZE; ucc->netbuf = malloc((size_t) ucc->netbuf_size); } //serialize the payload into a websocket conformant message uint64_t out_size = 0; ws_serialize(&h, &ucc->seed, buf, ucc->netbuf, &out_size); //write full network buffer return ucc->write(ucc->ctx, ucc->netbuf, (uint32_t) out_size); } UNCURL_EXPORT int32_t uncurl_ws_read(struct uncurl_conn *ucc, char *buf, uint32_t buf_len, uint8_t *opcode) { int32_t e; char header_buf[WS_HEADER_SIZE]; struct ws_header h; //first two bytes contain most control information e = ucc->read(ucc->ctx, header_buf, 2); if (e != UNCURL_OK) return e; ws_parse_header0(&h, header_buf); *opcode = h.opcode; //read the payload size and mask e = ucc->read(ucc->ctx, header_buf, h.addtl_bytes); if (e != UNCURL_OK) return e; ws_parse_header1(&h, header_buf); //check bounds if (h.payload_len > ucc->opts.max_body || h.payload_len > INT32_MAX) return UNCURL_ERR_MAX_BODY; if (h.payload_len > buf_len) return UNCURL_ERR_BUFFER; e = ucc->read(ucc->ctx, buf, (uint32_t) h.payload_len); if (e != UNCURL_OK) return e; //unmask the data if necessary if (h.mask) ws_mask(buf, buf, h.payload_len, h.masking_key); return (int32_t) h.payload_len; } UNCURL_EXPORT int32_t uncurl_ws_close(struct uncurl_conn *ucc, uint16_t status_code) { uint16_t status_code_be = htons(status_code); return uncurl_ws_write(ucc, (char *) &status_code_be, sizeof(uint16_t), UNCURL_WSOP_CLOSE); } /*** HELPERS ***/ UNCURL_EXPORT int32_t uncurl_get_status_code(struct uncurl_conn *ucc, int32_t *status_code) { *status_code = 0; return http_get_status_code(ucc->hin, status_code); } UNCURL_EXPORT int32_t uncurl_get_header(struct uncurl_conn *ucc, char *key, int32_t *val_int, char **val_str) { return http_get_header(ucc->hin, key, val_int, val_str); } UNCURL_EXPORT int32_t uncurl_parse_url(char *url, struct uncurl_info *uci) { memset(uci, 0, sizeof(struct uncurl_info)); return http_parse_url(url, &uci->scheme, &uci->host, &uci->port, &uci->path); } UNCURL_EXPORT int8_t uncurl_check_header(struct uncurl_conn *ucc, char *name, char *subval) { int32_t e; char *val = NULL; e = uncurl_get_header_str(ucc, name, &val); if (e == UNCURL_OK && strstr(http_lc(val), subval)) return 1; return 0; } UNCURL_EXPORT void uncurl_free_info(struct uncurl_info *uci) { free(uci->host); free(uci->path); }
./CrossVul/dataset_final_sorted/CWE-352/c/good_612_0
crossvul-cpp_data_bad_612_0
#include "uncurl/uncurl.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include "net.h" #include "tls.h" #include "http.h" #include "ws.h" #define LEN_IP4 16 #define LEN_CHUNK 64 #define LEN_ORIGIN 512 #if defined(__WINDOWS__) #include <winsock2.h> #define strdup(a) _strdup(a) #else #include <arpa/inet.h> #endif struct uncurl_opts { uint32_t max_header; uint32_t max_body; }; struct uncurl_tls_ctx { struct tls_state *tlss; }; struct uncurl_conn { struct uncurl_opts opts; struct net_opts nopts; struct tls_opts topts; char *hout; struct http_header *hin; struct net_context *net; struct tls_context *tls; void *ctx; int32_t (*read)(void *ctx, char *buf, uint32_t buf_size); int32_t (*write)(void *ctx, char *buf, uint32_t buf_size); char *host; uint16_t port; uint32_t seed; uint8_t ws_mask; char *netbuf; uint64_t netbuf_size; }; /*** TLS CONTEXT ***/ UNCURL_EXPORT void uncurl_free_tls_ctx(struct uncurl_tls_ctx *uc_tls) { if (!uc_tls) return; tlss_free(uc_tls->tlss); free(uc_tls); } UNCURL_EXPORT int32_t uncurl_new_tls_ctx(struct uncurl_tls_ctx **uc_tls_in) { int32_t e; struct uncurl_tls_ctx *uc_tls = *uc_tls_in = calloc(1, sizeof(struct uncurl_tls_ctx)); e = tlss_alloc(&uc_tls->tlss); if (e == UNCURL_OK) return e; uncurl_free_tls_ctx(uc_tls); *uc_tls_in = NULL; return e; } UNCURL_EXPORT int32_t uncurl_set_cacert(struct uncurl_tls_ctx *uc_tls, char *cacert, size_t size) { return tlss_load_cacert(uc_tls->tlss, cacert, size); } UNCURL_EXPORT int32_t uncurl_set_cacert_file(struct uncurl_tls_ctx *uc_tls, char *cacert_file) { return tlss_load_cacert_file(uc_tls->tlss, cacert_file); } UNCURL_EXPORT int32_t uncurl_set_cert_and_key_file(struct uncurl_tls_ctx *uc_tls, char *cert_file, char *key_file) { return tlss_load_cert_and_key_file(uc_tls->tlss, cert_file, key_file); } /*** CONNECTION ***/ static void uncurl_default_opts(struct uncurl_opts *opts) { opts->max_header = 1024; opts->max_body = 128 * 1024 * 1024; } UNCURL_EXPORT struct uncurl_conn *uncurl_new_conn(struct uncurl_conn *parent) { struct uncurl_conn *ucc = calloc(1, sizeof(struct uncurl_conn)); if (parent) { memcpy(&ucc->opts, &parent->opts, sizeof(struct uncurl_opts)); memcpy(&ucc->nopts, &parent->nopts, sizeof(struct net_opts)); memcpy(&ucc->topts, &parent->topts, sizeof(struct tls_opts)); } else { uncurl_default_opts(&ucc->opts); net_default_opts(&ucc->nopts); tls_default_opts(&ucc->topts); } ucc->seed = ws_rand(&ucc->seed); return ucc; } static void uncurl_attach_net(struct uncurl_conn *ucc) { ucc->ctx = ucc->net; ucc->read = net_read; ucc->write = net_write; } static void uncurl_attach_tls(struct uncurl_conn *ucc) { ucc->ctx = ucc->tls; ucc->read = tls_read; ucc->write = tls_write; } UNCURL_EXPORT int32_t uncurl_connect(struct uncurl_tls_ctx *uc_tls, struct uncurl_conn *ucc, int32_t scheme, char *host, uint16_t port) { int32_t e; //set state ucc->host = strdup(host); ucc->port = port; //resolve the hostname into an ip4 address char ip4[LEN_IP4]; e = net_getip4(ucc->host, ip4, LEN_IP4); if (e != UNCURL_OK) return e; //make the net connection e = net_connect(&ucc->net, ip4, ucc->port, &ucc->nopts); if (e != UNCURL_OK) return e; //default read/write callbacks uncurl_attach_net(ucc); if (scheme == UNCURL_HTTPS || scheme == UNCURL_WSS) { if (!uc_tls) return UNCURL_TLS_ERR_CONTEXT; e = tls_connect(&ucc->tls, uc_tls->tlss, ucc->net, ucc->host, &ucc->topts); if (e != UNCURL_OK) return e; //tls read/write callbacks uncurl_attach_tls(ucc); } return UNCURL_OK; } UNCURL_EXPORT int32_t uncurl_listen(struct uncurl_conn *ucc, char *bind_ip4, uint16_t port) { int32_t e; ucc->port = port; e = net_listen(&ucc->net, bind_ip4, ucc->port, &ucc->nopts); if (e != UNCURL_OK) return e; return UNCURL_OK; } UNCURL_EXPORT int32_t uncurl_accept(struct uncurl_tls_ctx *uc_tls, struct uncurl_conn *ucc, struct uncurl_conn **ucc_new_in, int32_t scheme) { int32_t r = UNCURL_ERR_DEFAULT; int32_t e; struct uncurl_conn *ucc_new = *ucc_new_in = uncurl_new_conn(ucc); struct net_context *new_net = NULL; e = net_accept(ucc->net, &new_net); if (e != UNCURL_OK) {r = e; goto uncurl_accept_end;} ucc_new->net = new_net; uncurl_attach_net(ucc_new); if (scheme == UNCURL_HTTPS || scheme == UNCURL_WSS) { if (!uc_tls) return UNCURL_TLS_ERR_CONTEXT; e = tls_accept(&ucc_new->tls, uc_tls->tlss, ucc_new->net, &ucc_new->topts); if (e != UNCURL_OK) {r = e; goto uncurl_accept_end;} //tls read/write callbacks uncurl_attach_tls(ucc_new); } return UNCURL_OK; uncurl_accept_end: free(ucc_new); *ucc_new_in = NULL; return r; } UNCURL_EXPORT int32_t uncurl_poll(struct uncurl_conn *ucc, int32_t timeout_ms) { return net_poll(ucc->net, NET_POLLIN, timeout_ms); } UNCURL_EXPORT void uncurl_get_socket(struct uncurl_conn *ucc, void *socket) { net_get_socket(ucc->net, socket); } UNCURL_EXPORT void uncurl_close(struct uncurl_conn *ucc) { if (!ucc) return; tls_close(ucc->tls); net_close(ucc->net); free(ucc->host); http_free_header(ucc->hin); free(ucc->hout); free(ucc->netbuf); free(ucc); } UNCURL_EXPORT void uncurl_set_option(struct uncurl_conn *ucc, int32_t opt, int32_t val) { switch (opt) { //uncurl options case UNCURL_OPT_MAX_HEADER: ucc->opts.max_header = (uint32_t) val; break; case UNCURL_OPT_MAX_BODY: ucc->opts.max_body = (uint32_t) val; break; //net options case UNCURL_NOPT_READ_TIMEOUT: ucc->nopts.read_timeout = val; break; case UNCURL_NOPT_CONNECT_TIMEOUT: ucc->nopts.connect_timeout = val; break; case UNCURL_NOPT_ACCEPT_TIMEOUT: ucc->nopts.accept_timeout = val; break; case UNCURL_NOPT_READ_BUF: ucc->nopts.read_buf = val; break; case UNCURL_NOPT_WRITE_BUF: ucc->nopts.write_buf = val; break; case UNCURL_NOPT_KEEPALIVE: ucc->nopts.keepalive = val; break; case UNCURL_NOPT_TCP_NODELAY: ucc->nopts.tcp_nodelay = val; break; case UNCURL_NOPT_REUSEADDR: ucc->nopts.reuseaddr = val; break; //tls options case UNCURL_TOPT_VERIFY_HOST: ucc->topts.verify_host = val; break; } } /*** REQUEST ***/ UNCURL_EXPORT void uncurl_set_header_str(struct uncurl_conn *ucc, char *name, char *value) { ucc->hout = http_set_header(ucc->hout, name, HTTP_STRING, value); } UNCURL_EXPORT void uncurl_set_header_int(struct uncurl_conn *ucc, char *name, int32_t value) { ucc->hout = http_set_header(ucc->hout, name, HTTP_INT, &value); } UNCURL_EXPORT void uncurl_free_header(struct uncurl_conn *ucc) { free(ucc->hout); ucc->hout = NULL; } UNCURL_EXPORT int32_t uncurl_write_header(struct uncurl_conn *ucc, char *str0, char *str1, int32_t type) { int32_t e; //generate the HTTP request/response header char *h = (type == UNCURL_REQUEST) ? http_request(str0, ucc->host, str1, ucc->hout) : http_response(str0, str1, ucc->hout); //write the header to the HTTP client/server e = ucc->write(ucc->ctx, h, (uint32_t) strlen(h)); free(h); return e; } UNCURL_EXPORT int32_t uncurl_write_body(struct uncurl_conn *ucc, char *body, uint32_t body_len) { int32_t e; e = ucc->write(ucc->ctx, body, body_len); return e; } /*** RESPONSE ***/ static int32_t uncurl_read_header_(struct uncurl_conn *ucc, char **header) { int32_t r = UNCURL_ERR_MAX_HEADER; uint32_t max_header = ucc->opts.max_header; char *h = *header = calloc(max_header, 1); uint32_t x = 0; for (; x < max_header - 1; x++) { int32_t e; e = ucc->read(ucc->ctx, h + x, 1); if (e != UNCURL_OK) {r = e; break;} if (x > 2 && h[x - 3] == '\r' && h[x - 2] == '\n' && h[x - 1] == '\r' && h[x] == '\n') return UNCURL_OK; } free(h); *header = NULL; return r; } UNCURL_EXPORT int32_t uncurl_read_header(struct uncurl_conn *ucc) { int32_t e; //free any exiting response headers if (ucc->hin) http_free_header(ucc->hin); ucc->hin = NULL; //read the HTTP response header char *header = NULL; e = uncurl_read_header_(ucc, &header); if (e == UNCURL_OK) { //parse the header into the http_header struct ucc->hin = http_parse_header(header); free(header); } return e; } static int32_t uncurl_read_chunk_len(struct uncurl_conn *ucc, uint32_t *len) { int32_t r = UNCURL_ERR_MAX_CHUNK; char chunk_len[LEN_CHUNK]; memset(chunk_len, 0, LEN_CHUNK); for (uint32_t x = 0; x < LEN_CHUNK - 1; x++) { int32_t e; e = ucc->read(ucc->ctx, chunk_len + x, 1); if (e != UNCURL_OK) {r = e; break;} if (x > 0 && chunk_len[x - 1] == '\r' && chunk_len[x] == '\n') { chunk_len[x - 1] = '\0'; *len = strtoul(chunk_len, NULL, 16); return UNCURL_OK; } } *len = 0; return r; } static int32_t uncurl_response_body_chunked(struct uncurl_conn *ucc, char **body, uint32_t *body_len) { uint32_t offset = 0; uint32_t chunk_len = 0; do { int32_t e; //read the chunk size one byte at a time e = uncurl_read_chunk_len(ucc, &chunk_len); if (e != UNCURL_OK) return e; if (offset + chunk_len > ucc->opts.max_body) return UNCURL_ERR_MAX_BODY; //make room for chunk and "\r\n" after chunk *body = realloc(*body, offset + chunk_len + 2); //read chunk into buffer with extra 2 bytes for "\r\n" e = ucc->read(ucc->ctx, *body + offset, chunk_len + 2); if (e != UNCURL_OK) return e; offset += chunk_len; } while (chunk_len > 0); (*body)[offset] = '\0'; *body_len = offset; return UNCURL_OK; } UNCURL_EXPORT int32_t uncurl_read_body_all(struct uncurl_conn *ucc, char **body, uint32_t *body_len) { int32_t r = UNCURL_ERR_DEFAULT; int32_t e; *body = NULL; *body_len = 0; //look for chunked response if (uncurl_check_header(ucc, "Transfer-Encoding", "chunked")) { e = uncurl_response_body_chunked(ucc, body, body_len); if (e != UNCURL_OK) {r = e; goto uncurl_response_body_end;} r = UNCURL_OK; } //fall through to using Content-Length if (r != UNCURL_OK) { e = uncurl_get_header_int(ucc, "Content-Length", (int32_t *) body_len); if (e != UNCURL_OK) {r = e; goto uncurl_response_body_end;} if (*body_len == 0) {r = UNCURL_ERR_NO_BODY; goto uncurl_response_body_end;} if (*body_len > ucc->opts.max_body) {r = UNCURL_ERR_MAX_BODY; goto uncurl_response_body_end;} *body = calloc(*body_len + 1, 1); e = ucc->read(ucc->ctx, *body, *body_len); if (e != UNCURL_OK) {r = e; goto uncurl_response_body_end;} r = UNCURL_OK; } uncurl_response_body_end: if (r != UNCURL_OK) { free(*body); *body = NULL; } return r; } /*** WEBSOCKETS ***/ UNCURL_EXPORT int32_t uncurl_ws_connect(struct uncurl_conn *ucc, char *path, char *origin) { int32_t e; int32_t r = UNCURL_ERR_DEFAULT; //obligatory websocket headers char *sec_key = ws_create_key(&ucc->seed); uncurl_set_header_str(ucc, "Upgrade", "websocket"); uncurl_set_header_str(ucc, "Connection", "Upgrade"); uncurl_set_header_str(ucc, "Sec-WebSocket-Key", sec_key); uncurl_set_header_str(ucc, "Sec-WebSocket-Version", "13"); //optional origin header if (origin) uncurl_set_header_str(ucc, "Origin", origin); //write the header e = uncurl_write_header(ucc, "GET", path, UNCURL_REQUEST); if (e != UNCURL_OK) {r = e; goto uncurl_ws_connect_end;} //we expect a 101 response code from the server e = uncurl_read_header(ucc); if (e != UNCURL_OK) {r = e; goto uncurl_ws_connect_end;} //make sure we have a 101 from the server int32_t status_code = 0; e = uncurl_get_status_code(ucc, &status_code); if (e != UNCURL_OK) {r = e; goto uncurl_ws_connect_end;} if (status_code != 101) {r = UNCURL_WS_ERR_STATUS; goto uncurl_ws_connect_end;} //validate the security key response char *server_sec_key = NULL; e = uncurl_get_header_str(ucc, "Sec-WebSocket-Accept", &server_sec_key); if (e != UNCURL_OK) {r = e; goto uncurl_ws_connect_end;} if (!ws_validate_key(sec_key, server_sec_key)) {r = UNCURL_WS_ERR_KEY; goto uncurl_ws_connect_end;} //client must send masked messages ucc->ws_mask = 1; r = UNCURL_OK; uncurl_ws_connect_end: free(sec_key); return r; } UNCURL_EXPORT int32_t uncurl_ws_accept(struct uncurl_conn *ucc, char **origins, int32_t n_origins) { int32_t e; //wait for the client's request header e = uncurl_read_header(ucc); if (e != UNCURL_OK) return e; //set obligatory headers uncurl_set_header_str(ucc, "Upgrade", "websocket"); uncurl_set_header_str(ucc, "Connection", "Upgrade"); //check the origin header against our whitelist char *origin = NULL; e = uncurl_get_header_str(ucc, "Origin", &origin); if (e != UNCURL_OK) return e; bool origin_ok = false; for (int32_t x = 0; x < n_origins; x++) if (strstr(origin, origins[x])) {origin_ok = true; break;} if (!origin_ok) return UNCURL_WS_ERR_ORIGIN; //read the key and set a compliant response header char *sec_key = NULL; e = uncurl_get_header_str(ucc, "Sec-WebSocket-Key", &sec_key); if (e != UNCURL_OK) return e; char *accept_key = ws_create_accept_key(sec_key); uncurl_set_header_str(ucc, "Sec-WebSocket-Accept", accept_key); free(accept_key); //write the response header e = uncurl_write_header(ucc, "101", "Switching Protocols", UNCURL_RESPONSE); if (e != UNCURL_OK) return e; //server does not send masked messages ucc->ws_mask = 0; return UNCURL_OK; } UNCURL_EXPORT int32_t uncurl_ws_write(struct uncurl_conn *ucc, char *buf, uint32_t buf_len, uint8_t opcode) { struct ws_header h; memset(&h, 0, sizeof(struct ws_header)); h.fin = 1; h.mask = ucc->ws_mask; h.opcode = opcode; h.payload_len = buf_len; //resize the serialized buffer if (h.payload_len + WS_HEADER_SIZE > ucc->netbuf_size) { free(ucc->netbuf); ucc->netbuf_size = h.payload_len + WS_HEADER_SIZE; ucc->netbuf = malloc((size_t) ucc->netbuf_size); } //serialize the payload into a websocket conformant message uint64_t out_size = 0; ws_serialize(&h, &ucc->seed, buf, ucc->netbuf, &out_size); //write full network buffer return ucc->write(ucc->ctx, ucc->netbuf, (uint32_t) out_size); } UNCURL_EXPORT int32_t uncurl_ws_read(struct uncurl_conn *ucc, char *buf, uint32_t buf_len, uint8_t *opcode) { int32_t e; char header_buf[WS_HEADER_SIZE]; struct ws_header h; //first two bytes contain most control information e = ucc->read(ucc->ctx, header_buf, 2); if (e != UNCURL_OK) return e; ws_parse_header0(&h, header_buf); *opcode = h.opcode; //read the payload size and mask e = ucc->read(ucc->ctx, header_buf, h.addtl_bytes); if (e != UNCURL_OK) return e; ws_parse_header1(&h, header_buf); //check bounds if (h.payload_len > ucc->opts.max_body || h.payload_len > INT32_MAX) return UNCURL_ERR_MAX_BODY; if (h.payload_len > buf_len) return UNCURL_ERR_BUFFER; e = ucc->read(ucc->ctx, buf, (uint32_t) h.payload_len); if (e != UNCURL_OK) return e; //unmask the data if necessary if (h.mask) ws_mask(buf, buf, h.payload_len, h.masking_key); return (int32_t) h.payload_len; } UNCURL_EXPORT int32_t uncurl_ws_close(struct uncurl_conn *ucc, uint16_t status_code) { uint16_t status_code_be = htons(status_code); return uncurl_ws_write(ucc, (char *) &status_code_be, sizeof(uint16_t), UNCURL_WSOP_CLOSE); } /*** HELPERS ***/ UNCURL_EXPORT int32_t uncurl_get_status_code(struct uncurl_conn *ucc, int32_t *status_code) { *status_code = 0; return http_get_status_code(ucc->hin, status_code); } UNCURL_EXPORT int32_t uncurl_get_header(struct uncurl_conn *ucc, char *key, int32_t *val_int, char **val_str) { return http_get_header(ucc->hin, key, val_int, val_str); } UNCURL_EXPORT int32_t uncurl_parse_url(char *url, struct uncurl_info *uci) { memset(uci, 0, sizeof(struct uncurl_info)); return http_parse_url(url, &uci->scheme, &uci->host, &uci->port, &uci->path); } UNCURL_EXPORT int8_t uncurl_check_header(struct uncurl_conn *ucc, char *name, char *subval) { int32_t e; char *val = NULL; e = uncurl_get_header_str(ucc, name, &val); if (e == UNCURL_OK && strstr(http_lc(val), subval)) return 1; return 0; } UNCURL_EXPORT void uncurl_free_info(struct uncurl_info *uci) { free(uci->host); free(uci->path); }
./CrossVul/dataset_final_sorted/CWE-352/c/bad_612_0
crossvul-cpp_data_bad_3200_1
/* * Bittorrent Client using Qt and libtorrent. * Copyright (C) 2015 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org> * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * In addition, as a special exception, the copyright holders give permission to * link this program with the OpenSSL project's "OpenSSL" library (or with * modified versions of it that use the same license as the "OpenSSL" library), * and distribute the linked executables. 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), 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. */ #include "string.h" #include <cmath> #include <QByteArray> #include <QtGlobal> #include <QLocale> #ifdef QBT_USES_QT5 #include <QCollator> #endif #ifdef Q_OS_MAC #include <QThreadStorage> #endif namespace { class NaturalCompare { public: explicit NaturalCompare(const bool caseSensitive = true) : m_caseSensitive(caseSensitive) { #ifdef QBT_USES_QT5 #if defined(Q_OS_WIN) // Without ICU library, QCollator uses the native API on Windows 7+. But that API // sorts older versions of μTorrent differently than the newer ones because the // 'μ' character is encoded differently and the native API can't cope with that. // So default to using our custom natural sorting algorithm instead. // See #5238 and #5240 // Without ICU library, QCollator doesn't support `setNumericMode(true)` on OS older than Win7 // if (QSysInfo::windowsVersion() < QSysInfo::WV_WINDOWS7) return; #endif m_collator.setNumericMode(true); m_collator.setCaseSensitivity(caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive); #endif } bool operator()(const QString &left, const QString &right) const { #ifdef QBT_USES_QT5 #if defined(Q_OS_WIN) // Without ICU library, QCollator uses the native API on Windows 7+. But that API // sorts older versions of μTorrent differently than the newer ones because the // 'μ' character is encoded differently and the native API can't cope with that. // So default to using our custom natural sorting algorithm instead. // See #5238 and #5240 // Without ICU library, QCollator doesn't support `setNumericMode(true)` on OS older than Win7 // if (QSysInfo::windowsVersion() < QSysInfo::WV_WINDOWS7) return lessThan(left, right); #endif return (m_collator.compare(left, right) < 0); #else return lessThan(left, right); #endif } bool lessThan(const QString &left, const QString &right) const { // Return value `false` indicates `right` should go before `left`, otherwise, after int posL = 0; int posR = 0; while (true) { while (true) { if ((posL == left.size()) || (posR == right.size())) return (left.size() < right.size()); // when a shorter string is another string's prefix, shorter string place before longer string QChar leftChar = m_caseSensitive ? left[posL] : left[posL].toLower(); QChar rightChar = m_caseSensitive ? right[posR] : right[posR].toLower(); if (leftChar == rightChar) ; // compare next character else if (leftChar.isDigit() && rightChar.isDigit()) break; // Both are digits, break this loop and compare numbers else return leftChar < rightChar; ++posL; ++posR; } int startL = posL; while ((posL < left.size()) && left[posL].isDigit()) ++posL; #ifdef QBT_USES_QT5 int numL = left.midRef(startL, posL - startL).toInt(); #else int numL = left.mid(startL, posL - startL).toInt(); #endif int startR = posR; while ((posR < right.size()) && right[posR].isDigit()) ++posR; #ifdef QBT_USES_QT5 int numR = right.midRef(startR, posR - startR).toInt(); #else int numR = right.mid(startR, posR - startR).toInt(); #endif if (numL != numR) return (numL < numR); // Strings + digits do match and we haven't hit string end // Do another round } return false; } private: #ifdef QBT_USES_QT5 QCollator m_collator; #endif const bool m_caseSensitive; }; } bool Utils::String::naturalCompareCaseSensitive(const QString &left, const QString &right) { // provide a single `NaturalCompare` instance for easy use // https://doc.qt.io/qt-5/threads-reentrancy.html #ifdef Q_OS_MAC // workaround for Apple xcode: https://stackoverflow.com/a/29929949 static QThreadStorage<NaturalCompare> nCmp; if (!nCmp.hasLocalData()) nCmp.setLocalData(NaturalCompare(true)); return (nCmp.localData())(left, right); #else thread_local NaturalCompare nCmp(true); return nCmp(left, right); #endif } bool Utils::String::naturalCompareCaseInsensitive(const QString &left, const QString &right) { // provide a single `NaturalCompare` instance for easy use // https://doc.qt.io/qt-5/threads-reentrancy.html #ifdef Q_OS_MAC // workaround for Apple xcode: https://stackoverflow.com/a/29929949 static QThreadStorage<NaturalCompare> nCmp; if (!nCmp.hasLocalData()) nCmp.setLocalData(NaturalCompare(false)); return (nCmp.localData())(left, right); #else thread_local NaturalCompare nCmp(false); return nCmp(left, right); #endif } QString Utils::String::fromStdString(const std::string &str) { return QString::fromUtf8(str.c_str()); } std::string Utils::String::toStdString(const QString &str) { #ifdef QBT_USES_QT5 return str.toStdString(); #else QByteArray utf8 = str.toUtf8(); return std::string(utf8.constData(), utf8.length()); #endif } // to send numbers instead of strings with suffixes QString Utils::String::fromDouble(double n, int precision) { /* HACK because QString rounds up. Eg QString::number(0.999*100.0, 'f' ,1) == 99.9 ** but QString::number(0.9999*100.0, 'f' ,1) == 100.0 The problem manifests when ** the number has more digits after the decimal than we want AND the digit after ** our 'wanted' is >= 5. In this case our last digit gets rounded up. So for each ** precision we add an extra 0 behind 1 in the below algorithm. */ double prec = std::pow(10.0, precision); return QLocale::system().toString(std::floor(n * prec) / prec, 'f', precision); } // Implements constant-time comparison to protect against timing attacks // Taken from https://crackstation.net/hashing-security.htm bool Utils::String::slowEquals(const QByteArray &a, const QByteArray &b) { int lengthA = a.length(); int lengthB = b.length(); int diff = lengthA ^ lengthB; for (int i = 0; (i < lengthA) && (i < lengthB); i++) diff |= a[i] ^ b[i]; return (diff == 0); }
./CrossVul/dataset_final_sorted/CWE-79/cpp/bad_3200_1
crossvul-cpp_data_good_3200_5
/* * Bittorrent Client using Qt4 and libtorrent. * Copyright (C) 2006 Christophe Dumez * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * In addition, as a special exception, the copyright holders give permission to * link this program with the OpenSSL project's "OpenSSL" library (or with * modified versions of it that use the same license as the "OpenSSL" library), * and distribute the linked executables. 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), 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. * * Contact : chris@qbittorrent.org */ #include "propertieswidget.h" #include <QDebug> #include <QTimer> #include <QListWidgetItem> #include <QVBoxLayout> #include <QStackedWidget> #include <QSplitter> #include <QHeaderView> #include <QAction> #include <QMenu> #include <QFileDialog> #include <QBitArray> #include "base/bittorrent/session.h" #include "base/preferences.h" #include "base/utils/fs.h" #include "base/utils/misc.h" #include "base/utils/string.h" #include "base/unicodestrings.h" #include "proplistdelegate.h" #include "torrentcontentfiltermodel.h" #include "torrentcontentmodel.h" #include "peerlistwidget.h" #include "speedwidget.h" #include "trackerlist.h" #include "mainwindow.h" #include "messageboxraised.h" #include "downloadedpiecesbar.h" #include "pieceavailabilitybar.h" #include "proptabbar.h" #include "guiiconprovider.h" #include "lineedit.h" #include "transferlistwidget.h" #include "autoexpandabledialog.h" PropertiesWidget::PropertiesWidget(QWidget *parent, MainWindow *main_window, TransferListWidget *transferList) : QWidget(parent), transferList(transferList), main_window(main_window), m_torrent(0) { setupUi(this); setAutoFillBackground(true); state = VISIBLE; // Set Properties list model PropListModel = new TorrentContentFilterModel(); filesList->setModel(PropListModel); PropDelegate = new PropListDelegate(this); filesList->setItemDelegate(PropDelegate); filesList->setSortingEnabled(true); // Torrent content filtering m_contentFilterLine = new LineEdit(this); m_contentFilterLine->setPlaceholderText(tr("Filter files...")); m_contentFilterLine->setMaximumSize(300, m_contentFilterLine->size().height()); connect(m_contentFilterLine, SIGNAL(textChanged(QString)), this, SLOT(filterText(QString))); contentFilterLayout->insertWidget(3, m_contentFilterLine); // SIGNAL/SLOTS connect(filesList, SIGNAL(clicked(const QModelIndex&)), filesList, SLOT(edit(const QModelIndex&))); connect(selectAllButton, SIGNAL(clicked()), PropListModel, SLOT(selectAll())); connect(selectNoneButton, SIGNAL(clicked()), PropListModel, SLOT(selectNone())); connect(filesList, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(displayFilesListMenu(const QPoint&))); connect(filesList, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(openDoubleClickedFile(const QModelIndex&))); connect(PropListModel, SIGNAL(filteredFilesChanged()), this, SLOT(filteredFilesChanged())); connect(listWebSeeds, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(displayWebSeedListMenu(const QPoint&))); connect(transferList, SIGNAL(currentTorrentChanged(BitTorrent::TorrentHandle * const)), this, SLOT(loadTorrentInfos(BitTorrent::TorrentHandle * const))); connect(PropDelegate, SIGNAL(filteredFilesChanged()), this, SLOT(filteredFilesChanged())); connect(stackedProperties, SIGNAL(currentChanged(int)), this, SLOT(loadDynamicData())); connect(BitTorrent::Session::instance(), SIGNAL(torrentSavePathChanged(BitTorrent::TorrentHandle * const)), this, SLOT(updateSavePath(BitTorrent::TorrentHandle * const))); connect(BitTorrent::Session::instance(), SIGNAL(torrentMetadataLoaded(BitTorrent::TorrentHandle * const)), this, SLOT(updateTorrentInfos(BitTorrent::TorrentHandle * const))); connect(filesList->header(), SIGNAL(sectionMoved(int,int,int)), this, SLOT(saveSettings())); connect(filesList->header(), SIGNAL(sectionResized(int,int,int)), this, SLOT(saveSettings())); connect(filesList->header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), this, SLOT(saveSettings())); #ifdef QBT_USES_QT5 // set bar height relative to screen dpi int barHeight = devicePixelRatio() * 18; #else // set bar height relative to font height QFont defFont; QFontMetrics fMetrics(defFont, 0); // need to be device-dependent int barHeight = fMetrics.height() * 5 / 4; #endif // Downloaded pieces progress bar tempProgressBarArea->setVisible(false); downloaded_pieces = new DownloadedPiecesBar(this); groupBarLayout->addWidget(downloaded_pieces, 0, 1); downloaded_pieces->setFixedHeight(barHeight); downloaded_pieces->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); // Pieces availability bar tempAvailabilityBarArea->setVisible(false); pieces_availability = new PieceAvailabilityBar(this); groupBarLayout->addWidget(pieces_availability, 1, 1); pieces_availability->setFixedHeight(barHeight); pieces_availability->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); // Tracker list trackerList = new TrackerList(this); trackerUpButton->setIcon(GuiIconProvider::instance()->getIcon("go-up")); trackerUpButton->setIconSize(Utils::Misc::smallIconSize()); trackerDownButton->setIcon(GuiIconProvider::instance()->getIcon("go-down")); trackerDownButton->setIconSize(Utils::Misc::smallIconSize()); connect(trackerUpButton, SIGNAL(clicked()), trackerList, SLOT(moveSelectionUp())); connect(trackerDownButton, SIGNAL(clicked()), trackerList, SLOT(moveSelectionDown())); horizontalLayout_trackers->insertWidget(0, trackerList); connect(trackerList->header(), SIGNAL(sectionMoved(int,int,int)), trackerList, SLOT(saveSettings())); connect(trackerList->header(), SIGNAL(sectionResized(int,int,int)), trackerList, SLOT(saveSettings())); connect(trackerList->header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), trackerList, SLOT(saveSettings())); // Peers list peersList = new PeerListWidget(this); peerpage_layout->addWidget(peersList); connect(peersList->header(), SIGNAL(sectionMoved(int,int,int)), peersList, SLOT(saveSettings())); connect(peersList->header(), SIGNAL(sectionResized(int,int,int)), peersList, SLOT(saveSettings())); connect(peersList->header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), peersList, SLOT(saveSettings())); // Speed widget speedWidget = new SpeedWidget(this); speed_layout->addWidget(speedWidget); // Tab bar m_tabBar = new PropTabBar(); m_tabBar->setContentsMargins(0, 5, 0, 0); verticalLayout->addLayout(m_tabBar); connect(m_tabBar, SIGNAL(tabChanged(int)), stackedProperties, SLOT(setCurrentIndex(int))); connect(m_tabBar, SIGNAL(tabChanged(int)), this, SLOT(saveSettings())); connect(m_tabBar, SIGNAL(visibilityToggled(bool)), SLOT(setVisibility(bool))); connect(m_tabBar, SIGNAL(visibilityToggled(bool)), this, SLOT(saveSettings())); // Dynamic data refresher refreshTimer = new QTimer(this); connect(refreshTimer, SIGNAL(timeout()), this, SLOT(loadDynamicData())); refreshTimer->start(3000); // 3sec editHotkeyFile = new QShortcut(Qt::Key_F2, filesList, 0, 0, Qt::WidgetShortcut); connect(editHotkeyFile, SIGNAL(activated()), SLOT(renameSelectedFile())); editHotkeyWeb = new QShortcut(Qt::Key_F2, listWebSeeds, 0, 0, Qt::WidgetShortcut); connect(editHotkeyWeb, SIGNAL(activated()), SLOT(editWebSeed())); connect(listWebSeeds, SIGNAL(doubleClicked(QModelIndex)), SLOT(editWebSeed())); deleteHotkeyWeb = new QShortcut(QKeySequence::Delete, listWebSeeds, 0, 0, Qt::WidgetShortcut); connect(deleteHotkeyWeb, SIGNAL(activated()), SLOT(deleteSelectedUrlSeeds())); openHotkeyFile = new QShortcut(Qt::Key_Return, filesList, 0, 0, Qt::WidgetShortcut); connect(openHotkeyFile, SIGNAL(activated()), SLOT(openSelectedFile())); } PropertiesWidget::~PropertiesWidget() { qDebug() << Q_FUNC_INFO << "ENTER"; delete refreshTimer; delete trackerList; delete peersList; delete speedWidget; delete downloaded_pieces; delete pieces_availability; delete PropListModel; delete PropDelegate; delete m_tabBar; delete editHotkeyFile; delete editHotkeyWeb; delete deleteHotkeyWeb; delete openHotkeyFile; qDebug() << Q_FUNC_INFO << "EXIT"; } void PropertiesWidget::showPiecesAvailability(bool show) { avail_pieces_lbl->setVisible(show); pieces_availability->setVisible(show); avail_average_lbl->setVisible(show); if (show || !downloaded_pieces->isVisible()) line_2->setVisible(show); } void PropertiesWidget::showPiecesDownloaded(bool show) { downloaded_pieces_lbl->setVisible(show); downloaded_pieces->setVisible(show); progress_lbl->setVisible(show); if (show || !pieces_availability->isVisible()) line_2->setVisible(show); } void PropertiesWidget::setVisibility(bool visible) { if (!visible && ( state == VISIBLE) ) { QSplitter *hSplitter = static_cast<QSplitter *>(parentWidget()); stackedProperties->setVisible(false); slideSizes = hSplitter->sizes(); hSplitter->handle(1)->setVisible(false); hSplitter->handle(1)->setDisabled(true); QList<int> sizes = QList<int>() << hSplitter->geometry().height() - 30 << 30; hSplitter->setSizes(sizes); state = REDUCED; return; } if (visible && ( state == REDUCED) ) { stackedProperties->setVisible(true); QSplitter *hSplitter = static_cast<QSplitter *>(parentWidget()); hSplitter->handle(1)->setDisabled(false); hSplitter->handle(1)->setVisible(true); hSplitter->setSizes(slideSizes); state = VISIBLE; // Force refresh loadDynamicData(); } } void PropertiesWidget::clear() { qDebug("Clearing torrent properties"); save_path->clear(); lbl_creationDate->clear(); label_total_pieces_val->clear(); hash_lbl->clear(); comment_text->clear(); progress_lbl->clear(); trackerList->clear(); downloaded_pieces->clear(); pieces_availability->clear(); avail_average_lbl->clear(); wasted->clear(); upTotal->clear(); dlTotal->clear(); peersList->clear(); lbl_uplimit->clear(); lbl_dllimit->clear(); lbl_elapsed->clear(); lbl_connections->clear(); reannounce_lbl->clear(); shareRatio->clear(); listWebSeeds->clear(); m_contentFilterLine->clear(); PropListModel->model()->clear(); label_eta_val->clear(); label_seeds_val->clear(); label_peers_val->clear(); label_dl_speed_val->clear(); label_upload_speed_val->clear(); label_total_size_val->clear(); label_completed_on_val->clear(); label_last_complete_val->clear(); label_created_by_val->clear(); label_added_on_val->clear(); } BitTorrent::TorrentHandle *PropertiesWidget::getCurrentTorrent() const { return m_torrent; } void PropertiesWidget::updateSavePath(BitTorrent::TorrentHandle *const torrent) { if (m_torrent == torrent) save_path->setText(Utils::Fs::toNativePath(m_torrent->savePath())); } void PropertiesWidget::loadTrackers(BitTorrent::TorrentHandle *const torrent) { if (torrent == m_torrent) trackerList->loadTrackers(); } void PropertiesWidget::updateTorrentInfos(BitTorrent::TorrentHandle *const torrent) { if (m_torrent == torrent) loadTorrentInfos(m_torrent); } void PropertiesWidget::loadTorrentInfos(BitTorrent::TorrentHandle *const torrent) { clear(); m_torrent = torrent; downloaded_pieces->setTorrent(m_torrent); pieces_availability->setTorrent(m_torrent); if (!m_torrent) return; // Save path updateSavePath(m_torrent); // Hash hash_lbl->setText(m_torrent->hash()); PropListModel->model()->clear(); if (m_torrent->hasMetadata()) { // Creation date lbl_creationDate->setText(m_torrent->creationDate().toString(Qt::DefaultLocaleShortDate)); label_total_size_val->setText(Utils::Misc::friendlyUnit(m_torrent->totalSize())); // Comment comment_text->setText(Utils::Misc::parseHtmlLinks(Utils::String::toHtmlEscaped(m_torrent->comment()))); // URL seeds loadUrlSeeds(); label_created_by_val->setText(Utils::String::toHtmlEscaped(m_torrent->creator())); // List files in torrent PropListModel->model()->setupModelData(m_torrent->info()); filesList->setExpanded(PropListModel->index(0, 0), true); // Load file priorities PropListModel->model()->updateFilesPriorities(m_torrent->filePriorities()); } // Load dynamic data loadDynamicData(); } void PropertiesWidget::readSettings() { const Preferences *const pref = Preferences::instance(); // Restore splitter sizes QStringList sizes_str = pref->getPropSplitterSizes().split(","); if (sizes_str.size() == 2) { slideSizes << sizes_str.first().toInt(); slideSizes << sizes_str.last().toInt(); QSplitter *hSplitter = static_cast<QSplitter *>(parentWidget()); hSplitter->setSizes(slideSizes); } const int current_tab = pref->getPropCurTab(); const bool visible = pref->getPropVisible(); // the following will call saveSettings but shouldn't change any state if (!filesList->header()->restoreState(pref->getPropFileListState())) filesList->header()->resizeSection(0, 400); // Default m_tabBar->setCurrentIndex(current_tab); if (!visible) setVisibility(false); } void PropertiesWidget::saveSettings() { Preferences *const pref = Preferences::instance(); pref->setPropVisible(state==VISIBLE); // Splitter sizes QSplitter *hSplitter = static_cast<QSplitter *>(parentWidget()); QList<int> sizes; if (state == VISIBLE) sizes = hSplitter->sizes(); else sizes = slideSizes; qDebug("Sizes: %d", sizes.size()); if (sizes.size() == 2) pref->setPropSplitterSizes(QString::number(sizes.first()) + ',' + QString::number(sizes.last())); pref->setPropFileListState(filesList->header()->saveState()); // Remember current tab pref->setPropCurTab(m_tabBar->currentIndex()); } void PropertiesWidget::reloadPreferences() { // Take program preferences into consideration peersList->updatePeerHostNameResolutionState(); peersList->updatePeerCountryResolutionState(); } void PropertiesWidget::loadDynamicData() { // Refresh only if the torrent handle is valid and if visible if (!m_torrent || (main_window->currentTabWidget() != transferList) || (state != VISIBLE)) return; // Transfer infos switch (stackedProperties->currentIndex()) { case PropTabBar::MAIN_TAB: { wasted->setText(Utils::Misc::friendlyUnit(m_torrent->wastedSize())); upTotal->setText(tr("%1 (%2 this session)").arg(Utils::Misc::friendlyUnit(m_torrent->totalUpload())) .arg(Utils::Misc::friendlyUnit(m_torrent->totalPayloadUpload()))); dlTotal->setText(tr("%1 (%2 this session)").arg(Utils::Misc::friendlyUnit(m_torrent->totalDownload())) .arg(Utils::Misc::friendlyUnit(m_torrent->totalPayloadDownload()))); lbl_uplimit->setText(m_torrent->uploadLimit() <= 0 ? QString::fromUtf8(C_INFINITY) : Utils::Misc::friendlyUnit(m_torrent->uploadLimit(), true)); lbl_dllimit->setText(m_torrent->downloadLimit() <= 0 ? QString::fromUtf8(C_INFINITY) : Utils::Misc::friendlyUnit(m_torrent->downloadLimit(), true)); QString elapsed_txt; if (m_torrent->isSeed()) elapsed_txt = tr("%1 (seeded for %2)", "e.g. 4m39s (seeded for 3m10s)") .arg(Utils::Misc::userFriendlyDuration(m_torrent->activeTime())) .arg(Utils::Misc::userFriendlyDuration(m_torrent->seedingTime())); else elapsed_txt = Utils::Misc::userFriendlyDuration(m_torrent->activeTime()); lbl_elapsed->setText(elapsed_txt); lbl_connections->setText(tr("%1 (%2 max)", "%1 and %2 are numbers, e.g. 3 (10 max)") .arg(m_torrent->connectionsCount()) .arg(m_torrent->connectionsLimit() < 0 ? QString::fromUtf8(C_INFINITY) : QString::number(m_torrent->connectionsLimit()))); label_eta_val->setText(Utils::Misc::userFriendlyDuration(m_torrent->eta())); // Update next announce time reannounce_lbl->setText(Utils::Misc::userFriendlyDuration(m_torrent->nextAnnounce())); // Update ratio info const qreal ratio = m_torrent->realRatio(); shareRatio->setText(ratio > BitTorrent::TorrentHandle::MAX_RATIO ? QString::fromUtf8(C_INFINITY) : Utils::String::fromDouble(ratio, 2)); label_seeds_val->setText(tr("%1 (%2 total)", "%1 and %2 are numbers, e.g. 3 (10 total)") .arg(QString::number(m_torrent->seedsCount())) .arg(QString::number(m_torrent->totalSeedsCount()))); label_peers_val->setText(tr("%1 (%2 total)", "%1 and %2 are numbers, e.g. 3 (10 total)") .arg(QString::number(m_torrent->leechsCount())) .arg(QString::number(m_torrent->totalLeechersCount()))); label_dl_speed_val->setText(tr("%1 (%2 avg.)", "%1 and %2 are speed rates, e.g. 200KiB/s (100KiB/s avg.)") .arg(Utils::Misc::friendlyUnit(m_torrent->downloadPayloadRate(), true)) .arg(Utils::Misc::friendlyUnit(m_torrent->totalDownload() / (1 + m_torrent->activeTime() - m_torrent->finishedTime()), true))); label_upload_speed_val->setText(tr("%1 (%2 avg.)", "%1 and %2 are speed rates, e.g. 200KiB/s (100KiB/s avg.)") .arg(Utils::Misc::friendlyUnit(m_torrent->uploadPayloadRate(), true)) .arg(Utils::Misc::friendlyUnit(m_torrent->totalUpload() / (1 + m_torrent->activeTime()), true))); label_last_complete_val->setText(m_torrent->lastSeenComplete().isValid() ? m_torrent->lastSeenComplete().toString(Qt::DefaultLocaleShortDate) : tr("Never")); label_completed_on_val->setText(m_torrent->completedTime().isValid() ? m_torrent->completedTime().toString(Qt::DefaultLocaleShortDate) : ""); label_added_on_val->setText(m_torrent->addedTime().toString(Qt::DefaultLocaleShortDate)); if (m_torrent->hasMetadata()) { label_total_pieces_val->setText(tr("%1 x %2 (have %3)", "(torrent pieces) eg 152 x 4MB (have 25)").arg(m_torrent->piecesCount()).arg(Utils::Misc::friendlyUnit(m_torrent->pieceLength())).arg(m_torrent->piecesHave())); if (!m_torrent->isSeed() && !m_torrent->isPaused() && !m_torrent->isQueued() && !m_torrent->isChecking()) { // Pieces availability showPiecesAvailability(true); pieces_availability->setAvailability(m_torrent->pieceAvailability()); avail_average_lbl->setText(Utils::String::fromDouble(m_torrent->distributedCopies(), 3)); } else { showPiecesAvailability(false); } // Progress qreal progress = m_torrent->progress() * 100.; progress_lbl->setText(Utils::String::fromDouble(progress, 1) + "%"); downloaded_pieces->setProgress(m_torrent->pieces(), m_torrent->downloadingPieces()); } else { showPiecesAvailability(false); } break; } case PropTabBar::TRACKERS_TAB: { // Trackers trackerList->loadTrackers(); break; } case PropTabBar::PEERS_TAB: { // Load peers peersList->loadPeers(m_torrent); break; } case PropTabBar::FILES_TAB: { // Files progress if (m_torrent->hasMetadata()) { qDebug("Updating priorities in files tab"); filesList->setUpdatesEnabled(false); PropListModel->model()->updateFilesProgress(m_torrent->filesProgress()); // XXX: We don't update file priorities regularly for performance // reasons. This means that priorities will not be updated if // set from the Web UI. // PropListModel->model()->updateFilesPriorities(h.file_priorities()); filesList->setUpdatesEnabled(true); } break; } default:; } } void PropertiesWidget::loadUrlSeeds() { listWebSeeds->clear(); qDebug("Loading URL seeds"); const QList<QUrl> hc_seeds = m_torrent->urlSeeds(); // Add url seeds foreach (const QUrl &hc_seed, hc_seeds) { qDebug("Loading URL seed: %s", qPrintable(hc_seed.toString())); new QListWidgetItem(hc_seed.toString(), listWebSeeds); } } void PropertiesWidget::openDoubleClickedFile(const QModelIndex &index) { if (!index.isValid()) return; if (!m_torrent || !m_torrent->hasMetadata()) return; if (PropListModel->itemType(index) == TorrentContentModelItem::FileType) openFile(index); else openFolder(index, false); } void PropertiesWidget::openFile(const QModelIndex &index) { int i = PropListModel->getFileIndex(index); const QDir saveDir(m_torrent->savePath(true)); const QString filename = m_torrent->filePath(i); const QString file_path = Utils::Fs::expandPath(saveDir.absoluteFilePath(filename)); qDebug("Trying to open file at %s", qPrintable(file_path)); // Flush data m_torrent->flushCache(); Utils::Misc::openPath(file_path); } void PropertiesWidget::openFolder(const QModelIndex &index, bool containing_folder) { QString absolute_path; // FOLDER if (PropListModel->itemType(index) == TorrentContentModelItem::FolderType) { // Generate relative path to selected folder QStringList path_items; path_items << index.data().toString(); QModelIndex parent = PropListModel->parent(index); while (parent.isValid()) { path_items.prepend(parent.data().toString()); parent = PropListModel->parent(parent); } if (path_items.isEmpty()) return; const QDir saveDir(m_torrent->savePath(true)); const QString relative_path = path_items.join("/"); absolute_path = Utils::Fs::expandPath(saveDir.absoluteFilePath(relative_path)); } else { int i = PropListModel->getFileIndex(index); const QDir saveDir(m_torrent->savePath(true)); const QString relative_path = m_torrent->filePath(i); absolute_path = Utils::Fs::expandPath(saveDir.absoluteFilePath(relative_path)); } // Flush data m_torrent->flushCache(); if (containing_folder) Utils::Misc::openFolderSelect(absolute_path); else Utils::Misc::openPath(absolute_path); } void PropertiesWidget::displayFilesListMenu(const QPoint &) { if (!m_torrent) return; QModelIndexList selectedRows = filesList->selectionModel()->selectedRows(0); if (selectedRows.empty()) return; QMenu myFilesLlistMenu; QAction *actOpen = 0; QAction *actOpenContainingFolder = 0; QAction *actRename = 0; if (selectedRows.size() == 1) { actOpen = myFilesLlistMenu.addAction(GuiIconProvider::instance()->getIcon("folder-documents"), tr("Open")); actOpenContainingFolder = myFilesLlistMenu.addAction(GuiIconProvider::instance()->getIcon("inode-directory"), tr("Open Containing Folder")); actRename = myFilesLlistMenu.addAction(GuiIconProvider::instance()->getIcon("edit-rename"), tr("Rename...")); myFilesLlistMenu.addSeparator(); } QMenu subMenu; if (!m_torrent->isSeed()) { subMenu.setTitle(tr("Priority")); subMenu.addAction(actionNot_downloaded); subMenu.addAction(actionNormal); subMenu.addAction(actionHigh); subMenu.addAction(actionMaximum); myFilesLlistMenu.addMenu(&subMenu); } // Call menu const QAction *act = myFilesLlistMenu.exec(QCursor::pos()); // The selected torrent might have disappeared during exec() // from the current view thus leaving invalid indices. const QModelIndex index = *(selectedRows.begin()); if (!index.isValid()) return; if (act) { if (act == actOpen) { openDoubleClickedFile(index); } else if (act == actOpenContainingFolder) { openFolder(index, true); } else if (act == actRename) { renameSelectedFile(); } else { int prio = prio::NORMAL; if (act == actionHigh) prio = prio::HIGH; else if (act == actionMaximum) prio = prio::MAXIMUM; else if (act == actionNot_downloaded) prio = prio::IGNORED; qDebug("Setting files priority"); foreach (QModelIndex index, selectedRows) { qDebug("Setting priority(%d) for file at row %d", prio, index.row()); PropListModel->setData(PropListModel->index(index.row(), PRIORITY, index.parent()), prio); } // Save changes filteredFilesChanged(); } } } void PropertiesWidget::displayWebSeedListMenu(const QPoint &) { if (!m_torrent) return; QMenu seedMenu; QModelIndexList rows = listWebSeeds->selectionModel()->selectedRows(); QAction *actAdd = seedMenu.addAction(GuiIconProvider::instance()->getIcon("list-add"), tr("New Web seed")); QAction *actDel = 0; QAction *actCpy = 0; QAction *actEdit = 0; if (rows.size()) { actDel = seedMenu.addAction(GuiIconProvider::instance()->getIcon("list-remove"), tr("Remove Web seed")); seedMenu.addSeparator(); actCpy = seedMenu.addAction(GuiIconProvider::instance()->getIcon("edit-copy"), tr("Copy Web seed URL")); actEdit = seedMenu.addAction(GuiIconProvider::instance()->getIcon("edit-rename"), tr("Edit Web seed URL")); } const QAction *act = seedMenu.exec(QCursor::pos()); if (act) { if (act == actAdd) askWebSeed(); else if (act == actDel) deleteSelectedUrlSeeds(); else if (act == actCpy) copySelectedWebSeedsToClipboard(); else if (act == actEdit) editWebSeed(); } } void PropertiesWidget::renameSelectedFile() { const QModelIndexList selectedIndexes = filesList->selectionModel()->selectedRows(0); if (selectedIndexes.size() != 1) return; const QModelIndex index = selectedIndexes.first(); if (!index.isValid()) return; // Ask for new name bool ok; QString new_name_last = AutoExpandableDialog::getText(this, tr("Rename the file"), tr("New name:"), QLineEdit::Normal, index.data().toString(), &ok).trimmed(); if (ok && !new_name_last.isEmpty()) { if (!Utils::Fs::isValidFileSystemName(new_name_last)) { MessageBoxRaised::warning(this, tr("The file could not be renamed"), tr("This file name contains forbidden characters, please choose a different one."), QMessageBox::Ok); return; } if (PropListModel->itemType(index) == TorrentContentModelItem::FileType) { // File renaming const int file_index = PropListModel->getFileIndex(index); if (!m_torrent || !m_torrent->hasMetadata()) return; QString old_name = m_torrent->filePath(file_index); if (old_name.endsWith(".!qB") && !new_name_last.endsWith(".!qB")) new_name_last += ".!qB"; QStringList path_items = old_name.split("/"); path_items.removeLast(); path_items << new_name_last; QString new_name = path_items.join("/"); if (Utils::Fs::sameFileNames(old_name, new_name)) { qDebug("Name did not change"); return; } new_name = Utils::Fs::expandPath(new_name); qDebug("New name: %s", qPrintable(new_name)); // Check if that name is already used for (int i = 0; i < m_torrent->filesCount(); ++i) { if (i == file_index) continue; if (Utils::Fs::sameFileNames(m_torrent->filePath(i), new_name)) { // Display error message MessageBoxRaised::warning(this, tr("The file could not be renamed"), tr("This name is already in use in this folder. Please use a different name."), QMessageBox::Ok); return; } } const bool force_recheck = QFile::exists(m_torrent->savePath(true) + "/" + new_name); qDebug("Renaming %s to %s", qPrintable(old_name), qPrintable(new_name)); m_torrent->renameFile(file_index, new_name); // Force recheck if (force_recheck) m_torrent->forceRecheck(); // Rename if torrent files model too if (new_name_last.endsWith(".!qB")) new_name_last.chop(4); PropListModel->setData(index, new_name_last); } else { // Folder renaming QStringList path_items; path_items << index.data().toString(); QModelIndex parent = PropListModel->parent(index); while (parent.isValid()) { path_items.prepend(parent.data().toString()); parent = PropListModel->parent(parent); } const QString old_path = path_items.join("/"); path_items.removeLast(); path_items << new_name_last; QString new_path = path_items.join("/"); if (Utils::Fs::sameFileNames(old_path, new_path)) { qDebug("Name did not change"); return; } if (!new_path.endsWith("/")) new_path += "/"; // Check for overwriting for (int i = 0; i < m_torrent->filesCount(); ++i) { const QString &current_name = m_torrent->filePath(i); #if defined(Q_OS_UNIX) || defined(Q_WS_QWS) if (current_name.startsWith(new_path, Qt::CaseSensitive)) { #else if (current_name.startsWith(new_path, Qt::CaseInsensitive)) { #endif QMessageBox::warning(this, tr("The folder could not be renamed"), tr("This name is already in use in this folder. Please use a different name."), QMessageBox::Ok); return; } } bool force_recheck = false; // Replace path in all files for (int i = 0; i < m_torrent->filesCount(); ++i) { const QString current_name = m_torrent->filePath(i); if (current_name.startsWith(old_path)) { QString new_name = current_name; new_name.replace(0, old_path.length(), new_path); if (!force_recheck && QDir(m_torrent->savePath(true)).exists(new_name)) force_recheck = true; new_name = Utils::Fs::expandPath(new_name); qDebug("Rename %s to %s", qPrintable(current_name), qPrintable(new_name)); m_torrent->renameFile(i, new_name); } } // Force recheck if (force_recheck) m_torrent->forceRecheck(); // Rename folder in torrent files model too PropListModel->setData(index, new_name_last); // Remove old folder const QDir old_folder(m_torrent->savePath(true) + "/" + old_path); int timeout = 10; while (!QDir().rmpath(old_folder.absolutePath()) && timeout > 0) { // FIXME: We should not sleep here (freezes the UI for 1 second) Utils::Misc::msleep(100); --timeout; } } } } void PropertiesWidget::openSelectedFile() { const QModelIndexList selectedIndexes = filesList->selectionModel()->selectedRows(0); if (selectedIndexes.size() != 1) return; openDoubleClickedFile(selectedIndexes.first()); } void PropertiesWidget::askWebSeed() { bool ok; // Ask user for a new url seed const QString url_seed = AutoExpandableDialog::getText(this, tr("New URL seed", "New HTTP source"), tr("New URL seed:"), QLineEdit::Normal, QString::fromUtf8("http://www."), &ok); if (!ok) return; qDebug("Adding %s web seed", qPrintable(url_seed)); if (!listWebSeeds->findItems(url_seed, Qt::MatchFixedString).empty()) { QMessageBox::warning(this, "qBittorrent", tr("This URL seed is already in the list."), QMessageBox::Ok); return; } if (m_torrent) m_torrent->addUrlSeeds(QList<QUrl>() << url_seed); // Refresh the seeds list loadUrlSeeds(); } void PropertiesWidget::deleteSelectedUrlSeeds() { const QList<QListWidgetItem *> selectedItems = listWebSeeds->selectedItems(); if (selectedItems.isEmpty()) return; QList<QUrl> urlSeeds; foreach (const QListWidgetItem *item, selectedItems) urlSeeds << item->text(); m_torrent->removeUrlSeeds(urlSeeds); // Refresh list loadUrlSeeds(); } void PropertiesWidget::copySelectedWebSeedsToClipboard() const { const QList<QListWidgetItem *> selected_items = listWebSeeds->selectedItems(); if (selected_items.isEmpty()) return; QStringList urls_to_copy; foreach (QListWidgetItem *item, selected_items) urls_to_copy << item->text(); QApplication::clipboard()->setText(urls_to_copy.join("\n")); } void PropertiesWidget::editWebSeed() { const QList<QListWidgetItem *> selected_items = listWebSeeds->selectedItems(); if (selected_items.size() != 1) return; const QListWidgetItem *selected_item = selected_items.last(); const QString old_seed = selected_item->text(); bool result; const QString new_seed = AutoExpandableDialog::getText(this, tr("Web seed editing"), tr("Web seed URL:"), QLineEdit::Normal, old_seed, &result); if (!result) return; if (!listWebSeeds->findItems(new_seed, Qt::MatchFixedString).empty()) { QMessageBox::warning(this, tr("qBittorrent"), tr("This URL seed is already in the list."), QMessageBox::Ok); return; } m_torrent->removeUrlSeeds(QList<QUrl>() << old_seed); m_torrent->addUrlSeeds(QList<QUrl>() << new_seed); loadUrlSeeds(); } bool PropertiesWidget::applyPriorities() { qDebug("Saving files priorities"); const QVector<int> priorities = PropListModel->model()->getFilePriorities(); // Prioritize the files qDebug("prioritize files: %d", priorities[0]); m_torrent->prioritizeFiles(priorities); return true; } void PropertiesWidget::filteredFilesChanged() { if (m_torrent) applyPriorities(); } void PropertiesWidget::filterText(const QString &filter) { PropListModel->setFilterRegExp(QRegExp(filter, Qt::CaseInsensitive, QRegExp::WildcardUnix)); if (filter.isEmpty()) { filesList->collapseAll(); filesList->expand(PropListModel->index(0, 0)); } else { filesList->expandAll(); } }
./CrossVul/dataset_final_sorted/CWE-79/cpp/good_3200_5
crossvul-cpp_data_bad_3200_0
#include "logger.h" #include <QDateTime> Logger* Logger::m_instance = 0; Logger::Logger() : lock(QReadWriteLock::Recursive) , msgCounter(0) , peerCounter(0) { } Logger::~Logger() {} Logger *Logger::instance() { return m_instance; } void Logger::initInstance() { if (!m_instance) m_instance = new Logger; } void Logger::freeInstance() { if (m_instance) { delete m_instance; m_instance = 0; } } void Logger::addMessage(const QString &message, const Log::MsgType &type) { QWriteLocker locker(&lock); Log::Msg temp = { msgCounter++, QDateTime::currentMSecsSinceEpoch(), type, message }; m_messages.push_back(temp); if (m_messages.size() >= MAX_LOG_MESSAGES) m_messages.pop_front(); emit newLogMessage(temp); } void Logger::addPeer(const QString &ip, bool blocked, const QString &reason) { QWriteLocker locker(&lock); Log::Peer temp = { peerCounter++, QDateTime::currentMSecsSinceEpoch(), ip, blocked, reason }; m_peers.push_back(temp); if (m_peers.size() >= MAX_LOG_MESSAGES) m_peers.pop_front(); emit newLogPeer(temp); } QVector<Log::Msg> Logger::getMessages(int lastKnownId) const { QReadLocker locker(&lock); int diff = msgCounter - lastKnownId - 1; int size = m_messages.size(); if ((lastKnownId == -1) || (diff >= size)) return m_messages; if (diff <= 0) return QVector<Log::Msg>(); return m_messages.mid(size - diff); } QVector<Log::Peer> Logger::getPeers(int lastKnownId) const { QReadLocker locker(&lock); int diff = peerCounter - lastKnownId - 1; int size = m_peers.size(); if ((lastKnownId == -1) || (diff >= size)) return m_peers; if (diff <= 0) return QVector<Log::Peer>(); return m_peers.mid(size - diff); }
./CrossVul/dataset_final_sorted/CWE-79/cpp/bad_3200_0
crossvul-cpp_data_good_3200_4
/* * Bittorrent Client using Qt4 and libtorrent. * Copyright (C) 2006 Christophe Dumez * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * In addition, as a special exception, the copyright holders give permission to * link this program with the OpenSSL project's "OpenSSL" library (or with * modified versions of it that use the same license as the "OpenSSL" library), * and distribute the linked executables. 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), 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. * * Contact : chris@qbittorrent.org */ #include <QStandardItemModel> #include <QSortFilterProxyModel> #include <QSet> #include <QHeaderView> #include <QMenu> #include <QClipboard> #include <QMessageBox> #include <QWheelEvent> #ifdef QBT_USES_QT5 #include <QTableView> #endif #include "base/net/reverseresolution.h" #include "base/bittorrent/torrenthandle.h" #include "base/bittorrent/peerinfo.h" #include "base/preferences.h" #include "base/logger.h" #include "base/unicodestrings.h" #include "propertieswidget.h" #include "base/net/geoipmanager.h" #include "peersadditiondlg.h" #include "speedlimitdlg.h" #include "guiiconprovider.h" #include "peerlistdelegate.h" #include "peerlistsortmodel.h" #include "peerlistwidget.h" PeerListWidget::PeerListWidget(PropertiesWidget *parent) : QTreeView(parent) , m_properties(parent) { // Load settings loadSettings(); // Visual settings setUniformRowHeights(true); setRootIsDecorated(false); setItemsExpandable(false); setAllColumnsShowFocus(true); setSelectionMode(QAbstractItemView::ExtendedSelection); header()->setStretchLastSection(false); // List Model m_listModel = new QStandardItemModel(0, PeerListDelegate::COL_COUNT); m_listModel->setHeaderData(PeerListDelegate::COUNTRY, Qt::Horizontal, tr("Country")); // Country flag column m_listModel->setHeaderData(PeerListDelegate::IP, Qt::Horizontal, tr("IP")); m_listModel->setHeaderData(PeerListDelegate::PORT, Qt::Horizontal, tr("Port")); m_listModel->setHeaderData(PeerListDelegate::FLAGS, Qt::Horizontal, tr("Flags")); m_listModel->setHeaderData(PeerListDelegate::CONNECTION, Qt::Horizontal, tr("Connection")); m_listModel->setHeaderData(PeerListDelegate::CLIENT, Qt::Horizontal, tr("Client", "i.e.: Client application")); m_listModel->setHeaderData(PeerListDelegate::PROGRESS, Qt::Horizontal, tr("Progress", "i.e: % downloaded")); m_listModel->setHeaderData(PeerListDelegate::DOWN_SPEED, Qt::Horizontal, tr("Down Speed", "i.e: Download speed")); m_listModel->setHeaderData(PeerListDelegate::UP_SPEED, Qt::Horizontal, tr("Up Speed", "i.e: Upload speed")); m_listModel->setHeaderData(PeerListDelegate::TOT_DOWN, Qt::Horizontal, tr("Downloaded", "i.e: total data downloaded")); m_listModel->setHeaderData(PeerListDelegate::TOT_UP, Qt::Horizontal, tr("Uploaded", "i.e: total data uploaded")); m_listModel->setHeaderData(PeerListDelegate::RELEVANCE, Qt::Horizontal, tr("Relevance", "i.e: How relevant this peer is to us. How many pieces it has that we don't.")); m_listModel->setHeaderData(PeerListDelegate::DOWNLOADING_PIECE, Qt::Horizontal, tr("Files", "i.e. files that are being downloaded right now")); // Set header text alignment m_listModel->setHeaderData(PeerListDelegate::PORT, Qt::Horizontal, QVariant(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole); m_listModel->setHeaderData(PeerListDelegate::PROGRESS, Qt::Horizontal, QVariant(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole); m_listModel->setHeaderData(PeerListDelegate::DOWN_SPEED, Qt::Horizontal, QVariant(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole); m_listModel->setHeaderData(PeerListDelegate::UP_SPEED, Qt::Horizontal, QVariant(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole); m_listModel->setHeaderData(PeerListDelegate::TOT_DOWN, Qt::Horizontal, QVariant(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole); m_listModel->setHeaderData(PeerListDelegate::TOT_UP, Qt::Horizontal, QVariant(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole); m_listModel->setHeaderData(PeerListDelegate::RELEVANCE, Qt::Horizontal, QVariant(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole); // Proxy model to support sorting without actually altering the underlying model m_proxyModel = new PeerListSortModel(); m_proxyModel->setDynamicSortFilter(true); m_proxyModel->setSourceModel(m_listModel); m_proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); setModel(m_proxyModel); hideColumn(PeerListDelegate::IP_HIDDEN); hideColumn(PeerListDelegate::COL_COUNT); m_resolveCountries = Preferences::instance()->resolvePeerCountries(); if (!m_resolveCountries) hideColumn(PeerListDelegate::COUNTRY); //Ensure that at least one column is visible at all times bool atLeastOne = false; for (unsigned int i = 0; i < PeerListDelegate::IP_HIDDEN; i++) { if (!isColumnHidden(i)) { atLeastOne = true; break; } } if (!atLeastOne) setColumnHidden(PeerListDelegate::IP, false); //To also mitigate the above issue, we have to resize each column when //its size is 0, because explicitly 'showing' the column isn't enough //in the above scenario. for (unsigned int i = 0; i < PeerListDelegate::IP_HIDDEN; i++) if ((columnWidth(i) <= 0) && !isColumnHidden(i)) resizeColumnToContents(i); // Context menu setContextMenuPolicy(Qt::CustomContextMenu); connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showPeerListMenu(QPoint))); // List delegate m_listDelegate = new PeerListDelegate(this); setItemDelegate(m_listDelegate); // Enable sorting setSortingEnabled(true); // IP to Hostname resolver updatePeerHostNameResolutionState(); // SIGNAL/SLOT header()->setContextMenuPolicy(Qt::CustomContextMenu); connect(header(), SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(displayToggleColumnsMenu(const QPoint &))); connect(header(), SIGNAL(sectionClicked(int)), SLOT(handleSortColumnChanged(int))); handleSortColumnChanged(header()->sortIndicatorSection()); m_copyHotkey = new QShortcut(QKeySequence::Copy, this, SLOT(copySelectedPeers()), 0, Qt::WidgetShortcut); #ifdef QBT_USES_QT5 // This hack fixes reordering of first column with Qt5. // https://github.com/qtproject/qtbase/commit/e0fc088c0c8bc61dbcaf5928b24986cd61a22777 QTableView unused; unused.setVerticalHeader(this->header()); this->header()->setParent(this); unused.setVerticalHeader(new QHeaderView(Qt::Horizontal)); #endif } PeerListWidget::~PeerListWidget() { saveSettings(); delete m_proxyModel; delete m_listModel; delete m_listDelegate; if (m_resolver) delete m_resolver; delete m_copyHotkey; } void PeerListWidget::displayToggleColumnsMenu(const QPoint&) { QMenu hideshowColumn(this); hideshowColumn.setTitle(tr("Column visibility")); QList<QAction*> actions; for (int i = 0; i < PeerListDelegate::IP_HIDDEN; ++i) { if ((i == PeerListDelegate::COUNTRY) && !Preferences::instance()->resolvePeerCountries()) { actions.append(nullptr); // keep the index in sync continue; } QAction *myAct = hideshowColumn.addAction(m_listModel->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString()); myAct->setCheckable(true); myAct->setChecked(!isColumnHidden(i)); actions.append(myAct); } int visibleCols = 0; for (unsigned int i = 0; i < PeerListDelegate::IP_HIDDEN; i++) { if (!isColumnHidden(i)) visibleCols++; if (visibleCols > 1) break; } // Call menu QAction *act = hideshowColumn.exec(QCursor::pos()); if (act) { int col = actions.indexOf(act); Q_ASSERT(col >= 0); Q_ASSERT(visibleCols > 0); if (!isColumnHidden(col) && (visibleCols == 1)) return; qDebug("Toggling column %d visibility", col); setColumnHidden(col, !isColumnHidden(col)); if (!isColumnHidden(col) && (columnWidth(col) <= 5)) setColumnWidth(col, 100); saveSettings(); } } void PeerListWidget::updatePeerHostNameResolutionState() { if (Preferences::instance()->resolvePeerHostNames()) { if (!m_resolver) { m_resolver = new Net::ReverseResolution(this); connect(m_resolver, SIGNAL(ipResolved(QString, QString)), SLOT(handleResolved(QString, QString))); loadPeers(m_properties->getCurrentTorrent(), true); } } else if (m_resolver) { delete m_resolver; } } void PeerListWidget::updatePeerCountryResolutionState() { if (Preferences::instance()->resolvePeerCountries() != m_resolveCountries) { m_resolveCountries = !m_resolveCountries; if (m_resolveCountries) { loadPeers(m_properties->getCurrentTorrent()); showColumn(PeerListDelegate::COUNTRY); if (columnWidth(PeerListDelegate::COUNTRY) <= 0) resizeColumnToContents(PeerListDelegate::COUNTRY); } else { hideColumn(PeerListDelegate::COUNTRY); } } } void PeerListWidget::showPeerListMenu(const QPoint&) { QMenu menu; bool emptyMenu = true; BitTorrent::TorrentHandle *const torrent = m_properties->getCurrentTorrent(); if (!torrent) return; // Add Peer Action QAction *addPeerAct = 0; if (!torrent->isQueued() && !torrent->isChecking()) { addPeerAct = menu.addAction(GuiIconProvider::instance()->getIcon("user-group-new"), tr("Add a new peer...")); emptyMenu = false; } QAction *banAct = 0; QAction *copyPeerAct = 0; if (!selectionModel()->selectedRows().isEmpty()) { copyPeerAct = menu.addAction(GuiIconProvider::instance()->getIcon("edit-copy"), tr("Copy IP:port")); menu.addSeparator(); banAct = menu.addAction(GuiIconProvider::instance()->getIcon("user-group-delete"), tr("Ban peer permanently")); emptyMenu = false; } if (emptyMenu) return; QAction *act = menu.exec(QCursor::pos()); if (act == 0) return; if (act == addPeerAct) { QList<BitTorrent::PeerAddress> peersList = PeersAdditionDlg::askForPeers(); int peerCount = 0; foreach (const BitTorrent::PeerAddress &addr, peersList) { if (torrent->connectPeer(addr)) { qDebug("Adding peer %s...", qPrintable(addr.ip.toString())); Logger::instance()->addMessage(tr("Manually adding peer '%1'...").arg(addr.ip.toString())); peerCount++; } else { Logger::instance()->addMessage(tr("The peer '%1' could not be added to this torrent.").arg(addr.ip.toString()), Log::WARNING); } } if (peerCount < peersList.length()) QMessageBox::information(0, tr("Peer addition"), tr("Some peers could not be added. Check the Log for details.")); else if (peerCount > 0) QMessageBox::information(0, tr("Peer addition"), tr("The peers were added to this torrent.")); return; } if (act == banAct) { banSelectedPeers(); return; } if (act == copyPeerAct) { copySelectedPeers(); return; } } void PeerListWidget::banSelectedPeers() { // Confirm first int ret = QMessageBox::question(this, tr("Ban peer permanently"), tr("Are you sure you want to ban permanently the selected peers?"), tr("&Yes"), tr("&No"), QString(), 0, 1); if (ret) return; QModelIndexList selectedIndexes = selectionModel()->selectedRows(); foreach (const QModelIndex &index, selectedIndexes) { int row = m_proxyModel->mapToSource(index).row(); QString ip = m_listModel->data(m_listModel->index(row, PeerListDelegate::IP_HIDDEN)).toString(); qDebug("Banning peer %s...", ip.toLocal8Bit().data()); Logger::instance()->addMessage(tr("Manually banning peer '%1'...").arg(ip)); BitTorrent::Session::instance()->banIP(ip); } // Refresh list loadPeers(m_properties->getCurrentTorrent()); } void PeerListWidget::copySelectedPeers() { QModelIndexList selectedIndexes = selectionModel()->selectedRows(); QStringList selectedPeers; foreach (const QModelIndex &index, selectedIndexes) { int row = m_proxyModel->mapToSource(index).row(); QString ip = m_listModel->data(m_listModel->index(row, PeerListDelegate::IP_HIDDEN)).toString(); QString myport = m_listModel->data(m_listModel->index(row, PeerListDelegate::PORT)).toString(); if (ip.indexOf(".") == -1) // IPv6 selectedPeers << "[" + ip + "]:" + myport; else // IPv4 selectedPeers << ip + ":" + myport; } QApplication::clipboard()->setText(selectedPeers.join("\n")); } void PeerListWidget::clear() { qDebug("clearing peer list"); m_peerItems.clear(); m_peerAddresses.clear(); m_missingFlags.clear(); int nbrows = m_listModel->rowCount(); if (nbrows > 0) { qDebug("Cleared %d peers", nbrows); m_listModel->removeRows(0, nbrows); } } void PeerListWidget::loadSettings() { header()->restoreState(Preferences::instance()->getPeerListState()); } void PeerListWidget::saveSettings() const { Preferences::instance()->setPeerListState(header()->saveState()); } void PeerListWidget::loadPeers(BitTorrent::TorrentHandle *const torrent, bool forceHostnameResolution) { if (!torrent) return; QList<BitTorrent::PeerInfo> peers = torrent->peers(); QSet<QString> oldeersSet = m_peerItems.keys().toSet(); foreach (const BitTorrent::PeerInfo &peer, peers) { BitTorrent::PeerAddress addr = peer.address(); if (addr.ip.isNull()) continue; QString peerIp = addr.ip.toString(); if (m_peerItems.contains(peerIp)) { // Update existing peer updatePeer(peerIp, torrent, peer); oldeersSet.remove(peerIp); if (forceHostnameResolution && m_resolver) m_resolver->resolve(peerIp); } else { // Add new peer m_peerItems[peerIp] = addPeer(peerIp, torrent, peer); m_peerAddresses[peerIp] = addr; // Resolve peer host name is asked if (m_resolver) m_resolver->resolve(peerIp); } } // Delete peers that are gone QSetIterator<QString> it(oldeersSet); while (it.hasNext()) { const QString& ip = it.next(); m_missingFlags.remove(ip); m_peerAddresses.remove(ip); QStandardItem *item = m_peerItems.take(ip); m_listModel->removeRow(item->row()); } } QStandardItem* PeerListWidget::addPeer(const QString& ip, BitTorrent::TorrentHandle *const torrent, const BitTorrent::PeerInfo &peer) { int row = m_listModel->rowCount(); // Adding Peer to peer list m_listModel->insertRow(row); m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP), ip); m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP), ip, Qt::ToolTipRole); m_listModel->setData(m_listModel->index(row, PeerListDelegate::PORT), peer.address().port); m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP_HIDDEN), ip); if (m_resolveCountries) { const QIcon ico = GuiIconProvider::instance()->getFlagIcon(peer.country()); if (!ico.isNull()) { m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), ico, Qt::DecorationRole); const QString countryName = Net::GeoIPManager::CountryName(peer.country()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), countryName, Qt::ToolTipRole); } else { m_missingFlags.insert(ip); } } m_listModel->setData(m_listModel->index(row, PeerListDelegate::CONNECTION), peer.connectionType()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flags()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flagsDescription(), Qt::ToolTipRole); m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), Utils::String::toHtmlEscaped(peer.client())); m_listModel->setData(m_listModel->index(row, PeerListDelegate::PROGRESS), peer.progress()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWN_SPEED), peer.payloadDownSpeed()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::UP_SPEED), peer.payloadUpSpeed()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_DOWN), peer.totalDownload()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_UP), peer.totalUpload()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::RELEVANCE), peer.relevance()); QStringList downloadingFiles(torrent->info().filesForPiece(peer.downloadingPieceIndex())); m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(";"))); m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String("\n")), Qt::ToolTipRole); return m_listModel->item(row, PeerListDelegate::IP); } void PeerListWidget::updatePeer(const QString &ip, BitTorrent::TorrentHandle *const torrent, const BitTorrent::PeerInfo &peer) { QStandardItem *item = m_peerItems.value(ip); int row = item->row(); if (m_resolveCountries) { const QIcon ico = GuiIconProvider::instance()->getFlagIcon(peer.country()); if (!ico.isNull()) { m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), ico, Qt::DecorationRole); const QString countryName = Net::GeoIPManager::CountryName(peer.country()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), countryName, Qt::ToolTipRole); m_missingFlags.remove(ip); } } m_listModel->setData(m_listModel->index(row, PeerListDelegate::CONNECTION), peer.connectionType()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::PORT), peer.address().port); m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flags()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flagsDescription(), Qt::ToolTipRole); m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), Utils::String::toHtmlEscaped(peer.client())); m_listModel->setData(m_listModel->index(row, PeerListDelegate::PROGRESS), peer.progress()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWN_SPEED), peer.payloadDownSpeed()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::UP_SPEED), peer.payloadUpSpeed()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_DOWN), peer.totalDownload()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_UP), peer.totalUpload()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::RELEVANCE), peer.relevance()); QStringList downloadingFiles(torrent->info().filesForPiece(peer.downloadingPieceIndex())); m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(";"))); m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String("\n")), Qt::ToolTipRole); } void PeerListWidget::handleResolved(const QString &ip, const QString &hostname) { QStandardItem *item = m_peerItems.value(ip, 0); if (item) { qDebug("Resolved %s -> %s", qPrintable(ip), qPrintable(hostname)); item->setData(hostname, Qt::DisplayRole); } } void PeerListWidget::handleSortColumnChanged(int col) { if (col == PeerListDelegate::COUNTRY) { qDebug("Sorting by decoration"); m_proxyModel->setSortRole(Qt::ToolTipRole); } else { m_proxyModel->setSortRole(Qt::DisplayRole); } } void PeerListWidget::wheelEvent(QWheelEvent *event) { event->accept(); if(event->modifiers() & Qt::ShiftModifier) { // Shift + scroll = horizontal scroll QWheelEvent scrollHEvent(event->pos(), event->globalPos(), event->delta(), event->buttons(), event->modifiers(), Qt::Horizontal); QTreeView::wheelEvent(&scrollHEvent); return; } QTreeView::wheelEvent(event); // event delegated to base class }
./CrossVul/dataset_final_sorted/CWE-79/cpp/good_3200_4
crossvul-cpp_data_good_3200_0
#include "logger.h" #include <QDateTime> #include "base/utils/string.h" Logger* Logger::m_instance = 0; Logger::Logger() : lock(QReadWriteLock::Recursive) , msgCounter(0) , peerCounter(0) { } Logger::~Logger() {} Logger *Logger::instance() { return m_instance; } void Logger::initInstance() { if (!m_instance) m_instance = new Logger; } void Logger::freeInstance() { if (m_instance) { delete m_instance; m_instance = 0; } } void Logger::addMessage(const QString &message, const Log::MsgType &type) { QWriteLocker locker(&lock); Log::Msg temp = { msgCounter++, QDateTime::currentMSecsSinceEpoch(), type, Utils::String::toHtmlEscaped(message) }; m_messages.push_back(temp); if (m_messages.size() >= MAX_LOG_MESSAGES) m_messages.pop_front(); emit newLogMessage(temp); } void Logger::addPeer(const QString &ip, bool blocked, const QString &reason) { QWriteLocker locker(&lock); Log::Peer temp = { peerCounter++, QDateTime::currentMSecsSinceEpoch(), Utils::String::toHtmlEscaped(ip), blocked, Utils::String::toHtmlEscaped(reason) }; m_peers.push_back(temp); if (m_peers.size() >= MAX_LOG_MESSAGES) m_peers.pop_front(); emit newLogPeer(temp); } QVector<Log::Msg> Logger::getMessages(int lastKnownId) const { QReadLocker locker(&lock); int diff = msgCounter - lastKnownId - 1; int size = m_messages.size(); if ((lastKnownId == -1) || (diff >= size)) return m_messages; if (diff <= 0) return QVector<Log::Msg>(); return m_messages.mid(size - diff); } QVector<Log::Peer> Logger::getPeers(int lastKnownId) const { QReadLocker locker(&lock); int diff = peerCounter - lastKnownId - 1; int size = m_peers.size(); if ((lastKnownId == -1) || (diff >= size)) return m_peers; if (diff <= 0) return QVector<Log::Peer>(); return m_peers.mid(size - diff); }
./CrossVul/dataset_final_sorted/CWE-79/cpp/good_3200_0
crossvul-cpp_data_good_3200_1
/* * Bittorrent Client using Qt and libtorrent. * Copyright (C) 2015 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org> * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * In addition, as a special exception, the copyright holders give permission to * link this program with the OpenSSL project's "OpenSSL" library (or with * modified versions of it that use the same license as the "OpenSSL" library), * and distribute the linked executables. 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), 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. */ #include "string.h" #include <cmath> #include <QByteArray> #include <QtGlobal> #include <QLocale> #ifdef QBT_USES_QT5 #include <QCollator> #endif #ifdef Q_OS_MAC #include <QThreadStorage> #endif namespace { class NaturalCompare { public: explicit NaturalCompare(const bool caseSensitive = true) : m_caseSensitive(caseSensitive) { #ifdef QBT_USES_QT5 #if defined(Q_OS_WIN) // Without ICU library, QCollator uses the native API on Windows 7+. But that API // sorts older versions of μTorrent differently than the newer ones because the // 'μ' character is encoded differently and the native API can't cope with that. // So default to using our custom natural sorting algorithm instead. // See #5238 and #5240 // Without ICU library, QCollator doesn't support `setNumericMode(true)` on OS older than Win7 // if (QSysInfo::windowsVersion() < QSysInfo::WV_WINDOWS7) return; #endif m_collator.setNumericMode(true); m_collator.setCaseSensitivity(caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive); #endif } bool operator()(const QString &left, const QString &right) const { #ifdef QBT_USES_QT5 #if defined(Q_OS_WIN) // Without ICU library, QCollator uses the native API on Windows 7+. But that API // sorts older versions of μTorrent differently than the newer ones because the // 'μ' character is encoded differently and the native API can't cope with that. // So default to using our custom natural sorting algorithm instead. // See #5238 and #5240 // Without ICU library, QCollator doesn't support `setNumericMode(true)` on OS older than Win7 // if (QSysInfo::windowsVersion() < QSysInfo::WV_WINDOWS7) return lessThan(left, right); #endif return (m_collator.compare(left, right) < 0); #else return lessThan(left, right); #endif } bool lessThan(const QString &left, const QString &right) const { // Return value `false` indicates `right` should go before `left`, otherwise, after int posL = 0; int posR = 0; while (true) { while (true) { if ((posL == left.size()) || (posR == right.size())) return (left.size() < right.size()); // when a shorter string is another string's prefix, shorter string place before longer string QChar leftChar = m_caseSensitive ? left[posL] : left[posL].toLower(); QChar rightChar = m_caseSensitive ? right[posR] : right[posR].toLower(); if (leftChar == rightChar) ; // compare next character else if (leftChar.isDigit() && rightChar.isDigit()) break; // Both are digits, break this loop and compare numbers else return leftChar < rightChar; ++posL; ++posR; } int startL = posL; while ((posL < left.size()) && left[posL].isDigit()) ++posL; #ifdef QBT_USES_QT5 int numL = left.midRef(startL, posL - startL).toInt(); #else int numL = left.mid(startL, posL - startL).toInt(); #endif int startR = posR; while ((posR < right.size()) && right[posR].isDigit()) ++posR; #ifdef QBT_USES_QT5 int numR = right.midRef(startR, posR - startR).toInt(); #else int numR = right.mid(startR, posR - startR).toInt(); #endif if (numL != numR) return (numL < numR); // Strings + digits do match and we haven't hit string end // Do another round } return false; } private: #ifdef QBT_USES_QT5 QCollator m_collator; #endif const bool m_caseSensitive; }; } bool Utils::String::naturalCompareCaseSensitive(const QString &left, const QString &right) { // provide a single `NaturalCompare` instance for easy use // https://doc.qt.io/qt-5/threads-reentrancy.html #ifdef Q_OS_MAC // workaround for Apple xcode: https://stackoverflow.com/a/29929949 static QThreadStorage<NaturalCompare> nCmp; if (!nCmp.hasLocalData()) nCmp.setLocalData(NaturalCompare(true)); return (nCmp.localData())(left, right); #else thread_local NaturalCompare nCmp(true); return nCmp(left, right); #endif } bool Utils::String::naturalCompareCaseInsensitive(const QString &left, const QString &right) { // provide a single `NaturalCompare` instance for easy use // https://doc.qt.io/qt-5/threads-reentrancy.html #ifdef Q_OS_MAC // workaround for Apple xcode: https://stackoverflow.com/a/29929949 static QThreadStorage<NaturalCompare> nCmp; if (!nCmp.hasLocalData()) nCmp.setLocalData(NaturalCompare(false)); return (nCmp.localData())(left, right); #else thread_local NaturalCompare nCmp(false); return nCmp(left, right); #endif } QString Utils::String::fromStdString(const std::string &str) { return QString::fromUtf8(str.c_str()); } std::string Utils::String::toStdString(const QString &str) { #ifdef QBT_USES_QT5 return str.toStdString(); #else QByteArray utf8 = str.toUtf8(); return std::string(utf8.constData(), utf8.length()); #endif } // to send numbers instead of strings with suffixes QString Utils::String::fromDouble(double n, int precision) { /* HACK because QString rounds up. Eg QString::number(0.999*100.0, 'f' ,1) == 99.9 ** but QString::number(0.9999*100.0, 'f' ,1) == 100.0 The problem manifests when ** the number has more digits after the decimal than we want AND the digit after ** our 'wanted' is >= 5. In this case our last digit gets rounded up. So for each ** precision we add an extra 0 behind 1 in the below algorithm. */ double prec = std::pow(10.0, precision); return QLocale::system().toString(std::floor(n * prec) / prec, 'f', precision); } // Implements constant-time comparison to protect against timing attacks // Taken from https://crackstation.net/hashing-security.htm bool Utils::String::slowEquals(const QByteArray &a, const QByteArray &b) { int lengthA = a.length(); int lengthB = b.length(); int diff = lengthA ^ lengthB; for (int i = 0; (i < lengthA) && (i < lengthB); i++) diff |= a[i] ^ b[i]; return (diff == 0); } QString Utils::String::toHtmlEscaped(const QString &str) { #ifdef QBT_USES_QT5 return str.toHtmlEscaped(); #else return Qt::escape(str); #endif }
./CrossVul/dataset_final_sorted/CWE-79/cpp/good_3200_1
crossvul-cpp_data_bad_3200_5
/* * Bittorrent Client using Qt4 and libtorrent. * Copyright (C) 2006 Christophe Dumez * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * In addition, as a special exception, the copyright holders give permission to * link this program with the OpenSSL project's "OpenSSL" library (or with * modified versions of it that use the same license as the "OpenSSL" library), * and distribute the linked executables. 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), 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. * * Contact : chris@qbittorrent.org */ #include "propertieswidget.h" #include <QDebug> #include <QTimer> #include <QListWidgetItem> #include <QVBoxLayout> #include <QStackedWidget> #include <QSplitter> #include <QHeaderView> #include <QAction> #include <QMenu> #include <QFileDialog> #include <QBitArray> #include "base/bittorrent/session.h" #include "base/preferences.h" #include "base/utils/fs.h" #include "base/utils/misc.h" #include "base/utils/string.h" #include "base/unicodestrings.h" #include "proplistdelegate.h" #include "torrentcontentfiltermodel.h" #include "torrentcontentmodel.h" #include "peerlistwidget.h" #include "speedwidget.h" #include "trackerlist.h" #include "mainwindow.h" #include "messageboxraised.h" #include "downloadedpiecesbar.h" #include "pieceavailabilitybar.h" #include "proptabbar.h" #include "guiiconprovider.h" #include "lineedit.h" #include "transferlistwidget.h" #include "autoexpandabledialog.h" PropertiesWidget::PropertiesWidget(QWidget *parent, MainWindow *main_window, TransferListWidget *transferList) : QWidget(parent), transferList(transferList), main_window(main_window), m_torrent(0) { setupUi(this); setAutoFillBackground(true); state = VISIBLE; // Set Properties list model PropListModel = new TorrentContentFilterModel(); filesList->setModel(PropListModel); PropDelegate = new PropListDelegate(this); filesList->setItemDelegate(PropDelegate); filesList->setSortingEnabled(true); // Torrent content filtering m_contentFilterLine = new LineEdit(this); m_contentFilterLine->setPlaceholderText(tr("Filter files...")); m_contentFilterLine->setMaximumSize(300, m_contentFilterLine->size().height()); connect(m_contentFilterLine, SIGNAL(textChanged(QString)), this, SLOT(filterText(QString))); contentFilterLayout->insertWidget(3, m_contentFilterLine); // SIGNAL/SLOTS connect(filesList, SIGNAL(clicked(const QModelIndex&)), filesList, SLOT(edit(const QModelIndex&))); connect(selectAllButton, SIGNAL(clicked()), PropListModel, SLOT(selectAll())); connect(selectNoneButton, SIGNAL(clicked()), PropListModel, SLOT(selectNone())); connect(filesList, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(displayFilesListMenu(const QPoint&))); connect(filesList, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(openDoubleClickedFile(const QModelIndex&))); connect(PropListModel, SIGNAL(filteredFilesChanged()), this, SLOT(filteredFilesChanged())); connect(listWebSeeds, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(displayWebSeedListMenu(const QPoint&))); connect(transferList, SIGNAL(currentTorrentChanged(BitTorrent::TorrentHandle * const)), this, SLOT(loadTorrentInfos(BitTorrent::TorrentHandle * const))); connect(PropDelegate, SIGNAL(filteredFilesChanged()), this, SLOT(filteredFilesChanged())); connect(stackedProperties, SIGNAL(currentChanged(int)), this, SLOT(loadDynamicData())); connect(BitTorrent::Session::instance(), SIGNAL(torrentSavePathChanged(BitTorrent::TorrentHandle * const)), this, SLOT(updateSavePath(BitTorrent::TorrentHandle * const))); connect(BitTorrent::Session::instance(), SIGNAL(torrentMetadataLoaded(BitTorrent::TorrentHandle * const)), this, SLOT(updateTorrentInfos(BitTorrent::TorrentHandle * const))); connect(filesList->header(), SIGNAL(sectionMoved(int,int,int)), this, SLOT(saveSettings())); connect(filesList->header(), SIGNAL(sectionResized(int,int,int)), this, SLOT(saveSettings())); connect(filesList->header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), this, SLOT(saveSettings())); #ifdef QBT_USES_QT5 // set bar height relative to screen dpi int barHeight = devicePixelRatio() * 18; #else // set bar height relative to font height QFont defFont; QFontMetrics fMetrics(defFont, 0); // need to be device-dependent int barHeight = fMetrics.height() * 5 / 4; #endif // Downloaded pieces progress bar tempProgressBarArea->setVisible(false); downloaded_pieces = new DownloadedPiecesBar(this); groupBarLayout->addWidget(downloaded_pieces, 0, 1); downloaded_pieces->setFixedHeight(barHeight); downloaded_pieces->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); // Pieces availability bar tempAvailabilityBarArea->setVisible(false); pieces_availability = new PieceAvailabilityBar(this); groupBarLayout->addWidget(pieces_availability, 1, 1); pieces_availability->setFixedHeight(barHeight); pieces_availability->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); // Tracker list trackerList = new TrackerList(this); trackerUpButton->setIcon(GuiIconProvider::instance()->getIcon("go-up")); trackerUpButton->setIconSize(Utils::Misc::smallIconSize()); trackerDownButton->setIcon(GuiIconProvider::instance()->getIcon("go-down")); trackerDownButton->setIconSize(Utils::Misc::smallIconSize()); connect(trackerUpButton, SIGNAL(clicked()), trackerList, SLOT(moveSelectionUp())); connect(trackerDownButton, SIGNAL(clicked()), trackerList, SLOT(moveSelectionDown())); horizontalLayout_trackers->insertWidget(0, trackerList); connect(trackerList->header(), SIGNAL(sectionMoved(int,int,int)), trackerList, SLOT(saveSettings())); connect(trackerList->header(), SIGNAL(sectionResized(int,int,int)), trackerList, SLOT(saveSettings())); connect(trackerList->header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), trackerList, SLOT(saveSettings())); // Peers list peersList = new PeerListWidget(this); peerpage_layout->addWidget(peersList); connect(peersList->header(), SIGNAL(sectionMoved(int,int,int)), peersList, SLOT(saveSettings())); connect(peersList->header(), SIGNAL(sectionResized(int,int,int)), peersList, SLOT(saveSettings())); connect(peersList->header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), peersList, SLOT(saveSettings())); // Speed widget speedWidget = new SpeedWidget(this); speed_layout->addWidget(speedWidget); // Tab bar m_tabBar = new PropTabBar(); m_tabBar->setContentsMargins(0, 5, 0, 0); verticalLayout->addLayout(m_tabBar); connect(m_tabBar, SIGNAL(tabChanged(int)), stackedProperties, SLOT(setCurrentIndex(int))); connect(m_tabBar, SIGNAL(tabChanged(int)), this, SLOT(saveSettings())); connect(m_tabBar, SIGNAL(visibilityToggled(bool)), SLOT(setVisibility(bool))); connect(m_tabBar, SIGNAL(visibilityToggled(bool)), this, SLOT(saveSettings())); // Dynamic data refresher refreshTimer = new QTimer(this); connect(refreshTimer, SIGNAL(timeout()), this, SLOT(loadDynamicData())); refreshTimer->start(3000); // 3sec editHotkeyFile = new QShortcut(Qt::Key_F2, filesList, 0, 0, Qt::WidgetShortcut); connect(editHotkeyFile, SIGNAL(activated()), SLOT(renameSelectedFile())); editHotkeyWeb = new QShortcut(Qt::Key_F2, listWebSeeds, 0, 0, Qt::WidgetShortcut); connect(editHotkeyWeb, SIGNAL(activated()), SLOT(editWebSeed())); connect(listWebSeeds, SIGNAL(doubleClicked(QModelIndex)), SLOT(editWebSeed())); deleteHotkeyWeb = new QShortcut(QKeySequence::Delete, listWebSeeds, 0, 0, Qt::WidgetShortcut); connect(deleteHotkeyWeb, SIGNAL(activated()), SLOT(deleteSelectedUrlSeeds())); openHotkeyFile = new QShortcut(Qt::Key_Return, filesList, 0, 0, Qt::WidgetShortcut); connect(openHotkeyFile, SIGNAL(activated()), SLOT(openSelectedFile())); } PropertiesWidget::~PropertiesWidget() { qDebug() << Q_FUNC_INFO << "ENTER"; delete refreshTimer; delete trackerList; delete peersList; delete speedWidget; delete downloaded_pieces; delete pieces_availability; delete PropListModel; delete PropDelegate; delete m_tabBar; delete editHotkeyFile; delete editHotkeyWeb; delete deleteHotkeyWeb; delete openHotkeyFile; qDebug() << Q_FUNC_INFO << "EXIT"; } void PropertiesWidget::showPiecesAvailability(bool show) { avail_pieces_lbl->setVisible(show); pieces_availability->setVisible(show); avail_average_lbl->setVisible(show); if (show || !downloaded_pieces->isVisible()) line_2->setVisible(show); } void PropertiesWidget::showPiecesDownloaded(bool show) { downloaded_pieces_lbl->setVisible(show); downloaded_pieces->setVisible(show); progress_lbl->setVisible(show); if (show || !pieces_availability->isVisible()) line_2->setVisible(show); } void PropertiesWidget::setVisibility(bool visible) { if (!visible && ( state == VISIBLE) ) { QSplitter *hSplitter = static_cast<QSplitter *>(parentWidget()); stackedProperties->setVisible(false); slideSizes = hSplitter->sizes(); hSplitter->handle(1)->setVisible(false); hSplitter->handle(1)->setDisabled(true); QList<int> sizes = QList<int>() << hSplitter->geometry().height() - 30 << 30; hSplitter->setSizes(sizes); state = REDUCED; return; } if (visible && ( state == REDUCED) ) { stackedProperties->setVisible(true); QSplitter *hSplitter = static_cast<QSplitter *>(parentWidget()); hSplitter->handle(1)->setDisabled(false); hSplitter->handle(1)->setVisible(true); hSplitter->setSizes(slideSizes); state = VISIBLE; // Force refresh loadDynamicData(); } } void PropertiesWidget::clear() { qDebug("Clearing torrent properties"); save_path->clear(); lbl_creationDate->clear(); label_total_pieces_val->clear(); hash_lbl->clear(); comment_text->clear(); progress_lbl->clear(); trackerList->clear(); downloaded_pieces->clear(); pieces_availability->clear(); avail_average_lbl->clear(); wasted->clear(); upTotal->clear(); dlTotal->clear(); peersList->clear(); lbl_uplimit->clear(); lbl_dllimit->clear(); lbl_elapsed->clear(); lbl_connections->clear(); reannounce_lbl->clear(); shareRatio->clear(); listWebSeeds->clear(); m_contentFilterLine->clear(); PropListModel->model()->clear(); label_eta_val->clear(); label_seeds_val->clear(); label_peers_val->clear(); label_dl_speed_val->clear(); label_upload_speed_val->clear(); label_total_size_val->clear(); label_completed_on_val->clear(); label_last_complete_val->clear(); label_created_by_val->clear(); label_added_on_val->clear(); } BitTorrent::TorrentHandle *PropertiesWidget::getCurrentTorrent() const { return m_torrent; } void PropertiesWidget::updateSavePath(BitTorrent::TorrentHandle *const torrent) { if (m_torrent == torrent) save_path->setText(Utils::Fs::toNativePath(m_torrent->savePath())); } void PropertiesWidget::loadTrackers(BitTorrent::TorrentHandle *const torrent) { if (torrent == m_torrent) trackerList->loadTrackers(); } void PropertiesWidget::updateTorrentInfos(BitTorrent::TorrentHandle *const torrent) { if (m_torrent == torrent) loadTorrentInfos(m_torrent); } void PropertiesWidget::loadTorrentInfos(BitTorrent::TorrentHandle *const torrent) { clear(); m_torrent = torrent; downloaded_pieces->setTorrent(m_torrent); pieces_availability->setTorrent(m_torrent); if (!m_torrent) return; // Save path updateSavePath(m_torrent); // Hash hash_lbl->setText(m_torrent->hash()); PropListModel->model()->clear(); if (m_torrent->hasMetadata()) { // Creation date lbl_creationDate->setText(m_torrent->creationDate().toString(Qt::DefaultLocaleShortDate)); label_total_size_val->setText(Utils::Misc::friendlyUnit(m_torrent->totalSize())); // Comment comment_text->setText(Utils::Misc::parseHtmlLinks(m_torrent->comment())); // URL seeds loadUrlSeeds(); label_created_by_val->setText(m_torrent->creator()); // List files in torrent PropListModel->model()->setupModelData(m_torrent->info()); filesList->setExpanded(PropListModel->index(0, 0), true); // Load file priorities PropListModel->model()->updateFilesPriorities(m_torrent->filePriorities()); } // Load dynamic data loadDynamicData(); } void PropertiesWidget::readSettings() { const Preferences *const pref = Preferences::instance(); // Restore splitter sizes QStringList sizes_str = pref->getPropSplitterSizes().split(","); if (sizes_str.size() == 2) { slideSizes << sizes_str.first().toInt(); slideSizes << sizes_str.last().toInt(); QSplitter *hSplitter = static_cast<QSplitter *>(parentWidget()); hSplitter->setSizes(slideSizes); } const int current_tab = pref->getPropCurTab(); const bool visible = pref->getPropVisible(); // the following will call saveSettings but shouldn't change any state if (!filesList->header()->restoreState(pref->getPropFileListState())) filesList->header()->resizeSection(0, 400); // Default m_tabBar->setCurrentIndex(current_tab); if (!visible) setVisibility(false); } void PropertiesWidget::saveSettings() { Preferences *const pref = Preferences::instance(); pref->setPropVisible(state==VISIBLE); // Splitter sizes QSplitter *hSplitter = static_cast<QSplitter *>(parentWidget()); QList<int> sizes; if (state == VISIBLE) sizes = hSplitter->sizes(); else sizes = slideSizes; qDebug("Sizes: %d", sizes.size()); if (sizes.size() == 2) pref->setPropSplitterSizes(QString::number(sizes.first()) + ',' + QString::number(sizes.last())); pref->setPropFileListState(filesList->header()->saveState()); // Remember current tab pref->setPropCurTab(m_tabBar->currentIndex()); } void PropertiesWidget::reloadPreferences() { // Take program preferences into consideration peersList->updatePeerHostNameResolutionState(); peersList->updatePeerCountryResolutionState(); } void PropertiesWidget::loadDynamicData() { // Refresh only if the torrent handle is valid and if visible if (!m_torrent || (main_window->currentTabWidget() != transferList) || (state != VISIBLE)) return; // Transfer infos switch (stackedProperties->currentIndex()) { case PropTabBar::MAIN_TAB: { wasted->setText(Utils::Misc::friendlyUnit(m_torrent->wastedSize())); upTotal->setText(tr("%1 (%2 this session)").arg(Utils::Misc::friendlyUnit(m_torrent->totalUpload())) .arg(Utils::Misc::friendlyUnit(m_torrent->totalPayloadUpload()))); dlTotal->setText(tr("%1 (%2 this session)").arg(Utils::Misc::friendlyUnit(m_torrent->totalDownload())) .arg(Utils::Misc::friendlyUnit(m_torrent->totalPayloadDownload()))); lbl_uplimit->setText(m_torrent->uploadLimit() <= 0 ? QString::fromUtf8(C_INFINITY) : Utils::Misc::friendlyUnit(m_torrent->uploadLimit(), true)); lbl_dllimit->setText(m_torrent->downloadLimit() <= 0 ? QString::fromUtf8(C_INFINITY) : Utils::Misc::friendlyUnit(m_torrent->downloadLimit(), true)); QString elapsed_txt; if (m_torrent->isSeed()) elapsed_txt = tr("%1 (seeded for %2)", "e.g. 4m39s (seeded for 3m10s)") .arg(Utils::Misc::userFriendlyDuration(m_torrent->activeTime())) .arg(Utils::Misc::userFriendlyDuration(m_torrent->seedingTime())); else elapsed_txt = Utils::Misc::userFriendlyDuration(m_torrent->activeTime()); lbl_elapsed->setText(elapsed_txt); lbl_connections->setText(tr("%1 (%2 max)", "%1 and %2 are numbers, e.g. 3 (10 max)") .arg(m_torrent->connectionsCount()) .arg(m_torrent->connectionsLimit() < 0 ? QString::fromUtf8(C_INFINITY) : QString::number(m_torrent->connectionsLimit()))); label_eta_val->setText(Utils::Misc::userFriendlyDuration(m_torrent->eta())); // Update next announce time reannounce_lbl->setText(Utils::Misc::userFriendlyDuration(m_torrent->nextAnnounce())); // Update ratio info const qreal ratio = m_torrent->realRatio(); shareRatio->setText(ratio > BitTorrent::TorrentHandle::MAX_RATIO ? QString::fromUtf8(C_INFINITY) : Utils::String::fromDouble(ratio, 2)); label_seeds_val->setText(tr("%1 (%2 total)", "%1 and %2 are numbers, e.g. 3 (10 total)") .arg(QString::number(m_torrent->seedsCount())) .arg(QString::number(m_torrent->totalSeedsCount()))); label_peers_val->setText(tr("%1 (%2 total)", "%1 and %2 are numbers, e.g. 3 (10 total)") .arg(QString::number(m_torrent->leechsCount())) .arg(QString::number(m_torrent->totalLeechersCount()))); label_dl_speed_val->setText(tr("%1 (%2 avg.)", "%1 and %2 are speed rates, e.g. 200KiB/s (100KiB/s avg.)") .arg(Utils::Misc::friendlyUnit(m_torrent->downloadPayloadRate(), true)) .arg(Utils::Misc::friendlyUnit(m_torrent->totalDownload() / (1 + m_torrent->activeTime() - m_torrent->finishedTime()), true))); label_upload_speed_val->setText(tr("%1 (%2 avg.)", "%1 and %2 are speed rates, e.g. 200KiB/s (100KiB/s avg.)") .arg(Utils::Misc::friendlyUnit(m_torrent->uploadPayloadRate(), true)) .arg(Utils::Misc::friendlyUnit(m_torrent->totalUpload() / (1 + m_torrent->activeTime()), true))); label_last_complete_val->setText(m_torrent->lastSeenComplete().isValid() ? m_torrent->lastSeenComplete().toString(Qt::DefaultLocaleShortDate) : tr("Never")); label_completed_on_val->setText(m_torrent->completedTime().isValid() ? m_torrent->completedTime().toString(Qt::DefaultLocaleShortDate) : ""); label_added_on_val->setText(m_torrent->addedTime().toString(Qt::DefaultLocaleShortDate)); if (m_torrent->hasMetadata()) { label_total_pieces_val->setText(tr("%1 x %2 (have %3)", "(torrent pieces) eg 152 x 4MB (have 25)").arg(m_torrent->piecesCount()).arg(Utils::Misc::friendlyUnit(m_torrent->pieceLength())).arg(m_torrent->piecesHave())); if (!m_torrent->isSeed() && !m_torrent->isPaused() && !m_torrent->isQueued() && !m_torrent->isChecking()) { // Pieces availability showPiecesAvailability(true); pieces_availability->setAvailability(m_torrent->pieceAvailability()); avail_average_lbl->setText(Utils::String::fromDouble(m_torrent->distributedCopies(), 3)); } else { showPiecesAvailability(false); } // Progress qreal progress = m_torrent->progress() * 100.; progress_lbl->setText(Utils::String::fromDouble(progress, 1) + "%"); downloaded_pieces->setProgress(m_torrent->pieces(), m_torrent->downloadingPieces()); } else { showPiecesAvailability(false); } break; } case PropTabBar::TRACKERS_TAB: { // Trackers trackerList->loadTrackers(); break; } case PropTabBar::PEERS_TAB: { // Load peers peersList->loadPeers(m_torrent); break; } case PropTabBar::FILES_TAB: { // Files progress if (m_torrent->hasMetadata()) { qDebug("Updating priorities in files tab"); filesList->setUpdatesEnabled(false); PropListModel->model()->updateFilesProgress(m_torrent->filesProgress()); // XXX: We don't update file priorities regularly for performance // reasons. This means that priorities will not be updated if // set from the Web UI. // PropListModel->model()->updateFilesPriorities(h.file_priorities()); filesList->setUpdatesEnabled(true); } break; } default:; } } void PropertiesWidget::loadUrlSeeds() { listWebSeeds->clear(); qDebug("Loading URL seeds"); const QList<QUrl> hc_seeds = m_torrent->urlSeeds(); // Add url seeds foreach (const QUrl &hc_seed, hc_seeds) { qDebug("Loading URL seed: %s", qPrintable(hc_seed.toString())); new QListWidgetItem(hc_seed.toString(), listWebSeeds); } } void PropertiesWidget::openDoubleClickedFile(const QModelIndex &index) { if (!index.isValid()) return; if (!m_torrent || !m_torrent->hasMetadata()) return; if (PropListModel->itemType(index) == TorrentContentModelItem::FileType) openFile(index); else openFolder(index, false); } void PropertiesWidget::openFile(const QModelIndex &index) { int i = PropListModel->getFileIndex(index); const QDir saveDir(m_torrent->savePath(true)); const QString filename = m_torrent->filePath(i); const QString file_path = Utils::Fs::expandPath(saveDir.absoluteFilePath(filename)); qDebug("Trying to open file at %s", qPrintable(file_path)); // Flush data m_torrent->flushCache(); Utils::Misc::openPath(file_path); } void PropertiesWidget::openFolder(const QModelIndex &index, bool containing_folder) { QString absolute_path; // FOLDER if (PropListModel->itemType(index) == TorrentContentModelItem::FolderType) { // Generate relative path to selected folder QStringList path_items; path_items << index.data().toString(); QModelIndex parent = PropListModel->parent(index); while (parent.isValid()) { path_items.prepend(parent.data().toString()); parent = PropListModel->parent(parent); } if (path_items.isEmpty()) return; const QDir saveDir(m_torrent->savePath(true)); const QString relative_path = path_items.join("/"); absolute_path = Utils::Fs::expandPath(saveDir.absoluteFilePath(relative_path)); } else { int i = PropListModel->getFileIndex(index); const QDir saveDir(m_torrent->savePath(true)); const QString relative_path = m_torrent->filePath(i); absolute_path = Utils::Fs::expandPath(saveDir.absoluteFilePath(relative_path)); } // Flush data m_torrent->flushCache(); if (containing_folder) Utils::Misc::openFolderSelect(absolute_path); else Utils::Misc::openPath(absolute_path); } void PropertiesWidget::displayFilesListMenu(const QPoint &) { if (!m_torrent) return; QModelIndexList selectedRows = filesList->selectionModel()->selectedRows(0); if (selectedRows.empty()) return; QMenu myFilesLlistMenu; QAction *actOpen = 0; QAction *actOpenContainingFolder = 0; QAction *actRename = 0; if (selectedRows.size() == 1) { actOpen = myFilesLlistMenu.addAction(GuiIconProvider::instance()->getIcon("folder-documents"), tr("Open")); actOpenContainingFolder = myFilesLlistMenu.addAction(GuiIconProvider::instance()->getIcon("inode-directory"), tr("Open Containing Folder")); actRename = myFilesLlistMenu.addAction(GuiIconProvider::instance()->getIcon("edit-rename"), tr("Rename...")); myFilesLlistMenu.addSeparator(); } QMenu subMenu; if (!m_torrent->isSeed()) { subMenu.setTitle(tr("Priority")); subMenu.addAction(actionNot_downloaded); subMenu.addAction(actionNormal); subMenu.addAction(actionHigh); subMenu.addAction(actionMaximum); myFilesLlistMenu.addMenu(&subMenu); } // Call menu const QAction *act = myFilesLlistMenu.exec(QCursor::pos()); // The selected torrent might have disappeared during exec() // from the current view thus leaving invalid indices. const QModelIndex index = *(selectedRows.begin()); if (!index.isValid()) return; if (act) { if (act == actOpen) { openDoubleClickedFile(index); } else if (act == actOpenContainingFolder) { openFolder(index, true); } else if (act == actRename) { renameSelectedFile(); } else { int prio = prio::NORMAL; if (act == actionHigh) prio = prio::HIGH; else if (act == actionMaximum) prio = prio::MAXIMUM; else if (act == actionNot_downloaded) prio = prio::IGNORED; qDebug("Setting files priority"); foreach (QModelIndex index, selectedRows) { qDebug("Setting priority(%d) for file at row %d", prio, index.row()); PropListModel->setData(PropListModel->index(index.row(), PRIORITY, index.parent()), prio); } // Save changes filteredFilesChanged(); } } } void PropertiesWidget::displayWebSeedListMenu(const QPoint &) { if (!m_torrent) return; QMenu seedMenu; QModelIndexList rows = listWebSeeds->selectionModel()->selectedRows(); QAction *actAdd = seedMenu.addAction(GuiIconProvider::instance()->getIcon("list-add"), tr("New Web seed")); QAction *actDel = 0; QAction *actCpy = 0; QAction *actEdit = 0; if (rows.size()) { actDel = seedMenu.addAction(GuiIconProvider::instance()->getIcon("list-remove"), tr("Remove Web seed")); seedMenu.addSeparator(); actCpy = seedMenu.addAction(GuiIconProvider::instance()->getIcon("edit-copy"), tr("Copy Web seed URL")); actEdit = seedMenu.addAction(GuiIconProvider::instance()->getIcon("edit-rename"), tr("Edit Web seed URL")); } const QAction *act = seedMenu.exec(QCursor::pos()); if (act) { if (act == actAdd) askWebSeed(); else if (act == actDel) deleteSelectedUrlSeeds(); else if (act == actCpy) copySelectedWebSeedsToClipboard(); else if (act == actEdit) editWebSeed(); } } void PropertiesWidget::renameSelectedFile() { const QModelIndexList selectedIndexes = filesList->selectionModel()->selectedRows(0); if (selectedIndexes.size() != 1) return; const QModelIndex index = selectedIndexes.first(); if (!index.isValid()) return; // Ask for new name bool ok; QString new_name_last = AutoExpandableDialog::getText(this, tr("Rename the file"), tr("New name:"), QLineEdit::Normal, index.data().toString(), &ok).trimmed(); if (ok && !new_name_last.isEmpty()) { if (!Utils::Fs::isValidFileSystemName(new_name_last)) { MessageBoxRaised::warning(this, tr("The file could not be renamed"), tr("This file name contains forbidden characters, please choose a different one."), QMessageBox::Ok); return; } if (PropListModel->itemType(index) == TorrentContentModelItem::FileType) { // File renaming const int file_index = PropListModel->getFileIndex(index); if (!m_torrent || !m_torrent->hasMetadata()) return; QString old_name = m_torrent->filePath(file_index); if (old_name.endsWith(".!qB") && !new_name_last.endsWith(".!qB")) new_name_last += ".!qB"; QStringList path_items = old_name.split("/"); path_items.removeLast(); path_items << new_name_last; QString new_name = path_items.join("/"); if (Utils::Fs::sameFileNames(old_name, new_name)) { qDebug("Name did not change"); return; } new_name = Utils::Fs::expandPath(new_name); qDebug("New name: %s", qPrintable(new_name)); // Check if that name is already used for (int i = 0; i < m_torrent->filesCount(); ++i) { if (i == file_index) continue; if (Utils::Fs::sameFileNames(m_torrent->filePath(i), new_name)) { // Display error message MessageBoxRaised::warning(this, tr("The file could not be renamed"), tr("This name is already in use in this folder. Please use a different name."), QMessageBox::Ok); return; } } const bool force_recheck = QFile::exists(m_torrent->savePath(true) + "/" + new_name); qDebug("Renaming %s to %s", qPrintable(old_name), qPrintable(new_name)); m_torrent->renameFile(file_index, new_name); // Force recheck if (force_recheck) m_torrent->forceRecheck(); // Rename if torrent files model too if (new_name_last.endsWith(".!qB")) new_name_last.chop(4); PropListModel->setData(index, new_name_last); } else { // Folder renaming QStringList path_items; path_items << index.data().toString(); QModelIndex parent = PropListModel->parent(index); while (parent.isValid()) { path_items.prepend(parent.data().toString()); parent = PropListModel->parent(parent); } const QString old_path = path_items.join("/"); path_items.removeLast(); path_items << new_name_last; QString new_path = path_items.join("/"); if (Utils::Fs::sameFileNames(old_path, new_path)) { qDebug("Name did not change"); return; } if (!new_path.endsWith("/")) new_path += "/"; // Check for overwriting for (int i = 0; i < m_torrent->filesCount(); ++i) { const QString &current_name = m_torrent->filePath(i); #if defined(Q_OS_UNIX) || defined(Q_WS_QWS) if (current_name.startsWith(new_path, Qt::CaseSensitive)) { #else if (current_name.startsWith(new_path, Qt::CaseInsensitive)) { #endif QMessageBox::warning(this, tr("The folder could not be renamed"), tr("This name is already in use in this folder. Please use a different name."), QMessageBox::Ok); return; } } bool force_recheck = false; // Replace path in all files for (int i = 0; i < m_torrent->filesCount(); ++i) { const QString current_name = m_torrent->filePath(i); if (current_name.startsWith(old_path)) { QString new_name = current_name; new_name.replace(0, old_path.length(), new_path); if (!force_recheck && QDir(m_torrent->savePath(true)).exists(new_name)) force_recheck = true; new_name = Utils::Fs::expandPath(new_name); qDebug("Rename %s to %s", qPrintable(current_name), qPrintable(new_name)); m_torrent->renameFile(i, new_name); } } // Force recheck if (force_recheck) m_torrent->forceRecheck(); // Rename folder in torrent files model too PropListModel->setData(index, new_name_last); // Remove old folder const QDir old_folder(m_torrent->savePath(true) + "/" + old_path); int timeout = 10; while (!QDir().rmpath(old_folder.absolutePath()) && timeout > 0) { // FIXME: We should not sleep here (freezes the UI for 1 second) Utils::Misc::msleep(100); --timeout; } } } } void PropertiesWidget::openSelectedFile() { const QModelIndexList selectedIndexes = filesList->selectionModel()->selectedRows(0); if (selectedIndexes.size() != 1) return; openDoubleClickedFile(selectedIndexes.first()); } void PropertiesWidget::askWebSeed() { bool ok; // Ask user for a new url seed const QString url_seed = AutoExpandableDialog::getText(this, tr("New URL seed", "New HTTP source"), tr("New URL seed:"), QLineEdit::Normal, QString::fromUtf8("http://www."), &ok); if (!ok) return; qDebug("Adding %s web seed", qPrintable(url_seed)); if (!listWebSeeds->findItems(url_seed, Qt::MatchFixedString).empty()) { QMessageBox::warning(this, "qBittorrent", tr("This URL seed is already in the list."), QMessageBox::Ok); return; } if (m_torrent) m_torrent->addUrlSeeds(QList<QUrl>() << url_seed); // Refresh the seeds list loadUrlSeeds(); } void PropertiesWidget::deleteSelectedUrlSeeds() { const QList<QListWidgetItem *> selectedItems = listWebSeeds->selectedItems(); if (selectedItems.isEmpty()) return; QList<QUrl> urlSeeds; foreach (const QListWidgetItem *item, selectedItems) urlSeeds << item->text(); m_torrent->removeUrlSeeds(urlSeeds); // Refresh list loadUrlSeeds(); } void PropertiesWidget::copySelectedWebSeedsToClipboard() const { const QList<QListWidgetItem *> selected_items = listWebSeeds->selectedItems(); if (selected_items.isEmpty()) return; QStringList urls_to_copy; foreach (QListWidgetItem *item, selected_items) urls_to_copy << item->text(); QApplication::clipboard()->setText(urls_to_copy.join("\n")); } void PropertiesWidget::editWebSeed() { const QList<QListWidgetItem *> selected_items = listWebSeeds->selectedItems(); if (selected_items.size() != 1) return; const QListWidgetItem *selected_item = selected_items.last(); const QString old_seed = selected_item->text(); bool result; const QString new_seed = AutoExpandableDialog::getText(this, tr("Web seed editing"), tr("Web seed URL:"), QLineEdit::Normal, old_seed, &result); if (!result) return; if (!listWebSeeds->findItems(new_seed, Qt::MatchFixedString).empty()) { QMessageBox::warning(this, tr("qBittorrent"), tr("This URL seed is already in the list."), QMessageBox::Ok); return; } m_torrent->removeUrlSeeds(QList<QUrl>() << old_seed); m_torrent->addUrlSeeds(QList<QUrl>() << new_seed); loadUrlSeeds(); } bool PropertiesWidget::applyPriorities() { qDebug("Saving files priorities"); const QVector<int> priorities = PropListModel->model()->getFilePriorities(); // Prioritize the files qDebug("prioritize files: %d", priorities[0]); m_torrent->prioritizeFiles(priorities); return true; } void PropertiesWidget::filteredFilesChanged() { if (m_torrent) applyPriorities(); } void PropertiesWidget::filterText(const QString &filter) { PropListModel->setFilterRegExp(QRegExp(filter, Qt::CaseInsensitive, QRegExp::WildcardUnix)); if (filter.isEmpty()) { filesList->collapseAll(); filesList->expand(PropListModel->index(0, 0)); } else { filesList->expandAll(); } }
./CrossVul/dataset_final_sorted/CWE-79/cpp/bad_3200_5
crossvul-cpp_data_good_2407_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 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. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/wddx/ext_wddx.h" #include <string> #include <vector> namespace HPHP { WddxPacket::WddxPacket(const Variant& comment, bool manualPacket, bool sVar) : m_packetString(""), m_packetClosed(false), m_manualPacketCreation(manualPacket) { std::string header = "<header/>"; if (!comment.isNull() && !sVar) { std::string scomment = comment.toString().data(); header = "<header><comment>" + scomment + "</comment></header>"; } m_packetString = "<wddxPacket version='1.0'>" + header + "<data>"; if (m_manualPacketCreation) { m_packetString = m_packetString + "<struct>"; } } bool WddxPacket::add_var(const String& varName, bool hasVarTag) { VarEnv* v = g_context->getVarEnv(); if (!v) return false; Variant varVariant = *reinterpret_cast<Variant*>(v->lookup(varName.get())); return recursiveAddVar(varName, varVariant, hasVarTag); } std::string WddxPacket::packet_end() { if (!m_packetClosed) { if (m_manualPacketCreation) { m_packetString += "</struct>"; } m_packetString += "</data></wddxPacket>"; } m_packetClosed = true; return m_packetString; } bool WddxPacket::serialize_value(const Variant& varVariant) { return recursiveAddVar(empty_string_ref, varVariant, false); } bool WddxPacket::recursiveAddVar(const String& varName, const Variant& varVariant, bool hasVarTag) { bool isArray = varVariant.isArray(); bool isObject = varVariant.isObject(); if (isArray || isObject) { if (hasVarTag) { m_packetString += "<var name='"; m_packetString += varName.data(); m_packetString += "'>"; } Array varAsArray; Object varAsObject = varVariant.toObject(); if (isArray) varAsArray = varVariant.toArray(); if (isObject) varAsArray = varAsObject.toArray(); int length = varAsArray.length(); if (length > 0) { ArrayIter it = ArrayIter(varAsArray); if (it.first().isString()) isObject = true; if (isObject) { m_packetString += "<struct>"; if (!isArray) { m_packetString += "<var name='php_class_name'><string>"; m_packetString += varAsObject->o_getClassName().c_str(); m_packetString += "</string></var>"; } } else { m_packetString += "<array length='"; m_packetString += std::to_string(length); m_packetString += "'>"; } for (ArrayIter it(varAsArray); it; ++it) { Variant key = it.first(); Variant value = it.second(); recursiveAddVar(key.toString(), value, isObject); } if (isObject) { m_packetString += "</struct>"; } else { m_packetString += "</array>"; } } else { //empty object if (isObject) { m_packetString += "<struct>"; if (!isArray) { m_packetString += "<var name='php_class_name'><string>"; m_packetString += varAsObject->o_getClassName().c_str(); m_packetString += "</string></var>"; } m_packetString += "</struct>"; } } if (hasVarTag) { m_packetString += "</var>"; } return true; } std::string varType = getDataTypeString(varVariant.getType()).data(); if (!getWddxEncoded(varType, "", varName, false).empty()) { std::string varValue; if (varType.compare("boolean") == 0) { varValue = varVariant.toBoolean() ? "true" : "false"; } else { varValue = StringUtil::HtmlEncode(varVariant.toString(), StringUtil::QuoteStyle::Double, "UTF-8", false, false).toCppString(); } m_packetString += getWddxEncoded(varType, varValue, varName, hasVarTag); return true; } return false; } std::string WddxPacket::getWddxEncoded(const std::string& varType, const std::string& varValue, const String& varName, bool hasVarTag) { if (varType.compare("NULL") == 0) { return wrapValue("<null/>", "", "", varName, hasVarTag); } if (varType.compare("boolean") == 0) { return wrapValue("<boolean value='", "'/>", varValue, varName, hasVarTag); } if (varType.compare("integer") == 0 || varType.compare("double") == 0) { return wrapValue("<number>", "</number>", varValue, varName, hasVarTag); } if (varType.compare("string") == 0) { return wrapValue("<string>", "</string>", varValue, varName, hasVarTag); } return ""; } std::string WddxPacket::wrapValue(const std::string& start, const std::string& end, const std::string& varValue, const String& varName, bool hasVarTag) { std::string startVar = ""; std::string endVar = ""; if (hasVarTag) { startVar += "<var name='"; startVar += varName.data(); startVar += "'>"; endVar = "</var>"; } return startVar + start + varValue + end + endVar; } ////////////////////////////////////////////////////////////////////////////// // helpers void find_var_recursive(const TypedValue* tv, WddxPacket* wddxPacket) { if (tvIsString(tv)) { String var_name = tvCastToString(tv); wddxPacket->add_var(var_name, true); } if (tv->m_type == KindOfArray) { for (ArrayIter iter(tv->m_data.parr); iter; ++iter) { find_var_recursive(iter.secondRef().asTypedValue(), wddxPacket); } } } static TypedValue* add_vars_helper(ActRec* ar) { int start_index = 1; Resource packet_id = getArg<KindOfResource>(ar, 0); auto wddxPacket = packet_id.getTyped<WddxPacket>(); for (int i = start_index; i < ar->numArgs(); i++) { auto const tv = getArg(ar, i); find_var_recursive(tv, wddxPacket); } return arReturn(ar, true); } static TypedValue* serialize_vars_helper(ActRec* ar) { WddxPacket* wddxPacket = newres<WddxPacket>(empty_string_variant_ref, true, true); int start_index = 0; for (int i = start_index; i < ar->numArgs(); i++) { auto const tv = getArg(ar, i); find_var_recursive(tv, wddxPacket); } Variant packet = wddxPacket->packet_end(); return arReturn(ar, std::move(packet)); } ////////////////////////////////////////////////////////////////////////////// // functions static TypedValue* HHVM_FN(wddx_add_vars)(ActRec* ar) { return add_vars_helper(ar); } static TypedValue* HHVM_FN(wddx_serialize_vars)(ActRec* ar) { return serialize_vars_helper(ar); } static String HHVM_FUNCTION(wddx_packet_end, const Resource& packet_id) { auto wddxPacket = packet_id.getTyped<WddxPacket>(); std::string packetString = wddxPacket->packet_end(); return String(packetString); } static Resource HHVM_FUNCTION(wddx_packet_start, const Variant& comment) { auto wddxPacket = newres<WddxPacket>(comment, true, false); return Resource(wddxPacket); } static String HHVM_FUNCTION(wddx_serialize_value, const Variant& var, const Variant& comment) { WddxPacket* wddxPacket = newres<WddxPacket>(comment, false, false); wddxPacket->serialize_value(var); const std::string packetString = wddxPacket->packet_end(); return String(packetString); } ////////////////////////////////////////////////////////////////////////////// class wddxExtension : public Extension { public: wddxExtension() : Extension("wddx") {} virtual void moduleInit() { HHVM_FE(wddx_add_vars); HHVM_FE(wddx_packet_end); HHVM_FE(wddx_packet_start); HHVM_FE(wddx_serialize_value); HHVM_FE(wddx_serialize_vars); loadSystemlib(); } } s_wddx_extension; // Uncomment for non-bundled module //HHVM_GET_MODULE(wddx); ////////////////////////////////////////////////////////////////////////////// } // namespace HPHP
./CrossVul/dataset_final_sorted/CWE-79/cpp/good_2407_0
crossvul-cpp_data_bad_3200_4
/* * Bittorrent Client using Qt4 and libtorrent. * Copyright (C) 2006 Christophe Dumez * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * In addition, as a special exception, the copyright holders give permission to * link this program with the OpenSSL project's "OpenSSL" library (or with * modified versions of it that use the same license as the "OpenSSL" library), * and distribute the linked executables. 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), 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. * * Contact : chris@qbittorrent.org */ #include <QStandardItemModel> #include <QSortFilterProxyModel> #include <QSet> #include <QHeaderView> #include <QMenu> #include <QClipboard> #include <QMessageBox> #include <QWheelEvent> #ifdef QBT_USES_QT5 #include <QTableView> #endif #include "base/net/reverseresolution.h" #include "base/bittorrent/torrenthandle.h" #include "base/bittorrent/peerinfo.h" #include "base/preferences.h" #include "base/logger.h" #include "base/unicodestrings.h" #include "propertieswidget.h" #include "base/net/geoipmanager.h" #include "peersadditiondlg.h" #include "speedlimitdlg.h" #include "guiiconprovider.h" #include "peerlistdelegate.h" #include "peerlistsortmodel.h" #include "peerlistwidget.h" PeerListWidget::PeerListWidget(PropertiesWidget *parent) : QTreeView(parent) , m_properties(parent) { // Load settings loadSettings(); // Visual settings setUniformRowHeights(true); setRootIsDecorated(false); setItemsExpandable(false); setAllColumnsShowFocus(true); setSelectionMode(QAbstractItemView::ExtendedSelection); header()->setStretchLastSection(false); // List Model m_listModel = new QStandardItemModel(0, PeerListDelegate::COL_COUNT); m_listModel->setHeaderData(PeerListDelegate::COUNTRY, Qt::Horizontal, tr("Country")); // Country flag column m_listModel->setHeaderData(PeerListDelegate::IP, Qt::Horizontal, tr("IP")); m_listModel->setHeaderData(PeerListDelegate::PORT, Qt::Horizontal, tr("Port")); m_listModel->setHeaderData(PeerListDelegate::FLAGS, Qt::Horizontal, tr("Flags")); m_listModel->setHeaderData(PeerListDelegate::CONNECTION, Qt::Horizontal, tr("Connection")); m_listModel->setHeaderData(PeerListDelegate::CLIENT, Qt::Horizontal, tr("Client", "i.e.: Client application")); m_listModel->setHeaderData(PeerListDelegate::PROGRESS, Qt::Horizontal, tr("Progress", "i.e: % downloaded")); m_listModel->setHeaderData(PeerListDelegate::DOWN_SPEED, Qt::Horizontal, tr("Down Speed", "i.e: Download speed")); m_listModel->setHeaderData(PeerListDelegate::UP_SPEED, Qt::Horizontal, tr("Up Speed", "i.e: Upload speed")); m_listModel->setHeaderData(PeerListDelegate::TOT_DOWN, Qt::Horizontal, tr("Downloaded", "i.e: total data downloaded")); m_listModel->setHeaderData(PeerListDelegate::TOT_UP, Qt::Horizontal, tr("Uploaded", "i.e: total data uploaded")); m_listModel->setHeaderData(PeerListDelegate::RELEVANCE, Qt::Horizontal, tr("Relevance", "i.e: How relevant this peer is to us. How many pieces it has that we don't.")); m_listModel->setHeaderData(PeerListDelegate::DOWNLOADING_PIECE, Qt::Horizontal, tr("Files", "i.e. files that are being downloaded right now")); // Set header text alignment m_listModel->setHeaderData(PeerListDelegate::PORT, Qt::Horizontal, QVariant(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole); m_listModel->setHeaderData(PeerListDelegate::PROGRESS, Qt::Horizontal, QVariant(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole); m_listModel->setHeaderData(PeerListDelegate::DOWN_SPEED, Qt::Horizontal, QVariant(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole); m_listModel->setHeaderData(PeerListDelegate::UP_SPEED, Qt::Horizontal, QVariant(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole); m_listModel->setHeaderData(PeerListDelegate::TOT_DOWN, Qt::Horizontal, QVariant(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole); m_listModel->setHeaderData(PeerListDelegate::TOT_UP, Qt::Horizontal, QVariant(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole); m_listModel->setHeaderData(PeerListDelegate::RELEVANCE, Qt::Horizontal, QVariant(Qt::AlignRight | Qt::AlignVCenter), Qt::TextAlignmentRole); // Proxy model to support sorting without actually altering the underlying model m_proxyModel = new PeerListSortModel(); m_proxyModel->setDynamicSortFilter(true); m_proxyModel->setSourceModel(m_listModel); m_proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); setModel(m_proxyModel); hideColumn(PeerListDelegate::IP_HIDDEN); hideColumn(PeerListDelegate::COL_COUNT); m_resolveCountries = Preferences::instance()->resolvePeerCountries(); if (!m_resolveCountries) hideColumn(PeerListDelegate::COUNTRY); //Ensure that at least one column is visible at all times bool atLeastOne = false; for (unsigned int i = 0; i < PeerListDelegate::IP_HIDDEN; i++) { if (!isColumnHidden(i)) { atLeastOne = true; break; } } if (!atLeastOne) setColumnHidden(PeerListDelegate::IP, false); //To also mitigate the above issue, we have to resize each column when //its size is 0, because explicitly 'showing' the column isn't enough //in the above scenario. for (unsigned int i = 0; i < PeerListDelegate::IP_HIDDEN; i++) if ((columnWidth(i) <= 0) && !isColumnHidden(i)) resizeColumnToContents(i); // Context menu setContextMenuPolicy(Qt::CustomContextMenu); connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showPeerListMenu(QPoint))); // List delegate m_listDelegate = new PeerListDelegate(this); setItemDelegate(m_listDelegate); // Enable sorting setSortingEnabled(true); // IP to Hostname resolver updatePeerHostNameResolutionState(); // SIGNAL/SLOT header()->setContextMenuPolicy(Qt::CustomContextMenu); connect(header(), SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(displayToggleColumnsMenu(const QPoint &))); connect(header(), SIGNAL(sectionClicked(int)), SLOT(handleSortColumnChanged(int))); handleSortColumnChanged(header()->sortIndicatorSection()); m_copyHotkey = new QShortcut(QKeySequence::Copy, this, SLOT(copySelectedPeers()), 0, Qt::WidgetShortcut); #ifdef QBT_USES_QT5 // This hack fixes reordering of first column with Qt5. // https://github.com/qtproject/qtbase/commit/e0fc088c0c8bc61dbcaf5928b24986cd61a22777 QTableView unused; unused.setVerticalHeader(this->header()); this->header()->setParent(this); unused.setVerticalHeader(new QHeaderView(Qt::Horizontal)); #endif } PeerListWidget::~PeerListWidget() { saveSettings(); delete m_proxyModel; delete m_listModel; delete m_listDelegate; if (m_resolver) delete m_resolver; delete m_copyHotkey; } void PeerListWidget::displayToggleColumnsMenu(const QPoint&) { QMenu hideshowColumn(this); hideshowColumn.setTitle(tr("Column visibility")); QList<QAction*> actions; for (int i = 0; i < PeerListDelegate::IP_HIDDEN; ++i) { if ((i == PeerListDelegate::COUNTRY) && !Preferences::instance()->resolvePeerCountries()) { actions.append(nullptr); // keep the index in sync continue; } QAction *myAct = hideshowColumn.addAction(m_listModel->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString()); myAct->setCheckable(true); myAct->setChecked(!isColumnHidden(i)); actions.append(myAct); } int visibleCols = 0; for (unsigned int i = 0; i < PeerListDelegate::IP_HIDDEN; i++) { if (!isColumnHidden(i)) visibleCols++; if (visibleCols > 1) break; } // Call menu QAction *act = hideshowColumn.exec(QCursor::pos()); if (act) { int col = actions.indexOf(act); Q_ASSERT(col >= 0); Q_ASSERT(visibleCols > 0); if (!isColumnHidden(col) && (visibleCols == 1)) return; qDebug("Toggling column %d visibility", col); setColumnHidden(col, !isColumnHidden(col)); if (!isColumnHidden(col) && (columnWidth(col) <= 5)) setColumnWidth(col, 100); saveSettings(); } } void PeerListWidget::updatePeerHostNameResolutionState() { if (Preferences::instance()->resolvePeerHostNames()) { if (!m_resolver) { m_resolver = new Net::ReverseResolution(this); connect(m_resolver, SIGNAL(ipResolved(QString, QString)), SLOT(handleResolved(QString, QString))); loadPeers(m_properties->getCurrentTorrent(), true); } } else if (m_resolver) { delete m_resolver; } } void PeerListWidget::updatePeerCountryResolutionState() { if (Preferences::instance()->resolvePeerCountries() != m_resolveCountries) { m_resolveCountries = !m_resolveCountries; if (m_resolveCountries) { loadPeers(m_properties->getCurrentTorrent()); showColumn(PeerListDelegate::COUNTRY); if (columnWidth(PeerListDelegate::COUNTRY) <= 0) resizeColumnToContents(PeerListDelegate::COUNTRY); } else { hideColumn(PeerListDelegate::COUNTRY); } } } void PeerListWidget::showPeerListMenu(const QPoint&) { QMenu menu; bool emptyMenu = true; BitTorrent::TorrentHandle *const torrent = m_properties->getCurrentTorrent(); if (!torrent) return; // Add Peer Action QAction *addPeerAct = 0; if (!torrent->isQueued() && !torrent->isChecking()) { addPeerAct = menu.addAction(GuiIconProvider::instance()->getIcon("user-group-new"), tr("Add a new peer...")); emptyMenu = false; } QAction *banAct = 0; QAction *copyPeerAct = 0; if (!selectionModel()->selectedRows().isEmpty()) { copyPeerAct = menu.addAction(GuiIconProvider::instance()->getIcon("edit-copy"), tr("Copy IP:port")); menu.addSeparator(); banAct = menu.addAction(GuiIconProvider::instance()->getIcon("user-group-delete"), tr("Ban peer permanently")); emptyMenu = false; } if (emptyMenu) return; QAction *act = menu.exec(QCursor::pos()); if (act == 0) return; if (act == addPeerAct) { QList<BitTorrent::PeerAddress> peersList = PeersAdditionDlg::askForPeers(); int peerCount = 0; foreach (const BitTorrent::PeerAddress &addr, peersList) { if (torrent->connectPeer(addr)) { qDebug("Adding peer %s...", qPrintable(addr.ip.toString())); Logger::instance()->addMessage(tr("Manually adding peer '%1'...").arg(addr.ip.toString())); peerCount++; } else { Logger::instance()->addMessage(tr("The peer '%1' could not be added to this torrent.").arg(addr.ip.toString()), Log::WARNING); } } if (peerCount < peersList.length()) QMessageBox::information(0, tr("Peer addition"), tr("Some peers could not be added. Check the Log for details.")); else if (peerCount > 0) QMessageBox::information(0, tr("Peer addition"), tr("The peers were added to this torrent.")); return; } if (act == banAct) { banSelectedPeers(); return; } if (act == copyPeerAct) { copySelectedPeers(); return; } } void PeerListWidget::banSelectedPeers() { // Confirm first int ret = QMessageBox::question(this, tr("Ban peer permanently"), tr("Are you sure you want to ban permanently the selected peers?"), tr("&Yes"), tr("&No"), QString(), 0, 1); if (ret) return; QModelIndexList selectedIndexes = selectionModel()->selectedRows(); foreach (const QModelIndex &index, selectedIndexes) { int row = m_proxyModel->mapToSource(index).row(); QString ip = m_listModel->data(m_listModel->index(row, PeerListDelegate::IP_HIDDEN)).toString(); qDebug("Banning peer %s...", ip.toLocal8Bit().data()); Logger::instance()->addMessage(tr("Manually banning peer '%1'...").arg(ip)); BitTorrent::Session::instance()->banIP(ip); } // Refresh list loadPeers(m_properties->getCurrentTorrent()); } void PeerListWidget::copySelectedPeers() { QModelIndexList selectedIndexes = selectionModel()->selectedRows(); QStringList selectedPeers; foreach (const QModelIndex &index, selectedIndexes) { int row = m_proxyModel->mapToSource(index).row(); QString ip = m_listModel->data(m_listModel->index(row, PeerListDelegate::IP_HIDDEN)).toString(); QString myport = m_listModel->data(m_listModel->index(row, PeerListDelegate::PORT)).toString(); if (ip.indexOf(".") == -1) // IPv6 selectedPeers << "[" + ip + "]:" + myport; else // IPv4 selectedPeers << ip + ":" + myport; } QApplication::clipboard()->setText(selectedPeers.join("\n")); } void PeerListWidget::clear() { qDebug("clearing peer list"); m_peerItems.clear(); m_peerAddresses.clear(); m_missingFlags.clear(); int nbrows = m_listModel->rowCount(); if (nbrows > 0) { qDebug("Cleared %d peers", nbrows); m_listModel->removeRows(0, nbrows); } } void PeerListWidget::loadSettings() { header()->restoreState(Preferences::instance()->getPeerListState()); } void PeerListWidget::saveSettings() const { Preferences::instance()->setPeerListState(header()->saveState()); } void PeerListWidget::loadPeers(BitTorrent::TorrentHandle *const torrent, bool forceHostnameResolution) { if (!torrent) return; QList<BitTorrent::PeerInfo> peers = torrent->peers(); QSet<QString> oldeersSet = m_peerItems.keys().toSet(); foreach (const BitTorrent::PeerInfo &peer, peers) { BitTorrent::PeerAddress addr = peer.address(); if (addr.ip.isNull()) continue; QString peerIp = addr.ip.toString(); if (m_peerItems.contains(peerIp)) { // Update existing peer updatePeer(peerIp, torrent, peer); oldeersSet.remove(peerIp); if (forceHostnameResolution && m_resolver) m_resolver->resolve(peerIp); } else { // Add new peer m_peerItems[peerIp] = addPeer(peerIp, torrent, peer); m_peerAddresses[peerIp] = addr; // Resolve peer host name is asked if (m_resolver) m_resolver->resolve(peerIp); } } // Delete peers that are gone QSetIterator<QString> it(oldeersSet); while (it.hasNext()) { const QString& ip = it.next(); m_missingFlags.remove(ip); m_peerAddresses.remove(ip); QStandardItem *item = m_peerItems.take(ip); m_listModel->removeRow(item->row()); } } QStandardItem* PeerListWidget::addPeer(const QString& ip, BitTorrent::TorrentHandle *const torrent, const BitTorrent::PeerInfo &peer) { int row = m_listModel->rowCount(); // Adding Peer to peer list m_listModel->insertRow(row); m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP), ip); m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP), ip, Qt::ToolTipRole); m_listModel->setData(m_listModel->index(row, PeerListDelegate::PORT), peer.address().port); m_listModel->setData(m_listModel->index(row, PeerListDelegate::IP_HIDDEN), ip); if (m_resolveCountries) { const QIcon ico = GuiIconProvider::instance()->getFlagIcon(peer.country()); if (!ico.isNull()) { m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), ico, Qt::DecorationRole); const QString countryName = Net::GeoIPManager::CountryName(peer.country()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), countryName, Qt::ToolTipRole); } else { m_missingFlags.insert(ip); } } m_listModel->setData(m_listModel->index(row, PeerListDelegate::CONNECTION), peer.connectionType()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flags()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flagsDescription(), Qt::ToolTipRole); m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), peer.client()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::PROGRESS), peer.progress()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWN_SPEED), peer.payloadDownSpeed()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::UP_SPEED), peer.payloadUpSpeed()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_DOWN), peer.totalDownload()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_UP), peer.totalUpload()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::RELEVANCE), peer.relevance()); QStringList downloadingFiles(torrent->info().filesForPiece(peer.downloadingPieceIndex())); m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(";"))); m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String("\n")), Qt::ToolTipRole); return m_listModel->item(row, PeerListDelegate::IP); } void PeerListWidget::updatePeer(const QString &ip, BitTorrent::TorrentHandle *const torrent, const BitTorrent::PeerInfo &peer) { QStandardItem *item = m_peerItems.value(ip); int row = item->row(); if (m_resolveCountries) { const QIcon ico = GuiIconProvider::instance()->getFlagIcon(peer.country()); if (!ico.isNull()) { m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), ico, Qt::DecorationRole); const QString countryName = Net::GeoIPManager::CountryName(peer.country()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::COUNTRY), countryName, Qt::ToolTipRole); m_missingFlags.remove(ip); } } m_listModel->setData(m_listModel->index(row, PeerListDelegate::CONNECTION), peer.connectionType()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::PORT), peer.address().port); m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flags()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::FLAGS), peer.flagsDescription(), Qt::ToolTipRole); m_listModel->setData(m_listModel->index(row, PeerListDelegate::CLIENT), peer.client()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::PROGRESS), peer.progress()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWN_SPEED), peer.payloadDownSpeed()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::UP_SPEED), peer.payloadUpSpeed()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_DOWN), peer.totalDownload()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::TOT_UP), peer.totalUpload()); m_listModel->setData(m_listModel->index(row, PeerListDelegate::RELEVANCE), peer.relevance()); QStringList downloadingFiles(torrent->info().filesForPiece(peer.downloadingPieceIndex())); m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String(";"))); m_listModel->setData(m_listModel->index(row, PeerListDelegate::DOWNLOADING_PIECE), downloadingFiles.join(QLatin1String("\n")), Qt::ToolTipRole); } void PeerListWidget::handleResolved(const QString &ip, const QString &hostname) { QStandardItem *item = m_peerItems.value(ip, 0); if (item) { qDebug("Resolved %s -> %s", qPrintable(ip), qPrintable(hostname)); item->setData(hostname, Qt::DisplayRole); } } void PeerListWidget::handleSortColumnChanged(int col) { if (col == PeerListDelegate::COUNTRY) { qDebug("Sorting by decoration"); m_proxyModel->setSortRole(Qt::ToolTipRole); } else { m_proxyModel->setSortRole(Qt::DisplayRole); } } void PeerListWidget::wheelEvent(QWheelEvent *event) { event->accept(); if(event->modifiers() & Qt::ShiftModifier) { // Shift + scroll = horizontal scroll QWheelEvent scrollHEvent(event->pos(), event->globalPos(), event->delta(), event->buttons(), event->modifiers(), Qt::Horizontal); QTreeView::wheelEvent(&scrollHEvent); return; } QTreeView::wheelEvent(event); // event delegated to base class }
./CrossVul/dataset_final_sorted/CWE-79/cpp/bad_3200_4
crossvul-cpp_data_bad_2407_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-79/cpp/bad_2407_0
crossvul-cpp_data_bad_384_0
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | 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. | +----------------------------------------------------------------------+ | Authors: Sascha Schumann <sascha@schumann.cx> | | Parts based on Apache 1.3 SAPI module by | | Rasmus Lerdorf and Zeev Suraski | +----------------------------------------------------------------------+ */ /* $Id$ */ #define ZEND_INCLUDE_FULL_WINDOWS_HEADERS #include "php.h" #include "php_main.h" #include "php_ini.h" #include "php_variables.h" #include "SAPI.h" #include <fcntl.h> #include "ext/standard/php_smart_str.h" #ifndef NETWARE #include "ext/standard/php_standard.h" #else #include "ext/standard/basic_functions.h" #endif #include "apr_strings.h" #include "ap_config.h" #include "util_filter.h" #include "httpd.h" #include "http_config.h" #include "http_request.h" #include "http_core.h" #include "http_protocol.h" #include "http_log.h" #include "http_main.h" #include "util_script.h" #include "http_core.h" #include "ap_mpm.h" #include "php_apache.h" #ifdef PHP_WIN32 # if _MSC_VER <= 1300 # include "win32/php_strtoi64.h" # endif #endif /* UnixWare and Netware define shutdown to _shutdown, which causes problems later * on when using a structure member named shutdown. Since this source * file does not use the system call shutdown, it is safe to #undef it.K */ #undef shutdown #define PHP_MAGIC_TYPE "application/x-httpd-php" #define PHP_SOURCE_MAGIC_TYPE "application/x-httpd-php-source" #define PHP_SCRIPT "php5-script" /* A way to specify the location of the php.ini dir in an apache directive */ char *apache2_php_ini_path_override = NULL; static int php_apache_sapi_ub_write(const char *str, uint str_length TSRMLS_DC) { request_rec *r; php_struct *ctx; ctx = SG(server_context); r = ctx->r; if (ap_rwrite(str, str_length, r) < 0) { php_handle_aborted_connection(); } return str_length; /* we always consume all the data passed to us. */ } static int php_apache_sapi_header_handler(sapi_header_struct *sapi_header, sapi_header_op_enum op, sapi_headers_struct *sapi_headers TSRMLS_DC) { php_struct *ctx; char *val, *ptr; ctx = SG(server_context); switch (op) { case SAPI_HEADER_DELETE: apr_table_unset(ctx->r->headers_out, sapi_header->header); return 0; case SAPI_HEADER_DELETE_ALL: apr_table_clear(ctx->r->headers_out); return 0; case SAPI_HEADER_ADD: case SAPI_HEADER_REPLACE: val = strchr(sapi_header->header, ':'); if (!val) { return 0; } ptr = val; *val = '\0'; do { val++; } while (*val == ' '); if (!strcasecmp(sapi_header->header, "content-type")) { if (ctx->content_type) { efree(ctx->content_type); } ctx->content_type = estrdup(val); } else if (!strcasecmp(sapi_header->header, "content-length")) { apr_off_t clen = 0; if (APR_SUCCESS != apr_strtoff(&clen, val, (char **) NULL, 10)) { /* We'll fall back to strtol, since that's what we used to * do anyway. */ clen = (apr_off_t) strtol(val, (char **) NULL, 10); } ap_set_content_length(ctx->r, clen); } else if (op == SAPI_HEADER_REPLACE) { apr_table_set(ctx->r->headers_out, sapi_header->header, val); } else { apr_table_add(ctx->r->headers_out, sapi_header->header, val); } *ptr = ':'; return SAPI_HEADER_ADD; default: return 0; } } static int php_apache_sapi_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC) { php_struct *ctx = SG(server_context); const char *sline = SG(sapi_headers).http_status_line; ctx->r->status = SG(sapi_headers).http_response_code; /* httpd requires that r->status_line is set to the first digit of * the status-code: */ if (sline && strlen(sline) > 12 && strncmp(sline, "HTTP/1.", 7) == 0 && sline[8] == ' ') { ctx->r->status_line = apr_pstrdup(ctx->r->pool, sline + 9); ctx->r->proto_num = 1000 + (sline[7]-'0'); if ((sline[7]-'0') == 0) { apr_table_set(ctx->r->subprocess_env, "force-response-1.0", "true"); } } /* call ap_set_content_type only once, else each time we call it, configured output filters for that content type will be added */ if (!ctx->content_type) { ctx->content_type = sapi_get_default_content_type(TSRMLS_C); } ap_set_content_type(ctx->r, apr_pstrdup(ctx->r->pool, ctx->content_type)); efree(ctx->content_type); ctx->content_type = NULL; return SAPI_HEADER_SENT_SUCCESSFULLY; } static int php_apache_sapi_read_post(char *buf, uint count_bytes TSRMLS_DC) { apr_size_t len, tlen=0; php_struct *ctx = SG(server_context); request_rec *r; apr_bucket_brigade *brigade; r = ctx->r; brigade = ctx->brigade; len = count_bytes; /* * This loop is needed because ap_get_brigade() can return us partial data * which would cause premature termination of request read. Therefor we * need to make sure that if data is available we fill the buffer completely. */ while (ap_get_brigade(r->input_filters, brigade, AP_MODE_READBYTES, APR_BLOCK_READ, len) == APR_SUCCESS) { apr_brigade_flatten(brigade, buf, &len); apr_brigade_cleanup(brigade); tlen += len; if (tlen == count_bytes || !len) { break; } buf += len; len = count_bytes - tlen; } return tlen; } static struct stat* php_apache_sapi_get_stat(TSRMLS_D) { php_struct *ctx = SG(server_context); ctx->finfo.st_uid = ctx->r->finfo.user; ctx->finfo.st_gid = ctx->r->finfo.group; ctx->finfo.st_dev = ctx->r->finfo.device; ctx->finfo.st_ino = ctx->r->finfo.inode; #if defined(NETWARE) && defined(CLIB_STAT_PATCH) ctx->finfo.st_atime.tv_sec = apr_time_sec(ctx->r->finfo.atime); ctx->finfo.st_mtime.tv_sec = apr_time_sec(ctx->r->finfo.mtime); ctx->finfo.st_ctime.tv_sec = apr_time_sec(ctx->r->finfo.ctime); #else ctx->finfo.st_atime = apr_time_sec(ctx->r->finfo.atime); ctx->finfo.st_mtime = apr_time_sec(ctx->r->finfo.mtime); ctx->finfo.st_ctime = apr_time_sec(ctx->r->finfo.ctime); #endif ctx->finfo.st_size = ctx->r->finfo.size; ctx->finfo.st_nlink = ctx->r->finfo.nlink; return &ctx->finfo; } static char * php_apache_sapi_read_cookies(TSRMLS_D) { php_struct *ctx = SG(server_context); const char *http_cookie; http_cookie = apr_table_get(ctx->r->headers_in, "cookie"); /* The SAPI interface should use 'const char *' */ return (char *) http_cookie; } static char * php_apache_sapi_getenv(char *name, size_t name_len TSRMLS_DC) { php_struct *ctx = SG(server_context); const char *env_var; if (ctx == NULL) { return NULL; } env_var = apr_table_get(ctx->r->subprocess_env, name); return (char *) env_var; } static void php_apache_sapi_register_variables(zval *track_vars_array TSRMLS_DC) { php_struct *ctx = SG(server_context); const apr_array_header_t *arr = apr_table_elts(ctx->r->subprocess_env); char *key, *val; int new_val_len; APR_ARRAY_FOREACH_OPEN(arr, key, val) if (!val) { val = ""; } if (sapi_module.input_filter(PARSE_SERVER, key, &val, strlen(val), (unsigned int *)&new_val_len TSRMLS_CC)) { php_register_variable_safe(key, val, new_val_len, track_vars_array TSRMLS_CC); } APR_ARRAY_FOREACH_CLOSE() if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &ctx->r->uri, strlen(ctx->r->uri), (unsigned int *)&new_val_len TSRMLS_CC)) { php_register_variable_safe("PHP_SELF", ctx->r->uri, new_val_len, track_vars_array TSRMLS_CC); } } static void php_apache_sapi_flush(void *server_context) { php_struct *ctx; request_rec *r; TSRMLS_FETCH(); ctx = server_context; /* If we haven't registered a server_context yet, * then don't bother flushing. */ if (!server_context) { return; } r = ctx->r; sapi_send_headers(TSRMLS_C); r->status = SG(sapi_headers).http_response_code; SG(headers_sent) = 1; if (ap_rflush(r) < 0 || r->connection->aborted) { php_handle_aborted_connection(); } } static void php_apache_sapi_log_message(char *msg TSRMLS_DC) { php_struct *ctx; ctx = SG(server_context); if (ctx == NULL) { /* we haven't initialized our ctx yet, oh well */ ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, 0, NULL, "%s", msg); } else { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, ctx->r, "%s", msg); } } static void php_apache_sapi_log_message_ex(char *msg, request_rec *r TSRMLS_DC) { if (r) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, msg, r->filename); } else { php_apache_sapi_log_message(msg TSRMLS_CC); } } static double php_apache_sapi_get_request_time(TSRMLS_D) { php_struct *ctx = SG(server_context); return ((double) apr_time_as_msec(ctx->r->request_time)) / 1000.0; } extern zend_module_entry php_apache_module; static int php_apache2_startup(sapi_module_struct *sapi_module) { if (php_module_startup(sapi_module, &php_apache_module, 1)==FAILURE) { return FAILURE; } return SUCCESS; } static sapi_module_struct apache2_sapi_module = { "apache2handler", "Apache 2.0 Handler", php_apache2_startup, /* startup */ php_module_shutdown_wrapper, /* shutdown */ NULL, /* activate */ NULL, /* deactivate */ php_apache_sapi_ub_write, /* unbuffered write */ php_apache_sapi_flush, /* flush */ php_apache_sapi_get_stat, /* get uid */ php_apache_sapi_getenv, /* getenv */ php_error, /* error handler */ php_apache_sapi_header_handler, /* header handler */ php_apache_sapi_send_headers, /* send headers handler */ NULL, /* send header handler */ php_apache_sapi_read_post, /* read POST data */ php_apache_sapi_read_cookies, /* read Cookies */ php_apache_sapi_register_variables, php_apache_sapi_log_message, /* Log message */ php_apache_sapi_get_request_time, /* Request Time */ NULL, /* Child Terminate */ STANDARD_SAPI_MODULE_PROPERTIES }; static apr_status_t php_apache_server_shutdown(void *tmp) { apache2_sapi_module.shutdown(&apache2_sapi_module); sapi_shutdown(); #ifdef ZTS tsrm_shutdown(); #endif return APR_SUCCESS; } static apr_status_t php_apache_child_shutdown(void *tmp) { apache2_sapi_module.shutdown(&apache2_sapi_module); #if defined(ZTS) && !defined(PHP_WIN32) tsrm_shutdown(); #endif return APR_SUCCESS; } static void php_apache_add_version(apr_pool_t *p) { TSRMLS_FETCH(); if (PG(expose_php)) { ap_add_version_component(p, "PHP/" PHP_VERSION); } } static int php_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp) { #ifndef ZTS int threaded_mpm; ap_mpm_query(AP_MPMQ_IS_THREADED, &threaded_mpm); if(threaded_mpm) { ap_log_error(APLOG_MARK, APLOG_CRIT, 0, 0, "Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe. You need to recompile PHP."); return DONE; } #endif /* When this is NULL, apache won't override the hard-coded default * php.ini path setting. */ apache2_php_ini_path_override = NULL; return OK; } static int php_apache_server_startup(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) { void *data = NULL; const char *userdata_key = "apache2hook_post_config"; /* Apache will load, unload and then reload a DSO module. This * prevents us from starting PHP until the second load. */ apr_pool_userdata_get(&data, userdata_key, s->process->pool); if (data == NULL) { /* We must use set() here and *not* setn(), otherwise the * static string pointed to by userdata_key will be mapped * to a different location when the DSO is reloaded and the * pointers won't match, causing get() to return NULL when * we expected it to return non-NULL. */ apr_pool_userdata_set((const void *)1, userdata_key, apr_pool_cleanup_null, s->process->pool); return OK; } /* Set up our overridden path. */ if (apache2_php_ini_path_override) { apache2_sapi_module.php_ini_path_override = apache2_php_ini_path_override; } #ifdef ZTS tsrm_startup(1, 1, 0, NULL); #endif sapi_startup(&apache2_sapi_module); apache2_sapi_module.startup(&apache2_sapi_module); apr_pool_cleanup_register(pconf, NULL, php_apache_server_shutdown, apr_pool_cleanup_null); php_apache_add_version(pconf); return OK; } static apr_status_t php_server_context_cleanup(void *data_) { void **data = data_; *data = NULL; return APR_SUCCESS; } static int php_apache_request_ctor(request_rec *r, php_struct *ctx TSRMLS_DC) { char *content_length; const char *auth; SG(sapi_headers).http_response_code = !r->status ? HTTP_OK : r->status; SG(request_info).content_type = apr_table_get(r->headers_in, "Content-Type"); SG(request_info).query_string = apr_pstrdup(r->pool, r->args); SG(request_info).request_method = r->method; SG(request_info).proto_num = r->proto_num; SG(request_info).request_uri = apr_pstrdup(r->pool, r->uri); SG(request_info).path_translated = apr_pstrdup(r->pool, r->filename); r->no_local_copy = 1; content_length = (char *) apr_table_get(r->headers_in, "Content-Length"); SG(request_info).content_length = (content_length ? atol(content_length) : 0); apr_table_unset(r->headers_out, "Content-Length"); apr_table_unset(r->headers_out, "Last-Modified"); apr_table_unset(r->headers_out, "Expires"); apr_table_unset(r->headers_out, "ETag"); auth = apr_table_get(r->headers_in, "Authorization"); php_handle_auth_data(auth TSRMLS_CC); if (SG(request_info).auth_user == NULL && r->user) { SG(request_info).auth_user = estrdup(r->user); } ctx->r->user = apr_pstrdup(ctx->r->pool, SG(request_info).auth_user); return php_request_startup(TSRMLS_C); } static void php_apache_request_dtor(request_rec *r TSRMLS_DC) { php_request_shutdown(NULL); } static void php_apache_ini_dtor(request_rec *r, request_rec *p TSRMLS_DC) { if (strcmp(r->protocol, "INCLUDED")) { zend_try { zend_ini_deactivate(TSRMLS_C); } zend_end_try(); } else { typedef struct { HashTable config; } php_conf_rec; char *str; uint str_len; php_conf_rec *c = ap_get_module_config(r->per_dir_config, &php5_module); for (zend_hash_internal_pointer_reset(&c->config); zend_hash_get_current_key_ex(&c->config, &str, &str_len, NULL, 0, NULL) == HASH_KEY_IS_STRING; zend_hash_move_forward(&c->config) ) { zend_restore_ini_entry(str, str_len, ZEND_INI_STAGE_SHUTDOWN); } } if (p) { ((php_struct *)SG(server_context))->r = p; } else { apr_pool_cleanup_run(r->pool, (void *)&SG(server_context), php_server_context_cleanup); } } static int php_handler(request_rec *r) { php_struct * volatile ctx; void *conf; apr_bucket_brigade * volatile brigade; apr_bucket *bucket; apr_status_t rv; request_rec * volatile parent_req = NULL; TSRMLS_FETCH(); #define PHPAP_INI_OFF php_apache_ini_dtor(r, parent_req TSRMLS_CC); conf = ap_get_module_config(r->per_dir_config, &php5_module); /* apply_config() needs r in some cases, so allocate server_context early */ ctx = SG(server_context); if (ctx == NULL || (ctx && ctx->request_processed && !strcmp(r->protocol, "INCLUDED"))) { normal: ctx = SG(server_context) = apr_pcalloc(r->pool, sizeof(*ctx)); /* register a cleanup so we clear out the SG(server_context) * after each request. Note: We pass in the pointer to the * server_context in case this is handled by a different thread. */ apr_pool_cleanup_register(r->pool, (void *)&SG(server_context), php_server_context_cleanup, apr_pool_cleanup_null); ctx->r = r; ctx = NULL; /* May look weird to null it here, but it is to catch the right case in the first_try later on */ } else { parent_req = ctx->r; ctx->r = r; } apply_config(conf); if (strcmp(r->handler, PHP_MAGIC_TYPE) && strcmp(r->handler, PHP_SOURCE_MAGIC_TYPE) && strcmp(r->handler, PHP_SCRIPT)) { /* Check for xbithack in this case. */ if (!AP2(xbithack) || strcmp(r->handler, "text/html") || !(r->finfo.protection & APR_UEXECUTE)) { PHPAP_INI_OFF; return DECLINED; } } /* Give a 404 if PATH_INFO is used but is explicitly disabled in * the configuration; default behaviour is to accept. */ if (r->used_path_info == AP_REQ_REJECT_PATH_INFO && r->path_info && r->path_info[0]) { PHPAP_INI_OFF; return HTTP_NOT_FOUND; } /* handle situations where user turns the engine off */ if (!AP2(engine)) { PHPAP_INI_OFF; return DECLINED; } if (r->finfo.filetype == 0) { php_apache_sapi_log_message_ex("script '%s' not found or unable to stat", r TSRMLS_CC); PHPAP_INI_OFF; return HTTP_NOT_FOUND; } if (r->finfo.filetype == APR_DIR) { php_apache_sapi_log_message_ex("attempt to invoke directory '%s' as script", r TSRMLS_CC); PHPAP_INI_OFF; return HTTP_FORBIDDEN; } /* Setup the CGI variables if this is the main request */ if (r->main == NULL || /* .. or if the sub-request environment differs from the main-request. */ r->subprocess_env != r->main->subprocess_env ) { /* setup standard CGI variables */ ap_add_common_vars(r); ap_add_cgi_vars(r); } zend_first_try { if (ctx == NULL) { brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc); ctx = SG(server_context); ctx->brigade = brigade; if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) { zend_bailout(); } } else { if (!parent_req) { parent_req = ctx->r; } if (parent_req && parent_req->handler && strcmp(parent_req->handler, PHP_MAGIC_TYPE) && strcmp(parent_req->handler, PHP_SOURCE_MAGIC_TYPE) && strcmp(parent_req->handler, PHP_SCRIPT)) { if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) { zend_bailout(); } } /* * check if coming due to ErrorDocument * We make a special exception of 413 (Invalid POST request) as the invalidity of the request occurs * during processing of the request by PHP during POST processing. Therefor we need to re-use the exiting * PHP instance to handle the request rather then creating a new one. */ if (parent_req && parent_req->status != HTTP_OK && parent_req->status != 413 && strcmp(r->protocol, "INCLUDED")) { parent_req = NULL; goto normal; } ctx->r = r; brigade = ctx->brigade; } if (AP2(last_modified)) { ap_update_mtime(r, r->finfo.mtime); ap_set_last_modified(r); } /* Determine if we need to parse the file or show the source */ if (strncmp(r->handler, PHP_SOURCE_MAGIC_TYPE, sizeof(PHP_SOURCE_MAGIC_TYPE) - 1) == 0) { zend_syntax_highlighter_ini syntax_highlighter_ini; php_get_highlight_struct(&syntax_highlighter_ini); highlight_file((char *)r->filename, &syntax_highlighter_ini TSRMLS_CC); } else { zend_file_handle zfd; zfd.type = ZEND_HANDLE_FILENAME; zfd.filename = (char *) r->filename; zfd.free_filename = 0; zfd.opened_path = NULL; if (!parent_req) { php_execute_script(&zfd TSRMLS_CC); } else { zend_execute_scripts(ZEND_INCLUDE TSRMLS_CC, NULL, 1, &zfd); } apr_table_set(r->notes, "mod_php_memory_usage", apr_psprintf(ctx->r->pool, "%" APR_SIZE_T_FMT, zend_memory_peak_usage(1 TSRMLS_CC))); } } zend_end_try(); if (!parent_req) { php_apache_request_dtor(r TSRMLS_CC); ctx->request_processed = 1; bucket = apr_bucket_eos_create(r->connection->bucket_alloc); APR_BRIGADE_INSERT_TAIL(brigade, bucket); rv = ap_pass_brigade(r->output_filters, brigade); if (rv != APR_SUCCESS || r->connection->aborted) { zend_first_try { php_handle_aborted_connection(); } zend_end_try(); } apr_brigade_cleanup(brigade); apr_pool_cleanup_run(r->pool, (void *)&SG(server_context), php_server_context_cleanup); } else { ctx->r = parent_req; } return OK; } static void php_apache_child_init(apr_pool_t *pchild, server_rec *s) { apr_pool_cleanup_register(pchild, NULL, php_apache_child_shutdown, apr_pool_cleanup_null); } void php_ap2_register_hook(apr_pool_t *p) { ap_hook_pre_config(php_pre_config, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_post_config(php_apache_server_startup, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_handler(php_handler, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_child_init(php_apache_child_init, NULL, NULL, APR_HOOK_MIDDLE); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-79/c/bad_384_0
crossvul-cpp_data_good_384_0
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | 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. | +----------------------------------------------------------------------+ | Authors: Sascha Schumann <sascha@schumann.cx> | | Parts based on Apache 1.3 SAPI module by | | Rasmus Lerdorf and Zeev Suraski | +----------------------------------------------------------------------+ */ /* $Id$ */ #define ZEND_INCLUDE_FULL_WINDOWS_HEADERS #include "php.h" #include "php_main.h" #include "php_ini.h" #include "php_variables.h" #include "SAPI.h" #include <fcntl.h> #include "ext/standard/php_smart_str.h" #ifndef NETWARE #include "ext/standard/php_standard.h" #else #include "ext/standard/basic_functions.h" #endif #include "apr_strings.h" #include "ap_config.h" #include "util_filter.h" #include "httpd.h" #include "http_config.h" #include "http_request.h" #include "http_core.h" #include "http_protocol.h" #include "http_log.h" #include "http_main.h" #include "util_script.h" #include "http_core.h" #include "ap_mpm.h" #include "php_apache.h" #ifdef PHP_WIN32 # if _MSC_VER <= 1300 # include "win32/php_strtoi64.h" # endif #endif /* UnixWare and Netware define shutdown to _shutdown, which causes problems later * on when using a structure member named shutdown. Since this source * file does not use the system call shutdown, it is safe to #undef it.K */ #undef shutdown #define PHP_MAGIC_TYPE "application/x-httpd-php" #define PHP_SOURCE_MAGIC_TYPE "application/x-httpd-php-source" #define PHP_SCRIPT "php5-script" /* A way to specify the location of the php.ini dir in an apache directive */ char *apache2_php_ini_path_override = NULL; static int php_apache_sapi_ub_write(const char *str, uint str_length TSRMLS_DC) { request_rec *r; php_struct *ctx; ctx = SG(server_context); r = ctx->r; if (ap_rwrite(str, str_length, r) < 0) { php_handle_aborted_connection(); } return str_length; /* we always consume all the data passed to us. */ } static int php_apache_sapi_header_handler(sapi_header_struct *sapi_header, sapi_header_op_enum op, sapi_headers_struct *sapi_headers TSRMLS_DC) { php_struct *ctx; char *val, *ptr; ctx = SG(server_context); switch (op) { case SAPI_HEADER_DELETE: apr_table_unset(ctx->r->headers_out, sapi_header->header); return 0; case SAPI_HEADER_DELETE_ALL: apr_table_clear(ctx->r->headers_out); return 0; case SAPI_HEADER_ADD: case SAPI_HEADER_REPLACE: val = strchr(sapi_header->header, ':'); if (!val) { return 0; } ptr = val; *val = '\0'; do { val++; } while (*val == ' '); if (!strcasecmp(sapi_header->header, "content-type")) { if (ctx->content_type) { efree(ctx->content_type); } ctx->content_type = estrdup(val); } else if (!strcasecmp(sapi_header->header, "content-length")) { apr_off_t clen = 0; if (APR_SUCCESS != apr_strtoff(&clen, val, (char **) NULL, 10)) { /* We'll fall back to strtol, since that's what we used to * do anyway. */ clen = (apr_off_t) strtol(val, (char **) NULL, 10); } ap_set_content_length(ctx->r, clen); } else if (op == SAPI_HEADER_REPLACE) { apr_table_set(ctx->r->headers_out, sapi_header->header, val); } else { apr_table_add(ctx->r->headers_out, sapi_header->header, val); } *ptr = ':'; return SAPI_HEADER_ADD; default: return 0; } } static int php_apache_sapi_send_headers(sapi_headers_struct *sapi_headers TSRMLS_DC) { php_struct *ctx = SG(server_context); const char *sline = SG(sapi_headers).http_status_line; ctx->r->status = SG(sapi_headers).http_response_code; /* httpd requires that r->status_line is set to the first digit of * the status-code: */ if (sline && strlen(sline) > 12 && strncmp(sline, "HTTP/1.", 7) == 0 && sline[8] == ' ') { ctx->r->status_line = apr_pstrdup(ctx->r->pool, sline + 9); ctx->r->proto_num = 1000 + (sline[7]-'0'); if ((sline[7]-'0') == 0) { apr_table_set(ctx->r->subprocess_env, "force-response-1.0", "true"); } } /* call ap_set_content_type only once, else each time we call it, configured output filters for that content type will be added */ if (!ctx->content_type) { ctx->content_type = sapi_get_default_content_type(TSRMLS_C); } ap_set_content_type(ctx->r, apr_pstrdup(ctx->r->pool, ctx->content_type)); efree(ctx->content_type); ctx->content_type = NULL; return SAPI_HEADER_SENT_SUCCESSFULLY; } static int php_apache_sapi_read_post(char *buf, uint count_bytes TSRMLS_DC) { apr_size_t len, tlen=0; php_struct *ctx = SG(server_context); request_rec *r; apr_bucket_brigade *brigade; r = ctx->r; brigade = ctx->brigade; len = count_bytes; /* * This loop is needed because ap_get_brigade() can return us partial data * which would cause premature termination of request read. Therefor we * need to make sure that if data is available we fill the buffer completely. */ while (ap_get_brigade(r->input_filters, brigade, AP_MODE_READBYTES, APR_BLOCK_READ, len) == APR_SUCCESS) { apr_brigade_flatten(brigade, buf, &len); apr_brigade_cleanup(brigade); tlen += len; if (tlen == count_bytes || !len) { break; } buf += len; len = count_bytes - tlen; } return tlen; } static struct stat* php_apache_sapi_get_stat(TSRMLS_D) { php_struct *ctx = SG(server_context); ctx->finfo.st_uid = ctx->r->finfo.user; ctx->finfo.st_gid = ctx->r->finfo.group; ctx->finfo.st_dev = ctx->r->finfo.device; ctx->finfo.st_ino = ctx->r->finfo.inode; #if defined(NETWARE) && defined(CLIB_STAT_PATCH) ctx->finfo.st_atime.tv_sec = apr_time_sec(ctx->r->finfo.atime); ctx->finfo.st_mtime.tv_sec = apr_time_sec(ctx->r->finfo.mtime); ctx->finfo.st_ctime.tv_sec = apr_time_sec(ctx->r->finfo.ctime); #else ctx->finfo.st_atime = apr_time_sec(ctx->r->finfo.atime); ctx->finfo.st_mtime = apr_time_sec(ctx->r->finfo.mtime); ctx->finfo.st_ctime = apr_time_sec(ctx->r->finfo.ctime); #endif ctx->finfo.st_size = ctx->r->finfo.size; ctx->finfo.st_nlink = ctx->r->finfo.nlink; return &ctx->finfo; } static char * php_apache_sapi_read_cookies(TSRMLS_D) { php_struct *ctx = SG(server_context); const char *http_cookie; http_cookie = apr_table_get(ctx->r->headers_in, "cookie"); /* The SAPI interface should use 'const char *' */ return (char *) http_cookie; } static char * php_apache_sapi_getenv(char *name, size_t name_len TSRMLS_DC) { php_struct *ctx = SG(server_context); const char *env_var; if (ctx == NULL) { return NULL; } env_var = apr_table_get(ctx->r->subprocess_env, name); return (char *) env_var; } static void php_apache_sapi_register_variables(zval *track_vars_array TSRMLS_DC) { php_struct *ctx = SG(server_context); const apr_array_header_t *arr = apr_table_elts(ctx->r->subprocess_env); char *key, *val; int new_val_len; APR_ARRAY_FOREACH_OPEN(arr, key, val) if (!val) { val = ""; } if (sapi_module.input_filter(PARSE_SERVER, key, &val, strlen(val), (unsigned int *)&new_val_len TSRMLS_CC)) { php_register_variable_safe(key, val, new_val_len, track_vars_array TSRMLS_CC); } APR_ARRAY_FOREACH_CLOSE() if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &ctx->r->uri, strlen(ctx->r->uri), (unsigned int *)&new_val_len TSRMLS_CC)) { php_register_variable_safe("PHP_SELF", ctx->r->uri, new_val_len, track_vars_array TSRMLS_CC); } } static void php_apache_sapi_flush(void *server_context) { php_struct *ctx; request_rec *r; TSRMLS_FETCH(); ctx = server_context; /* If we haven't registered a server_context yet, * then don't bother flushing. */ if (!server_context) { return; } r = ctx->r; sapi_send_headers(TSRMLS_C); r->status = SG(sapi_headers).http_response_code; SG(headers_sent) = 1; if (ap_rflush(r) < 0 || r->connection->aborted) { php_handle_aborted_connection(); } } static void php_apache_sapi_log_message(char *msg TSRMLS_DC) { php_struct *ctx; ctx = SG(server_context); if (ctx == NULL) { /* we haven't initialized our ctx yet, oh well */ ap_log_error(APLOG_MARK, APLOG_ERR | APLOG_STARTUP, 0, NULL, "%s", msg); } else { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, ctx->r, "%s", msg); } } static void php_apache_sapi_log_message_ex(char *msg, request_rec *r TSRMLS_DC) { if (r) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, msg, r->filename); } else { php_apache_sapi_log_message(msg TSRMLS_CC); } } static double php_apache_sapi_get_request_time(TSRMLS_D) { php_struct *ctx = SG(server_context); return ((double) apr_time_as_msec(ctx->r->request_time)) / 1000.0; } extern zend_module_entry php_apache_module; static int php_apache2_startup(sapi_module_struct *sapi_module) { if (php_module_startup(sapi_module, &php_apache_module, 1)==FAILURE) { return FAILURE; } return SUCCESS; } static sapi_module_struct apache2_sapi_module = { "apache2handler", "Apache 2.0 Handler", php_apache2_startup, /* startup */ php_module_shutdown_wrapper, /* shutdown */ NULL, /* activate */ NULL, /* deactivate */ php_apache_sapi_ub_write, /* unbuffered write */ php_apache_sapi_flush, /* flush */ php_apache_sapi_get_stat, /* get uid */ php_apache_sapi_getenv, /* getenv */ php_error, /* error handler */ php_apache_sapi_header_handler, /* header handler */ php_apache_sapi_send_headers, /* send headers handler */ NULL, /* send header handler */ php_apache_sapi_read_post, /* read POST data */ php_apache_sapi_read_cookies, /* read Cookies */ php_apache_sapi_register_variables, php_apache_sapi_log_message, /* Log message */ php_apache_sapi_get_request_time, /* Request Time */ NULL, /* Child Terminate */ STANDARD_SAPI_MODULE_PROPERTIES }; static apr_status_t php_apache_server_shutdown(void *tmp) { apache2_sapi_module.shutdown(&apache2_sapi_module); sapi_shutdown(); #ifdef ZTS tsrm_shutdown(); #endif return APR_SUCCESS; } static apr_status_t php_apache_child_shutdown(void *tmp) { apache2_sapi_module.shutdown(&apache2_sapi_module); #if defined(ZTS) && !defined(PHP_WIN32) tsrm_shutdown(); #endif return APR_SUCCESS; } static void php_apache_add_version(apr_pool_t *p) { TSRMLS_FETCH(); if (PG(expose_php)) { ap_add_version_component(p, "PHP/" PHP_VERSION); } } static int php_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp) { #ifndef ZTS int threaded_mpm; ap_mpm_query(AP_MPMQ_IS_THREADED, &threaded_mpm); if(threaded_mpm) { ap_log_error(APLOG_MARK, APLOG_CRIT, 0, 0, "Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe. You need to recompile PHP."); return DONE; } #endif /* When this is NULL, apache won't override the hard-coded default * php.ini path setting. */ apache2_php_ini_path_override = NULL; return OK; } static int php_apache_server_startup(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) { void *data = NULL; const char *userdata_key = "apache2hook_post_config"; /* Apache will load, unload and then reload a DSO module. This * prevents us from starting PHP until the second load. */ apr_pool_userdata_get(&data, userdata_key, s->process->pool); if (data == NULL) { /* We must use set() here and *not* setn(), otherwise the * static string pointed to by userdata_key will be mapped * to a different location when the DSO is reloaded and the * pointers won't match, causing get() to return NULL when * we expected it to return non-NULL. */ apr_pool_userdata_set((const void *)1, userdata_key, apr_pool_cleanup_null, s->process->pool); return OK; } /* Set up our overridden path. */ if (apache2_php_ini_path_override) { apache2_sapi_module.php_ini_path_override = apache2_php_ini_path_override; } #ifdef ZTS tsrm_startup(1, 1, 0, NULL); #endif sapi_startup(&apache2_sapi_module); apache2_sapi_module.startup(&apache2_sapi_module); apr_pool_cleanup_register(pconf, NULL, php_apache_server_shutdown, apr_pool_cleanup_null); php_apache_add_version(pconf); return OK; } static apr_status_t php_server_context_cleanup(void *data_) { void **data = data_; *data = NULL; return APR_SUCCESS; } static int php_apache_request_ctor(request_rec *r, php_struct *ctx TSRMLS_DC) { char *content_length; const char *auth; SG(sapi_headers).http_response_code = !r->status ? HTTP_OK : r->status; SG(request_info).content_type = apr_table_get(r->headers_in, "Content-Type"); SG(request_info).query_string = apr_pstrdup(r->pool, r->args); SG(request_info).request_method = r->method; SG(request_info).proto_num = r->proto_num; SG(request_info).request_uri = apr_pstrdup(r->pool, r->uri); SG(request_info).path_translated = apr_pstrdup(r->pool, r->filename); r->no_local_copy = 1; content_length = (char *) apr_table_get(r->headers_in, "Content-Length"); SG(request_info).content_length = (content_length ? atol(content_length) : 0); apr_table_unset(r->headers_out, "Content-Length"); apr_table_unset(r->headers_out, "Last-Modified"); apr_table_unset(r->headers_out, "Expires"); apr_table_unset(r->headers_out, "ETag"); auth = apr_table_get(r->headers_in, "Authorization"); php_handle_auth_data(auth TSRMLS_CC); if (SG(request_info).auth_user == NULL && r->user) { SG(request_info).auth_user = estrdup(r->user); } ctx->r->user = apr_pstrdup(ctx->r->pool, SG(request_info).auth_user); return php_request_startup(TSRMLS_C); } static void php_apache_request_dtor(request_rec *r TSRMLS_DC) { php_request_shutdown(NULL); } static void php_apache_ini_dtor(request_rec *r, request_rec *p TSRMLS_DC) { if (strcmp(r->protocol, "INCLUDED")) { zend_try { zend_ini_deactivate(TSRMLS_C); } zend_end_try(); } else { typedef struct { HashTable config; } php_conf_rec; char *str; uint str_len; php_conf_rec *c = ap_get_module_config(r->per_dir_config, &php5_module); for (zend_hash_internal_pointer_reset(&c->config); zend_hash_get_current_key_ex(&c->config, &str, &str_len, NULL, 0, NULL) == HASH_KEY_IS_STRING; zend_hash_move_forward(&c->config) ) { zend_restore_ini_entry(str, str_len, ZEND_INI_STAGE_SHUTDOWN); } } if (p) { ((php_struct *)SG(server_context))->r = p; } else { apr_pool_cleanup_run(r->pool, (void *)&SG(server_context), php_server_context_cleanup); } } static int php_handler(request_rec *r) { php_struct * volatile ctx; void *conf; apr_bucket_brigade * volatile brigade; apr_bucket *bucket; apr_status_t rv; request_rec * volatile parent_req = NULL; TSRMLS_FETCH(); #define PHPAP_INI_OFF php_apache_ini_dtor(r, parent_req TSRMLS_CC); conf = ap_get_module_config(r->per_dir_config, &php5_module); /* apply_config() needs r in some cases, so allocate server_context early */ ctx = SG(server_context); if (ctx == NULL || (ctx && ctx->request_processed && !strcmp(r->protocol, "INCLUDED"))) { normal: ctx = SG(server_context) = apr_pcalloc(r->pool, sizeof(*ctx)); /* register a cleanup so we clear out the SG(server_context) * after each request. Note: We pass in the pointer to the * server_context in case this is handled by a different thread. */ apr_pool_cleanup_register(r->pool, (void *)&SG(server_context), php_server_context_cleanup, apr_pool_cleanup_null); ctx->r = r; ctx = NULL; /* May look weird to null it here, but it is to catch the right case in the first_try later on */ } else { parent_req = ctx->r; ctx->r = r; } apply_config(conf); if (strcmp(r->handler, PHP_MAGIC_TYPE) && strcmp(r->handler, PHP_SOURCE_MAGIC_TYPE) && strcmp(r->handler, PHP_SCRIPT)) { /* Check for xbithack in this case. */ if (!AP2(xbithack) || strcmp(r->handler, "text/html") || !(r->finfo.protection & APR_UEXECUTE)) { PHPAP_INI_OFF; return DECLINED; } } /* Give a 404 if PATH_INFO is used but is explicitly disabled in * the configuration; default behaviour is to accept. */ if (r->used_path_info == AP_REQ_REJECT_PATH_INFO && r->path_info && r->path_info[0]) { PHPAP_INI_OFF; return HTTP_NOT_FOUND; } /* handle situations where user turns the engine off */ if (!AP2(engine)) { PHPAP_INI_OFF; return DECLINED; } if (r->finfo.filetype == 0) { php_apache_sapi_log_message_ex("script '%s' not found or unable to stat", r TSRMLS_CC); PHPAP_INI_OFF; return HTTP_NOT_FOUND; } if (r->finfo.filetype == APR_DIR) { php_apache_sapi_log_message_ex("attempt to invoke directory '%s' as script", r TSRMLS_CC); PHPAP_INI_OFF; return HTTP_FORBIDDEN; } /* Setup the CGI variables if this is the main request */ if (r->main == NULL || /* .. or if the sub-request environment differs from the main-request. */ r->subprocess_env != r->main->subprocess_env ) { /* setup standard CGI variables */ ap_add_common_vars(r); ap_add_cgi_vars(r); } zend_first_try { if (ctx == NULL) { brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc); ctx = SG(server_context); ctx->brigade = brigade; if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) { zend_bailout(); } } else { if (!parent_req) { parent_req = ctx->r; } if (parent_req && parent_req->handler && strcmp(parent_req->handler, PHP_MAGIC_TYPE) && strcmp(parent_req->handler, PHP_SOURCE_MAGIC_TYPE) && strcmp(parent_req->handler, PHP_SCRIPT)) { if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) { zend_bailout(); } } /* * check if coming due to ErrorDocument * We make a special exception of 413 (Invalid POST request) as the invalidity of the request occurs * during processing of the request by PHP during POST processing. Therefor we need to re-use the exiting * PHP instance to handle the request rather then creating a new one. */ if (parent_req && parent_req->status != HTTP_OK && parent_req->status != 413 && strcmp(r->protocol, "INCLUDED")) { parent_req = NULL; goto normal; } ctx->r = r; brigade = ctx->brigade; } if (AP2(last_modified)) { ap_update_mtime(r, r->finfo.mtime); ap_set_last_modified(r); } /* Determine if we need to parse the file or show the source */ if (strncmp(r->handler, PHP_SOURCE_MAGIC_TYPE, sizeof(PHP_SOURCE_MAGIC_TYPE) - 1) == 0) { zend_syntax_highlighter_ini syntax_highlighter_ini; php_get_highlight_struct(&syntax_highlighter_ini); highlight_file((char *)r->filename, &syntax_highlighter_ini TSRMLS_CC); } else { zend_file_handle zfd; zfd.type = ZEND_HANDLE_FILENAME; zfd.filename = (char *) r->filename; zfd.free_filename = 0; zfd.opened_path = NULL; if (!parent_req) { php_execute_script(&zfd TSRMLS_CC); } else { zend_execute_scripts(ZEND_INCLUDE TSRMLS_CC, NULL, 1, &zfd); } apr_table_set(r->notes, "mod_php_memory_usage", apr_psprintf(ctx->r->pool, "%" APR_SIZE_T_FMT, zend_memory_peak_usage(1 TSRMLS_CC))); } } zend_end_try(); if (!parent_req) { php_apache_request_dtor(r TSRMLS_CC); ctx->request_processed = 1; apr_brigade_cleanup(brigade); bucket = apr_bucket_eos_create(r->connection->bucket_alloc); APR_BRIGADE_INSERT_TAIL(brigade, bucket); rv = ap_pass_brigade(r->output_filters, brigade); if (rv != APR_SUCCESS || r->connection->aborted) { zend_first_try { php_handle_aborted_connection(); } zend_end_try(); } apr_brigade_cleanup(brigade); apr_pool_cleanup_run(r->pool, (void *)&SG(server_context), php_server_context_cleanup); } else { ctx->r = parent_req; } return OK; } static void php_apache_child_init(apr_pool_t *pchild, server_rec *s) { apr_pool_cleanup_register(pchild, NULL, php_apache_child_shutdown, apr_pool_cleanup_null); } void php_ap2_register_hook(apr_pool_t *p) { ap_hook_pre_config(php_pre_config, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_post_config(php_apache_server_startup, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_handler(php_handler, NULL, NULL, APR_HOOK_MIDDLE); ap_hook_child_init(php_apache_child_init, NULL, NULL, APR_HOOK_MIDDLE); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-79/c/good_384_0
crossvul-cpp_data_good_720_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" // 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); if (cfg->scrub_request_headers != 0) { 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) { 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" " localStorage.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>", DONE); } 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(localStorage.getItem('mod_auth_openidc_preserve_post_params'));\n" " localStorage.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, DONE); } /* * 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", cookieName); 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"); 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)), DONE); 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) { 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"); 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 */ if (oidc_refresh_access_token_before_expiry(r, cfg, session, oidc_cfg_dir_refresh_access_token_before_expiry(r)) == TRUE) needs_save = TRUE; /* 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, DONE); } /* * 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, DONE); } /* * 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_session_set_check_session_iframe(r, session, provider->check_session_iframe); oidc_session_set_client_id(r, session, provider->client_id); 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); } if (provider->end_session_endpoint != NULL) oidc_session_set_logout_endpoint(r, session, provider->end_session_endpoint); /* 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) { 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 DONE; /* 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&amp;%s=%s&amp;%s=%s&amp;%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&amp;%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&amp;%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. &quot;mike@seed.gluu.org&quot;, or an IDP identifier (eg. &quot;mitreid.org&quot;):</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, DONE); } /* * 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)); } /* * 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) { /* 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, DONE); } /* 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>", DONE); } /* 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>", DONE); /* 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; int rc = HTTP_BAD_REQUEST; apr_table_t *params = apr_table_make(r->pool, 8); if (oidc_util_read_post_params(r, params) == 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; } // clear the session cache oidc_cache_set_sid(r, sid, NULL, 0); oidc_cache_set_session(r, uuid, NULL, 0); rc = DONE; 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) { /* 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); } } const char *end_session_endpoint = oidc_session_get_logout_endpoint(r, session); if (end_session_endpoint != NULL) { const char *id_token_hint = oidc_session_get_idtoken(r, session); char *logout_request = apr_pstrdup(r->pool, 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, DONE); } 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 DONE; } 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, DONE); } /* * 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, *client_id = NULL, *check_session_iframe = 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); } /* see if this is a request for the OP iframe */ if (apr_strnatcmp("iframe_op", cmd) == 0) { check_session_iframe = oidc_session_get_check_session_iframe(r, session); if (check_session_iframe != NULL) { return oidc_handle_session_management_iframe_op(r, c, session, check_session_iframe); } return HTTP_NOT_FOUND; } /* see if this is a request for the RP iframe */ if (apr_strnatcmp("iframe_rp", cmd) == 0) { client_id = oidc_session_get_client_id(r, session); check_session_iframe = oidc_session_get_check_session_iframe(r, session); if ((client_id != NULL) && (check_session_iframe != NULL)) { return oidc_handle_session_management_iframe_rp(r, c, session, client_id, check_session_iframe); } oidc_debug(r, "iframe_rp command issued but no client (%s) and/or no check_session_iframe (%s) set", client_id, 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); oidc_get_provider_from_session(r, c, session, &provider); 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, DONE); } /* * handle a request to invalidate a cached access token introspection result */ static 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 DONE; } #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) { apr_byte_t needs_save = FALSE; char *s_format = NULL, *s_interval = 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) { 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_EXP, json_integer(apr_time_sec(session->expiry))); 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)); } /* JSON-encode the result */ char *r_value = oidc_util_encode_json_object(r, json, 0); /* 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"); return HTTP_INTERNAL_SERVER_ERROR; } /* return the stringified JSON result */ return oidc_util_http_send(r, r_value, strlen(r_value), OIDC_CONTENT_TYPE_JSON, DONE); } /* * 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 remote user, set headers/env-vars, update expiry, update userinfo + AT */ return oidc_handle_existing_session(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 /* * handle content generating requests */ int oidc_content_handler(request_rec *r) { oidc_cfg *c = ap_get_module_config(r->server->module_config, &auth_openidc_module); int rc = DECLINED; if (oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, c))) { if (oidc_util_request_has_parameter(r, OIDC_REDIRECT_URI_REQUEST_INFO)) { oidc_session_t *session = NULL; oidc_session_load(r, &session); /* handle request for session info */ rc = oidc_handle_info_request(r, c, session); /* free resources allocated for the session */ oidc_session_free(r, session); } } return rc; } 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-79/c/good_720_2
crossvul-cpp_data_good_1838_3
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2015 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. | +----------------------------------------------------------------------+ | Original design: Shane Caraveo <shane@caraveo.com> | | Authors: Andi Gutmans <andi@zend.com> | | Zeev Suraski <zeev@zend.com> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <ctype.h> #include <sys/stat.h> #include "php.h" #include "SAPI.h" #include "php_variables.h" #include "php_ini.h" #include "ext/standard/php_string.h" #include "ext/standard/pageinfo.h" #if (HAVE_PCRE || HAVE_BUNDLED_PCRE) && !defined(COMPILE_DL_PCRE) #include "ext/pcre/php_pcre.h" #endif #ifdef ZTS #include "TSRM.h" #endif #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #elif defined(PHP_WIN32) #include "win32/time.h" #endif #include "rfc1867.h" #ifdef PHP_WIN32 #define STRCASECMP stricmp #else #define STRCASECMP strcasecmp #endif #include "php_content_types.h" #ifdef ZTS SAPI_API int sapi_globals_id; #else sapi_globals_struct sapi_globals; #endif static void sapi_globals_ctor(sapi_globals_struct *sapi_globals TSRMLS_DC) { memset(sapi_globals, 0, sizeof(*sapi_globals)); zend_hash_init_ex(&sapi_globals->known_post_content_types, 5, NULL, NULL, 1, 0); php_setup_sapi_content_types(TSRMLS_C); } static void sapi_globals_dtor(sapi_globals_struct *sapi_globals TSRMLS_DC) { zend_hash_destroy(&sapi_globals->known_post_content_types); } /* True globals (no need for thread safety) */ SAPI_API sapi_module_struct sapi_module; SAPI_API void sapi_startup(sapi_module_struct *sf) { #ifdef ZEND_SIGNALS zend_signal_startup(); #endif sf->ini_entries = NULL; sapi_module = *sf; #ifdef ZTS ts_allocate_id(&sapi_globals_id, sizeof(sapi_globals_struct), (ts_allocate_ctor) sapi_globals_ctor, (ts_allocate_dtor) sapi_globals_dtor); # ifdef PHP_WIN32 _configthreadlocale(_ENABLE_PER_THREAD_LOCALE); # endif #else sapi_globals_ctor(&sapi_globals); #endif virtual_cwd_startup(); /* Could use shutdown to free the main cwd but it would just slow it down for CGI */ #ifdef PHP_WIN32 tsrm_win32_startup(); #endif reentrancy_startup(); } SAPI_API void sapi_shutdown(void) { #ifdef ZTS ts_free_id(sapi_globals_id); #else sapi_globals_dtor(&sapi_globals); #endif reentrancy_shutdown(); virtual_cwd_shutdown(); #ifdef PHP_WIN32 tsrm_win32_shutdown(); #endif } SAPI_API void sapi_free_header(sapi_header_struct *sapi_header) { efree(sapi_header->header); } /* {{{ proto bool header_register_callback(mixed callback) call a header function */ PHP_FUNCTION(header_register_callback) { zval *callback_func; char *callback_name; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &callback_func) == FAILURE) { return; } if (!zend_is_callable(callback_func, 0, &callback_name TSRMLS_CC)) { efree(callback_name); RETURN_FALSE; } efree(callback_name); if (SG(callback_func)) { zval_ptr_dtor(&SG(callback_func)); SG(fci_cache) = empty_fcall_info_cache; } SG(callback_func) = callback_func; Z_ADDREF_P(SG(callback_func)); RETURN_TRUE; } /* }}} */ static void sapi_run_header_callback(TSRMLS_D) { int error; zend_fcall_info fci; char *callback_name = NULL; char *callback_error = NULL; zval *retval_ptr = NULL; if (zend_fcall_info_init(SG(callback_func), 0, &fci, &SG(fci_cache), &callback_name, &callback_error TSRMLS_CC) == SUCCESS) { fci.retval_ptr_ptr = &retval_ptr; error = zend_call_function(&fci, &SG(fci_cache) TSRMLS_CC); if (error == FAILURE) { goto callback_failed; } else if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } } else { callback_failed: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not call the sapi_header_callback"); } if (callback_name) { efree(callback_name); } if (callback_error) { efree(callback_error); } } SAPI_API void sapi_handle_post(void *arg TSRMLS_DC) { if (SG(request_info).post_entry && SG(request_info).content_type_dup) { SG(request_info).post_entry->post_handler(SG(request_info).content_type_dup, arg TSRMLS_CC); if (SG(request_info).post_data) { efree(SG(request_info).post_data); SG(request_info).post_data = NULL; } efree(SG(request_info).content_type_dup); SG(request_info).content_type_dup = NULL; } } static void sapi_read_post_data(TSRMLS_D) { sapi_post_entry *post_entry; uint content_type_length = strlen(SG(request_info).content_type); char *content_type = estrndup(SG(request_info).content_type, content_type_length); char *p; char oldchar=0; void (*post_reader_func)(TSRMLS_D) = NULL; /* dedicated implementation for increased performance: * - Make the content type lowercase * - Trim descriptive data, stay with the content-type only */ for (p=content_type; p<content_type+content_type_length; p++) { switch (*p) { case ';': case ',': case ' ': content_type_length = p-content_type; oldchar = *p; *p = 0; break; default: *p = tolower(*p); break; } } /* now try to find an appropriate POST content handler */ if (zend_hash_find(&SG(known_post_content_types), content_type, content_type_length+1, (void **) &post_entry) == SUCCESS) { /* found one, register it for use */ SG(request_info).post_entry = post_entry; post_reader_func = post_entry->post_reader; } else { /* fallback */ SG(request_info).post_entry = NULL; if (!sapi_module.default_post_reader) { /* no default reader ? */ SG(request_info).content_type_dup = NULL; sapi_module.sapi_error(E_WARNING, "Unsupported content type: '%s'", content_type); return; } } if (oldchar) { *(p-1) = oldchar; } SG(request_info).content_type_dup = content_type; if(post_reader_func) { post_reader_func(TSRMLS_C); } if(sapi_module.default_post_reader) { sapi_module.default_post_reader(TSRMLS_C); } } SAPI_API SAPI_POST_READER_FUNC(sapi_read_standard_form_data) { int read_bytes; int allocated_bytes=SAPI_POST_BLOCK_SIZE+1; if ((SG(post_max_size) > 0) && (SG(request_info).content_length > SG(post_max_size))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "POST Content-Length of %ld bytes exceeds the limit of %ld bytes", SG(request_info).content_length, SG(post_max_size)); return; } SG(request_info).post_data = emalloc(allocated_bytes); for (;;) { read_bytes = sapi_module.read_post(SG(request_info).post_data+SG(read_post_bytes), SAPI_POST_BLOCK_SIZE TSRMLS_CC); if (read_bytes<=0) { break; } SG(read_post_bytes) += read_bytes; if ((SG(post_max_size) > 0) && (SG(read_post_bytes) > SG(post_max_size))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Actual POST length does not match Content-Length, and exceeds %ld bytes", SG(post_max_size)); break; } if (read_bytes < SAPI_POST_BLOCK_SIZE) { break; } if (SG(read_post_bytes)+SAPI_POST_BLOCK_SIZE >= allocated_bytes) { allocated_bytes = SG(read_post_bytes)+SAPI_POST_BLOCK_SIZE+1; SG(request_info).post_data = erealloc(SG(request_info).post_data, allocated_bytes); } } SG(request_info).post_data[SG(read_post_bytes)] = 0; /* terminating NULL */ SG(request_info).post_data_length = SG(read_post_bytes); } static inline char *get_default_content_type(uint prefix_len, uint *len TSRMLS_DC) { char *mimetype, *charset, *content_type; uint mimetype_len, charset_len; if (SG(default_mimetype)) { mimetype = SG(default_mimetype); mimetype_len = strlen(SG(default_mimetype)); } else { mimetype = SAPI_DEFAULT_MIMETYPE; mimetype_len = sizeof(SAPI_DEFAULT_MIMETYPE) - 1; } if (SG(default_charset)) { charset = SG(default_charset); charset_len = strlen(SG(default_charset)); } else { charset = SAPI_DEFAULT_CHARSET; charset_len = sizeof(SAPI_DEFAULT_CHARSET) - 1; } if (*charset && strncasecmp(mimetype, "text/", 5) == 0) { char *p; *len = prefix_len + mimetype_len + sizeof("; charset=") - 1 + charset_len; content_type = (char*)emalloc(*len + 1); p = content_type + prefix_len; memcpy(p, mimetype, mimetype_len); p += mimetype_len; memcpy(p, "; charset=", sizeof("; charset=") - 1); p += sizeof("; charset=") - 1; memcpy(p, charset, charset_len + 1); } else { *len = prefix_len + mimetype_len; content_type = (char*)emalloc(*len + 1); memcpy(content_type + prefix_len, mimetype, mimetype_len + 1); } return content_type; } SAPI_API char *sapi_get_default_content_type(TSRMLS_D) { uint len; return get_default_content_type(0, &len TSRMLS_CC); } SAPI_API void sapi_get_default_content_type_header(sapi_header_struct *default_header TSRMLS_DC) { uint len; default_header->header = get_default_content_type(sizeof("Content-type: ")-1, &len TSRMLS_CC); default_header->header_len = len; memcpy(default_header->header, "Content-type: ", sizeof("Content-type: ") - 1); } /* * Add charset on content-type header if the MIME type starts with * "text/", the default_charset directive is not empty and * there is not already a charset option in there. * * If "mimetype" is non-NULL, it should point to a pointer allocated * with emalloc(). If a charset is added, the string will be * re-allocated and the new length is returned. If mimetype is * unchanged, 0 is returned. * */ SAPI_API size_t sapi_apply_default_charset(char **mimetype, size_t len TSRMLS_DC) { char *charset, *newtype; size_t newlen; charset = SG(default_charset) ? SG(default_charset) : SAPI_DEFAULT_CHARSET; if (*mimetype != NULL) { if (*charset && strncmp(*mimetype, "text/", 5) == 0 && strstr(*mimetype, "charset=") == NULL) { newlen = len + (sizeof(";charset=")-1) + strlen(charset); newtype = emalloc(newlen + 1); PHP_STRLCPY(newtype, *mimetype, newlen + 1, len); strlcat(newtype, ";charset=", newlen + 1); strlcat(newtype, charset, newlen + 1); efree(*mimetype); *mimetype = newtype; return newlen; } } return 0; } SAPI_API void sapi_activate_headers_only(TSRMLS_D) { if (SG(request_info).headers_read == 1) return; SG(request_info).headers_read = 1; zend_llist_init(&SG(sapi_headers).headers, sizeof(sapi_header_struct), (void (*)(void *)) sapi_free_header, 0); SG(sapi_headers).send_default_content_type = 1; /* SG(sapi_headers).http_response_code = 200; */ SG(sapi_headers).http_status_line = NULL; SG(sapi_headers).mimetype = NULL; SG(read_post_bytes) = 0; SG(request_info).post_data = NULL; SG(request_info).raw_post_data = NULL; SG(request_info).current_user = NULL; SG(request_info).current_user_length = 0; SG(request_info).no_headers = 0; SG(request_info).post_entry = NULL; SG(global_request_time) = 0; /* * It's possible to override this general case in the activate() callback, * if necessary. */ if (SG(request_info).request_method && !strcmp(SG(request_info).request_method, "HEAD")) { SG(request_info).headers_only = 1; } else { SG(request_info).headers_only = 0; } if (SG(server_context)) { SG(request_info).cookie_data = sapi_module.read_cookies(TSRMLS_C); if (sapi_module.activate) { sapi_module.activate(TSRMLS_C); } } if (sapi_module.input_filter_init ) { sapi_module.input_filter_init(TSRMLS_C); } } /* * Called from php_request_startup() for every request. */ SAPI_API void sapi_activate(TSRMLS_D) { zend_llist_init(&SG(sapi_headers).headers, sizeof(sapi_header_struct), (void (*)(void *)) sapi_free_header, 0); SG(sapi_headers).send_default_content_type = 1; /* SG(sapi_headers).http_response_code = 200; */ SG(sapi_headers).http_status_line = NULL; SG(sapi_headers).mimetype = NULL; SG(headers_sent) = 0; SG(callback_run) = 0; SG(callback_func) = NULL; SG(read_post_bytes) = 0; SG(request_info).post_data = NULL; SG(request_info).raw_post_data = NULL; SG(request_info).current_user = NULL; SG(request_info).current_user_length = 0; SG(request_info).no_headers = 0; SG(request_info).post_entry = NULL; SG(request_info).proto_num = 1000; /* Default to HTTP 1.0 */ SG(global_request_time) = 0; /* It's possible to override this general case in the activate() callback, if necessary. */ if (SG(request_info).request_method && !strcmp(SG(request_info).request_method, "HEAD")) { SG(request_info).headers_only = 1; } else { SG(request_info).headers_only = 0; } SG(rfc1867_uploaded_files) = NULL; /* Handle request method */ if (SG(server_context)) { if (PG(enable_post_data_reading) && SG(request_info).request_method) { if (SG(request_info).content_type && !strcmp(SG(request_info).request_method, "POST")) { /* HTTP POST may contain form data to be processed into variables * depending on given content type */ sapi_read_post_data(TSRMLS_C); } else { /* Any other method with content payload will fill $HTTP_RAW_POST_DATA * if it is enabled by always_populate_raw_post_data. * It's up to the webserver to decide whether to allow a method or not. */ SG(request_info).content_type_dup = NULL; if (sapi_module.default_post_reader) { sapi_module.default_post_reader(TSRMLS_C); } } } else { SG(request_info).content_type_dup = NULL; } /* Cookies */ SG(request_info).cookie_data = sapi_module.read_cookies(TSRMLS_C); if (sapi_module.activate) { sapi_module.activate(TSRMLS_C); } } if (sapi_module.input_filter_init) { sapi_module.input_filter_init(TSRMLS_C); } } static void sapi_send_headers_free(TSRMLS_D) { if (SG(sapi_headers).http_status_line) { efree(SG(sapi_headers).http_status_line); SG(sapi_headers).http_status_line = NULL; } } SAPI_API void sapi_deactivate(TSRMLS_D) { zend_llist_destroy(&SG(sapi_headers).headers); if (SG(request_info).post_data) { efree(SG(request_info).post_data); } else if (SG(server_context)) { if(sapi_module.read_post) { /* make sure we've consumed all request input data */ char dummy[SAPI_POST_BLOCK_SIZE]; int read_bytes; while((read_bytes = sapi_module.read_post(dummy, sizeof(dummy)-1 TSRMLS_CC)) > 0) { SG(read_post_bytes) += read_bytes; } } } if (SG(request_info).raw_post_data) { efree(SG(request_info).raw_post_data); } if (SG(request_info).auth_user) { efree(SG(request_info).auth_user); } if (SG(request_info).auth_password) { efree(SG(request_info).auth_password); } if (SG(request_info).auth_digest) { efree(SG(request_info).auth_digest); } if (SG(request_info).content_type_dup) { efree(SG(request_info).content_type_dup); } if (SG(request_info).current_user) { efree(SG(request_info).current_user); } if (sapi_module.deactivate) { sapi_module.deactivate(TSRMLS_C); } if (SG(rfc1867_uploaded_files)) { destroy_uploaded_files_hash(TSRMLS_C); } if (SG(sapi_headers).mimetype) { efree(SG(sapi_headers).mimetype); SG(sapi_headers).mimetype = NULL; } sapi_send_headers_free(TSRMLS_C); SG(sapi_started) = 0; SG(headers_sent) = 0; SG(callback_run) = 0; if (SG(callback_func)) { zval_ptr_dtor(&SG(callback_func)); } SG(request_info).headers_read = 0; SG(global_request_time) = 0; } SAPI_API void sapi_initialize_empty_request(TSRMLS_D) { SG(server_context) = NULL; SG(request_info).request_method = NULL; SG(request_info).auth_digest = SG(request_info).auth_user = SG(request_info).auth_password = NULL; SG(request_info).content_type_dup = NULL; } static int sapi_extract_response_code(const char *header_line) { int code = 200; const char *ptr; for (ptr = header_line; *ptr; ptr++) { if (*ptr == ' ' && *(ptr + 1) != ' ') { code = atoi(ptr + 1); break; } } return code; } static void sapi_update_response_code(int ncode TSRMLS_DC) { /* if the status code did not change, we do not want to change the status line, and no need to change the code */ if (SG(sapi_headers).http_response_code == ncode) { return; } if (SG(sapi_headers).http_status_line) { efree(SG(sapi_headers).http_status_line); SG(sapi_headers).http_status_line = NULL; } SG(sapi_headers).http_response_code = ncode; } /* * since zend_llist_del_element only remove one matched item once, * we should remove them by ourself */ static void sapi_remove_header(zend_llist *l, char *name, uint len) { sapi_header_struct *header; zend_llist_element *next; zend_llist_element *current=l->head; while (current) { header = (sapi_header_struct *)(current->data); next = current->next; if (header->header_len > len && header->header[len] == ':' && !strncasecmp(header->header, name, len)) { if (current->prev) { current->prev->next = next; } else { l->head = next; } if (next) { next->prev = current->prev; } else { l->tail = current->prev; } sapi_free_header(header); efree(current); --l->count; } current = next; } } SAPI_API int sapi_add_header_ex(char *header_line, uint header_line_len, zend_bool duplicate, zend_bool replace TSRMLS_DC) { sapi_header_line ctr = {0}; int r; ctr.line = header_line; ctr.line_len = header_line_len; r = sapi_header_op(replace ? SAPI_HEADER_REPLACE : SAPI_HEADER_ADD, &ctr TSRMLS_CC); if (!duplicate) efree(header_line); return r; } static void sapi_header_add_op(sapi_header_op_enum op, sapi_header_struct *sapi_header TSRMLS_DC) { if (!sapi_module.header_handler || (SAPI_HEADER_ADD & sapi_module.header_handler(sapi_header, op, &SG(sapi_headers) TSRMLS_CC))) { if (op == SAPI_HEADER_REPLACE) { char *colon_offset = strchr(sapi_header->header, ':'); if (colon_offset) { char sav = *colon_offset; *colon_offset = 0; sapi_remove_header(&SG(sapi_headers).headers, sapi_header->header, strlen(sapi_header->header)); *colon_offset = sav; } } zend_llist_add_element(&SG(sapi_headers).headers, (void *) sapi_header); } else { sapi_free_header(sapi_header); } } SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg TSRMLS_DC) { sapi_header_struct sapi_header; char *colon_offset; char *header_line; uint header_line_len; int http_response_code; if (SG(headers_sent) && !SG(request_info).no_headers) { const char *output_start_filename = php_output_get_start_filename(TSRMLS_C); int output_start_lineno = php_output_get_start_lineno(TSRMLS_C); if (output_start_filename) { sapi_module.sapi_error(E_WARNING, "Cannot modify header information - headers already sent by (output started at %s:%d)", output_start_filename, output_start_lineno); } else { sapi_module.sapi_error(E_WARNING, "Cannot modify header information - headers already sent"); } return FAILURE; } switch (op) { case SAPI_HEADER_SET_STATUS: sapi_update_response_code((int)(zend_intptr_t) arg TSRMLS_CC); return SUCCESS; case SAPI_HEADER_ADD: case SAPI_HEADER_REPLACE: case SAPI_HEADER_DELETE: { sapi_header_line *p = arg; if (!p->line || !p->line_len) { return FAILURE; } header_line = p->line; header_line_len = p->line_len; http_response_code = p->response_code; break; } case SAPI_HEADER_DELETE_ALL: if (sapi_module.header_handler) { sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC); } zend_llist_clean(&SG(sapi_headers).headers); return SUCCESS; default: return FAILURE; } header_line = estrndup(header_line, header_line_len); /* cut off trailing spaces, linefeeds and carriage-returns */ if (header_line_len && isspace(header_line[header_line_len-1])) { do { header_line_len--; } while(header_line_len && isspace(header_line[header_line_len-1])); header_line[header_line_len]='\0'; } if (op == SAPI_HEADER_DELETE) { if (strchr(header_line, ':')) { efree(header_line); sapi_module.sapi_error(E_WARNING, "Header to delete may not contain colon."); return FAILURE; } if (sapi_module.header_handler) { sapi_header.header = header_line; sapi_header.header_len = header_line_len; sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC); } sapi_remove_header(&SG(sapi_headers).headers, header_line, header_line_len); efree(header_line); return SUCCESS; } else { /* new line/NUL character safety check */ int i; for (i = 0; i < header_line_len; i++) { /* RFC 7230 ch. 3.2.4 deprecates folding support */ if (header_line[i] == '\n' || header_line[i] == '\r') { efree(header_line); sapi_module.sapi_error(E_WARNING, "Header may not contain " "more than a single header, new line detected"); return FAILURE; } if (header_line[i] == '\0') { efree(header_line); sapi_module.sapi_error(E_WARNING, "Header may not contain NUL bytes"); return FAILURE; } } } sapi_header.header = header_line; sapi_header.header_len = header_line_len; /* Check the header for a few cases that we have special support for in SAPI */ if (header_line_len>=5 && !strncasecmp(header_line, "HTTP/", 5)) { /* filter out the response code */ sapi_update_response_code(sapi_extract_response_code(header_line) TSRMLS_CC); /* sapi_update_response_code doesn't free the status line if the code didn't change */ if (SG(sapi_headers).http_status_line) { efree(SG(sapi_headers).http_status_line); } SG(sapi_headers).http_status_line = header_line; return SUCCESS; } else { colon_offset = strchr(header_line, ':'); if (colon_offset) { *colon_offset = 0; if (!STRCASECMP(header_line, "Content-Type")) { char *ptr = colon_offset+1, *mimetype = NULL, *newheader; size_t len = header_line_len - (ptr - header_line), newlen; while (*ptr == ' ') { ptr++; len--; } /* Disable possible output compression for images */ if (!strncmp(ptr, "image/", sizeof("image/")-1)) { zend_alter_ini_entry("zlib.output_compression", sizeof("zlib.output_compression"), "0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME); } mimetype = estrdup(ptr); newlen = sapi_apply_default_charset(&mimetype, len TSRMLS_CC); if (!SG(sapi_headers).mimetype){ SG(sapi_headers).mimetype = estrdup(mimetype); } if (newlen != 0) { newlen += sizeof("Content-type: "); newheader = emalloc(newlen); PHP_STRLCPY(newheader, "Content-type: ", newlen, sizeof("Content-type: ")-1); strlcat(newheader, mimetype, newlen); sapi_header.header = newheader; sapi_header.header_len = newlen - 1; efree(header_line); } efree(mimetype); SG(sapi_headers).send_default_content_type = 0; } else if (!STRCASECMP(header_line, "Content-Length")) { /* Script is setting Content-length. The script cannot reasonably * know the size of the message body after compression, so it's best * do disable compression altogether. This contributes to making scripts * portable between setups that have and don't have zlib compression * enabled globally. See req #44164 */ zend_alter_ini_entry("zlib.output_compression", sizeof("zlib.output_compression"), "0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME); } else if (!STRCASECMP(header_line, "Location")) { if ((SG(sapi_headers).http_response_code < 300 || SG(sapi_headers).http_response_code > 399) && SG(sapi_headers).http_response_code != 201) { /* Return a Found Redirect if one is not already specified */ if (http_response_code) { /* user specified redirect code */ sapi_update_response_code(http_response_code TSRMLS_CC); } else if (SG(request_info).proto_num > 1000 && SG(request_info).request_method && strcmp(SG(request_info).request_method, "HEAD") && strcmp(SG(request_info).request_method, "GET")) { sapi_update_response_code(303 TSRMLS_CC); } else { sapi_update_response_code(302 TSRMLS_CC); } } } else if (!STRCASECMP(header_line, "WWW-Authenticate")) { /* HTTP Authentication */ sapi_update_response_code(401 TSRMLS_CC); /* authentication-required */ } if (sapi_header.header==header_line) { *colon_offset = ':'; } } } if (http_response_code) { sapi_update_response_code(http_response_code TSRMLS_CC); } sapi_header_add_op(op, &sapi_header TSRMLS_CC); return SUCCESS; } SAPI_API int sapi_send_headers(TSRMLS_D) { int retval; int ret = FAILURE; if (SG(headers_sent) || SG(request_info).no_headers || SG(callback_run)) { return SUCCESS; } /* Success-oriented. We set headers_sent to 1 here to avoid an infinite loop * in case of an error situation. */ if (SG(sapi_headers).send_default_content_type && sapi_module.send_headers) { sapi_header_struct default_header; uint len; SG(sapi_headers).mimetype = get_default_content_type(0, &len TSRMLS_CC); default_header.header_len = sizeof("Content-type: ") - 1 + len; default_header.header = emalloc(default_header.header_len + 1); memcpy(default_header.header, "Content-type: ", sizeof("Content-type: ") - 1); memcpy(default_header.header + sizeof("Content-type: ") - 1, SG(sapi_headers).mimetype, len + 1); sapi_header_add_op(SAPI_HEADER_ADD, &default_header TSRMLS_CC); SG(sapi_headers).send_default_content_type = 0; } if (SG(callback_func) && !SG(callback_run)) { SG(callback_run) = 1; sapi_run_header_callback(TSRMLS_C); } SG(headers_sent) = 1; if (sapi_module.send_headers) { retval = sapi_module.send_headers(&SG(sapi_headers) TSRMLS_CC); } else { retval = SAPI_HEADER_DO_SEND; } switch (retval) { case SAPI_HEADER_SENT_SUCCESSFULLY: ret = SUCCESS; break; case SAPI_HEADER_DO_SEND: { sapi_header_struct http_status_line; char buf[255]; if (SG(sapi_headers).http_status_line) { http_status_line.header = SG(sapi_headers).http_status_line; http_status_line.header_len = strlen(SG(sapi_headers).http_status_line); } else { http_status_line.header = buf; http_status_line.header_len = slprintf(buf, sizeof(buf), "HTTP/1.0 %d X", SG(sapi_headers).http_response_code); } sapi_module.send_header(&http_status_line, SG(server_context) TSRMLS_CC); } zend_llist_apply_with_argument(&SG(sapi_headers).headers, (llist_apply_with_arg_func_t) sapi_module.send_header, SG(server_context) TSRMLS_CC); if(SG(sapi_headers).send_default_content_type) { sapi_header_struct default_header; sapi_get_default_content_type_header(&default_header TSRMLS_CC); sapi_module.send_header(&default_header, SG(server_context) TSRMLS_CC); sapi_free_header(&default_header); } sapi_module.send_header(NULL, SG(server_context) TSRMLS_CC); ret = SUCCESS; break; case SAPI_HEADER_SEND_FAILED: SG(headers_sent) = 0; ret = FAILURE; break; } sapi_send_headers_free(TSRMLS_C); return ret; } SAPI_API int sapi_register_post_entries(sapi_post_entry *post_entries TSRMLS_DC) { sapi_post_entry *p=post_entries; while (p->content_type) { if (sapi_register_post_entry(p TSRMLS_CC) == FAILURE) { return FAILURE; } p++; } return SUCCESS; } SAPI_API int sapi_register_post_entry(sapi_post_entry *post_entry TSRMLS_DC) { if (SG(sapi_started) && EG(in_execution)) { return FAILURE; } return zend_hash_add(&SG(known_post_content_types), post_entry->content_type, post_entry->content_type_len+1, (void *) post_entry, sizeof(sapi_post_entry), NULL); } SAPI_API void sapi_unregister_post_entry(sapi_post_entry *post_entry TSRMLS_DC) { if (SG(sapi_started) && EG(in_execution)) { return; } zend_hash_del(&SG(known_post_content_types), post_entry->content_type, post_entry->content_type_len+1); } SAPI_API int sapi_register_default_post_reader(void (*default_post_reader)(TSRMLS_D) TSRMLS_DC) { if (SG(sapi_started) && EG(in_execution)) { return FAILURE; } sapi_module.default_post_reader = default_post_reader; return SUCCESS; } SAPI_API int sapi_register_treat_data(void (*treat_data)(int arg, char *str, zval *destArray TSRMLS_DC) TSRMLS_DC) { if (SG(sapi_started) && EG(in_execution)) { return FAILURE; } sapi_module.treat_data = treat_data; return SUCCESS; } SAPI_API int sapi_register_input_filter(unsigned int (*input_filter)(int arg, char *var, char **val, unsigned int val_len, unsigned int *new_val_len TSRMLS_DC), unsigned int (*input_filter_init)(TSRMLS_D) TSRMLS_DC) { if (SG(sapi_started) && EG(in_execution)) { return FAILURE; } sapi_module.input_filter = input_filter; sapi_module.input_filter_init = input_filter_init; return SUCCESS; } SAPI_API int sapi_flush(TSRMLS_D) { if (sapi_module.flush) { sapi_module.flush(SG(server_context)); return SUCCESS; } else { return FAILURE; } } SAPI_API struct stat *sapi_get_stat(TSRMLS_D) { if (sapi_module.get_stat) { return sapi_module.get_stat(TSRMLS_C); } else { if (!SG(request_info).path_translated || (VCWD_STAT(SG(request_info).path_translated, &SG(global_stat)) == -1)) { return NULL; } return &SG(global_stat); } } SAPI_API char *sapi_getenv(char *name, size_t name_len TSRMLS_DC) { if (sapi_module.getenv) { char *value, *tmp = sapi_module.getenv(name, name_len TSRMLS_CC); if (tmp) { value = estrdup(tmp); } else { return NULL; } if (sapi_module.input_filter) { sapi_module.input_filter(PARSE_STRING, name, &value, strlen(value), NULL TSRMLS_CC); } return value; } return NULL; } SAPI_API int sapi_get_fd(int *fd TSRMLS_DC) { if (sapi_module.get_fd) { return sapi_module.get_fd(fd TSRMLS_CC); } else { return FAILURE; } } SAPI_API int sapi_force_http_10(TSRMLS_D) { if (sapi_module.force_http_10) { return sapi_module.force_http_10(TSRMLS_C); } else { return FAILURE; } } SAPI_API int sapi_get_target_uid(uid_t *obj TSRMLS_DC) { if (sapi_module.get_target_uid) { return sapi_module.get_target_uid(obj TSRMLS_CC); } else { return FAILURE; } } SAPI_API int sapi_get_target_gid(gid_t *obj TSRMLS_DC) { if (sapi_module.get_target_gid) { return sapi_module.get_target_gid(obj TSRMLS_CC); } else { return FAILURE; } } SAPI_API double sapi_get_request_time(TSRMLS_D) { if(SG(global_request_time)) return SG(global_request_time); if (sapi_module.get_request_time && SG(server_context)) { SG(global_request_time) = sapi_module.get_request_time(TSRMLS_C); } else { struct timeval tp = {0}; if (!gettimeofday(&tp, NULL)) { SG(global_request_time) = (double)(tp.tv_sec + tp.tv_usec / 1000000.00); } else { SG(global_request_time) = (double)time(0); } } return SG(global_request_time); } SAPI_API void sapi_terminate_process(TSRMLS_D) { if (sapi_module.terminate_process) { sapi_module.terminate_process(TSRMLS_C); } } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-79/c/good_1838_3
crossvul-cpp_data_bad_1838_3
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2015 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. | +----------------------------------------------------------------------+ | Original design: Shane Caraveo <shane@caraveo.com> | | Authors: Andi Gutmans <andi@zend.com> | | Zeev Suraski <zeev@zend.com> | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <ctype.h> #include <sys/stat.h> #include "php.h" #include "SAPI.h" #include "php_variables.h" #include "php_ini.h" #include "ext/standard/php_string.h" #include "ext/standard/pageinfo.h" #if (HAVE_PCRE || HAVE_BUNDLED_PCRE) && !defined(COMPILE_DL_PCRE) #include "ext/pcre/php_pcre.h" #endif #ifdef ZTS #include "TSRM.h" #endif #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #elif defined(PHP_WIN32) #include "win32/time.h" #endif #include "rfc1867.h" #ifdef PHP_WIN32 #define STRCASECMP stricmp #else #define STRCASECMP strcasecmp #endif #include "php_content_types.h" #ifdef ZTS SAPI_API int sapi_globals_id; #else sapi_globals_struct sapi_globals; #endif static void sapi_globals_ctor(sapi_globals_struct *sapi_globals TSRMLS_DC) { memset(sapi_globals, 0, sizeof(*sapi_globals)); zend_hash_init_ex(&sapi_globals->known_post_content_types, 5, NULL, NULL, 1, 0); php_setup_sapi_content_types(TSRMLS_C); } static void sapi_globals_dtor(sapi_globals_struct *sapi_globals TSRMLS_DC) { zend_hash_destroy(&sapi_globals->known_post_content_types); } /* True globals (no need for thread safety) */ SAPI_API sapi_module_struct sapi_module; SAPI_API void sapi_startup(sapi_module_struct *sf) { #ifdef ZEND_SIGNALS zend_signal_startup(); #endif sf->ini_entries = NULL; sapi_module = *sf; #ifdef ZTS ts_allocate_id(&sapi_globals_id, sizeof(sapi_globals_struct), (ts_allocate_ctor) sapi_globals_ctor, (ts_allocate_dtor) sapi_globals_dtor); # ifdef PHP_WIN32 _configthreadlocale(_ENABLE_PER_THREAD_LOCALE); # endif #else sapi_globals_ctor(&sapi_globals); #endif virtual_cwd_startup(); /* Could use shutdown to free the main cwd but it would just slow it down for CGI */ #ifdef PHP_WIN32 tsrm_win32_startup(); #endif reentrancy_startup(); } SAPI_API void sapi_shutdown(void) { #ifdef ZTS ts_free_id(sapi_globals_id); #else sapi_globals_dtor(&sapi_globals); #endif reentrancy_shutdown(); virtual_cwd_shutdown(); #ifdef PHP_WIN32 tsrm_win32_shutdown(); #endif } SAPI_API void sapi_free_header(sapi_header_struct *sapi_header) { efree(sapi_header->header); } /* {{{ proto bool header_register_callback(mixed callback) call a header function */ PHP_FUNCTION(header_register_callback) { zval *callback_func; char *callback_name; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &callback_func) == FAILURE) { return; } if (!zend_is_callable(callback_func, 0, &callback_name TSRMLS_CC)) { efree(callback_name); RETURN_FALSE; } efree(callback_name); if (SG(callback_func)) { zval_ptr_dtor(&SG(callback_func)); SG(fci_cache) = empty_fcall_info_cache; } SG(callback_func) = callback_func; Z_ADDREF_P(SG(callback_func)); RETURN_TRUE; } /* }}} */ static void sapi_run_header_callback(TSRMLS_D) { int error; zend_fcall_info fci; char *callback_name = NULL; char *callback_error = NULL; zval *retval_ptr = NULL; if (zend_fcall_info_init(SG(callback_func), 0, &fci, &SG(fci_cache), &callback_name, &callback_error TSRMLS_CC) == SUCCESS) { fci.retval_ptr_ptr = &retval_ptr; error = zend_call_function(&fci, &SG(fci_cache) TSRMLS_CC); if (error == FAILURE) { goto callback_failed; } else if (retval_ptr) { zval_ptr_dtor(&retval_ptr); } } else { callback_failed: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not call the sapi_header_callback"); } if (callback_name) { efree(callback_name); } if (callback_error) { efree(callback_error); } } SAPI_API void sapi_handle_post(void *arg TSRMLS_DC) { if (SG(request_info).post_entry && SG(request_info).content_type_dup) { SG(request_info).post_entry->post_handler(SG(request_info).content_type_dup, arg TSRMLS_CC); if (SG(request_info).post_data) { efree(SG(request_info).post_data); SG(request_info).post_data = NULL; } efree(SG(request_info).content_type_dup); SG(request_info).content_type_dup = NULL; } } static void sapi_read_post_data(TSRMLS_D) { sapi_post_entry *post_entry; uint content_type_length = strlen(SG(request_info).content_type); char *content_type = estrndup(SG(request_info).content_type, content_type_length); char *p; char oldchar=0; void (*post_reader_func)(TSRMLS_D) = NULL; /* dedicated implementation for increased performance: * - Make the content type lowercase * - Trim descriptive data, stay with the content-type only */ for (p=content_type; p<content_type+content_type_length; p++) { switch (*p) { case ';': case ',': case ' ': content_type_length = p-content_type; oldchar = *p; *p = 0; break; default: *p = tolower(*p); break; } } /* now try to find an appropriate POST content handler */ if (zend_hash_find(&SG(known_post_content_types), content_type, content_type_length+1, (void **) &post_entry) == SUCCESS) { /* found one, register it for use */ SG(request_info).post_entry = post_entry; post_reader_func = post_entry->post_reader; } else { /* fallback */ SG(request_info).post_entry = NULL; if (!sapi_module.default_post_reader) { /* no default reader ? */ SG(request_info).content_type_dup = NULL; sapi_module.sapi_error(E_WARNING, "Unsupported content type: '%s'", content_type); return; } } if (oldchar) { *(p-1) = oldchar; } SG(request_info).content_type_dup = content_type; if(post_reader_func) { post_reader_func(TSRMLS_C); } if(sapi_module.default_post_reader) { sapi_module.default_post_reader(TSRMLS_C); } } SAPI_API SAPI_POST_READER_FUNC(sapi_read_standard_form_data) { int read_bytes; int allocated_bytes=SAPI_POST_BLOCK_SIZE+1; if ((SG(post_max_size) > 0) && (SG(request_info).content_length > SG(post_max_size))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "POST Content-Length of %ld bytes exceeds the limit of %ld bytes", SG(request_info).content_length, SG(post_max_size)); return; } SG(request_info).post_data = emalloc(allocated_bytes); for (;;) { read_bytes = sapi_module.read_post(SG(request_info).post_data+SG(read_post_bytes), SAPI_POST_BLOCK_SIZE TSRMLS_CC); if (read_bytes<=0) { break; } SG(read_post_bytes) += read_bytes; if ((SG(post_max_size) > 0) && (SG(read_post_bytes) > SG(post_max_size))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Actual POST length does not match Content-Length, and exceeds %ld bytes", SG(post_max_size)); break; } if (read_bytes < SAPI_POST_BLOCK_SIZE) { break; } if (SG(read_post_bytes)+SAPI_POST_BLOCK_SIZE >= allocated_bytes) { allocated_bytes = SG(read_post_bytes)+SAPI_POST_BLOCK_SIZE+1; SG(request_info).post_data = erealloc(SG(request_info).post_data, allocated_bytes); } } SG(request_info).post_data[SG(read_post_bytes)] = 0; /* terminating NULL */ SG(request_info).post_data_length = SG(read_post_bytes); } static inline char *get_default_content_type(uint prefix_len, uint *len TSRMLS_DC) { char *mimetype, *charset, *content_type; uint mimetype_len, charset_len; if (SG(default_mimetype)) { mimetype = SG(default_mimetype); mimetype_len = strlen(SG(default_mimetype)); } else { mimetype = SAPI_DEFAULT_MIMETYPE; mimetype_len = sizeof(SAPI_DEFAULT_MIMETYPE) - 1; } if (SG(default_charset)) { charset = SG(default_charset); charset_len = strlen(SG(default_charset)); } else { charset = SAPI_DEFAULT_CHARSET; charset_len = sizeof(SAPI_DEFAULT_CHARSET) - 1; } if (*charset && strncasecmp(mimetype, "text/", 5) == 0) { char *p; *len = prefix_len + mimetype_len + sizeof("; charset=") - 1 + charset_len; content_type = (char*)emalloc(*len + 1); p = content_type + prefix_len; memcpy(p, mimetype, mimetype_len); p += mimetype_len; memcpy(p, "; charset=", sizeof("; charset=") - 1); p += sizeof("; charset=") - 1; memcpy(p, charset, charset_len + 1); } else { *len = prefix_len + mimetype_len; content_type = (char*)emalloc(*len + 1); memcpy(content_type + prefix_len, mimetype, mimetype_len + 1); } return content_type; } SAPI_API char *sapi_get_default_content_type(TSRMLS_D) { uint len; return get_default_content_type(0, &len TSRMLS_CC); } SAPI_API void sapi_get_default_content_type_header(sapi_header_struct *default_header TSRMLS_DC) { uint len; default_header->header = get_default_content_type(sizeof("Content-type: ")-1, &len TSRMLS_CC); default_header->header_len = len; memcpy(default_header->header, "Content-type: ", sizeof("Content-type: ") - 1); } /* * Add charset on content-type header if the MIME type starts with * "text/", the default_charset directive is not empty and * there is not already a charset option in there. * * If "mimetype" is non-NULL, it should point to a pointer allocated * with emalloc(). If a charset is added, the string will be * re-allocated and the new length is returned. If mimetype is * unchanged, 0 is returned. * */ SAPI_API size_t sapi_apply_default_charset(char **mimetype, size_t len TSRMLS_DC) { char *charset, *newtype; size_t newlen; charset = SG(default_charset) ? SG(default_charset) : SAPI_DEFAULT_CHARSET; if (*mimetype != NULL) { if (*charset && strncmp(*mimetype, "text/", 5) == 0 && strstr(*mimetype, "charset=") == NULL) { newlen = len + (sizeof(";charset=")-1) + strlen(charset); newtype = emalloc(newlen + 1); PHP_STRLCPY(newtype, *mimetype, newlen + 1, len); strlcat(newtype, ";charset=", newlen + 1); strlcat(newtype, charset, newlen + 1); efree(*mimetype); *mimetype = newtype; return newlen; } } return 0; } SAPI_API void sapi_activate_headers_only(TSRMLS_D) { if (SG(request_info).headers_read == 1) return; SG(request_info).headers_read = 1; zend_llist_init(&SG(sapi_headers).headers, sizeof(sapi_header_struct), (void (*)(void *)) sapi_free_header, 0); SG(sapi_headers).send_default_content_type = 1; /* SG(sapi_headers).http_response_code = 200; */ SG(sapi_headers).http_status_line = NULL; SG(sapi_headers).mimetype = NULL; SG(read_post_bytes) = 0; SG(request_info).post_data = NULL; SG(request_info).raw_post_data = NULL; SG(request_info).current_user = NULL; SG(request_info).current_user_length = 0; SG(request_info).no_headers = 0; SG(request_info).post_entry = NULL; SG(global_request_time) = 0; /* * It's possible to override this general case in the activate() callback, * if necessary. */ if (SG(request_info).request_method && !strcmp(SG(request_info).request_method, "HEAD")) { SG(request_info).headers_only = 1; } else { SG(request_info).headers_only = 0; } if (SG(server_context)) { SG(request_info).cookie_data = sapi_module.read_cookies(TSRMLS_C); if (sapi_module.activate) { sapi_module.activate(TSRMLS_C); } } if (sapi_module.input_filter_init ) { sapi_module.input_filter_init(TSRMLS_C); } } /* * Called from php_request_startup() for every request. */ SAPI_API void sapi_activate(TSRMLS_D) { zend_llist_init(&SG(sapi_headers).headers, sizeof(sapi_header_struct), (void (*)(void *)) sapi_free_header, 0); SG(sapi_headers).send_default_content_type = 1; /* SG(sapi_headers).http_response_code = 200; */ SG(sapi_headers).http_status_line = NULL; SG(sapi_headers).mimetype = NULL; SG(headers_sent) = 0; SG(callback_run) = 0; SG(callback_func) = NULL; SG(read_post_bytes) = 0; SG(request_info).post_data = NULL; SG(request_info).raw_post_data = NULL; SG(request_info).current_user = NULL; SG(request_info).current_user_length = 0; SG(request_info).no_headers = 0; SG(request_info).post_entry = NULL; SG(request_info).proto_num = 1000; /* Default to HTTP 1.0 */ SG(global_request_time) = 0; /* It's possible to override this general case in the activate() callback, if necessary. */ if (SG(request_info).request_method && !strcmp(SG(request_info).request_method, "HEAD")) { SG(request_info).headers_only = 1; } else { SG(request_info).headers_only = 0; } SG(rfc1867_uploaded_files) = NULL; /* Handle request method */ if (SG(server_context)) { if (PG(enable_post_data_reading) && SG(request_info).request_method) { if (SG(request_info).content_type && !strcmp(SG(request_info).request_method, "POST")) { /* HTTP POST may contain form data to be processed into variables * depending on given content type */ sapi_read_post_data(TSRMLS_C); } else { /* Any other method with content payload will fill $HTTP_RAW_POST_DATA * if it is enabled by always_populate_raw_post_data. * It's up to the webserver to decide whether to allow a method or not. */ SG(request_info).content_type_dup = NULL; if (sapi_module.default_post_reader) { sapi_module.default_post_reader(TSRMLS_C); } } } else { SG(request_info).content_type_dup = NULL; } /* Cookies */ SG(request_info).cookie_data = sapi_module.read_cookies(TSRMLS_C); if (sapi_module.activate) { sapi_module.activate(TSRMLS_C); } } if (sapi_module.input_filter_init) { sapi_module.input_filter_init(TSRMLS_C); } } static void sapi_send_headers_free(TSRMLS_D) { if (SG(sapi_headers).http_status_line) { efree(SG(sapi_headers).http_status_line); SG(sapi_headers).http_status_line = NULL; } } SAPI_API void sapi_deactivate(TSRMLS_D) { zend_llist_destroy(&SG(sapi_headers).headers); if (SG(request_info).post_data) { efree(SG(request_info).post_data); } else if (SG(server_context)) { if(sapi_module.read_post) { /* make sure we've consumed all request input data */ char dummy[SAPI_POST_BLOCK_SIZE]; int read_bytes; while((read_bytes = sapi_module.read_post(dummy, sizeof(dummy)-1 TSRMLS_CC)) > 0) { SG(read_post_bytes) += read_bytes; } } } if (SG(request_info).raw_post_data) { efree(SG(request_info).raw_post_data); } if (SG(request_info).auth_user) { efree(SG(request_info).auth_user); } if (SG(request_info).auth_password) { efree(SG(request_info).auth_password); } if (SG(request_info).auth_digest) { efree(SG(request_info).auth_digest); } if (SG(request_info).content_type_dup) { efree(SG(request_info).content_type_dup); } if (SG(request_info).current_user) { efree(SG(request_info).current_user); } if (sapi_module.deactivate) { sapi_module.deactivate(TSRMLS_C); } if (SG(rfc1867_uploaded_files)) { destroy_uploaded_files_hash(TSRMLS_C); } if (SG(sapi_headers).mimetype) { efree(SG(sapi_headers).mimetype); SG(sapi_headers).mimetype = NULL; } sapi_send_headers_free(TSRMLS_C); SG(sapi_started) = 0; SG(headers_sent) = 0; SG(callback_run) = 0; if (SG(callback_func)) { zval_ptr_dtor(&SG(callback_func)); } SG(request_info).headers_read = 0; SG(global_request_time) = 0; } SAPI_API void sapi_initialize_empty_request(TSRMLS_D) { SG(server_context) = NULL; SG(request_info).request_method = NULL; SG(request_info).auth_digest = SG(request_info).auth_user = SG(request_info).auth_password = NULL; SG(request_info).content_type_dup = NULL; } static int sapi_extract_response_code(const char *header_line) { int code = 200; const char *ptr; for (ptr = header_line; *ptr; ptr++) { if (*ptr == ' ' && *(ptr + 1) != ' ') { code = atoi(ptr + 1); break; } } return code; } static void sapi_update_response_code(int ncode TSRMLS_DC) { /* if the status code did not change, we do not want to change the status line, and no need to change the code */ if (SG(sapi_headers).http_response_code == ncode) { return; } if (SG(sapi_headers).http_status_line) { efree(SG(sapi_headers).http_status_line); SG(sapi_headers).http_status_line = NULL; } SG(sapi_headers).http_response_code = ncode; } /* * since zend_llist_del_element only remove one matched item once, * we should remove them by ourself */ static void sapi_remove_header(zend_llist *l, char *name, uint len) { sapi_header_struct *header; zend_llist_element *next; zend_llist_element *current=l->head; while (current) { header = (sapi_header_struct *)(current->data); next = current->next; if (header->header_len > len && header->header[len] == ':' && !strncasecmp(header->header, name, len)) { if (current->prev) { current->prev->next = next; } else { l->head = next; } if (next) { next->prev = current->prev; } else { l->tail = current->prev; } sapi_free_header(header); efree(current); --l->count; } current = next; } } SAPI_API int sapi_add_header_ex(char *header_line, uint header_line_len, zend_bool duplicate, zend_bool replace TSRMLS_DC) { sapi_header_line ctr = {0}; int r; ctr.line = header_line; ctr.line_len = header_line_len; r = sapi_header_op(replace ? SAPI_HEADER_REPLACE : SAPI_HEADER_ADD, &ctr TSRMLS_CC); if (!duplicate) efree(header_line); return r; } static void sapi_header_add_op(sapi_header_op_enum op, sapi_header_struct *sapi_header TSRMLS_DC) { if (!sapi_module.header_handler || (SAPI_HEADER_ADD & sapi_module.header_handler(sapi_header, op, &SG(sapi_headers) TSRMLS_CC))) { if (op == SAPI_HEADER_REPLACE) { char *colon_offset = strchr(sapi_header->header, ':'); if (colon_offset) { char sav = *colon_offset; *colon_offset = 0; sapi_remove_header(&SG(sapi_headers).headers, sapi_header->header, strlen(sapi_header->header)); *colon_offset = sav; } } zend_llist_add_element(&SG(sapi_headers).headers, (void *) sapi_header); } else { sapi_free_header(sapi_header); } } SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg TSRMLS_DC) { sapi_header_struct sapi_header; char *colon_offset; char *header_line; uint header_line_len; int http_response_code; if (SG(headers_sent) && !SG(request_info).no_headers) { const char *output_start_filename = php_output_get_start_filename(TSRMLS_C); int output_start_lineno = php_output_get_start_lineno(TSRMLS_C); if (output_start_filename) { sapi_module.sapi_error(E_WARNING, "Cannot modify header information - headers already sent by (output started at %s:%d)", output_start_filename, output_start_lineno); } else { sapi_module.sapi_error(E_WARNING, "Cannot modify header information - headers already sent"); } return FAILURE; } switch (op) { case SAPI_HEADER_SET_STATUS: sapi_update_response_code((int)(zend_intptr_t) arg TSRMLS_CC); return SUCCESS; case SAPI_HEADER_ADD: case SAPI_HEADER_REPLACE: case SAPI_HEADER_DELETE: { sapi_header_line *p = arg; if (!p->line || !p->line_len) { return FAILURE; } header_line = p->line; header_line_len = p->line_len; http_response_code = p->response_code; break; } case SAPI_HEADER_DELETE_ALL: if (sapi_module.header_handler) { sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC); } zend_llist_clean(&SG(sapi_headers).headers); return SUCCESS; default: return FAILURE; } header_line = estrndup(header_line, header_line_len); /* cut off trailing spaces, linefeeds and carriage-returns */ if (header_line_len && isspace(header_line[header_line_len-1])) { do { header_line_len--; } while(header_line_len && isspace(header_line[header_line_len-1])); header_line[header_line_len]='\0'; } if (op == SAPI_HEADER_DELETE) { if (strchr(header_line, ':')) { efree(header_line); sapi_module.sapi_error(E_WARNING, "Header to delete may not contain colon."); return FAILURE; } if (sapi_module.header_handler) { sapi_header.header = header_line; sapi_header.header_len = header_line_len; sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC); } sapi_remove_header(&SG(sapi_headers).headers, header_line, header_line_len); efree(header_line); return SUCCESS; } else { /* new line/NUL character safety check */ int i; for (i = 0; i < header_line_len; i++) { /* RFC 2616 allows new lines if followed by SP or HT */ int illegal_break = (header_line[i+1] != ' ' && header_line[i+1] != '\t') && ( header_line[i] == '\n' || (header_line[i] == '\r' && header_line[i+1] != '\n')); if (illegal_break) { efree(header_line); sapi_module.sapi_error(E_WARNING, "Header may not contain " "more than a single header, new line detected"); return FAILURE; } if (header_line[i] == '\0') { efree(header_line); sapi_module.sapi_error(E_WARNING, "Header may not contain NUL bytes"); return FAILURE; } } } sapi_header.header = header_line; sapi_header.header_len = header_line_len; /* Check the header for a few cases that we have special support for in SAPI */ if (header_line_len>=5 && !strncasecmp(header_line, "HTTP/", 5)) { /* filter out the response code */ sapi_update_response_code(sapi_extract_response_code(header_line) TSRMLS_CC); /* sapi_update_response_code doesn't free the status line if the code didn't change */ if (SG(sapi_headers).http_status_line) { efree(SG(sapi_headers).http_status_line); } SG(sapi_headers).http_status_line = header_line; return SUCCESS; } else { colon_offset = strchr(header_line, ':'); if (colon_offset) { *colon_offset = 0; if (!STRCASECMP(header_line, "Content-Type")) { char *ptr = colon_offset+1, *mimetype = NULL, *newheader; size_t len = header_line_len - (ptr - header_line), newlen; while (*ptr == ' ') { ptr++; len--; } /* Disable possible output compression for images */ if (!strncmp(ptr, "image/", sizeof("image/")-1)) { zend_alter_ini_entry("zlib.output_compression", sizeof("zlib.output_compression"), "0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME); } mimetype = estrdup(ptr); newlen = sapi_apply_default_charset(&mimetype, len TSRMLS_CC); if (!SG(sapi_headers).mimetype){ SG(sapi_headers).mimetype = estrdup(mimetype); } if (newlen != 0) { newlen += sizeof("Content-type: "); newheader = emalloc(newlen); PHP_STRLCPY(newheader, "Content-type: ", newlen, sizeof("Content-type: ")-1); strlcat(newheader, mimetype, newlen); sapi_header.header = newheader; sapi_header.header_len = newlen - 1; efree(header_line); } efree(mimetype); SG(sapi_headers).send_default_content_type = 0; } else if (!STRCASECMP(header_line, "Content-Length")) { /* Script is setting Content-length. The script cannot reasonably * know the size of the message body after compression, so it's best * do disable compression altogether. This contributes to making scripts * portable between setups that have and don't have zlib compression * enabled globally. See req #44164 */ zend_alter_ini_entry("zlib.output_compression", sizeof("zlib.output_compression"), "0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME); } else if (!STRCASECMP(header_line, "Location")) { if ((SG(sapi_headers).http_response_code < 300 || SG(sapi_headers).http_response_code > 399) && SG(sapi_headers).http_response_code != 201) { /* Return a Found Redirect if one is not already specified */ if (http_response_code) { /* user specified redirect code */ sapi_update_response_code(http_response_code TSRMLS_CC); } else if (SG(request_info).proto_num > 1000 && SG(request_info).request_method && strcmp(SG(request_info).request_method, "HEAD") && strcmp(SG(request_info).request_method, "GET")) { sapi_update_response_code(303 TSRMLS_CC); } else { sapi_update_response_code(302 TSRMLS_CC); } } } else if (!STRCASECMP(header_line, "WWW-Authenticate")) { /* HTTP Authentication */ sapi_update_response_code(401 TSRMLS_CC); /* authentication-required */ } if (sapi_header.header==header_line) { *colon_offset = ':'; } } } if (http_response_code) { sapi_update_response_code(http_response_code TSRMLS_CC); } sapi_header_add_op(op, &sapi_header TSRMLS_CC); return SUCCESS; } SAPI_API int sapi_send_headers(TSRMLS_D) { int retval; int ret = FAILURE; if (SG(headers_sent) || SG(request_info).no_headers || SG(callback_run)) { return SUCCESS; } /* Success-oriented. We set headers_sent to 1 here to avoid an infinite loop * in case of an error situation. */ if (SG(sapi_headers).send_default_content_type && sapi_module.send_headers) { sapi_header_struct default_header; uint len; SG(sapi_headers).mimetype = get_default_content_type(0, &len TSRMLS_CC); default_header.header_len = sizeof("Content-type: ") - 1 + len; default_header.header = emalloc(default_header.header_len + 1); memcpy(default_header.header, "Content-type: ", sizeof("Content-type: ") - 1); memcpy(default_header.header + sizeof("Content-type: ") - 1, SG(sapi_headers).mimetype, len + 1); sapi_header_add_op(SAPI_HEADER_ADD, &default_header TSRMLS_CC); SG(sapi_headers).send_default_content_type = 0; } if (SG(callback_func) && !SG(callback_run)) { SG(callback_run) = 1; sapi_run_header_callback(TSRMLS_C); } SG(headers_sent) = 1; if (sapi_module.send_headers) { retval = sapi_module.send_headers(&SG(sapi_headers) TSRMLS_CC); } else { retval = SAPI_HEADER_DO_SEND; } switch (retval) { case SAPI_HEADER_SENT_SUCCESSFULLY: ret = SUCCESS; break; case SAPI_HEADER_DO_SEND: { sapi_header_struct http_status_line; char buf[255]; if (SG(sapi_headers).http_status_line) { http_status_line.header = SG(sapi_headers).http_status_line; http_status_line.header_len = strlen(SG(sapi_headers).http_status_line); } else { http_status_line.header = buf; http_status_line.header_len = slprintf(buf, sizeof(buf), "HTTP/1.0 %d X", SG(sapi_headers).http_response_code); } sapi_module.send_header(&http_status_line, SG(server_context) TSRMLS_CC); } zend_llist_apply_with_argument(&SG(sapi_headers).headers, (llist_apply_with_arg_func_t) sapi_module.send_header, SG(server_context) TSRMLS_CC); if(SG(sapi_headers).send_default_content_type) { sapi_header_struct default_header; sapi_get_default_content_type_header(&default_header TSRMLS_CC); sapi_module.send_header(&default_header, SG(server_context) TSRMLS_CC); sapi_free_header(&default_header); } sapi_module.send_header(NULL, SG(server_context) TSRMLS_CC); ret = SUCCESS; break; case SAPI_HEADER_SEND_FAILED: SG(headers_sent) = 0; ret = FAILURE; break; } sapi_send_headers_free(TSRMLS_C); return ret; } SAPI_API int sapi_register_post_entries(sapi_post_entry *post_entries TSRMLS_DC) { sapi_post_entry *p=post_entries; while (p->content_type) { if (sapi_register_post_entry(p TSRMLS_CC) == FAILURE) { return FAILURE; } p++; } return SUCCESS; } SAPI_API int sapi_register_post_entry(sapi_post_entry *post_entry TSRMLS_DC) { if (SG(sapi_started) && EG(in_execution)) { return FAILURE; } return zend_hash_add(&SG(known_post_content_types), post_entry->content_type, post_entry->content_type_len+1, (void *) post_entry, sizeof(sapi_post_entry), NULL); } SAPI_API void sapi_unregister_post_entry(sapi_post_entry *post_entry TSRMLS_DC) { if (SG(sapi_started) && EG(in_execution)) { return; } zend_hash_del(&SG(known_post_content_types), post_entry->content_type, post_entry->content_type_len+1); } SAPI_API int sapi_register_default_post_reader(void (*default_post_reader)(TSRMLS_D) TSRMLS_DC) { if (SG(sapi_started) && EG(in_execution)) { return FAILURE; } sapi_module.default_post_reader = default_post_reader; return SUCCESS; } SAPI_API int sapi_register_treat_data(void (*treat_data)(int arg, char *str, zval *destArray TSRMLS_DC) TSRMLS_DC) { if (SG(sapi_started) && EG(in_execution)) { return FAILURE; } sapi_module.treat_data = treat_data; return SUCCESS; } SAPI_API int sapi_register_input_filter(unsigned int (*input_filter)(int arg, char *var, char **val, unsigned int val_len, unsigned int *new_val_len TSRMLS_DC), unsigned int (*input_filter_init)(TSRMLS_D) TSRMLS_DC) { if (SG(sapi_started) && EG(in_execution)) { return FAILURE; } sapi_module.input_filter = input_filter; sapi_module.input_filter_init = input_filter_init; return SUCCESS; } SAPI_API int sapi_flush(TSRMLS_D) { if (sapi_module.flush) { sapi_module.flush(SG(server_context)); return SUCCESS; } else { return FAILURE; } } SAPI_API struct stat *sapi_get_stat(TSRMLS_D) { if (sapi_module.get_stat) { return sapi_module.get_stat(TSRMLS_C); } else { if (!SG(request_info).path_translated || (VCWD_STAT(SG(request_info).path_translated, &SG(global_stat)) == -1)) { return NULL; } return &SG(global_stat); } } SAPI_API char *sapi_getenv(char *name, size_t name_len TSRMLS_DC) { if (sapi_module.getenv) { char *value, *tmp = sapi_module.getenv(name, name_len TSRMLS_CC); if (tmp) { value = estrdup(tmp); } else { return NULL; } if (sapi_module.input_filter) { sapi_module.input_filter(PARSE_STRING, name, &value, strlen(value), NULL TSRMLS_CC); } return value; } return NULL; } SAPI_API int sapi_get_fd(int *fd TSRMLS_DC) { if (sapi_module.get_fd) { return sapi_module.get_fd(fd TSRMLS_CC); } else { return FAILURE; } } SAPI_API int sapi_force_http_10(TSRMLS_D) { if (sapi_module.force_http_10) { return sapi_module.force_http_10(TSRMLS_C); } else { return FAILURE; } } SAPI_API int sapi_get_target_uid(uid_t *obj TSRMLS_DC) { if (sapi_module.get_target_uid) { return sapi_module.get_target_uid(obj TSRMLS_CC); } else { return FAILURE; } } SAPI_API int sapi_get_target_gid(gid_t *obj TSRMLS_DC) { if (sapi_module.get_target_gid) { return sapi_module.get_target_gid(obj TSRMLS_CC); } else { return FAILURE; } } SAPI_API double sapi_get_request_time(TSRMLS_D) { if(SG(global_request_time)) return SG(global_request_time); if (sapi_module.get_request_time && SG(server_context)) { SG(global_request_time) = sapi_module.get_request_time(TSRMLS_C); } else { struct timeval tp = {0}; if (!gettimeofday(&tp, NULL)) { SG(global_request_time) = (double)(tp.tv_sec + tp.tv_usec / 1000000.00); } else { SG(global_request_time) = (double)time(0); } } return SG(global_request_time); } SAPI_API void sapi_terminate_process(TSRMLS_D) { if (sapi_module.terminate_process) { sapi_module.terminate_process(TSRMLS_C); } } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-79/c/bad_1838_3
crossvul-cpp_data_bad_720_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" // 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); if (cfg->scrub_request_headers != 0) { 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) { 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" " localStorage.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>", DONE); } 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(localStorage.getItem('mod_auth_openidc_preserve_post_params'));\n" " localStorage.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, DONE); } /* * 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", cookieName); 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"); 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)), DONE); 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) { 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"); 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 */ if (oidc_refresh_access_token_before_expiry(r, cfg, session, oidc_cfg_dir_refresh_access_token_before_expiry(r)) == TRUE) needs_save = TRUE; /* 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, DONE); } /* * 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, DONE); } /* * 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_session_set_check_session_iframe(r, session, provider->check_session_iframe); oidc_session_set_client_id(r, session, provider->client_id); 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); } if (provider->end_session_endpoint != NULL) oidc_session_set_logout_endpoint(r, session, provider->end_session_endpoint); /* 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) { 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 DONE; /* 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&amp;%s=%s&amp;%s=%s&amp;%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&amp;%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&amp;%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. &quot;mike@seed.gluu.org&quot;, or an IDP identifier (eg. &quot;mitreid.org&quot;):</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, DONE); } /* * 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)); } /* * 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) { /* 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, DONE); } /* 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>", DONE); } /* 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>", DONE); /* 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; int rc = HTTP_BAD_REQUEST; apr_table_t *params = apr_table_make(r->pool, 8); if (oidc_util_read_post_params(r, params) == 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; } // clear the session cache oidc_cache_set_sid(r, sid, NULL, 0); oidc_cache_set_session(r, uuid, NULL, 0); rc = DONE; 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) { /* 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); } } const char *end_session_endpoint = oidc_session_get_logout_endpoint(r, session); if (end_session_endpoint != NULL) { const char *id_token_hint = oidc_session_get_idtoken(r, session); char *logout_request = apr_pstrdup(r->pool, 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, DONE); } 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()', %s);\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 DONE; } char *s_poll_interval = NULL; oidc_util_get_request_parameter(r, "poll", &s_poll_interval); if (s_poll_interval == NULL) s_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, s_poll_interval, redirect_uri, redirect_uri); return oidc_util_html_send(r, NULL, java_script, "setTimer", NULL, DONE); } /* * 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, *client_id = NULL, *check_session_iframe = 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); } /* see if this is a request for the OP iframe */ if (apr_strnatcmp("iframe_op", cmd) == 0) { check_session_iframe = oidc_session_get_check_session_iframe(r, session); if (check_session_iframe != NULL) { return oidc_handle_session_management_iframe_op(r, c, session, check_session_iframe); } return HTTP_NOT_FOUND; } /* see if this is a request for the RP iframe */ if (apr_strnatcmp("iframe_rp", cmd) == 0) { client_id = oidc_session_get_client_id(r, session); check_session_iframe = oidc_session_get_check_session_iframe(r, session); if ((client_id != NULL) && (check_session_iframe != NULL)) { return oidc_handle_session_management_iframe_rp(r, c, session, client_id, check_session_iframe); } oidc_debug(r, "iframe_rp command issued but no client (%s) and/or no check_session_iframe (%s) set", client_id, 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); oidc_get_provider_from_session(r, c, session, &provider); 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, DONE); } /* * handle a request to invalidate a cached access token introspection result */ static 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 DONE; } #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) { apr_byte_t needs_save = FALSE; char *s_format = NULL, *s_interval = 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) { 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_EXP, json_integer(apr_time_sec(session->expiry))); 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)); } /* JSON-encode the result */ char *r_value = oidc_util_encode_json_object(r, json, 0); /* 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"); return HTTP_INTERNAL_SERVER_ERROR; } /* return the stringified JSON result */ return oidc_util_http_send(r, r_value, strlen(r_value), OIDC_CONTENT_TYPE_JSON, DONE); } /* * 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 remote user, set headers/env-vars, update expiry, update userinfo + AT */ return oidc_handle_existing_session(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 /* * handle content generating requests */ int oidc_content_handler(request_rec *r) { oidc_cfg *c = ap_get_module_config(r->server->module_config, &auth_openidc_module); int rc = DECLINED; if (oidc_util_request_matches_url(r, oidc_get_redirect_uri(r, c))) { if (oidc_util_request_has_parameter(r, OIDC_REDIRECT_URI_REQUEST_INFO)) { oidc_session_t *session = NULL; oidc_session_load(r, &session); /* handle request for session info */ rc = oidc_handle_info_request(r, c, session); /* free resources allocated for the session */ oidc_session_free(r, session); } } return rc; } 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-79/c/bad_720_2