project
stringclasses 633
values | commit_id
stringlengths 7
81
| target
int64 0
1
| func
stringlengths 5
484k
| cwe
stringclasses 131
values | big_vul_idx
float64 0
189k
⌀ | idx
int64 0
522k
| hash
stringlengths 34
39
| size
float64 1
24k
⌀ | message
stringlengths 0
11.5k
⌀ | dataset
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
NSDriverSockNew(Tcl_Interp *interp, NS_SOCKET sock,
const char *protocol, const char *driverName, const char *methodName,
Sock **sockPtrPtr)
{
int result = TCL_OK;
Driver *drvPtr;
NS_NONNULL_ASSERT(interp != NULL);
NS_NONNULL_ASSERT(protocol != NULL);
NS_NONNULL_ASSERT(methodName != NULL);
NS_NONNULL_ASSERT(sockPtrPtr != NULL);
drvPtr = LookupDriver(interp, protocol, driverName);
if (drvPtr == NULL) {
result = TCL_ERROR;
} else {
Sock *sockPtr;
Tcl_DString ds, *dsPtr = &ds;
Request *reqPtr;
sockPtr = SockNew(drvPtr);
sockPtr->servPtr = drvPtr->servPtr;
sockPtr->sock = sock;
RequestNew(sockPtr); // not sure if needed
// peerAddr is missing
Ns_GetTime(&sockPtr->acceptTime);
reqPtr = sockPtr->reqPtr;
Tcl_DStringInit(dsPtr);
Ns_DStringAppend(dsPtr, methodName);
Ns_StrToUpper(Ns_DStringValue(dsPtr));
reqPtr->request.line = Ns_DStringExport(dsPtr);
reqPtr->request.method = ns_strdup(methodName);
reqPtr->request.protocol = ns_strdup(protocol);
reqPtr->request.host = NULL;
reqPtr->request.query = NULL;
/* Ns_Log(Notice, "REQUEST LINE <%s>", reqPtr->request.line);*/
*sockPtrPtr = sockPtr;
}
return result;
}
|
CWE-787
| null | 519,546 |
266983489833164082345622720339483066792
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
PollFree(PollData *pdata)
{
NS_NONNULL_ASSERT(pdata != NULL);
ns_free(pdata->pfds);
memset(pdata, 0, sizeof(PollData));
}
|
CWE-787
| null | 519,547 |
193416345687898979134929138131882771588
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
WriterSubmitFilesObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv)
{
int result = TCL_OK;
Ns_Conn *conn;
int headers = 0, nrFiles;
Tcl_Obj *filesObj = NULL, **fileObjv;
Ns_ObjvSpec lopts[] = {
{"-headers", Ns_ObjvBool, &headers, INT2PTR(NS_TRUE)},
{NULL, NULL, NULL, NULL}
};
Ns_ObjvSpec args[] = {
{"files", Ns_ObjvObj, &filesObj, NULL},
{NULL, NULL, NULL, NULL}
};
if (unlikely(Ns_ParseObjv(lopts, args, interp, 2, objc, objv) != NS_OK)
|| NsConnRequire(interp, NS_CONN_REQUIRE_ALL, &conn) != NS_OK) {
result = TCL_ERROR;
} else if (unlikely( Ns_ConnSockPtr(conn) == NULL )) {
Ns_Log(Warning,
"NsWriterQueue: called without valid sockPtr, "
"maybe connection already closed");
Ns_TclPrintfResult(interp, "0");
result = TCL_OK;
} else if (Tcl_ListObjGetElements(interp, filesObj, &nrFiles, &fileObjv) != TCL_OK) {
Ns_TclPrintfResult(interp, "not a valid list of files: '%s'", Tcl_GetString(filesObj));
result = TCL_ERROR;
} else if (nrFiles == 0) {
Ns_TclPrintfResult(interp, "The provided list has to contain at least one file spec");
result = TCL_ERROR;
} else {
size_t totalbytes = 0u, i;
Tcl_Obj *keys[3], *filenameObj = NULL;
Ns_FileVec *filebufs;
const char *firstFilenameString = NULL;
Ns_ObjvValueRange offsetRange = {0, LLONG_MAX};
Ns_ObjvValueRange sizeRange = {1, LLONG_MAX};
filebufs = (Ns_FileVec *)ns_calloc((size_t)nrFiles, sizeof(Ns_FileVec));
keys[0] = Tcl_NewStringObj("filename", 8);
keys[1] = Tcl_NewStringObj("-offset", 7);
keys[2] = Tcl_NewStringObj("-size", 5);
Tcl_IncrRefCount(keys[0]);
Tcl_IncrRefCount(keys[1]);
Tcl_IncrRefCount(keys[2]);
for (i = 0u; i < (size_t)nrFiles; i++) {
filebufs[i].fd = NS_INVALID_FD;
}
/*
* Iterate over the list of dicts.
*/
for (i = 0u; i < (size_t)nrFiles; i++) {
Tcl_WideInt offset = 0, size = 0;
int rc, fd = NS_INVALID_FD;
const char *filenameString;
size_t nrbytes;
/*
* Get required "filename" element.
*/
filenameObj = NULL;
rc = Tcl_DictObjGet(interp, fileObjv[i], keys[0], &filenameObj);
if (rc != TCL_OK || filenameObj == NULL) {
Ns_TclPrintfResult(interp, "missing filename in dict '%s'",
Tcl_GetString(fileObjv[i]));
result = TCL_ERROR;
break;
}
filenameString = Tcl_GetString(filenameObj);
if (firstFilenameString == NULL) {
firstFilenameString = filenameString;
}
/*
* Get optional "-offset" and "-size" elements.
*/
if (WriterGetMemunitFromDict(interp, fileObjv[i], keys[1], &offsetRange, &offset) != TCL_OK) {
result = TCL_ERROR;
break;
}
if (WriterGetMemunitFromDict(interp, fileObjv[i], keys[2], &sizeRange, &size) != TCL_OK) {
result = TCL_ERROR;
break;
}
/*
* Check validity of the provided values
*/
result = WriterCheckInputParams(interp, Tcl_GetString(filenameObj),
(size_t)size, (off_t)offset,
&fd, &nrbytes);
if (result != TCL_OK) {
break;
}
filebufs[i].fd = fd;
filebufs[i].offset = offset;
filebufs[i].length = nrbytes;
totalbytes = totalbytes + (size_t)nrbytes;
}
Tcl_DecrRefCount(keys[0]);
Tcl_DecrRefCount(keys[1]);
Tcl_DecrRefCount(keys[2]);
/*
* If everything is ok, submit the request to the writer queue.
*/
if (result == TCL_OK) {
Ns_ReturnCode status;
if (headers != 0 && firstFilenameString != NULL) {
Ns_ConnSetTypeHeader(conn, Ns_GetMimeType(firstFilenameString));
}
status = NsWriterQueue(conn, totalbytes, NULL, NULL, NS_INVALID_FD, NULL, 0,
filebufs, nrFiles, NS_TRUE);
/*
* Provide a soft error like for "ns_writer submitfile".
*/
Tcl_SetObjResult(interp, Tcl_NewBooleanObj(status == NS_OK ? 1 : 0));
}
/*
* The NsWriterQueue() API makes the usual duplicates of the file
* descriptors and the Ns_FileVec structure, so we have to cleanup
* here.
*/
for (i = 0u; i < (size_t)nrFiles; i++) {
if (filebufs[i].fd != NS_INVALID_FD) {
(void) ns_close(filebufs[i].fd);
}
}
ns_free(filebufs);
}
return result;
}
|
CWE-787
| null | 519,548 |
326227786604716641344362789913016446356
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
SockSpoolerQueue(Driver *drvPtr, Sock *sockPtr)
{
bool trigger = NS_FALSE;
SpoolerQueue *queuePtr;
NS_NONNULL_ASSERT(drvPtr != NULL);
NS_NONNULL_ASSERT(sockPtr != NULL);
/*
* Get the next spooler thread from the list, all spooler requests are
* rotated between all spooler threads
*/
Ns_MutexLock(&drvPtr->spooler.lock);
if (drvPtr->spooler.curPtr == NULL) {
drvPtr->spooler.curPtr = drvPtr->spooler.firstPtr;
}
queuePtr = drvPtr->spooler.curPtr;
drvPtr->spooler.curPtr = drvPtr->spooler.curPtr->nextPtr;
Ns_MutexUnlock(&drvPtr->spooler.lock);
Ns_Log(Debug, "Spooler: %d: started fd=%d: %" PRIdz " bytes",
queuePtr->id, sockPtr->sock, sockPtr->reqPtr->length);
Ns_MutexLock(&queuePtr->lock);
if (queuePtr->sockPtr == NULL) {
trigger = NS_TRUE;
}
Push(sockPtr, queuePtr->sockPtr);
Ns_MutexUnlock(&queuePtr->lock);
/*
* Wake up spooler thread
*/
if (trigger) {
SockTrigger(queuePtr->pipe[1]);
}
return 1;
}
|
CWE-787
| null | 519,549 |
190387401116102381488897223609875701743
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
NsWriterQueue(Ns_Conn *conn, size_t nsend,
Tcl_Channel chan, FILE *fp, int fd,
struct iovec *bufs, int nbufs,
const Ns_FileVec *filebufs, int nfilebufs,
bool everysize)
{
Conn *connPtr;
WriterSock *wrSockPtr;
SpoolerQueue *queuePtr;
DrvWriter *wrPtr;
bool trigger = NS_FALSE;
size_t headerSize;
Ns_ReturnCode status = NS_OK;
Ns_FileVec *fbufs = NULL;
int nfbufs = 0;
NS_NONNULL_ASSERT(conn != NULL);
connPtr = (Conn *)conn;
if (unlikely(connPtr->sockPtr == NULL)) {
Ns_Log(Warning,
"NsWriterQueue: called without sockPtr size %" PRIdz " bufs %d flags %.6x stream %.6x chan %p fd %d",
nsend, nbufs, connPtr->flags, connPtr->flags & NS_CONN_STREAM,
(void *)chan, fd);
status = NS_ERROR;
wrPtr = NULL;
} else {
wrPtr = &connPtr->sockPtr->drvPtr->writer;
Ns_Log(DriverDebug,
"NsWriterQueue: size %" PRIdz " bufs %p (%d) flags %.6x stream %.6x chan %p fd %d thread %d",
nsend, (void *)bufs, nbufs, connPtr->flags, connPtr->flags & NS_CONN_STREAM,
(void *)chan, fd, wrPtr->threads);
if (unlikely(wrPtr->threads == 0)) {
Ns_Log(DriverDebug, "NsWriterQueue: no writer threads configured");
status = NS_ERROR;
} else if (nsend < (size_t)wrPtr->writersize && !everysize && connPtr->fd == 0) {
Ns_Log(DriverDebug, "NsWriterQueue: file is too small(%" PRIdz " < %" PRIdz ")",
nsend, wrPtr->writersize);
status = NS_ERROR;
}
}
if (status != NS_OK) {
return status;
}
assert(wrPtr != NULL);
/*
* In streaming mode, setup a temporary fd which is used as input and
* output. Streaming i/o will append to the file, while the write will
* read from it.
*/
if (((connPtr->flags & NS_CONN_STREAM) != 0u) || connPtr->fd > 0) {
if (wrPtr->doStream == NS_WRITER_STREAM_NONE) {
status = NS_ERROR;
} else if (unlikely(fp != NULL || fd != NS_INVALID_FD)) {
Ns_Log(DriverDebug, "NsWriterQueue: does not stream from this source via writer");
status = NS_ERROR;
} else {
status = WriterSetupStreamingMode(connPtr, bufs, nbufs, &fd);
}
if (unlikely(status != NS_OK)) {
if (status == NS_FILTER_BREAK) {
status = NS_OK;
}
return status;
}
/*
* As a result of successful WriterSetupStreamingMode(), we have fd
* set.
*/
assert(fd != NS_INVALID_FD);
} else {
if (fp != NULL) {
/*
* The client provided an open file pointer and closes it
*/
fd = ns_dup(fileno(fp));
} else if (fd != NS_INVALID_FD) {
/*
* The client provided an open file descriptor and closes it
*/
fd = ns_dup(fd);
} else if (chan != NULL) {
ClientData clientData;
/*
* The client provided an open Tcl channel and closes it
*/
if (Tcl_GetChannelHandle(chan, TCL_READABLE, &clientData) != TCL_OK) {
return NS_ERROR;
}
fd = ns_dup(PTR2INT(clientData));
} else if (filebufs != NULL && nfilebufs > 0) {
/*
* The client provided Ns_FileVec with open files. The client is
* responsible for closing it, like in all other cases.
*/
size_t i;
/*
* This is the only case, where fbufs will be != NULL,
* i.e. keeping a duplicate of the passed-in Ns_FileVec structure
* for which the client is responsible.
*/
fbufs = (Ns_FileVec *)ns_calloc((size_t)nfilebufs, sizeof(Ns_FileVec));
nfbufs = nfilebufs;
for (i = 0u; i < (size_t)nfilebufs; i++) {
fbufs[i].fd = ns_dup(filebufs[i].fd);
fbufs[i].length = filebufs[i].length;
fbufs[i].offset = filebufs[i].offset;
}
/*
* Place the fd of the first Ns_FileVec to fd.
*/
fd = fbufs[0].fd;
Ns_Log(DriverDebug, "NsWriterQueue: filevec mode, take first fd %d tosend %lu", fd, nsend);
}
}
Ns_Log(DriverDebug, "NsWriterQueue: writer threads %d nsend %" PRIdz " writersize %" PRIdz,
wrPtr->threads, nsend, wrPtr->writersize);
assert(connPtr->poolPtr != NULL);
connPtr->poolPtr->stats.spool++;
wrSockPtr = (WriterSock *)ns_calloc(1u, sizeof(WriterSock));
wrSockPtr->sockPtr = connPtr->sockPtr;
wrSockPtr->poolPtr = connPtr->poolPtr; /* just for being able to trace back the origin, e.g. list */
wrSockPtr->sockPtr->timeout.sec = 0;
wrSockPtr->flags = connPtr->flags;
wrSockPtr->refCount = 1;
/*
* Take the rate limit from the connection.
*/
wrSockPtr->rateLimit = connPtr->rateLimit;
if (wrSockPtr->rateLimit == -1) {
/*
* The value was not specified via connection. Use either the pool
* limit as a base for the computation or fall back to the driver
* default value.
*/
if (connPtr->poolPtr->rate.poolLimit > 0) {
/*
* Very optimistic start value, but values will float through via
* bandwidth management.
*/
wrSockPtr->rateLimit = connPtr->poolPtr->rate.poolLimit / 2;
} else {
wrSockPtr->rateLimit = wrPtr->rateLimit;
}
}
Ns_Log(WriterDebug, "### Writer(%d): initial rate limit %d KB/s",
wrSockPtr->sockPtr->sock, wrSockPtr->rateLimit);
/*
* Make sure we have proper content length header for
* keep-alive/pipelining.
*/
Ns_ConnSetLengthHeader(conn, nsend, (wrSockPtr->flags & NS_CONN_STREAM) != 0u);
/*
* Flush the headers
*/
if ((conn->flags & NS_CONN_SENTHDRS) == 0u) {
Tcl_DString ds;
Ns_DStringInit(&ds);
Ns_Log(DriverDebug, "### Writer(%d): add header", fd);
conn->flags |= NS_CONN_SENTHDRS;
(void)Ns_CompleteHeaders(conn, nsend, 0u, &ds);
headerSize = (size_t)Ns_DStringLength(&ds);
if (headerSize > 0u) {
wrSockPtr->headerString = ns_strdup(Tcl_DStringValue(&ds));
}
Ns_DStringFree(&ds);
} else {
headerSize = 0u;
}
if (fd != NS_INVALID_FD) {
/* maybe add mmap support for files (fd != NS_INVALID_FD) */
wrSockPtr->fd = fd;
wrSockPtr->c.file.bufs = fbufs;
wrSockPtr->c.file.nbufs = nfbufs;
Ns_Log(DriverDebug, "### Writer(%d) tosend %" PRIdz " files %d bufsize %" PRIdz,
fd, nsend, nfbufs, wrPtr->bufsize);
if (unlikely(headerSize >= wrPtr->bufsize)) {
/*
* We have a header which is larger than bufsize; place it
* as "leftover" and use the headerString as buffer for file
* reads (rather rare case)
*/
wrSockPtr->c.file.buf = (unsigned char *)wrSockPtr->headerString;
wrSockPtr->c.file.maxsize = headerSize;
wrSockPtr->c.file.bufsize = headerSize;
wrSockPtr->headerString = NULL;
} else if (headerSize > 0u) {
/*
* We have a header that fits into the bufsize; place it
* as "leftover" at the end of the buffer.
*/
wrSockPtr->c.file.buf = ns_malloc(wrPtr->bufsize);
memcpy(wrSockPtr->c.file.buf, wrSockPtr->headerString, headerSize);
wrSockPtr->c.file.bufsize = headerSize;
wrSockPtr->c.file.maxsize = wrPtr->bufsize;
ns_free(wrSockPtr->headerString);
wrSockPtr->headerString = NULL;
} else {
assert(wrSockPtr->headerString == NULL);
wrSockPtr->c.file.buf = ns_malloc(wrPtr->bufsize);
wrSockPtr->c.file.maxsize = wrPtr->bufsize;
}
wrSockPtr->c.file.bufoffset = 0;
wrSockPtr->c.file.toRead = nsend;
} else if (bufs != NULL) {
int i, j, headerbufs = (headerSize > 0u ? 1 : 0);
wrSockPtr->fd = NS_INVALID_FD;
if (nbufs+headerbufs < UIO_SMALLIOV) {
wrSockPtr->c.mem.bufs = wrSockPtr->c.mem.preallocated_bufs;
} else {
Ns_Log(DriverDebug, "NsWriterQueue: alloc %d iovecs", nbufs);
wrSockPtr->c.mem.bufs = ns_calloc((size_t)nbufs + (size_t)headerbufs, sizeof(struct iovec));
}
wrSockPtr->c.mem.nbufs = nbufs+headerbufs;
if (headerbufs != 0) {
wrSockPtr->c.mem.bufs[0].iov_base = wrSockPtr->headerString;
wrSockPtr->c.mem.bufs[0].iov_len = headerSize;
}
if (connPtr->fmap.addr != NULL) {
Ns_Log(DriverDebug, "NsWriterQueue: deliver fmapped %p", (void *)connPtr->fmap.addr);
/*
* Deliver an mmapped file, no need to copy content
*/
for (i = 0, j=headerbufs; i < nbufs; i++, j++) {
wrSockPtr->c.mem.bufs[j].iov_base = bufs[i].iov_base;
wrSockPtr->c.mem.bufs[j].iov_len = bufs[i].iov_len;
}
/*
* Make a copy of the fmap structure and make clear that
* we unmap in the writer thread.
*/
wrSockPtr->c.mem.fmap = connPtr->fmap;
connPtr->fmap.addr = NULL;
/* header string will be freed via wrSockPtr->headerString */
} else {
/*
* Deliver a content from iovec. The lifetime of the
* source is unknown, we have to copy the c.
*/
for (i = 0, j=headerbufs; i < nbufs; i++, j++) {
wrSockPtr->c.mem.bufs[j].iov_base = ns_malloc(bufs[i].iov_len);
wrSockPtr->c.mem.bufs[j].iov_len = bufs[i].iov_len;
memcpy(wrSockPtr->c.mem.bufs[j].iov_base, bufs[i].iov_base, bufs[i].iov_len);
}
/* header string will be freed a buf[0] */
wrSockPtr->headerString = NULL;
}
} else {
ns_free(wrSockPtr);
return NS_ERROR;
}
/*
* Add header size to total size.
*/
nsend += headerSize;
if (connPtr->clientData != NULL) {
wrSockPtr->clientData = ns_strdup(connPtr->clientData);
}
wrSockPtr->startTime = *Ns_ConnStartTime(conn);
/*
* Setup streaming context before sending potentially headers.
*/
if ((wrSockPtr->flags & NS_CONN_STREAM) != 0u) {
wrSockPtr->doStream = NS_WRITER_STREAM_ACTIVE;
assert(connPtr->strWriter == NULL);
/*
* Add a reference to the stream writer to the connection such
* it can efficiently append to a stream when multiple output
* operations happen. The backpointer (from the stream writer
* to the connection is needed to clear the reference to the
* writer in case the writer is deleted. No locks are needed,
* since nobody can share this structure yet.
*/
connPtr->strWriter = (NsWriterSock *)wrSockPtr;
wrSockPtr->connPtr = connPtr;
}
/*
* Tell connection, that writer handles the output (including
* closing the connection to the client).
*/
connPtr->flags |= NS_CONN_SENT_VIA_WRITER;
wrSockPtr->keep = connPtr->keep > 0 ? NS_TRUE : NS_FALSE;
wrSockPtr->size = nsend;
Ns_Log(DriverDebug, "NsWriterQueue NS_CONN_SENT_VIA_WRITER connPtr %p",
(void*)connPtr);
if ((wrSockPtr->flags & NS_CONN_STREAM) == 0u) {
Ns_Log(DriverDebug, "NsWriterQueue NS_CONN_SENT_VIA_WRITER connPtr %p clear sockPtr %p",
(void*)connPtr, (void*)connPtr->sockPtr);
connPtr->sockPtr = NULL;
connPtr->flags |= NS_CONN_CLOSED;
connPtr->nContentSent = nsend - headerSize;
}
/*
* Get the next writer thread from the list, all writer requests are
* rotated between all writer threads
*/
Ns_MutexLock(&wrPtr->lock);
if (wrPtr->curPtr == NULL) {
wrPtr->curPtr = wrPtr->firstPtr;
}
queuePtr = wrPtr->curPtr;
wrPtr->curPtr = wrPtr->curPtr->nextPtr;
Ns_MutexUnlock(&wrPtr->lock);
Ns_Log(WriterDebug, "Writer(%d): started: id=%d fd=%d, "
"size=%" PRIdz ", flags=%X, rate %d KB/s: %s",
wrSockPtr->sockPtr->sock,
queuePtr->id, wrSockPtr->fd,
nsend, wrSockPtr->flags,
wrSockPtr->rateLimit,
connPtr->request.line);
/*
* Now add new writer socket to the writer thread's queue
*/
wrSockPtr->queuePtr = queuePtr;
Ns_MutexLock(&queuePtr->lock);
if (queuePtr->sockPtr == NULL) {
trigger = NS_TRUE;
}
Push(wrSockPtr, queuePtr->sockPtr);
Ns_MutexUnlock(&queuePtr->lock);
/*
* Wake up writer thread
*/
if (trigger) {
SockTrigger(queuePtr->pipe[1]);
}
return NS_OK;
}
|
CWE-787
| null | 519,550 |
318621971776674846780513757066860561326
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
RequestNew(Sock *sockPtr)
{
Request *reqPtr;
bool reuseRequest = NS_TRUE;
NS_NONNULL_ASSERT(sockPtr != NULL);
/*
* Try to get a request from the pool of allocated Requests.
*/
Ns_MutexLock(&reqLock);
reqPtr = firstReqPtr;
if (likely(reqPtr != NULL)) {
firstReqPtr = reqPtr->nextPtr;
} else {
reuseRequest = NS_FALSE;
}
Ns_MutexUnlock(&reqLock);
if (reuseRequest) {
Ns_Log(DriverDebug, "RequestNew reuses a Request");
}
/*
* In case we failed, allocate a new Request.
*/
if (reqPtr == NULL) {
Ns_Log(DriverDebug, "RequestNew gets a fresh Request");
reqPtr = ns_calloc(1u, sizeof(Request));
Tcl_DStringInit(&reqPtr->buffer);
reqPtr->headers = Ns_SetCreate(NULL);
}
sockPtr->reqPtr = reqPtr;
}
|
CWE-787
| null | 519,551 |
194053899247853357748138859505100736567
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
GetSockStateName(SockState sockState)
{
int sockStateInt = (int)sockState;
static const char *sockStateStrings[] = {
"SOCK_READY",
"SOCK_MORE",
"SOCK_SPOOL",
"SOCK_ERROR",
"SOCK_CLOSE",
"SOCK_CLOSETIMEOUT",
"SOCK_READTIMEOUT",
"SOCK_WRITETIMEOUT",
"SOCK_READERROR",
"SOCK_WRITEERROR",
"SOCK_SHUTERROR",
"SOCK_BADREQUEST",
"SOCK_ENTITYTOOLARGE",
"SOCK_BADHEADER",
"SOCK_TOOMANYHEADERS",
NULL
};
if (sockStateInt < 0) {
sockStateInt = (- sockStateInt) + 2;
}
assert(sockStateInt < Ns_NrElements(sockStateStrings));
return sockStateStrings[sockStateInt];
}
|
CWE-787
| null | 519,552 |
87428394860972588339322229728803883611
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
WriterSend(WriterSock *curPtr, int *err) {
const struct iovec *bufs;
struct iovec vbuf;
int nbufs;
SpoolerState status = SPOOLER_OK;
size_t toWrite;
ssize_t n;
NS_NONNULL_ASSERT(curPtr != NULL);
NS_NONNULL_ASSERT(err != NULL);
/*
* Prepare send operation
*/
if (curPtr->fd != NS_INVALID_FD) {
/*
* We have a valid file descriptor, send data from file.
*
* Prepare sending a single buffer with curPtr->c.file.bufsize bytes
* from the curPtr->c.file.buf to the client.
*/
vbuf.iov_len = curPtr->c.file.bufsize;
vbuf.iov_base = (void *)curPtr->c.file.buf;
bufs = &vbuf;
nbufs = 1;
toWrite = curPtr->c.file.bufsize;
} else {
int i;
/*
* Prepare sending multiple memory buffers. Get length of remaining
* buffers.
*/
toWrite = 0u;
for (i = 0; i < curPtr->c.mem.nsbufs; i ++) {
toWrite += curPtr->c.mem.sbufs[i].iov_len;
}
Ns_Log(DriverDebug,
"### Writer wants to send remainder nbufs %d len %" PRIdz,
curPtr->c.mem.nsbufs, toWrite);
/*
* Add buffers from the source and fill structure up to max
*/
while (curPtr->c.mem.bufIdx < curPtr->c.mem.nbufs &&
curPtr->c.mem.sbufIdx < UIO_SMALLIOV) {
const struct iovec *vPtr = &curPtr->c.mem.bufs[curPtr->c.mem.bufIdx];
if (vPtr->iov_len > 0u && vPtr->iov_base != NULL) {
Ns_Log(DriverDebug,
"### Writer copies source %d to scratch %d len %" PRIiovlen,
curPtr->c.mem.bufIdx, curPtr->c.mem.sbufIdx, vPtr->iov_len);
toWrite += Ns_SetVec(curPtr->c.mem.sbufs, curPtr->c.mem.sbufIdx++,
vPtr->iov_base, vPtr->iov_len);
curPtr->c.mem.nsbufs++;
}
curPtr->c.mem.bufIdx++;
}
bufs = curPtr->c.mem.sbufs;
nbufs = curPtr->c.mem.nsbufs;
Ns_Log(DriverDebug, "### Writer wants to send %d bufs size %" PRIdz,
nbufs, toWrite);
}
/*
* Perform the actual send operation.
*/
n = NsDriverSend(curPtr->sockPtr, bufs, nbufs, 0u);
if (n == -1) {
*err = ns_sockerrno;
status = SPOOLER_WRITEERROR;
} else {
/*
* We have sent zero or more bytes.
*/
if (curPtr->doStream != NS_WRITER_STREAM_NONE) {
Ns_MutexLock(&curPtr->c.file.fdlock);
curPtr->size -= (size_t)n;
Ns_MutexUnlock(&curPtr->c.file.fdlock);
} else {
curPtr->size -= (size_t)n;
}
curPtr->nsent += n;
curPtr->sockPtr->timeout.sec = 0;
if (curPtr->fd != NS_INVALID_FD) {
/*
* File-descriptor based send operation. Reduce the (remainig)
* buffer size the amount of data sent and adjust the buffer
* offset. For partial send operations, this will lead to a
* remaining buffer size > 0.
*/
curPtr->c.file.bufsize -= (size_t)n;
curPtr->c.file.bufoffset = (off_t)n;
} else {
if (n < (ssize_t)toWrite) {
/*
* We have a partial transmit from the iovec
* structure. We have to compact it to fill content in
* the next round.
*/
curPtr->c.mem.sbufIdx = Ns_ResetVec(curPtr->c.mem.sbufs, curPtr->c.mem.nsbufs, (size_t)n);
curPtr->c.mem.nsbufs -= curPtr->c.mem.sbufIdx;
memmove(curPtr->c.mem.sbufs, curPtr->c.mem.sbufs + curPtr->c.mem.sbufIdx,
/* move the iovecs to the start of the scratch buffers */
sizeof(struct iovec) * (size_t)curPtr->c.mem.nsbufs);
}
}
}
return status;
}
|
CWE-787
| null | 519,553 |
19965968575474249033323970122137873671
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
DriverClose(Sock *sockPtr)
{
NS_NONNULL_ASSERT(sockPtr != NULL);
(*sockPtr->drvPtr->closeProc)((Ns_Sock *) sockPtr);
}
|
CWE-787
| null | 519,554 |
301805053982827089112460583419286637556
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
WriterSetupStreamingMode(Conn *connPtr, struct iovec *bufs, int nbufs, int *fdPtr)
{
bool first;
size_t wrote = 0u;
WriterSock *wrSockPtr1;
Ns_ReturnCode status = NS_OK;
NS_NONNULL_ASSERT(connPtr != NULL);
NS_NONNULL_ASSERT(bufs != NULL);
NS_NONNULL_ASSERT(fdPtr != NULL);
Ns_Log(DriverDebug, "NsWriterQueue: streaming writer job");
if (connPtr->fd == 0) {
/*
* Create a new temporary spool file and provide the fd to the
* connection thread via connPtr.
*/
first = NS_TRUE;
wrSockPtr1 = NULL;
*fdPtr = Ns_GetTemp();
connPtr->fd = *fdPtr;
Ns_Log(DriverDebug, "NsWriterQueue: new tmp file has fd %d", *fdPtr);
} else {
/*
* Reuse previously created spool file.
*/
first = NS_FALSE;
wrSockPtr1 = WriterSockRequire(connPtr);
if (wrSockPtr1 == NULL) {
Ns_Log(Notice,
"NsWriterQueue: writer job was already canceled (fd %d); maybe user dropped connection",
connPtr->fd);
return NS_ERROR;
} else {
/*
* lock only, when first == NS_FALSE.
*/
Ns_MutexLock(&wrSockPtr1->c.file.fdlock);
(void)ns_lseek(connPtr->fd, 0, SEEK_END);
}
}
/*
* For the time being, handle just "string data" in streaming
* output (iovec bufs). Write the content to the spool file.
*/
{
int i;
for (i = 0; i < nbufs; i++) {
ssize_t j = ns_write(connPtr->fd, bufs[i].iov_base, bufs[i].iov_len);
if (j > 0) {
wrote += (size_t)j;
Ns_Log(Debug, "NsWriterQueue: fd %d [%d] spooled %" PRIdz " of %" PRIiovlen " OK %d",
connPtr->fd, i, j, bufs[i].iov_len, (j == (ssize_t)bufs[i].iov_len));
} else {
Ns_Log(Warning, "NsWriterQueue: spool to fd %d write operation failed",
connPtr->fd);
}
}
}
if (first) {
//bufs = NULL;
connPtr->nContentSent = wrote;
#ifndef _WIN32
/*
* sock_set_blocking can't be used under windows, since sockets
* are under windows no file descriptors.
*/
(void)ns_sock_set_blocking(connPtr->fd, NS_FALSE);
#endif
/*
* Fall through to register stream writer with temp file
*/
} else {
WriterSock *writerSockPtr;
/*
* This is a later streaming operation, where the writer job
* (strWriter) was previously established.
*/
assert(wrSockPtr1 != NULL);
/*
* Update the controlling variables (size and toread) in the connPtr,
* and the length info for the access log, and trigger the writer to
* notify it about the change.
*/
writerSockPtr = (WriterSock *)connPtr->strWriter;
writerSockPtr->size += wrote;
writerSockPtr->c.file.toRead += wrote;
Ns_MutexUnlock(&wrSockPtr1->c.file.fdlock);
connPtr->nContentSent += wrote;
if (likely(wrSockPtr1->queuePtr != NULL)) {
SockTrigger(wrSockPtr1->queuePtr->pipe[1]);
}
WriterSockRelease(wrSockPtr1);
status = NS_FILTER_BREAK;
}
return status;
}
|
CWE-787
| null | 519,555 |
32530339895921850177904596256328642130
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
NsWaitDriversShutdown(const Ns_Time *toPtr)
{
Driver *drvPtr;
Ns_ReturnCode status = NS_OK;
for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) {
if ((drvPtr->flags & DRIVER_STARTED) == 0u) {
continue;
}
Ns_MutexLock(&drvPtr->lock);
while ((drvPtr->flags & DRIVER_STOPPED) == 0u && status == NS_OK) {
status = Ns_CondTimedWait(&drvPtr->cond, &drvPtr->lock, toPtr);
}
Ns_MutexUnlock(&drvPtr->lock);
if (status != NS_OK) {
Ns_Log(Warning, "[driver:%s]: shutdown timeout", drvPtr->threadName);
} else {
Ns_Log(Notice, "[driver:%s]: stopped", drvPtr->threadName);
Ns_ThreadJoin(&drvPtr->thread, NULL);
drvPtr->thread = NULL;
}
}
}
|
CWE-787
| null | 519,556 |
330148202356682677486722401782949274344
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
void NsDriverMapVirtualServers(void)
{
Driver *drvPtr;
for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) {
const Ns_Set *lset;
size_t j;
Tcl_DString ds, *dsPtr = &ds;
const char *path, *defserver, *moduleName;
moduleName = drvPtr->moduleName;
defserver = drvPtr->defserver;
/*
* Check for a "/servers" section for this driver module.
*/
path = Ns_ConfigGetPath(NULL, moduleName, "servers", (char *)0L);
lset = Ns_ConfigGetSection(path);
if (lset == NULL || Ns_SetSize(lset) == 0u) {
/*
* The driver module has no (or empty) ".../servers" section.
* There is no mapping from host name to virtual server defined.
*/
if (drvPtr->server == NULL) {
/*
* We have a global driver module. If there is at least a
* default server configured, we can use this for the mapping
* to the default server.
*/
if (defserver != NULL) {
NsServer *servPtr = NsGetServer(defserver);
Tcl_DStringInit(dsPtr);
ServerMapEntryAdd(dsPtr, Ns_InfoHostname(), servPtr, drvPtr, NS_TRUE);
Tcl_DStringFree(dsPtr);
Ns_Log(Notice, "Global driver has no mapping from host to server (section '%s' missing)",
moduleName);
} else {
/*
* Global driver, which has no default server, and no servers section.
*/
Ns_Fatal("%s: virtual servers configured,"
" but '%s' has no defaultserver defined", moduleName, path);
}
}
continue;
}
/*
* We have a ".../servers" section, the driver might be global or
* local. It is not clear, why we need the server map for the local
* driver, but for compatibility, we keep this.
*
*/
if (defserver == NULL) {
if (drvPtr->server != NULL) {
/*
* We have a local (server specific) driver. Since the code
* below assumes that we have a "defserver" set, we take the
* actual server as defserver.
*/
defserver = drvPtr->server;
} else {
/*
* We have a global driver, but no defserver.
*/
Ns_Fatal("%s: virtual servers configured,"
" but '%s' has no defaultserver defined", moduleName, path);
}
}
assert(defserver != NULL);
drvPtr->defMapPtr = NULL;
Ns_DStringInit(dsPtr);
for (j = 0u; j < Ns_SetSize(lset); ++j) {
const char *server = Ns_SetKey(lset, j);
const char *host = Ns_SetValue(lset, j);
NsServer *servPtr;
/*
* Perform an explicit lookup of the server.
*/
servPtr = NsGetServer(server);
if (servPtr == NULL) {
Ns_Log(Error, "%s: no such server: %s", moduleName, server);
} else {
char *writableHost, *hostName, *portStart;
writableHost = ns_strdup(host);
Ns_HttpParseHost(writableHost, &hostName, &portStart);
if (portStart == NULL) {
Tcl_DString hostDString;
/*
* The provided host entry does NOT contain a port.
*
* Add the provided entry to the virtual server map only,
* when the configured port is the default port for the
* protocol.
*/
if (drvPtr->port == drvPtr->defport) {
ServerMapEntryAdd(dsPtr, host, servPtr, drvPtr,
STREQ(defserver, server));
}
/*
* Auto-add configured port: Add always an entry with the
* explicitly configured port of the driver.
*/
Tcl_DStringInit(&hostDString);
Tcl_DStringAppend(&hostDString, host, -1);
(void) Ns_DStringPrintf(&hostDString, ":%hu", drvPtr->port);
ServerMapEntryAdd(dsPtr, hostDString.string, servPtr, drvPtr,
STREQ(defserver, server));
Tcl_DStringFree(&hostDString);
} else {
/*
* The provided host entry does contain a port.
*
* In case, the provided port is equal to the configured port
* of the driver, add an entry.
*/
unsigned short providedPort = (unsigned short)strtol(portStart+1, NULL, 10);
if (providedPort == drvPtr->port) {
ServerMapEntryAdd(dsPtr, host, servPtr, drvPtr,
STREQ(defserver, server));
/*
* In case, the provided port is equal to the default
* port of the driver, make sure that we have an entry
* without the port.
*/
if (providedPort == drvPtr->defport) {
ServerMapEntryAdd(dsPtr, hostName, servPtr, drvPtr,
STREQ(defserver, server));
}
} else {
Ns_Log(Warning, "%s: driver is listening on port %hu; "
"virtual host entry %s ignored",
moduleName, drvPtr->port, host);
}
}
ns_free(writableHost);
}
}
Ns_DStringFree(dsPtr);
if (drvPtr->defMapPtr == NULL) {
fprintf(stderr, "--- Server Map: ---\n");
Ns_SetPrint(lset);
Ns_Fatal("%s: default server '%s' not defined in '%s'", moduleName, defserver, path);
}
}
}
|
CWE-787
| null | 519,557 |
115675411260172737613462854046158231530
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
WriteWarningRaw(const char *msg, int fd, size_t wantWrite, ssize_t written)
{
fprintf(stderr, "%s: Warning: wanted to write %" PRIuz
" bytes, wrote %ld to file descriptor %d\n",
msg, wantWrite, (long)written, fd);
}
|
CWE-787
| null | 519,558 |
294507782949031019358854744229655472872
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
Ns_DriverInit(const char *server, const char *module, const Ns_DriverInitData *init)
{
Ns_ReturnCode status = NS_OK;
NsServer *servPtr = NULL;
bool alreadyInitialized = NS_FALSE;
NS_NONNULL_ASSERT(module != NULL);
NS_NONNULL_ASSERT(init != NULL);
/*
* If a server is provided, servPtr must be set.
*/
if (server != NULL) {
servPtr = NsGetServer(server);
if (unlikely(servPtr == NULL)) {
Ns_Log(Bug, "cannot lookup server structure for server: %s", module);
status = NS_ERROR;
}
} else {
alreadyInitialized = DriverModuleInitialized(module);
}
/*
* Check versions of drivers.
*/
if (status == NS_OK && init->version < NS_DRIVER_VERSION_4) {
Ns_Log(Warning, "%s: driver version is too old (version %d), Version 4 is recommended",
module, init->version);
}
#ifdef HAVE_IPV6
if (status == NS_OK && init->version < NS_DRIVER_VERSION_3) {
Ns_Log(Error, "%s: driver version is too old (version %d) and does not support IPv6",
module, init->version);
status = NS_ERROR;
}
#endif
if (status == NS_OK && init->version < NS_DRIVER_VERSION_2) {
Ns_Log(Error, "%s: version field of driver is invalid: %d",
module, init->version);
status = NS_ERROR;
}
if (!alreadyInitialized && status == NS_OK) {
const char *path, *host, *address, *defserver;
bool noHostNameGiven;
int nrDrivers, nrBindaddrs = 0, result;
Ns_Set *set;
Tcl_Obj *bindaddrsObj, **objv;
path = ((init->path != NULL) ? init->path : Ns_ConfigGetPath(server, module, (char *)0L));
set = Ns_ConfigCreateSection(path);
/*
* Determine the "defaultserver" the "hostname" / "address" for
* binding to and/or the HTTP location string.
*/
defserver = Ns_ConfigGetValue(path, "defaultserver");
address = Ns_ConfigGetValue(path, "address");
host = Ns_ConfigGetValue(path, "hostname");
noHostNameGiven = (host == NULL);
/*
* If the listen address was not specified, attempt to determine it
* through a DNS lookup of the specified hostname or the server's
* primary hostname.
*/
if (address == NULL) {
Tcl_DString ds;
Tcl_DStringInit(&ds);
if (noHostNameGiven) {
host = Ns_InfoHostname();
}
if (Ns_GetAllAddrByHost(&ds, host) == NS_TRUE) {
address = ns_strdup(Tcl_DStringValue(&ds));
if (path != NULL) {
Ns_SetUpdate(set, "address", address);
}
Ns_Log(Notice, "no address given, obtained address '%s' from host name %s", address, host);
}
Tcl_DStringFree(&ds);
}
if (address == NULL) {
address = NS_IP_UNSPECIFIED;
Ns_Log(Notice, "no address given, set address to unspecified address %s", address);
}
bindaddrsObj = Tcl_NewStringObj(address, -1);
result = Tcl_ListObjGetElements(NULL, bindaddrsObj, &nrBindaddrs, &objv);
if (result != TCL_OK || nrBindaddrs < 1 || nrBindaddrs >= MAX_LISTEN_ADDR_PER_DRIVER) {
Ns_Fatal("%s: bindaddrs '%s' is not a valid Tcl list containing addresses (max %d)",
module, address, MAX_LISTEN_ADDR_PER_DRIVER);
}
Tcl_IncrRefCount(bindaddrsObj);
/*
* If the hostname was not specified and not determined by the lookup
* above, set it to the first specified or derived IP address string.
*/
if (host == NULL) {
host = ns_strdup(Tcl_GetString(objv[0]));
}
if (noHostNameGiven && host != NULL && path != NULL) {
Ns_SetUpdate(set, "hostname", host);
}
Tcl_DecrRefCount(bindaddrsObj);
/*
* Get configured number of driver threads.
*/
nrDrivers = Ns_ConfigIntRange(path, "driverthreads", 1, 1, 64);
if (nrDrivers > 1) {
#if !defined(SO_REUSEPORT)
Ns_Log(Warning,
"server %s module %s requests %d driverthreads, but is not supported by the operating system",
server, module, nrDrivers);
Ns_SetUpdate(set, "driverthreads", "1");
nrDrivers = 1;
#endif
}
/*
* The common parameters are determined, create the driver thread(s)
*/
{
size_t maxModuleNameLength = strlen(module) + (size_t)TCL_INTEGER_SPACE + 1u;
char *moduleName = ns_malloc(maxModuleNameLength);
int i;
if (host == NULL) {
host = Ns_InfoHostname();
}
for (i = 0; i < nrDrivers; i++) {
snprintf(moduleName, maxModuleNameLength, "%s:%d", module, i);
status = DriverInit(server, module, moduleName, init,
servPtr, path,
address, defserver, host);
if (status != NS_OK) {
break;
}
}
ns_free(moduleName);
}
}
return status;
}
|
CWE-787
| null | 519,559 |
174307669063913066911316768985516649772
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
WriterGetInfoPtr(WriterSock *curPtr, Tcl_HashTable *pools)
{
NS_NONNULL_ASSERT(curPtr != NULL);
NS_NONNULL_ASSERT(pools != NULL);
if (curPtr->infoPtr == NULL) {
int isNew;
Tcl_HashEntry *hPtr;
hPtr = Tcl_CreateHashEntry(pools, (void*)curPtr->poolPtr, &isNew);
if (isNew == 1) {
/*
* This is a pool that we have not seen yet.
*/
curPtr->infoPtr = ns_malloc(sizeof(ConnPoolInfo));
curPtr->infoPtr->currentPoolRate = 0;
curPtr->infoPtr->threadSlot =
NsPoolAllocateThreadSlot(curPtr->poolPtr, Ns_ThreadId());
Tcl_SetHashValue(hPtr, curPtr->infoPtr);
Ns_Log(DriverDebug, "poollimit: pool '%s' allocate infoPtr with slot %lu poolLimit %d",
curPtr->poolPtr->pool,
curPtr->infoPtr->threadSlot,
curPtr->poolPtr->rate.poolLimit);
} else {
curPtr->infoPtr = (ConnPoolInfo *)Tcl_GetHashValue(hPtr);
}
}
return curPtr->infoPtr;
}
|
CWE-787
| null | 519,560 |
134953294861187833898999571665165995079
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
AsyncLogfileOpenObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv)
{
int result = TCL_OK;
unsigned int flags = O_APPEND;
char *fileNameString;
Tcl_Obj *flagsObj = NULL;
Ns_ObjvTable flagTable[] = {
{"APPEND", O_APPEND},
{"EXCL", O_EXCL},
#ifdef O_DSYNC
{"DSYNC", O_DSYNC},
#endif
#ifdef O_SYNC
{"SYNC", O_SYNC},
#endif
{"TRUNC", O_TRUNC},
{NULL, 0u}
};
Ns_ObjvSpec args[] = {
{"filename", Ns_ObjvString, &fileNameString, NULL},
{"?flags", Ns_ObjvObj, &flagsObj, NULL},
//{"mode", Ns_ObjvString, &mode, NULL},
{NULL, NULL, NULL, NULL}
};
if (unlikely(Ns_ParseObjv(NULL, args, interp, 2, objc, objv) != NS_OK)) {
result = TCL_ERROR;
} else if (flagsObj != NULL) {
Tcl_Obj **ov;
int oc;
result = Tcl_ListObjGetElements(interp, flagsObj, &oc, &ov);
if (result == TCL_OK && oc > 0) {
int i, opt;
flags = 0u;
for (i = 0; i < oc; i++) {
result = Tcl_GetIndexFromObjStruct(interp, ov[i], flagTable,
(int)sizeof(flagTable[0]),
"flag", 0, &opt);
if (result != TCL_OK) {
break;
} else {
flags = flagTable[opt].value;
}
}
}
}
if (result == TCL_OK) {
int fd;
fd = ns_open(fileNameString, (int)(O_CREAT | O_WRONLY | O_CLOEXEC | flags), 0644);
if (unlikely(fd == NS_INVALID_FD)) {
Ns_TclPrintfResult(interp, "could not open file '%s': %s",
fileNameString, Tcl_PosixError(interp));
result = TCL_ERROR;
} else {
Tcl_SetObjResult(interp, Tcl_NewIntObj(fd));
}
}
return result;
}
|
CWE-787
| null | 519,561 |
231121421326062729462166082425839213196
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
NsStopDrivers(void)
{
Driver *drvPtr;
NsAsyncWriterQueueDisable(NS_TRUE);
for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) {
Tcl_HashEntry *hPtr;
Tcl_HashSearch search;
if ((drvPtr->flags & DRIVER_STARTED) == 0u) {
continue;
}
Ns_MutexLock(&drvPtr->lock);
Ns_Log(Notice, "[driver:%s]: stopping", drvPtr->threadName);
drvPtr->flags |= DRIVER_SHUTDOWN;
Ns_CondBroadcast(&drvPtr->cond);
Ns_MutexUnlock(&drvPtr->lock);
SockTrigger(drvPtr->trigger[1]);
hPtr = Tcl_FirstHashEntry(&drvPtr->hosts, &search);
while (hPtr != NULL) {
Tcl_DeleteHashEntry(hPtr);
hPtr = Tcl_NextHashEntry(&search);
}
}
}
|
CWE-787
| null | 519,562 |
210286504979891165032577495059290146857
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
SpoolerThread(void *arg)
{
SpoolerQueue *queuePtr = (SpoolerQueue*)arg;
char charBuffer[1];
int pollTimeout;
bool stopping;
Sock *sockPtr, *nextPtr, *waitPtr, *readPtr;
Ns_Time now, diff;
const Driver *drvPtr;
PollData pdata;
Ns_ThreadSetName("-spooler%d-", queuePtr->id);
queuePtr->threadName = Ns_ThreadGetName();
/*
* Loop forever until signaled to shut down and all
* connections are complete and gracefully closed.
*/
Ns_Log(Notice, "spooler%d: accepting connections", queuePtr->id);
PollCreate(&pdata);
Ns_GetTime(&now);
waitPtr = readPtr = NULL;
stopping = NS_FALSE;
while (!stopping) {
/*
* If there are any read sockets, set the bits
* and determine the minimum relative timeout.
*/
PollReset(&pdata);
(void)PollSet(&pdata, queuePtr->pipe[0], (short)POLLIN, NULL);
if (readPtr == NULL) {
pollTimeout = 30 * 1000;
} else {
sockPtr = readPtr;
while (sockPtr != NULL) {
SockPoll(sockPtr, (short)POLLIN, &pdata);
sockPtr = sockPtr->nextPtr;
}
pollTimeout = -1;
}
/*
* Select and drain the trigger pipe if necessary.
*/
/*n =*/ (void) PollWait(&pdata, pollTimeout);
if (PollIn(&pdata, 0) && unlikely(ns_recv(queuePtr->pipe[0], charBuffer, 1u, 0) != 1)) {
Ns_Fatal("spooler: trigger ns_recv() failed: %s",
ns_sockstrerror(ns_sockerrno));
}
/*
* Attempt read-ahead of any new connections.
*/
Ns_GetTime(&now);
sockPtr = readPtr;
readPtr = NULL;
while (sockPtr != NULL) {
nextPtr = sockPtr->nextPtr;
drvPtr = sockPtr->drvPtr;
if (unlikely(PollHup(&pdata, sockPtr->pidx))) {
/*
* Peer has closed the connection
*/
SockRelease(sockPtr, SOCK_CLOSE, 0);
} else if (!PollIn(&pdata, sockPtr->pidx)) {
/*
* Got no data
*/
if (Ns_DiffTime(&sockPtr->timeout, &now, &diff) <= 0) {
SockRelease(sockPtr, SOCK_READTIMEOUT, 0);
queuePtr->queuesize--;
} else {
Push(sockPtr, readPtr);
}
} else {
/*
* Got some data
*/
SockState n = SockRead(sockPtr, 1, &now);
switch (n) {
case SOCK_MORE:
SockTimeout(sockPtr, &now, &drvPtr->recvwait);
Push(sockPtr, readPtr);
break;
case SOCK_READY:
assert(sockPtr->reqPtr != NULL);
SockSetServer(sockPtr);
Push(sockPtr, waitPtr);
break;
case SOCK_BADHEADER: NS_FALL_THROUGH; /* fall through */
case SOCK_BADREQUEST: NS_FALL_THROUGH; /* fall through */
case SOCK_CLOSE: NS_FALL_THROUGH; /* fall through */
case SOCK_CLOSETIMEOUT: NS_FALL_THROUGH; /* fall through */
case SOCK_ENTITYTOOLARGE: NS_FALL_THROUGH; /* fall through */
case SOCK_ERROR: NS_FALL_THROUGH; /* fall through */
case SOCK_READERROR: NS_FALL_THROUGH; /* fall through */
case SOCK_READTIMEOUT: NS_FALL_THROUGH; /* fall through */
case SOCK_SHUTERROR: NS_FALL_THROUGH; /* fall through */
case SOCK_SPOOL: NS_FALL_THROUGH; /* fall through */
case SOCK_TOOMANYHEADERS: NS_FALL_THROUGH; /* fall through */
case SOCK_WRITEERROR: NS_FALL_THROUGH; /* fall through */
case SOCK_WRITETIMEOUT:
SockRelease(sockPtr, n, errno);
queuePtr->queuesize--;
break;
}
}
sockPtr = nextPtr;
}
/*
* Attempt to queue any pending connection
* after reversing the list to ensure oldest
* connections are tried first.
*/
if (waitPtr != NULL) {
sockPtr = NULL;
while ((nextPtr = waitPtr) != NULL) {
waitPtr = nextPtr->nextPtr;
Push(nextPtr, sockPtr);
}
while (sockPtr != NULL) {
nextPtr = sockPtr->nextPtr;
if (!NsQueueConn(sockPtr, &now)) {
Push(sockPtr, waitPtr);
} else {
queuePtr->queuesize--;
}
sockPtr = nextPtr;
}
}
/*
* Add more connections from the spooler queue
*/
Ns_MutexLock(&queuePtr->lock);
if (waitPtr == NULL) {
sockPtr = (Sock*)queuePtr->sockPtr;
queuePtr->sockPtr = NULL;
while (sockPtr != NULL) {
nextPtr = sockPtr->nextPtr;
drvPtr = sockPtr->drvPtr;
SockTimeout(sockPtr, &now, &drvPtr->recvwait);
Push(sockPtr, readPtr);
queuePtr->queuesize++;
sockPtr = nextPtr;
}
}
/*
* Check for shutdown
*/
stopping = queuePtr->shutdown;
Ns_MutexUnlock(&queuePtr->lock);
}
PollFree(&pdata);
Ns_Log(Notice, "exiting");
Ns_MutexLock(&queuePtr->lock);
queuePtr->stopped = NS_TRUE;
Ns_CondBroadcast(&queuePtr->cond);
Ns_MutexUnlock(&queuePtr->lock);
}
|
CWE-787
| null | 519,563 |
206464726607207633931017443208120950610
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
SockParse(Sock *sockPtr)
{
const Tcl_DString *bufPtr;
const Driver *drvPtr;
Request *reqPtr;
char save;
SockState result;
NS_NONNULL_ASSERT(sockPtr != NULL);
drvPtr = sockPtr->drvPtr;
NsUpdateProgress((Ns_Sock *) sockPtr);
reqPtr = sockPtr->reqPtr;
bufPtr = &reqPtr->buffer;
/*
* Scan lines (header) until start of content (body-part)
*/
while (reqPtr->coff == 0u) {
char *s, *e;
size_t cnt;
/*
* Find the next header line.
*/
s = bufPtr->string + reqPtr->roff;
e = memchr(s, INTCHAR('\n'), reqPtr->avail);
if (unlikely(e == NULL)) {
/*
* Input not yet newline terminated - request more data.
*/
return SOCK_MORE;
}
/*
* Check for max single line overflows.
*
* Previous versions if the driver returned here directly an
* error code, which was handled via HTTP error message
* provided via SockError(). However, the SockError() handling
* closes the connection immediately. This has the
* consequence, that the HTTP client might never see the error
* message, since the request was not yet fully transmitted,
* but it will see a "broken pipe: 13" message instead. We
* read now the full request and return the message via
* ConnRunRequest().
*/
if (unlikely((e - s) > drvPtr->maxline)) {
sockPtr->keep = NS_FALSE;
if (reqPtr->request.line == NULL) {
Ns_Log(DriverDebug, "SockParse: maxline reached of %d bytes",
drvPtr->maxline);
sockPtr->flags = NS_CONN_REQUESTURITOOLONG;
Ns_Log(Warning, "request line is too long (%d bytes)", (int)(e - s));
} else {
sockPtr->flags = NS_CONN_LINETOOLONG;
Ns_Log(Warning, "request header line is too long (%d bytes)", (int)(e - s));
}
}
/*
* Update next read pointer to end of this line.
*/
cnt = (size_t)(e - s) + 1u;
reqPtr->roff += cnt;
reqPtr->avail -= cnt;
/*
* Adjust end pointer to the last content character before the line
* terminator.
*/
if (likely(e > s) && likely(*(e-1) == '\r')) {
--e;
}
/*
* Check for end of headers in case we have not done it yet.
*/
if (unlikely(e == s) && (reqPtr->coff == 0u)) {
/*
* We are at end of headers.
*/
reqPtr->coff = EndOfHeader(sockPtr);
/*
* In cases the client sent "expect: 100-continue", report back that
* everything is fine with the headers.
*/
if ((sockPtr->flags & NS_CONN_CONTINUE) != 0u) {
Ns_Log(Ns_LogRequestDebug, "honoring 100-continue");
/*
* In case, the request entity (body) was too large, we can
* return immediately the error message, when the client has
* flagged this via "Expect:". Otherwise we have to read the
* full request (although it is too large) to drain the
* channel. Otherwise, the server might close the connection
* *before* it has received full request with its body from
* the client. We just keep the flag and let
* Ns_ConnRunRequest() handle the error message.
*/
if ((sockPtr->flags & NS_CONN_ENTITYTOOLARGE) != 0u) {
Ns_Log(Ns_LogRequestDebug, "100-continue: entity too large");
return SOCK_ENTITYTOOLARGE;
/*
* We have no other error message flagged (future ones
* have to be handled here).
*/
} else {
struct iovec iov[1];
ssize_t sent;
/*
* Reply with "100 continue".
*/
Ns_Log(Ns_LogRequestDebug, "100-continue: reply CONTINUE");
iov[0].iov_base = (char *)"HTTP/1.1 100 Continue\r\n\r\n";
iov[0].iov_len = strlen(iov[0].iov_base);
sent = Ns_SockSendBufs((Ns_Sock *)sockPtr, iov, 1,
NULL, 0u);
if (sent != (ssize_t)iov[0].iov_len) {
Ns_Log(Warning, "could not deliver response: 100 Continue");
/*
* Should we bail out here?
*/
}
}
}
} else {
/*
* We have the request-line or a header line to process.
*/
save = *e;
*e = '\0';
if (unlikely(reqPtr->request.line == NULL)) {
/*
* There is no request-line set. The received line must the
* the request-line.
*/
Ns_Log(DriverDebug, "SockParse (%d): parse request line <%s>", sockPtr->sock, s);
if (Ns_ParseRequest(&reqPtr->request, s) == NS_ERROR) {
/*
* Invalid request.
*/
return SOCK_BADREQUEST;
}
/*
* HTTP 0.9 did not have a HTTP-version number or request headers
* and no empty line terminating the request header.
*/
if (unlikely(reqPtr->request.version < 1.0)) {
/*
* Pre-HTTP/1.0 request.
*/
reqPtr->coff = reqPtr->roff;
Ns_Log(Notice, "pre-HTTP/1.0 request <%s>", reqPtr->request.line);
}
} else if (Ns_ParseHeader(reqPtr->headers, s, Preserve) != NS_OK) {
/*
* Invalid header.
*/
return SOCK_BADHEADER;
} else {
/*
* Check for max number of headers
*/
if (unlikely(Ns_SetSize(reqPtr->headers) > (size_t)drvPtr->maxheaders)) {
Ns_Log(DriverDebug, "SockParse (%d): maxheaders reached of %d bytes",
sockPtr->sock, drvPtr->maxheaders);
return SOCK_TOOMANYHEADERS;
}
}
*e = save;
}
}
if (unlikely(reqPtr->request.line == NULL)) {
/*
* We are at end of headers, but we have not parsed a request line
* (maybe just two linefeeds).
*/
return SOCK_BADREQUEST;
}
/*
* We are in the request body.
*/
assert(reqPtr->coff > 0u);
assert(reqPtr->request.line != NULL);
/*
* Check if all content has arrived.
*/
Ns_Log(Debug, "=== length < avail (length %" PRIuz
", avail %" PRIuz ") tfd %d tfile %p chunkStartOff %" PRIuz,
reqPtr->length, reqPtr->avail, sockPtr->tfd,
(void *)sockPtr->tfile, reqPtr->chunkStartOff);
if (reqPtr->chunkStartOff != 0u) {
/*
* Chunked encoding was provided.
*/
SockState chunkState;
size_t currentContentLength;
chunkState = ChunkedDecode(reqPtr, NS_TRUE);
currentContentLength = reqPtr->chunkWriteOff - reqPtr->coff;
/*
* A chunk might be complete, but it might not be the last
* chunk from the client. The best thing would be to be able
* to read until EOF here. In cases, where the (optional)
* "expectedLength" was provided by the client, we terminate
* depending on that information
*/
if ((chunkState == SOCK_MORE)
|| (reqPtr->expectedLength != 0u && currentContentLength < reqPtr->expectedLength)) {
/*
* ChunkedDecode wants more data.
*/
return SOCK_MORE;
} else if (chunkState != SOCK_READY) {
return chunkState;
}
/*
* ChunkedDecode has enough data.
*/
reqPtr->length = (size_t)currentContentLength;
}
if (reqPtr->avail < reqPtr->length) {
Ns_Log(DriverDebug, "SockRead wait for more input");
/*
* Wait for more input.
*/
return SOCK_MORE;
}
Ns_Log(Dev, "=== all required data is available (avail %" PRIuz", length %" PRIuz ", "
"readahead %" TCL_LL_MODIFIER "d maxupload %" TCL_LL_MODIFIER "d) tfd %d",
reqPtr->avail, reqPtr->length, drvPtr->readahead, drvPtr->maxupload,
sockPtr->tfd);
/*
* We have all required data in the receive buffer or in a temporary file.
*
* - Uploads > "readahead": these are put into temporary files.
*
* - Uploads > "maxupload": these are put into temporary files
* without mmapping, no content parsing will be performed in memory.
*/
result = SOCK_READY;
if (sockPtr->tfile != NULL) {
reqPtr->content = NULL;
reqPtr->next = NULL;
reqPtr->avail = 0u;
Ns_Log(DriverDebug, "content spooled to file: size %" PRIdz ", file %s",
reqPtr->length, sockPtr->tfile);
/*
* Nothing more to do, return via SOCK_READY;
*/
} else {
/*
* Uploads < "maxupload" are spooled to files and mmapped in order to
* provide the usual interface via [ns_conn content].
*/
if (sockPtr->tfd > 0) {
#ifdef _WIN32
/*
* For _WIN32, tfd should never be set, since tfd-spooling is not
* implemented for windows.
*/
assert(0);
#else
int prot = PROT_READ | PROT_WRITE;
/*
* Add a byte to make sure, the string termination with \0 below falls
* always into the mmapped area. On some older OSes this might lead to
* crashes when we hitting page boundaries.
*/
ssize_t rc = ns_write(sockPtr->tfd, "\0", 1);
if (rc == -1) {
Ns_Log(Error, "socket: could not append terminating 0-byte");
}
sockPtr->tsize = reqPtr->length + 1;
sockPtr->taddr = mmap(0, sockPtr->tsize, prot, MAP_PRIVATE,
sockPtr->tfd, 0);
if (sockPtr->taddr == MAP_FAILED) {
sockPtr->taddr = NULL;
result = SOCK_ERROR;
} else {
reqPtr->content = sockPtr->taddr;
Ns_Log(Debug, "content spooled to mmapped file: readahead=%"
TCL_LL_MODIFIER "d, filesize=%" PRIdz,
drvPtr->readahead, sockPtr->tsize);
}
#endif
} else {
/*
* Set the content the begin of the remaining buffer (content offset).
* This happens as well when reqPtr->contentLength is 0, but it is
* needed for chunked input processing.
*/
reqPtr->content = bufPtr->string + reqPtr->coff;
}
reqPtr->next = reqPtr->content;
/*
* Add a terminating null character. The content might be from the receive
* buffer (Tcl_DString) or from the mmapped file. Non-mmapped files are handled
* above.
*/
if (reqPtr->length > 0u) {
Ns_Log(DriverDebug, "SockRead adds null terminating character at content[%" PRIuz "]", reqPtr->length);
reqPtr->savedChar = reqPtr->content[reqPtr->length];
reqPtr->content[reqPtr->length] = '\0';
if (sockPtr->taddr == NULL) {
LogBuffer(DriverDebug, "UPDATED BUFFER", sockPtr->reqPtr->buffer.string, (size_t)reqPtr->buffer.length);
}
}
}
return result;
}
|
CWE-787
| null | 519,564 |
133242962098013839151738445998407982698
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
DriverWriterFromObj( Tcl_Interp *interp, Tcl_Obj *driverObj, Ns_Conn *conn, DrvWriter **wrPtrPtr) {
Driver *drvPtr;
const char *driverName = NULL;
int driverNameLen = 0;
DrvWriter *wrPtr = NULL;
Ns_ReturnCode result;
/*
* If no driver is provided, take the current driver. The caller has
* to make sure that in cases, where no driver is specified, the
* command is run in a connection thread.
*/
if (driverObj == NULL) {
if (conn != NULL) {
driverName = Ns_ConnDriverName(conn);
driverNameLen = (int)strlen(driverName);
}
} else {
driverName = Tcl_GetStringFromObj(driverObj, &driverNameLen);
}
if (driverName != NULL) {
for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) {
if (strncmp(driverName, drvPtr->threadName, (size_t)driverNameLen) == 0) {
if (drvPtr->writer.firstPtr != NULL) {
wrPtr = &drvPtr->writer;
}
break;
}
}
}
if (unlikely(wrPtr == NULL)) {
Ns_TclPrintfResult(interp, "no writer configured for a driver with name %s",
driverName);
result = NS_ERROR;
} else {
*wrPtrPtr = wrPtr;
result = NS_OK;
}
return result;
}
|
CWE-787
| null | 519,565 |
248997038015597514762198258815544325287
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
NsDriverSendFile(Sock *sockPtr, Ns_FileVec *bufs, int nbufs, unsigned int flags)
{
ssize_t sent = -1;
const Driver *drvPtr;
NS_NONNULL_ASSERT(sockPtr != NULL);
NS_NONNULL_ASSERT(bufs != NULL);
drvPtr = sockPtr->drvPtr;
NS_NONNULL_ASSERT(drvPtr != NULL);
if (drvPtr->sendFileProc != NULL) {
/*
* TODO: The Ns_DriverSendFileProc signature should be modified
* to omit the timeout argument.
*/
sent = (*drvPtr->sendFileProc)((Ns_Sock *)sockPtr, bufs, nbufs, NULL, flags);
} else {
sent = Ns_SockSendFileBufs((Ns_Sock *)sockPtr, bufs, nbufs, flags);
}
return sent;
}
|
CWE-787
| null | 519,566 |
298398949884690051106213029068766299056
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
SockSetServer(Sock *sockPtr)
{
char *host;
Request *reqPtr;
bool bad_request = NS_FALSE;
Driver *drvPtr;
NS_NONNULL_ASSERT(sockPtr != NULL);
reqPtr = sockPtr->reqPtr;
assert(reqPtr != NULL);
drvPtr = sockPtr->drvPtr;
assert(drvPtr != NULL);
sockPtr->servPtr = drvPtr->servPtr;
sockPtr->location = drvPtr->location;
host = Ns_SetIGet(reqPtr->headers, "Host");
Ns_Log(DriverDebug, "SockSetServer host '%s' request line '%s'", host, reqPtr->request.line);
if (unlikely((host == NULL) && (reqPtr->request.version >= 1.1))) {
/*
* HTTP/1.1 requires host header
*/
Ns_Log(Notice, "request header field \"Host\" is missing in HTTP/1.1 request: \"%s\"\n",
reqPtr->request.line);
bad_request = NS_TRUE;
}
if (sockPtr->servPtr == NULL) {
const ServerMap *mapPtr = NULL;
if (host != NULL) {
const Tcl_HashEntry *hPtr;
size_t hostLength = strlen(host);
/*
* Remove trailing dot of host header field, since RFC 2976 allows
* fully qualified "absolute" DNS names in host fields (see e.g. §3.2.2).
*/
if (host[hostLength] == '.') {
host[hostLength] = '\0';
}
/*
* Convert provided host header field to lower case before hash
* lookup.
*/
Ns_StrToLower(host);
hPtr = Tcl_FindHashEntry(&drvPtr->hosts, host);
Ns_Log(DriverDebug, "SockSetServer driver '%s' host '%s' => %p",
drvPtr->moduleName, host, (void*)hPtr);
if (hPtr != NULL) {
/*
* Request with provided host header field could be resolved
* against a certain server.
*/
mapPtr = Tcl_GetHashValue(hPtr);
} else {
/*
* Host header field content is not found in the mapping table.
*/
Ns_Log(DriverDebug,
"cannot locate host header content '%s' in virtual hosts "
"table of driver '%s', fall back to default '%s'",
host, drvPtr->moduleName,
drvPtr->defMapPtr->location);
if (Ns_LogSeverityEnabled(DriverDebug)) {
Tcl_HashEntry *hPtr2;
Tcl_HashSearch search;
hPtr2 = Tcl_FirstHashEntry(&drvPtr->hosts, &search);
while (hPtr2 != NULL) {
Ns_Log(Notice, "... host entry: '%s'\n",
(char *)Tcl_GetHashKey(&drvPtr->hosts, hPtr2));
hPtr2 = Tcl_NextHashEntry(&search);
}
}
}
}
if (mapPtr == NULL) {
/*
* Could not lookup the virtual host, Get the default mapping from the driver.
*/
mapPtr = drvPtr->defMapPtr;
}
if (mapPtr != NULL) {
sockPtr->servPtr = mapPtr->servPtr;
sockPtr->location = mapPtr->location;
}
if (sockPtr->servPtr == NULL) {
Ns_Log(Warning, "cannot determine server for request: \"%s\" (host \"%s\")\n",
reqPtr->request.line, host);
bad_request = NS_TRUE;
}
}
if (unlikely(bad_request)) {
Ns_Log(DriverDebug, "SockSetServer sets method to BAD");
ns_free((char *)reqPtr->request.method);
reqPtr->request.method = ns_strdup("BAD");
}
}
|
CWE-787
| null | 519,567 |
276923340589032767124465081459689334188
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
AsyncLogfileWriteObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv)
{
int result = TCL_OK, binary = (int)NS_FALSE, sanitize;
Tcl_Obj *stringObj;
int fd = 0;
Ns_ObjvValueRange fd_range = {0, INT_MAX};
Ns_ObjvValueRange sanitize_range = {0, 2};
Ns_ObjvSpec opts[] = {
{"-binary", Ns_ObjvBool, &binary, INT2PTR(NS_TRUE)},
{"-sanitize", Ns_ObjvInt, &sanitize, &sanitize_range},
{NULL, NULL, NULL, NULL}
};
Ns_ObjvSpec args[] = {
{"fd", Ns_ObjvInt, &fd, &fd_range},
{"buffer", Ns_ObjvObj, &stringObj, NULL},
{NULL, NULL, NULL, NULL}
};
/*
* Take the config value as default for "-sanitize", but let the used
* override it on a per-case basis.
*/
sanitize = nsconf.sanitize_logfiles;
if (unlikely(Ns_ParseObjv(opts, args, interp, 2, objc, objv) != NS_OK)) {
result = TCL_ERROR;
} else {
const char *buffer;
int length;
Ns_ReturnCode rc;
if (binary == (int)NS_TRUE || NsTclObjIsByteArray(stringObj)) {
buffer = (const char *) Tcl_GetByteArrayFromObj(stringObj, &length);
} else {
buffer = Tcl_GetStringFromObj(stringObj, &length);
}
if (length > 0) {
if (sanitize > 0) {
Tcl_DString ds;
bool lastCharNewline = (buffer[length-1] == '\n');
Tcl_DStringInit(&ds);
if (lastCharNewline) {
length --;
}
Ns_DStringAppendPrintable(&ds, sanitize == 2, buffer, (size_t)length);
if (lastCharNewline) {
Tcl_DStringAppend(&ds, "\n", 1);
}
rc = NsAsyncWrite(fd, ds.string, (size_t)ds.length);
Tcl_DStringFree(&ds);
} else {
rc = NsAsyncWrite(fd, buffer, (size_t)length);
}
if (rc != NS_OK) {
Ns_TclPrintfResult(interp, "ns_asynclogfile: error during write operation on fd %d: %s",
fd, Tcl_PosixError(interp));
result = TCL_ERROR;
}
} else {
result = TCL_OK;
}
}
return result;
}
|
CWE-787
| null | 519,568 |
39768387092035288346840279721968773237
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
NsDriverRecv(Sock *sockPtr, struct iovec *bufs, int nbufs, Ns_Time *timeoutPtr)
{
ssize_t result;
const Driver *drvPtr;
NS_NONNULL_ASSERT(sockPtr != NULL);
drvPtr = sockPtr->drvPtr;
if (likely(drvPtr->recvProc != NULL)) {
result = (*drvPtr->recvProc)((Ns_Sock *) sockPtr, bufs, nbufs, timeoutPtr, 0u);
} else {
Ns_Log(Warning, "driver: no recvProc registered for driver %s", drvPtr->threadName);
result = -1;
}
return result;
}
|
CWE-787
| null | 519,569 |
321962516509269539589438863080298478150
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
LookupDriver(Tcl_Interp *interp, const char* protocol, const char *driverName)
{
Driver *drvPtr;
NS_NONNULL_ASSERT(interp != NULL);
NS_NONNULL_ASSERT(protocol != NULL);
for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) {
Ns_Log(DriverDebug, "... check Driver proto <%s> server %s name %s location %s",
drvPtr->protocol, drvPtr->server, drvPtr->threadName, drvPtr->location);
if (STREQ(drvPtr->protocol, protocol)) {
if (driverName == NULL) {
/*
* If there is no driver name given, take the first driver
* with the matching protocol.
*/
break;
} else if (STREQ(drvPtr->moduleName, driverName)) {
/*
* The driver name (name of the loaded module) is equal
*/
break;
}
}
}
if (drvPtr == NULL) {
if (driverName != NULL) {
Ns_TclPrintfResult(interp, "no driver for protocol '%s' & driver name '%s' found", protocol, driverName);
} else {
Ns_TclPrintfResult(interp, "no driver for protocol '%s' found", protocol);
}
}
return drvPtr;
}
|
CWE-787
| null | 519,570 |
9821940944397784190425124642114394752
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
WriterSockFileVecCleanup(WriterSock *wrSockPtr) {
NS_NONNULL_ASSERT(wrSockPtr != NULL);
if ( wrSockPtr->c.file.nbufs > 0) {
int i;
Ns_Log(DriverDebug, "WriterSockRelease nbufs %d", wrSockPtr->c.file.nbufs);
for (i = 0; i < wrSockPtr->c.file.nbufs; i++) {
/*
* The fd of c.file.currentbuf is always the same as
* wrSockPtr->fd and therefore already closed at this point.
*/
if ( (i != wrSockPtr->c.file.currentbuf)
&& (wrSockPtr->c.file.bufs[i].fd != NS_INVALID_FD) ) {
Ns_Log(DriverDebug, "WriterSockRelease must close fd %d",
wrSockPtr->c.file.bufs[i].fd);
ns_close(wrSockPtr->c.file.bufs[i].fd);
}
}
ns_free(wrSockPtr->c.file.bufs);
}
ns_free(wrSockPtr->c.file.buf);
}
|
CWE-787
| null | 519,571 |
139049136732030815634191858838690760114
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
DriverStatsObjCmd(ClientData UNUSED(clientData), Tcl_Interp *interp, int objc, Tcl_Obj *const* objv)
{
int result = TCL_OK;
if (Ns_ParseObjv(NULL, NULL, interp, 2, objc, objv) != NS_OK) {
result = TCL_ERROR;
} else {
const Driver *drvPtr;
Tcl_Obj *resultObj = Tcl_NewListObj(0, NULL);
/*
* Iterate over all drivers and collect results.
*/
for (drvPtr = firstDrvPtr; drvPtr != NULL; drvPtr = drvPtr->nextPtr) {
Tcl_Obj *listObj = Tcl_NewListObj(0, NULL);
Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("thread", 6));
Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->threadName, -1));
Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("module", 6));
Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj(drvPtr->moduleName, -1));
Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("received", 8));
Tcl_ListObjAppendElement(interp, listObj, Tcl_NewWideIntObj(drvPtr->stats.received));
Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("spooled", 7));
Tcl_ListObjAppendElement(interp, listObj, Tcl_NewWideIntObj(drvPtr->stats.spooled));
Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("partial", 7));
Tcl_ListObjAppendElement(interp, listObj, Tcl_NewWideIntObj(drvPtr->stats.partial));
Tcl_ListObjAppendElement(interp, listObj, Tcl_NewStringObj("errors", 6));
Tcl_ListObjAppendElement(interp, listObj, Tcl_NewWideIntObj(drvPtr->stats.errors));
Tcl_ListObjAppendElement(interp, resultObj, listObj);
}
Tcl_SetObjResult(interp, resultObj);
}
return result;
}
|
CWE-787
| null | 519,572 |
202217782686266816716496754104516915324
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
NsGetRequest(Sock *sockPtr, const Ns_Time *nowPtr)
{
Request *reqPtr;
NS_NONNULL_ASSERT(sockPtr != NULL);
/*
* The underlying "Request" structure is allocated by RequestNew(), which
* must be called for the "sockPtr" prior to calling this
* function. "reqPtr" should be NULL just in error cases.
*/
reqPtr = sockPtr->reqPtr;
if (likely(reqPtr != NULL)) {
if (likely(reqPtr->request.line != NULL)) {
Ns_Log(DriverDebug, "NsGetRequest got the pre-parsed request <%s> from the driver",
reqPtr->request.line);
} else if (sockPtr->drvPtr->requestProc == NULL) {
/*
* Non-HTTP driver can send the drvPtr->requestProc to perform
* their own request handling.
*/
SockState status;
Ns_Log(DriverDebug, "NsGetRequest has to read+parse the request");
/*
* We have no parsed request so far. So, do it now.
*/
do {
Ns_Log(DriverDebug, "NsGetRequest calls SockRead");
status = SockRead(sockPtr, 0, nowPtr);
} while (status == SOCK_MORE);
/*
* If anything went wrong, clean the request provided by
* SockRead() and flag the error by returning NULL.
*/
if (status != SOCK_READY) {
if (sockPtr->reqPtr != NULL) {
Ns_Log(DriverDebug, "NsGetRequest calls RequestFree");
RequestFree(sockPtr);
}
reqPtr = NULL;
}
} else {
Ns_Log(DriverDebug, "NsGetRequest found driver specific request Proc, "
"probably from a non-HTTP driver");
}
} else {
Ns_Log(DriverDebug, "NsGetRequest has reqPtr NULL");
}
return reqPtr;
}
|
CWE-787
| null | 519,573 |
330070394251121066326953887233295250335
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
NsDriverSend(Sock *sockPtr, const struct iovec *bufs, int nbufs, unsigned int flags)
{
ssize_t sent = -1;
const Driver *drvPtr;
NS_NONNULL_ASSERT(sockPtr != NULL);
drvPtr = sockPtr->drvPtr;
NS_NONNULL_ASSERT(drvPtr != NULL);
if (likely(drvPtr->sendProc != NULL)) {
/*
* TODO: The Ns_DriverSendProc signature should be modified
* to omit the timeout argument. Same with recvProc().
*/
sent = (*drvPtr->sendProc)((Ns_Sock *) sockPtr, bufs, nbufs, NULL, flags);
} else {
Ns_Log(Warning, "no sendProc registered for driver %s", drvPtr->threadName);
}
return sent;
}
|
CWE-787
| null | 519,574 |
65032389506192771617747958335430059284
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
SockError(Sock *sockPtr, SockState reason, int err)
{
const char *errMsg = NULL;
NS_NONNULL_ASSERT(sockPtr != NULL);
switch (reason) {
case SOCK_READY:
case SOCK_SPOOL:
case SOCK_MORE:
case SOCK_CLOSE:
case SOCK_CLOSETIMEOUT:
/* This is normal, never log. */
break;
case SOCK_READTIMEOUT:
/*
* For this case, whether this is acceptable or not
* depends upon whether this sock was a keep-alive
* that we were allowing to 'linger'.
*/
if (!sockPtr->keep) {
errMsg = "Timeout during read";
}
break;
case SOCK_WRITETIMEOUT:
errMsg = "Timeout during write";
break;
case SOCK_READERROR:
errMsg = "Unable to read request";
break;
case SOCK_WRITEERROR:
errMsg = "Unable to write request";
break;
case SOCK_SHUTERROR:
errMsg = "Unable to shutdown socket";
break;
case SOCK_BADREQUEST:
errMsg = "Bad Request";
SockSendResponse(sockPtr, 400, errMsg);
break;
case SOCK_TOOMANYHEADERS:
errMsg = "Too Many Request Headers";
SockSendResponse(sockPtr, 414, errMsg);
break;
case SOCK_BADHEADER:
errMsg = "Invalid Request Header";
SockSendResponse(sockPtr, 400, errMsg);
break;
case SOCK_ENTITYTOOLARGE:
errMsg = "Request Entity Too Large";
SockSendResponse(sockPtr, 413, errMsg);
break;
case SOCK_ERROR:
errMsg = "Unknown Error";
SockSendResponse(sockPtr, 400, errMsg);
break;
}
if (errMsg != NULL) {
char ipString[NS_IPADDR_SIZE];
Ns_Log(DriverDebug, "SockError: %s (%d: %s), sock: %d, peer: [%s]:%d, request: %.99s",
errMsg,
err, (err != 0) ? strerror(err) : NS_EMPTY_STRING,
sockPtr->sock,
ns_inet_ntop((struct sockaddr *)&(sockPtr->sa), ipString, sizeof(ipString)),
Ns_SockaddrGetPort((struct sockaddr *)&(sockPtr->sa)),
(sockPtr->reqPtr != NULL) ? sockPtr->reqPtr->buffer.string : NS_EMPTY_STRING);
}
}
|
CWE-787
| null | 519,575 |
170256607521737435618594218187195241658
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
DriverKeep(Sock *sockPtr)
{
Ns_DriverKeepProc *keepProc;
bool result;
NS_NONNULL_ASSERT(sockPtr != NULL);
keepProc = sockPtr->drvPtr->keepProc;
if (keepProc == NULL) {
result = NS_FALSE;
} else {
result = (keepProc)((Ns_Sock *) sockPtr);
}
return result;
}
|
CWE-787
| null | 519,576 |
218362435558822450419585459079674960345
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
WriterCheckInputParams(Tcl_Interp *interp, const char *filenameString,
size_t size, off_t offset,
int *fdPtr, size_t *nrbytesPtr)
{
int result = TCL_OK, rc;
struct stat st;
Ns_Log(DriverDebug, "WriterCheckInputParams %s offset %" PROTd " size %" PRIdz,
filenameString, offset, size);
/*
* Use stat() call to obtain information about the actual file to check
* later the plausibility of the parameters.
*/
rc = stat(filenameString, &st);
if (unlikely(rc != 0)) {
Ns_TclPrintfResult(interp, "file does not exist '%s'", filenameString);
result = TCL_ERROR;
} else {
size_t nrbytes = 0u;
int fd;
/*
* Try to open the file and check offset and size parameters.
*/
fd = ns_open(filenameString, O_RDONLY | O_CLOEXEC, 0);
if (unlikely(fd == NS_INVALID_FD)) {
Ns_TclPrintfResult(interp, "could not open file '%s'", filenameString);
result = TCL_ERROR;
} else if (unlikely(offset > st.st_size) || offset < 0) {
Ns_TclPrintfResult(interp, "offset must be a positive value less or equal filesize");
result = TCL_ERROR;
} else if (size > 0) {
if (unlikely((off_t)size + offset > st.st_size)) {
Ns_TclPrintfResult(interp, "offset + size must be less or equal filesize");
result = TCL_ERROR;
} else {
nrbytes = (size_t)size;
}
} else {
nrbytes = (size_t)st.st_size - (size_t)offset;
}
/*
* When an offset is provide, jump to this offset.
*/
if (offset > 0 && result == TCL_OK) {
if (ns_lseek(fd, (off_t)offset, SEEK_SET) == -1) {
Ns_TclPrintfResult(interp, "cannot seek to position %ld", (long)offset);
result = TCL_ERROR;
}
}
if (result == TCL_OK) {
*fdPtr = fd;
*nrbytesPtr = nrbytes;
} else if (fd != NS_INVALID_FD) {
/*
* On invalid parameters, close the fd.
*/
ns_close(fd);
}
}
return result;
}
|
CWE-787
| null | 519,577 |
8343558210042320450470221200192641943
| null | null |
other
|
naviserver
|
a5c3079f1d8996d5f34c9384a440acf3519ca3bb
| 0 |
PollWait(const PollData *pdata, int timeout)
{
int n;
NS_NONNULL_ASSERT(pdata != NULL);
do {
n = ns_poll(pdata->pfds, pdata->nfds, timeout);
} while (n < 0 && errno == NS_EINTR);
if (n < 0) {
Ns_Fatal("PollWait: ns_poll() failed: %s", ns_sockstrerror(ns_sockerrno));
}
return n;
}
|
CWE-787
| null | 519,578 |
312207329677193001523105770751377772705
| null | null |
other
|
cbang
|
1c1dba62bd3e6fa9d0d0c0aa21926043b75382c7
| 0 |
string TarFileReader::extract(ostream &out) {
if (!hasMore()) THROW("No more tar files");
readFile(out, pri->filter);
didReadHeader = false;
return getFilename();
}
|
CWE-22
| null | 519,598 |
45780304938795084989898951068614526727
| null | null |
other
|
cbang
|
1c1dba62bd3e6fa9d0d0c0aa21926043b75382c7
| 0 |
std::string TarFileReader::extract(const string &_path) {
if (_path.empty()) THROW("path cannot be empty");
if (!hasMore()) THROW("No more tar files");
string path = _path;
if (SystemUtilities::isDirectory(path)) {
path += "/" + getFilename();
// Check that path is under the target directory
string a = SystemUtilities::getCanonicalPath(_path);
string b = SystemUtilities::getCanonicalPath(path);
if (!String::startsWith(b, a))
THROW("Tar path points outside of the extraction directory: " << path);
}
LOG_DEBUG(5, "Extracting: " << path);
switch (getType()) {
case NORMAL_FILE: case CONTIGUOUS_FILE:
return extract(*SystemUtilities::oopen(path));
case DIRECTORY: SystemUtilities::ensureDirectory(path); break;
default: THROW("Unsupported tar file type " << getType());
}
return getFilename();
}
|
CWE-22
| null | 519,599 |
126216347100984769286755428881470936529
| null | null |
other
|
cbang
|
1c1dba62bd3e6fa9d0d0c0aa21926043b75382c7
| 0 |
bool TarFileReader::next() {
if (didReadHeader) {
skipFile(pri->filter);
didReadHeader = false;
}
return hasMore();
}
|
CWE-22
| null | 519,600 |
317386185112947027180642838873030159151
| null | null |
other
|
cbang
|
1c1dba62bd3e6fa9d0d0c0aa21926043b75382c7
| 0 |
bool TarFileReader::hasMore() {
if (!didReadHeader) {
SysError::clear();
if (!readHeader(pri->filter))
THROW("Tar file read failed: " << SysError());
didReadHeader = true;
}
return !isEOF();
}
|
CWE-22
| null | 519,601 |
109603305081189413819935102573247671013
| null | null |
other
|
cbang
|
1c1dba62bd3e6fa9d0d0c0aa21926043b75382c7
| 0 |
TarFileReader::TarFileReader(const string &path, compression_t compression) :
pri(new private_t), stream(SystemUtilities::iopen(path)),
didReadHeader(false) {
addCompression(compression == TARFILE_AUTO ? infer(path) : compression);
pri->filter.push(*this->stream);
}
|
CWE-22
| null | 519,602 |
274172865317188969369492896908396921773
| null | null |
other
|
cbang
|
1c1dba62bd3e6fa9d0d0c0aa21926043b75382c7
| 0 |
int main(int argc, char *argv[]) {
try {
for (int i = 1; i < argc; i++) {
string arg = argv[i];
if (arg == "--extract" && i < argc - 1) {
TarFileReader reader(argv[++i]);
while (reader.hasMore())
cout << reader.extract() << endl;
} else THROWS("Invalid arg '" << arg << "'");
}
return 0;
} catch (const Exception &e) {cerr << e.getMessage();}
return 1;
}
|
CWE-22
| null | 519,603 |
192360835161596799581671425287832396798
| null | null |
other
|
cbang
|
1c1dba62bd3e6fa9d0d0c0aa21926043b75382c7
| 0 |
TarFileReader::~TarFileReader() {
delete pri;
}
|
CWE-22
| null | 519,604 |
333425492903905954509763922923938175259
| null | null |
other
|
cbang
|
1c1dba62bd3e6fa9d0d0c0aa21926043b75382c7
| 0 |
TarFileReader::TarFileReader(istream &stream, compression_t compression) :
pri(new private_t), stream(SmartPointer<istream>::Phony(&stream)),
didReadHeader(false) {
addCompression(compression);
pri->filter.push(*this->stream);
}
|
CWE-22
| null | 519,605 |
248995382454258073383215125690752662729
| null | null |
other
|
cbang
|
1c1dba62bd3e6fa9d0d0c0aa21926043b75382c7
| 0 |
void TarFileReader::addCompression(compression_t compression) {
switch (compression) {
case TARFILE_NONE: break; // none
case TARFILE_BZIP2: pri->filter.push(BZip2Decompressor()); break;
case TARFILE_GZIP: pri->filter.push(io::zlib_decompressor()); break;
default: THROW("Invalid compression type " << compression);
}
}
|
CWE-22
| null | 519,606 |
28365394917881984055799653983891687166
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
CharCodeToUnicode::CharCodeToUnicode(GString *tagA) {
CharCode i;
tag = tagA;
mapLen = 256;
map = (Unicode *)gmallocn(mapLen, sizeof(Unicode));
for (i = 0; i < mapLen; ++i) {
map[i] = 0;
}
sMap = NULL;
sMapLen = sMapSize = 0;
refCnt = 1;
#if MULTITHREADED
gInitMutex(&mutex);
#endif
}
|
CWE-120
| null | 519,607 |
69380158267763218009318364886934189698
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
CharCodeToUnicode *CharCodeToUnicode::parseUnicodeToUnicode(
GString *fileName) {
FILE *f;
Unicode *mapA;
CharCodeToUnicodeString *sMapA;
CharCode size, oldSize, len, sMapSizeA, sMapLenA;
char buf[256];
char *tok;
Unicode u0;
Unicode uBuf[maxUnicodeString];
CharCodeToUnicode *ctu;
int line, n, i;
if (!(f = fopen(fileName->getCString(), "r"))) {
error(-1, "Couldn't open unicodeToUnicode file '%s'",
fileName->getCString());
return NULL;
}
size = 4096;
mapA = (Unicode *)gmallocn(size, sizeof(Unicode));
memset(mapA, 0, size * sizeof(Unicode));
len = 0;
sMapA = NULL;
sMapSizeA = sMapLenA = 0;
line = 0;
while (getLine(buf, sizeof(buf), f)) {
++line;
if (!(tok = strtok(buf, " \t\r\n")) ||
sscanf(tok, "%x", &u0) != 1) {
error(-1, "Bad line (%d) in unicodeToUnicode file '%s'",
line, fileName->getCString());
continue;
}
n = 0;
while (n < maxUnicodeString) {
if (!(tok = strtok(NULL, " \t\r\n"))) {
break;
}
if (sscanf(tok, "%x", &uBuf[n]) != 1) {
error(-1, "Bad line (%d) in unicodeToUnicode file '%s'",
line, fileName->getCString());
break;
}
++n;
}
if (n < 1) {
error(-1, "Bad line (%d) in unicodeToUnicode file '%s'",
line, fileName->getCString());
continue;
}
if (u0 >= size) {
oldSize = size;
while (u0 >= size) {
size *= 2;
}
mapA = (Unicode *)greallocn(mapA, size, sizeof(Unicode));
memset(mapA + oldSize, 0, (size - oldSize) * sizeof(Unicode));
}
if (n == 1) {
mapA[u0] = uBuf[0];
} else {
mapA[u0] = 0;
if (sMapLenA == sMapSizeA) {
sMapSizeA += 16;
sMapA = (CharCodeToUnicodeString *)
greallocn(sMapA, sMapSizeA, sizeof(CharCodeToUnicodeString));
}
sMapA[sMapLenA].c = u0;
for (i = 0; i < n; ++i) {
sMapA[sMapLenA].u[i] = uBuf[i];
}
sMapA[sMapLenA].len = n;
++sMapLenA;
}
if (u0 >= len) {
len = u0 + 1;
}
}
fclose(f);
ctu = new CharCodeToUnicode(fileName->copy(), mapA, len, gTrue,
sMapA, sMapLenA, sMapSizeA);
gfree(mapA);
return ctu;
}
|
CWE-120
| null | 519,608 |
46568281319290993471505110288806034925
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
void CharCodeToUnicode::decRefCnt() {
GBool done;
#if MULTITHREADED
gLockMutex(&mutex);
#endif
done = --refCnt == 0;
#if MULTITHREADED
gUnlockMutex(&mutex);
#endif
if (done) {
delete this;
}
}
|
CWE-120
| null | 519,609 |
287476997908665359129376649437396940769
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
void CharCodeToUnicode::setMapping(CharCode c, Unicode *u, int len) {
int i, j;
if (len == 1) {
map[c] = u[0];
} else {
for (i = 0; i < sMapLen; ++i) {
if (sMap[i].c == c) {
break;
}
}
if (i == sMapLen) {
if (sMapLen == sMapSize) {
sMapSize += 8;
sMap = (CharCodeToUnicodeString *)
greallocn(sMap, sMapSize, sizeof(CharCodeToUnicodeString));
}
++sMapLen;
}
map[c] = 0;
sMap[i].c = c;
sMap[i].len = len;
for (j = 0; j < len && j < maxUnicodeString; ++j) {
sMap[i].u[j] = u[j];
}
}
}
|
CWE-120
| null | 519,610 |
274434604159175384056679403959820037528
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
int CharCodeToUnicode::mapToUnicode(CharCode c, Unicode *u, int size) {
int i, j;
if (c >= mapLen) {
return 0;
}
if (map[c]) {
u[0] = map[c];
return 1;
}
for (i = 0; i < sMapLen; ++i) {
if (sMap[i].c == c) {
for (j = 0; j < sMap[i].len && j < size; ++j) {
u[j] = sMap[i].u[j];
}
return j;
}
}
return 0;
}
|
CWE-120
| null | 519,611 |
53035198773879841426988483474366297716
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
CharCodeToUnicode *CharCodeToUnicode::make8BitToUnicode(Unicode *toUnicode) {
return new CharCodeToUnicode(NULL, toUnicode, 256, gTrue, NULL, 0, 0);
}
|
CWE-120
| null | 519,612 |
83130728363094453513774825804165195875
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
CharCodeToUnicode *CharCodeToUnicode::parseCIDToUnicode(GString *fileName,
GString *collection) {
FILE *f;
Unicode *mapA;
CharCode size, mapLenA;
char buf[64];
Unicode u;
CharCodeToUnicode *ctu;
if (!(f = fopen(fileName->getCString(), "r"))) {
error(-1, "Couldn't open cidToUnicode file '%s'",
fileName->getCString());
return NULL;
}
size = 32768;
mapA = (Unicode *)gmallocn(size, sizeof(Unicode));
mapLenA = 0;
while (getLine(buf, sizeof(buf), f)) {
if (mapLenA == size) {
size *= 2;
mapA = (Unicode *)greallocn(mapA, size, sizeof(Unicode));
}
if (sscanf(buf, "%x", &u) == 1) {
mapA[mapLenA] = u;
} else {
error(-1, "Bad line (%d) in cidToUnicode file '%s'",
(int)(mapLenA + 1), fileName->getCString());
mapA[mapLenA] = 0;
}
++mapLenA;
}
fclose(f);
ctu = new CharCodeToUnicode(collection->copy(), mapA, mapLenA, gTrue,
NULL, 0, 0);
gfree(mapA);
return ctu;
}
|
CWE-120
| null | 519,613 |
128693535569120211793545524745114070071
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
static int getCharFromFile(void *data) {
return fgetc((FILE *)data);
}
|
CWE-120
| null | 519,614 |
180312240270557019496791345195326112717
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
CharCodeToUnicode *CharCodeToUnicode::parseCMap(GString *buf, int nBits) {
CharCodeToUnicode *ctu;
char *p;
ctu = new CharCodeToUnicode(NULL);
p = buf->getCString();
ctu->parseCMap1(&getCharFromString, &p, nBits);
return ctu;
}
|
CWE-120
| null | 519,615 |
39599171497573375538546163846807732738
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
CharCodeToUnicode::~CharCodeToUnicode() {
if (tag) {
delete tag;
}
gfree(map);
if (sMap) {
gfree(sMap);
}
#if MULTITHREADED
gDestroyMutex(&mutex);
#endif
}
|
CWE-120
| null | 519,616 |
279762313079820484563253348234975316524
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
CharCodeToUnicodeCache::CharCodeToUnicodeCache(int sizeA) {
int i;
size = sizeA;
cache = (CharCodeToUnicode **)gmallocn(size, sizeof(CharCodeToUnicode *));
for (i = 0; i < size; ++i) {
cache[i] = NULL;
}
}
|
CWE-120
| null | 519,617 |
258181857524557267855021313019245189800
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
CharCodeToUnicode::CharCodeToUnicode(GString *tagA, Unicode *mapA,
CharCode mapLenA, GBool copyMap,
CharCodeToUnicodeString *sMapA,
int sMapLenA, int sMapSizeA) {
tag = tagA;
mapLen = mapLenA;
if (copyMap) {
map = (Unicode *)gmallocn(mapLen, sizeof(Unicode));
memcpy(map, mapA, mapLen * sizeof(Unicode));
} else {
map = mapA;
}
sMap = sMapA;
sMapLen = sMapLenA;
sMapSize = sMapSizeA;
refCnt = 1;
#if MULTITHREADED
gInitMutex(&mutex);
#endif
}
|
CWE-120
| null | 519,618 |
303949026169596075625056987786348385211
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
static int getCharFromString(void *data) {
char *p;
int c;
p = *(char **)data;
if (*p) {
c = *p++;
*(char **)data = p;
} else {
c = EOF;
}
return c;
}
|
CWE-120
| null | 519,619 |
159296719525686923187595808357192651812
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
void CharCodeToUnicode::incRefCnt() {
#if MULTITHREADED
gLockMutex(&mutex);
#endif
++refCnt;
#if MULTITHREADED
gUnlockMutex(&mutex);
#endif
}
|
CWE-120
| null | 519,620 |
189301458801927460139838615976622077835
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
void CharCodeToUnicodeCache::add(CharCodeToUnicode *ctu) {
int i;
if (cache[size - 1]) {
cache[size - 1]->decRefCnt();
}
for (i = size - 1; i >= 1; --i) {
cache[i] = cache[i - 1];
}
cache[0] = ctu;
ctu->incRefCnt();
}
|
CWE-120
| null | 519,621 |
158400566244398423887146903028860916794
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
GBool CharCodeToUnicode::match(GString *tagA) {
return tag && !tag->cmp(tagA);
}
|
CWE-120
| null | 519,622 |
288399514904459178722679798555340664771
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
CharCodeToUnicodeCache::~CharCodeToUnicodeCache() {
int i;
for (i = 0; i < size; ++i) {
if (cache[i]) {
cache[i]->decRefCnt();
}
}
gfree(cache);
}
|
CWE-120
| null | 519,623 |
263010917054160293607216661967456620675
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
void CharCodeToUnicode::mergeCMap(GString *buf, int nBits) {
char *p;
p = buf->getCString();
parseCMap1(&getCharFromString, &p, nBits);
}
|
CWE-120
| null | 519,624 |
188867714103803793411828872152669667464
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
void CharCodeToUnicode::addMapping(CharCode code, char *uStr, int n,
int offset) {
CharCode oldLen, i;
Unicode u;
char uHex[5];
int j;
if (code >= mapLen) {
oldLen = mapLen;
mapLen = (code + 256) & ~255;
if (unlikely(code >= mapLen)) {
error(-1, "Illegal code value in CharCodeToUnicode::addMapping");
return;
} else {
map = (Unicode *)greallocn(map, mapLen, sizeof(Unicode));
for (i = oldLen; i < mapLen; ++i) {
map[i] = 0;
}
}
}
if (n <= 4) {
if (sscanf(uStr, "%x", &u) != 1) {
error(-1, "Illegal entry in ToUnicode CMap");
return;
}
map[code] = u + offset;
} else {
if (sMapLen >= sMapSize) {
sMapSize = sMapSize + 16;
sMap = (CharCodeToUnicodeString *)
greallocn(sMap, sMapSize, sizeof(CharCodeToUnicodeString));
}
map[code] = 0;
sMap[sMapLen].c = code;
sMap[sMapLen].len = n / 4;
for (j = 0; j < sMap[sMapLen].len && j < maxUnicodeString; ++j) {
strncpy(uHex, uStr + j*4, 4);
uHex[4] = '\0';
if (sscanf(uHex, "%x", &sMap[sMapLen].u[j]) != 1) {
error(-1, "Illegal entry in ToUnicode CMap");
}
}
sMap[sMapLen].u[sMap[sMapLen].len - 1] += offset;
++sMapLen;
}
}
|
CWE-120
| null | 519,625 |
89702516797840072167533563063616513361
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
CharCodeToUnicode *CharCodeToUnicodeCache::getCharCodeToUnicode(GString *tag) {
CharCodeToUnicode *ctu;
int i, j;
if (cache[0] && cache[0]->match(tag)) {
cache[0]->incRefCnt();
return cache[0];
}
for (i = 1; i < size; ++i) {
if (cache[i] && cache[i]->match(tag)) {
ctu = cache[i];
for (j = i; j >= 1; --j) {
cache[j] = cache[j - 1];
}
cache[0] = ctu;
ctu->incRefCnt();
return ctu;
}
}
return NULL;
}
|
CWE-120
| null | 519,626 |
11564558860434624999000908243587937766
| null | null |
other
|
pdf2json
|
80bf71f16c804108fd933e267fe31692aaa509b4
| 0 |
void CharCodeToUnicode::parseCMap1(int (*getCharFunc)(void *), void *data,
int nBits) {
PSTokenizer *pst;
char tok1[256], tok2[256], tok3[256];
int nDigits, n1, n2, n3;
CharCode i;
CharCode code1, code2;
GString *name;
FILE *f;
nDigits = nBits / 4;
pst = new PSTokenizer(getCharFunc, data);
pst->getToken(tok1, sizeof(tok1), &n1);
while (pst->getToken(tok2, sizeof(tok2), &n2)) {
if (!strcmp(tok2, "usecmap")) {
if (tok1[0] == '/') {
name = new GString(tok1 + 1);
if ((f = globalParams->findToUnicodeFile(name))) {
parseCMap1(&getCharFromFile, f, nBits);
fclose(f);
} else {
error(-1, "Couldn't find ToUnicode CMap file for '%s'",
name->getCString());
}
delete name;
}
pst->getToken(tok1, sizeof(tok1), &n1);
} else if (!strcmp(tok2, "beginbfchar")) {
while (pst->getToken(tok1, sizeof(tok1), &n1)) {
if (!strcmp(tok1, "endbfchar")) {
break;
}
if (!pst->getToken(tok2, sizeof(tok2), &n2) ||
!strcmp(tok2, "endbfchar")) {
error(-1, "Illegal entry in bfchar block in ToUnicode CMap");
break;
}
if (!(n1 == 2 + nDigits && tok1[0] == '<' && tok1[n1 - 1] == '>' &&
tok2[0] == '<' && tok2[n2 - 1] == '>')) {
error(-1, "Illegal entry in bfchar block in ToUnicode CMap");
continue;
}
tok1[n1 - 1] = tok2[n2 - 1] = '\0';
if (sscanf(tok1 + 1, "%x", &code1) != 1) {
error(-1, "Illegal entry in bfchar block in ToUnicode CMap");
continue;
}
addMapping(code1, tok2 + 1, n2 - 2, 0);
}
pst->getToken(tok1, sizeof(tok1), &n1);
} else if (!strcmp(tok2, "beginbfrange")) {
while (pst->getToken(tok1, sizeof(tok1), &n1)) {
if (!strcmp(tok1, "endbfrange")) {
break;
}
if (!pst->getToken(tok2, sizeof(tok2), &n2) ||
!strcmp(tok2, "endbfrange") ||
!pst->getToken(tok3, sizeof(tok3), &n3) ||
!strcmp(tok3, "endbfrange")) {
error(-1, "Illegal entry in bfrange block in ToUnicode CMap");
break;
}
if (!(n1 == 2 + nDigits && tok1[0] == '<' && tok1[n1 - 1] == '>' &&
n2 == 2 + nDigits && tok2[0] == '<' && tok2[n2 - 1] == '>')) {
error(-1, "Illegal entry in bfrange block in ToUnicode CMap");
continue;
}
tok1[n1 - 1] = tok2[n2 - 1] = '\0';
if (sscanf(tok1 + 1, "%x", &code1) != 1 ||
sscanf(tok2 + 1, "%x", &code2) != 1) {
error(-1, "Illegal entry in bfrange block in ToUnicode CMap");
continue;
}
if (!strcmp(tok3, "[")) {
i = 0;
while (pst->getToken(tok1, sizeof(tok1), &n1) &&
code1 + i <= code2) {
if (!strcmp(tok1, "]")) {
break;
}
if (tok1[0] == '<' && tok1[n1 - 1] == '>') {
tok1[n1 - 1] = '\0';
addMapping(code1 + i, tok1 + 1, n1 - 2, 0);
} else {
error(-1, "Illegal entry in bfrange block in ToUnicode CMap");
}
++i;
}
} else if (tok3[0] == '<' && tok3[n3 - 1] == '>') {
tok3[n3 - 1] = '\0';
for (i = 0; code1 <= code2; ++code1, ++i) {
addMapping(code1, tok3 + 1, n3 - 2, i);
}
} else {
error(-1, "Illegal entry in bfrange block in ToUnicode CMap");
}
}
pst->getToken(tok1, sizeof(tok1), &n1);
} else {
strcpy(tok1, tok2);
}
}
delete pst;
}
|
CWE-120
| null | 519,627 |
200834997553514355569795174130281210028
| null | null |
other
|
Platinum
|
9a4ceaccb1585ec35c45fd8e2585538fff6a865e
| 0 |
PLT_HttpServer::ServeFile(const NPT_HttpRequest& request,
const NPT_HttpRequestContext& context,
NPT_HttpResponse& response,
NPT_String file_path)
{
NPT_InputStreamReference stream;
NPT_File file(file_path);
NPT_FileInfo file_info;
// prevent hackers from accessing files outside of our root
if ((file_path.Find("../") >= 0) || (file_path.Find("..\\") >= 0) ||
NPT_FAILED(NPT_File::GetInfo(file_path, &file_info))) {
return NPT_ERROR_NO_SUCH_ITEM;
}
// check for range requests
const NPT_String* range_spec = request.GetHeaders().GetHeaderValue(NPT_HTTP_HEADER_RANGE);
// handle potential 304 only if range header not set
NPT_DateTime date;
NPT_TimeStamp timestamp;
if (NPT_SUCCEEDED(PLT_UPnPMessageHelper::GetIfModifiedSince((NPT_HttpMessage&)request, date)) &&
!range_spec) {
date.ToTimeStamp(timestamp);
NPT_LOG_INFO_5("File %s timestamps: request=%d (%s) vs file=%d (%s)",
(const char*)request.GetUrl().GetPath(),
(NPT_UInt32)timestamp.ToSeconds(),
(const char*)date.ToString(),
(NPT_UInt32)file_info.m_ModificationTime,
(const char*)NPT_DateTime(file_info.m_ModificationTime).ToString());
if (timestamp >= file_info.m_ModificationTime) {
// it's a match
NPT_LOG_FINE_1("Returning 304 for %s", request.GetUrl().GetPath().GetChars());
response.SetStatus(304, "Not Modified", NPT_HTTP_PROTOCOL_1_1);
return NPT_SUCCESS;
}
}
// open file
if (NPT_FAILED(file.Open(NPT_FILE_OPEN_MODE_READ)) ||
NPT_FAILED(file.GetInputStream(stream)) ||
stream.IsNull()) {
return NPT_ERROR_NO_SUCH_ITEM;
}
// set Last-Modified and Cache-Control headers
if (file_info.m_ModificationTime) {
NPT_DateTime last_modified = NPT_DateTime(file_info.m_ModificationTime);
response.GetHeaders().SetHeader("Last-Modified", last_modified.ToString(NPT_DateTime::FORMAT_RFC_1123), true);
response.GetHeaders().SetHeader("Cache-Control", "max-age=0,must-revalidate", true);
//response.GetHeaders().SetHeader("Cache-Control", "max-age=1800", true);
}
PLT_HttpRequestContext tmp_context(request, context);
return ServeStream(request, context, response, stream, PLT_MimeType::GetMimeType(file_path, &tmp_context));
}
|
CWE-22
| null | 519,628 |
329340563999228006325201950312908412659
| null | null |
other
|
Platinum
|
9a4ceaccb1585ec35c45fd8e2585538fff6a865e
| 0 |
PLT_HttpServer::SetupResponse(NPT_HttpRequest& request,
const NPT_HttpRequestContext& context,
NPT_HttpResponse& response)
{
NPT_String prefix = NPT_String::Format("PLT_HttpServer::SetupResponse %s request from %s for \"%s\"",
(const char*) request.GetMethod(),
(const char*) context.GetRemoteAddress().ToString(),
(const char*) request.GetUrl().ToString());
PLT_LOG_HTTP_REQUEST(NPT_LOG_LEVEL_FINE, prefix, &request);
NPT_List<NPT_HttpRequestHandler*> handlers = FindRequestHandlers(request);
if (handlers.GetItemCount() == 0) return NPT_ERROR_NO_SUCH_ITEM;
// ask the handler to setup the response
NPT_Result result = (*handlers.GetFirstItem())->SetupResponse(request, context, response);
// DLNA compliance
PLT_UPnPMessageHelper::SetDate(response);
if (request.GetHeaders().GetHeader("Accept-Language")) {
response.GetHeaders().SetHeader("Content-Language", "en");
}
return result;
}
|
CWE-22
| null | 519,629 |
303637798421978675405682655061285645313
| null | null |
other
|
Platinum
|
9a4ceaccb1585ec35c45fd8e2585538fff6a865e
| 0 |
PLT_HttpServer::ServeStream(const NPT_HttpRequest& request,
const NPT_HttpRequestContext& context,
NPT_HttpResponse& response,
NPT_InputStreamReference& body,
const char* content_type)
{
if (body.IsNull()) return NPT_FAILURE;
// set date
NPT_TimeStamp now;
NPT_System::GetCurrentTimeStamp(now);
response.GetHeaders().SetHeader("Date", NPT_DateTime(now).ToString(NPT_DateTime::FORMAT_RFC_1123), true);
// get entity
NPT_HttpEntity* entity = response.GetEntity();
NPT_CHECK_POINTER_FATAL(entity);
// set the content type
entity->SetContentType(content_type);
// check for range requests
const NPT_String* range_spec = request.GetHeaders().GetHeaderValue(NPT_HTTP_HEADER_RANGE);
// setup entity body
NPT_CHECK(NPT_HttpFileRequestHandler::SetupResponseBody(response, body, range_spec));
// set some default headers
if (response.GetEntity()->GetTransferEncoding() != NPT_HTTP_TRANSFER_ENCODING_CHUNKED) {
// set but don't replace Accept-Range header only if body is seekable
NPT_Position offset;
if (NPT_SUCCEEDED(body->Tell(offset)) && NPT_SUCCEEDED(body->Seek(offset))) {
response.GetHeaders().SetHeader(NPT_HTTP_HEADER_ACCEPT_RANGES, "bytes", false);
}
}
// set getcontentFeatures.dlna.org
const NPT_String* value = request.GetHeaders().GetHeaderValue("getcontentFeatures.dlna.org");
if (value) {
PLT_HttpRequestContext tmp_context(request, context);
const char* dlna = PLT_ProtocolInfo::GetDlnaExtension(entity->GetContentType(),
&tmp_context);
if (dlna) response.GetHeaders().SetHeader("ContentFeatures.DLNA.ORG", dlna, false);
}
// transferMode.dlna.org
value = request.GetHeaders().GetHeaderValue("transferMode.dlna.org");
if (value) {
// Interactive mode not supported?
/*if (value->Compare("Interactive", true) == 0) {
response.SetStatus(406, "Not Acceptable");
return NPT_SUCCESS;
}*/
response.GetHeaders().SetHeader("TransferMode.DLNA.ORG", value->GetChars(), false);
} else {
response.GetHeaders().SetHeader("TransferMode.DLNA.ORG", "Streaming", false);
}
if (request.GetHeaders().GetHeaderValue("TimeSeekRange.dlna.org")) {
response.SetStatus(406, "Not Acceptable");
return NPT_SUCCESS;
}
return NPT_SUCCESS;
}
|
CWE-22
| null | 519,630 |
161522666862738058710629316651869363124
| null | null |
other
|
Platinum
|
9a4ceaccb1585ec35c45fd8e2585538fff6a865e
| 0 |
PLT_HttpServer::~PLT_HttpServer()
{
Stop();
}
|
CWE-22
| null | 519,631 |
88426702517988153040521800541068700721
| null | null |
other
|
Platinum
|
9a4ceaccb1585ec35c45fd8e2585538fff6a865e
| 0 |
PLT_HttpServer::Start()
{
NPT_Result res = NPT_FAILURE;
// we can't start an already running server or restart an aborted server
// because the socket is shared create a new instance
if (m_Running || m_Aborted) NPT_CHECK_WARNING(NPT_ERROR_INVALID_STATE);
// if we're given a port for our http server, try it
if (m_Port) {
res = SetListenPort(m_Port, m_ReuseAddress);
// return right away if failed and not allowed to try again randomly
if (NPT_FAILED(res) && !m_AllowRandomPortOnBindFailure) {
NPT_CHECK_SEVERE(res);
}
}
// try random port now
if (!m_Port || NPT_FAILED(res)) {
int retries = 100;
do {
int random = NPT_System::GetRandomInteger();
int port = (unsigned short)(1024 + (random % 1024));
if (NPT_SUCCEEDED(SetListenPort(port, m_ReuseAddress))) {
break;
}
} while (--retries > 0);
if (retries == 0) NPT_CHECK_SEVERE(NPT_FAILURE);
}
// keep track of port server has successfully bound
m_Port = m_BoundPort;
// Tell server to try to listen to more incoming sockets
// (this could fail silently)
if (m_TaskManager->GetMaxTasks() > 20) {
m_Socket.Listen(m_TaskManager->GetMaxTasks());
}
// start a task to listen for incoming connections
PLT_HttpListenTask *task = new PLT_HttpListenTask(this, &m_Socket, false);
NPT_CHECK_SEVERE(m_TaskManager->StartTask(task));
NPT_SocketInfo info;
m_Socket.GetInfo(info);
NPT_LOG_INFO_2("HttpServer listening on %s:%d",
(const char*)info.local_address.GetIpAddress().ToString(),
m_Port);
m_Running = true;
return NPT_SUCCESS;
}
|
CWE-22
| null | 519,632 |
60194999946306721040150080394235710595
| null | null |
other
|
Platinum
|
9a4ceaccb1585ec35c45fd8e2585538fff6a865e
| 0 |
PLT_HttpServer::PLT_HttpServer(NPT_IpAddress address,
NPT_IpPort port,
bool allow_random_port_on_bind_failure, /* = false */
NPT_Cardinal max_clients, /* = 50 */
bool reuse_address) : /* = false */
NPT_HttpServer(address, port, true),
m_TaskManager(new PLT_TaskManager(max_clients)),
m_Address(address),
m_Port(port),
m_AllowRandomPortOnBindFailure(allow_random_port_on_bind_failure),
m_ReuseAddress(reuse_address),
m_Running(false),
m_Aborted(false)
{
}
|
CWE-22
| null | 519,633 |
108822032379652481685571792864354747836
| null | null |
other
|
Platinum
|
9a4ceaccb1585ec35c45fd8e2585538fff6a865e
| 0 |
PLT_HttpServer::Stop()
{
// we can't restart an aborted server
if (m_Aborted || !m_Running) NPT_CHECK_WARNING(NPT_ERROR_INVALID_STATE);
// stop all other pending tasks
m_TaskManager->Abort();
m_Running = false;
m_Aborted = true;
return NPT_SUCCESS;
}
|
CWE-22
| null | 519,634 |
55342958874365367682364338573529860607
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
void jsiFlagDebugValues(Jsi_Interp *interp, Jsi_Obj *obj)
{
Jsi_Value *v;
int oflags;
if (obj->ot != JSI_OT_OBJECT && obj->ot != JSI_OT_ARRAY)
return;
if (obj->tree) {
Jsi_TreeEntry *hPtr;
Jsi_TreeSearch srch;
for (hPtr=Jsi_TreeSearchFirst(obj->tree, &srch, JSI_TREE_ORDER_IN, NULL); hPtr;
hPtr=Jsi_TreeSearchNext(&srch)) {
v = (Jsi_Value*)Jsi_TreeValueGet(hPtr);
if (v == NULL || v->sig != JSI_SIG_VALUE) continue;
oflags = v->VD.flags;
v->VD.flags |= (MDB_VISITED|MDB_INOBJ);
if (oflags&MDB_VISITED || v->vt != JSI_VT_OBJECT)
continue;
jsiFlagDebugValues(interp, v->d.obj);
}
}
if (obj->arr) {
uint i;
for (i=0; i<obj->arrCnt; i++) {
v = obj->arr[i];
if (v == NULL || v->sig != JSI_SIG_VALUE) continue;
oflags = v->VD.flags;
v->VD.flags |= (MDB_VISITED|MDB_INOBJ);
if (oflags&MDB_VISITED || v->vt != JSI_VT_OBJECT)
continue;
jsiFlagDebugValues(interp, v->d.obj);
}
}
}
|
CWE-120
| null | 519,856 |
38320702984039439229483664849897515859
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static Jsi_RC SqliteTransactionCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
int rc;
Jsi_Db *jdb;
int argc = Jsi_ValueGetLength(interp, args);
if (!(jdb = dbGetDbHandle(interp, _this, funcPtr))) return JSI_ERROR;
Jsi_Value *pScript;
const char *zBegin = "SAVEPOINT _jsi_transaction";
if( jdb->nTransaction==0 && argc==2 ) {
Jsi_Value *arg = Jsi_ValueArrayIndex(interp, args, 0);
static const char *TTYPE_strs[] = {
"deferred", "exclusive", "immediate", 0
};
enum TTYPE_enum {
TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE
};
int ttype;
if( Jsi_ValueGetIndex(interp, arg, TTYPE_strs, "transaction type",
0, &ttype) ) {
return JSI_ERROR;
}
switch( (enum TTYPE_enum)ttype ) {
case TTYPE_DEFERRED: /* no-op */
;
break;
case TTYPE_EXCLUSIVE:
zBegin = "BEGIN EXCLUSIVE";
break;
case TTYPE_IMMEDIATE:
zBegin = "BEGIN IMMEDIATE";
break;
}
}
pScript = Jsi_ValueArrayIndex(interp, args, argc-1);
if(!Jsi_ValueIsFunction(interp, pScript))
return Jsi_LogError("expected function");
/* Run the SQLite BEGIN command to open a transaction or savepoint. */
jdb->disableAuth++;
rc = sqlite3_exec(jdb->db, zBegin, 0, 0 ,0);
jdb->disableAuth--;
if( rc!=SQLITE_OK )
return Jsi_LogError("%s", sqlite3_errmsg(jdb->db));
jdb->nTransaction++;
/* Evaluate the function , then
** call function dbTransPostCmd() to commit (or rollback) the transaction
** or savepoint. */
Jsi_RC rv = Jsi_FunctionInvoke(interp, pScript, NULL, NULL, NULL);
rv = dbTransPostCmd(jdb, interp, rv);
return rv;
}
|
CWE-120
| null | 519,857 |
85140162656165178151747480285905688026
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
bool jsi_StrIsBalanced(char *str) {
int cnt = 0, quote = 0;
char *cp = str;
while (*cp) {
switch (*cp) {
case '\\':
cp++;
break;
case '{': case '(': case '[':
cnt++;
break;
case '\'': case '\"':
quote++;
break;
case '}': case ')': case ']':
cnt--;
break;
}
if (*cp == 0)
break;
cp++;
}
return ((quote%2) == 0 && cnt <= 0);
}
|
CWE-120
| null | 519,858 |
71004339892159182490597816723996363093
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
int Jsi_Flush(Jsi_Interp *interp, Jsi_Channel chan) {
if (chan->fsPtr==0 || !chan->fsPtr->flushProc) return -1;
return chan->fsPtr->flushProc(chan);
}
|
CWE-120
| null | 519,859 |
109316637068229724728412295167102082240
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
int Jsi_Stat(Jsi_Interp *interp, Jsi_Value* path, Jsi_StatBuf *buf) {
void *data;
Jsi_Filesystem *fsPtr = Jsi_FilesystemForPath(interp, path, &data);
if (fsPtr == NULL || !fsPtr->statProc) return -1;
return fsPtr->statProc(interp, path, buf);
}
|
CWE-120
| null | 519,860 |
139897280353723900753611565271859750291
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
int Jsi_StackSize(Jsi_Stack *stack)
{
return stack->len;
}
|
CWE-120
| null | 519,861 |
177052565848299975580236256388450613770
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static Jsi_OpCodes *code_object(jsi_Pstate *p, jsi_Pline *line, int c) { JSI_NEW_CODESLN(0,OP_OBJECT, c); }
|
CWE-120
| null | 519,862 |
136696638747472198553490122506219457554
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static Jsi_TreeEntry *OneWordCreate( Jsi_Tree *treePtr, const void *key, bool *newPtr)
{
Jsi_TreeEntry *hPtr;
size_t size;
if ((hPtr = Jsi_TreeEntryFind(treePtr, key))) {
if (newPtr)
*newPtr = 0;
return hPtr;
}
if (newPtr)
*newPtr = 1;
size = sizeof(Jsi_TreeEntry);
hPtr = (Jsi_TreeEntry*)Jsi_Calloc(1,size);
SIGINIT(hPtr,TREEENTRY);
hPtr->typ = JSI_MAP_TREE;
hPtr->treePtr = treePtr;
hPtr->value = 0;
hPtr->key.oneWordValue = (void *)key;
treePtr->numEntries++;
return hPtr;
}
|
CWE-120
| null | 519,863 |
267916423680996702760476484979873463430
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static Jsi_RC FilesysFilenameCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
UdfGet(udf, _this, funcPtr);
if (udf->filename)
Jsi_ValueMakeStringDup(interp, ret, udf->filename);
return JSI_OK;
}
|
CWE-120
| null | 519,864 |
50884021734940122413462669703289249989
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
void Jsi_TreeDelete (Jsi_Tree *treePtr)
{
SIGASSERTV(treePtr, TREE);
if (treePtr->flags.destroyed)
return;
//Jsi_TreeClear(treePtr);
treePtr->flags.destroyed = 1;
destroy_node(treePtr->opts.interp, treePtr->root);
_JSI_MEMCLEAR(treePtr);
Jsi_Free(treePtr);
}
|
CWE-120
| null | 519,865 |
128186861351673873991758572496861512583
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static void jsiLNGetMatches(const char *str, linenoiseCompletions *lc) {
char buf[JSI_BUFSIZ], pre[JSI_BUFSIZ], hpre[6] = {};
const char *cp, *fnam = "Info.completions";
int i = 0, len;
int rc, isfile = 0, start = 0, end = Jsi_Strlen(str);
Jsi_Interp* interp = jsi_interactiveInterp;
if (!Jsi_Strncmp(str, "help ", 5)) {
Jsi_Strcpy(hpre, "help ");
str += 5;
end -= 5;
}
if (end<=0) return;
Jsi_Strncpy(buf, str, sizeof(buf)-1);
buf[sizeof(buf)-1] = 0;
pre[0] = 0;
if (end<=3 && !Jsi_Strncmp(str, "help", end)) {
linenoiseAddCompletion(lc, "help");
return;
}
if (!completeValues)
completeValues = Jsi_ValueNew1(interp);
Jsi_Value *func = interp->onComplete;
if (func == NULL || !Jsi_ValueIsFunction(interp, func)) {
for (i=0; jsiFilePreCmds[i]; i++)
if (!Jsi_Strncmp(buf, jsiFilePreCmds[i], Jsi_Strlen(jsiFilePreCmds[i]))) break;
if (jsiFilePreCmds[i] && ((cp=Jsi_Strrchr(buf, '(')) && (cp[1]=='\"' || cp[1]=='\''))) {
Jsi_Strcpy(pre, buf);
pre[cp-buf+2] = 0;
snprintf(buf, sizeof(buf), "%s*%s", cp+2, (buf[0]=='s'?".js*":""));
isfile = 1;
fnam = "File.glob";
}
}
func = Jsi_NameLookup(interp, fnam);
if (func && Jsi_ValueIsFunction(interp, func)) {
//printf("PATTERN: %s\n", str);
Jsi_Value *items[3] = {};;
i = 0;
items[i++] = Jsi_ValueNewStringDup(interp, buf);
if (!isfile) {
items[i++] = Jsi_ValueNewNumber(interp, (Jsi_Number)start);
items[i++] = Jsi_ValueNewNumber(interp, (Jsi_Number)end);
}
Jsi_Value *args = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, items, i, 0));
Jsi_IncrRefCount(interp, args);
rc = Jsi_FunctionInvoke(interp, func, args, &completeValues, interp->csc);
Jsi_DecrRefCount(interp, args);
if (rc != JSI_OK) {
fprintf(stderr, "bad completion: %s %d %d\n", str?str:"", start, end);
return;
}
const char *name;
Jsi_Interp* interp = jsi_interactiveInterp;
if (completeValues == NULL || !Jsi_ValueIsArray(interp, completeValues))
return;
Jsi_Value **arr = completeValues->d.obj->arr;
int aLen = completeValues->d.obj->arrCnt;
i = 0;
while (i<aLen)
{
name = Jsi_ValueString(interp, arr[i], &len);
if (name) {
if (!pre[0] && !hpre[0])
linenoiseAddCompletion(lc, name);
else {
snprintf(buf, sizeof(buf), "%s%s%s", hpre, pre, name);
linenoiseAddCompletion(lc, buf);
}
}
i++;
}
}
}
|
CWE-120
| null | 519,866 |
289488045105882607319879311382557878040
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
bool Jsi_ValueIsFalse(Jsi_Interp *interp, Jsi_Value *v)
{
if (v->vt == JSI_VT_BOOL) return v->d.val ? 0:1;
return 0;
}
|
CWE-120
| null | 519,867 |
29715253887931522749228480124392654309
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
Jsi_OptionsSet(Jsi_Interp *interp, Jsi_OptionSpec *specs, void* rec, const char *option, Jsi_Value *valuePtr, Jsi_Wide flags)
{
char *record = (char*)rec;
Jsi_OptionSpec *specPtr;
specs = jsi_GetCachedOptionSpecs(interp, specs);
const char *cp = NULL, *cb = NULL;
bool isSafe = interp->isSafe;
if (option) {
cp = Jsi_Strchr(option, '.');
cb = Jsi_Strchr(option, '[');
}
if (cp && (!cb || cp<cb) ) {
Jsi_DString dStr;
int len = (cp-option);
Jsi_DSInit(&dStr);
cp = Jsi_DSAppendLen(&dStr, option, len);
specPtr = Jsi_OptionsFind(interp, specs, cp, flags);
Jsi_DSFree(&dStr);
if (!specPtr || !specPtr->data|| specPtr->id != JSI_OPTION_CUSTOM || specPtr->custom != Jsi_Opt_SwitchSuboption)
return Jsi_LogError("unknown or bad sub-config option: %s", option);
cp = option+len+1;
return Jsi_OptionsSet(interp, (Jsi_OptionSpec *)(specPtr->data), (void*)(((char*)rec)+specPtr->offset), cp, valuePtr, flags);
}
if (cb && cb != option) {
char *ce = Jsi_Strchr(option, ']');
Jsi_Wide ul;
Jsi_DString dStr;
Jsi_DSInit(&dStr);
int len = 0;
if (ce && ce>cb) {
len = (ce-cb-1);
cp = Jsi_DSAppendLen(&dStr, cb+1, len);
}
if (len <= 0 || Jsi_GetWide(interp, cp, &ul, 0) != JSI_OK || ul<0)
return Jsi_LogError("bad sub-array option: %s", option);
len = (cb-option);
Jsi_DSSetLength(&dStr, 0);
cp = Jsi_DSAppendLen(&dStr, option, len);
specPtr = Jsi_OptionsFind(interp, specs, cp, flags);
Jsi_DSFree(&dStr);
if (!specPtr || !specPtr->init.OPT_CARRAY|| specPtr->id != JSI_OPTION_CUSTOM || specPtr->custom != Jsi_Opt_SwitchCArray) {
bail:
return Jsi_LogError("unknown or bad array option: %s", option);
}
cp = cb+1;
Jsi_OptionSpec *subSpec = specPtr->init.OPT_CARRAY;
int isize, size = specPtr->arrSize;
if (!subSpec || size<=0 || (isize=subSpec->size)<=0)
goto bail;
isize = isize/size;
uchar *s = (((uchar*)rec)+specPtr->offset + isize*ul);
if (ce[1] != '.' || !subSpec->data) {
if (Jsi_OptionsSet(interp, subSpec, (void*)s, subSpec->name, valuePtr, flags) != JSI_OK)
return JSI_ERROR;
} else {
if (Jsi_OptionsSet(interp, (Jsi_OptionSpec *)subSpec->data, (void*)s, ce+2, valuePtr, flags) != JSI_OK)
return JSI_ERROR;
}
return JSI_OK;
}
specPtr = Jsi_OptionsFind(interp, specs, option, flags);
if (!specPtr)
return JSI_ERROR;
return jsi_SetOption(interp, specPtr, option, record, valuePtr, flags, isSafe);
}
|
CWE-120
| null | 519,868 |
50248230279811541731249764749823359593
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static Jsi_OpCodes *code_shf(int right) { JSI_NEW_CODES(0,OP_SHF, right); }
|
CWE-120
| null | 519,869 |
242813754954393249391054667621101063434
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
Jsi_RC jsi_PkgDumpInfo(Jsi_Interp *interp, const char *name, Jsi_Value **ret) {
jsi_PkgInfo *ptr;
Jsi_HashEntry *hPtr = Jsi_HashEntryFind(interp->packageHash, name);
if (hPtr && ((ptr = (jsi_PkgInfo*)Jsi_HashValueGet(hPtr)))) {
Jsi_Obj *nobj = Jsi_ObjNew(interp);
Jsi_ValueMakeObject(interp, ret, nobj);
Jsi_ObjInsert(interp, nobj, "name", Jsi_ValueNewStringDup(interp, name), 0);
Jsi_ObjInsert(interp, nobj, "version", Jsi_ValueNewNumber(interp, ptr->version), 0);
Jsi_ObjInsert(interp, nobj, "lastReq", Jsi_ValueNewNumber(interp, ptr->lastReq), 0);
char buf[JSI_MAX_NUMBER_STRING*2];
jsi_VersionNormalize(ptr->version, buf, sizeof(buf));
Jsi_ObjInsert(interp, nobj, "verStr", Jsi_ValueNewStringDup(interp, buf), 0);
const char *cp = (ptr->loadFile?ptr->loadFile:"");
Jsi_ObjInsert(interp, nobj, "loadFile", Jsi_ValueNewStringDup(interp, cp), 0);
Jsi_Value *fval2, *fval = Jsi_NameLookup(interp, name);
if (!fval || !Jsi_ValueIsFunction(interp, fval))
fval = Jsi_ValueNewNull(interp);
Jsi_ObjInsert(interp, nobj, "func", fval, 0);
fval = ptr->popts.info;
if (!fval) fval = interp->NullValue;
if (!Jsi_ValueIsObjType(interp, fval, JSI_OT_FUNCTION))
Jsi_ObjInsert(interp, nobj, "info", fval, 0);
else {
fval2 = Jsi_ValueNew1(interp);
Jsi_RC rc = Jsi_FunctionInvoke(interp, fval, NULL, &fval2, NULL);
if (rc != JSI_OK)
Jsi_LogWarn("status call failed");
Jsi_ObjInsert(interp, nobj, "info", fval2, 0);
Jsi_DecrRefCount(interp, fval2);
}
fval = interp->NullValue;
if (ptr->popts.spec && ptr->popts.data) {
fval = Jsi_ValueNew1(interp);
Jsi_OptionsConf(interp, ptr->popts.spec, ptr->popts.data, NULL, &fval, 0);
}
Jsi_ObjInsert(interp, nobj, "status", fval, 0);
if (fval != interp->NullValue)
Jsi_DecrRefCount(interp, fval);
fval = Jsi_ValueNew1(interp);
Jsi_OptionsConf(interp, jsiModuleOptions, &ptr->popts.modConf, NULL, &fval, 0);
Jsi_ObjInsert(interp, nobj, "moduleOpts", fval, 0);
Jsi_DecrRefCount(interp, fval);
return JSI_OK;
}
return JSI_ERROR;
}
|
CWE-120
| null | 519,870 |
334582049725648847947109978414174238064
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
void *Jsi_HashGet(Jsi_Hash *tbl, const void *key, int flags) {
Jsi_HashEntry *hPtr;
hPtr = Jsi_HashEntryFind(tbl, key);
if (!hPtr)
return NULL;
return Jsi_HashValueGet(hPtr);
}
|
CWE-120
| null | 519,871 |
241579517596591068840727976944257419994
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static bool jsi_LogEnabled(Jsi_Interp *interp, uint code) {
if (!interp->activeFunc) return 0;
Jsi_CmdSpec *cs = interp->activeFunc->cmdSpec;
if (!cs)
return 0;
if (interp->activeFunc->parentSpec)
cs = interp->activeFunc->parentSpec;
int cofs = (code - JSI_LOG_TEST);
int ac = (cs->flags & (JSI_CMD_LOG_TEST<<cofs));
return (ac)!=0;
}
|
CWE-120
| null | 519,872 |
33724173969850774231813785378140780853
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static Jsi_RC KeyLocker(Jsi_Hash* tbl, int lock)
{
if (!lock)
Jsi_MutexUnlock(jsiIntData.mainInterp, jsiIntData.mainInterp->Mutex);
else
return Jsi_MutexLock(jsiIntData.mainInterp, jsiIntData.mainInterp->Mutex);
return JSI_OK;
}
|
CWE-120
| null | 519,873 |
76371307765285696029055694629947769218
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static Jsi_RC RegexpTestCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
int skip = 0, rc = 0;
Jsi_Value *v;
ChkRegexp(_this, funcPtr, v);
char *str = Jsi_ValueString(interp,Jsi_ValueArrayIndex(interp, args, skip), NULL);
if (!str)
return Jsi_LogError("expected string");
if (Jsi_RegExpMatch(interp, v, str, &rc, NULL) != JSI_OK)
return JSI_ERROR;
Jsi_ValueMakeBool(interp, ret, rc != 0);
return JSI_OK;
}
|
CWE-120
| null | 519,874 |
336224111615897092637125140888487286647
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static void destroy_node(Jsi_Interp *interp, Jsi_TreeEntry* n)
{
if (n == NULL) return;
if (n->right != NULL) destroy_node(interp, n->right);
if (n->left != NULL) destroy_node(interp, n->left);
n->left = n->right = NULL;
Jsi_TreeEntryDelete(n);
}
|
CWE-120
| null | 519,875 |
158538109091643831654661395838227390361
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static void jsi_CArrayFree(Jsi_Interp *interp, Jsi_OptionSpec* spec, void *ptr)
{
/*Jsi_OptionSpec *subSpec = spec->init.ini.OPT_CARRAY; // TODO: ???
if (!subSpec) {
Jsi_Value **v = (Jsi_Value**)ptr;
if (v)
Jsi_DecrRefCount(interp, *v);
}
int i, isize, size = spec->asize;
if ((isize=subSpec->size)<=0)
return;
isize = isize/size;
uchar *s = (uchar*)ptr;
for (i=0; i<size; i++) {
Jsi_OptionsFree(interp, subSpec, s, 0);
s += isize;
}*/
}
|
CWE-120
| null | 519,876 |
38791204815653643660287920862764272103
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static void jsi_ValueObjDelete(Jsi_Interp *interp, Jsi_Value *target, Jsi_Value *key, int force)
{
if (target->vt != JSI_VT_OBJECT) return;
const char *kstr = Jsi_ValueToString(interp, key, NULL);
Jsi_TreeEntry *hPtr;
if (!Jsi_ValueIsStringKey(interp, key)) {
Jsi_MapEntry *hePtr = Jsi_MapEntryFind(target->d.obj->tree->opts.interp->strKeyTbl, kstr);
if (hePtr)
kstr = (char*)Jsi_MapKeyGet(hePtr, 0);
}
hPtr = Jsi_TreeEntryFind(target->d.obj->tree, kstr);
if (hPtr == NULL || (hPtr->f.bits.dontdel && !force))
return;
Jsi_TreeEntryDelete(hPtr);
}
|
CWE-120
| null | 519,877 |
155143229726834234699463936438530073009
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static void dbUpdateHandler(
void *p,
int op,
const char *zDb,
const char *zTbl,
sqlite_int64 rowid
) {
Jsi_Db *jdb = (Jsi_Db *)p;
Jsi_Interp *interp = jdb->interp;
int rc, i = 0;
Jsi_Value *vpargs, *items[10] = {}, *ret;
assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
items[i++] = Jsi_ValueNewObj(interp, jdb->fobj);
items[i++] = Jsi_ValueMakeStringDup(interp, NULL, (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE");
items[i++] = Jsi_ValueMakeStringDup(interp, NULL, zDb);
items[i++] = Jsi_ValueMakeStringDup(interp, NULL, zTbl);
items[i++] = Jsi_ValueMakeNumber(interp, NULL, (Jsi_Number)rowid);
vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, items, i, 0));
Jsi_IncrRefCount(interp, vpargs);
ret = Jsi_ValueNew1(interp);
rc = Jsi_FunctionInvoke(interp, jdb->onUpdate, vpargs, &ret, NULL);
Jsi_DecrRefCount(interp, vpargs);
Jsi_DecrRefCount(interp, ret);
if (rc != JSI_OK)
jdb->errCnt++;
}
|
CWE-120
| null | 519,878 |
191487448743802981049885871939014864473
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static int jsi_FSUngetcProc(Jsi_Channel chan, int ch) {
return ungetc(ch, _JSI_GETFP(chan,1));
}
|
CWE-120
| null | 519,879 |
188347203894853443921825305009262416868
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static Jsi_RC dbStmtFreeProc(Jsi_Interp *interp, Jsi_HashEntry *hPtr, void *value) {
Jsi_Db *jdb = (Jsi_Db*)interp;
Jsi_ListEntry *l = (Jsi_ListEntry*)hPtr;
SqlPreparedStmt *prep = (SqlPreparedStmt *)Jsi_ListValueGet(l);
prep->elPtr = NULL;
dbPrepStmtFree(jdb, prep);
return JSI_OK;
}
|
CWE-120
| null | 519,880 |
334227195593746697401644348882586969206
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
Jsi_RC jsi_RegExpMatches(Jsi_Interp *interp, Jsi_Value *pattern, const char *str, int n, Jsi_Value *ret, int *ofs, bool match)
{
Jsi_Regex *re;
int regexec_flags = 0;
Jsi_Value *seq = pattern;
if (seq == NULL || seq->vt != JSI_VT_OBJECT || seq->d.obj->ot != JSI_OT_REGEXP) {
Jsi_ValueMakeNull(interp, &ret);
return JSI_OK;
}
re = seq->d.obj->d.robj;
regex_t *reg = &re->reg;
regmatch_t pos[MAX_SUBREGEX] = {};
int num_matches = 0, r;
int isglob = (re->eflags&JSI_REG_GLOB);
Jsi_Obj *obj;
do {
r = regexec(reg, str, MAX_SUBREGEX, pos, regexec_flags);
if (r >= REG_BADPAT) {
char buf[JSI_BUFSIZ];
regerror(r, reg, buf, sizeof(buf));
return Jsi_LogError("error while matching pattern: %s", buf);
}
if (r == REG_NOMATCH) {
if (num_matches == 0) {
Jsi_ValueMakeNull(interp, &ret);
return JSI_OK;
}
break;
}
if (num_matches == 0) {
obj = Jsi_ObjNewType(interp, JSI_OT_ARRAY);
obj->__proto__ = interp->Array_prototype;
Jsi_ValueMakeObject(interp, &ret, obj);
Jsi_ObjSetLength(interp, ret->d.obj, 0);
}
int i;
for (i = 0; i < MAX_SUBREGEX; ++i) {
if (pos[i].rm_so <= 0 && pos[i].rm_eo <= 0)
break;
if (i && pos[i].rm_so == pos[i-1].rm_so && pos[i].rm_eo == pos[i-1].rm_eo)
continue;
int olen = -1;
char *ostr = jsi_SubstrDup(str, -1, pos[i].rm_so, pos[i].rm_eo - pos[i].rm_so, &olen);
Jsi_Value *val = Jsi_ValueMakeBlob(interp, NULL, (uchar*)ostr, olen);
if (ofs)
*ofs = pos[i].rm_eo;
Jsi_ValueInsertArray(interp, ret, num_matches, val, 0);
num_matches++;
if ( match && isglob)
break;
}
if (num_matches && match && !isglob)
return JSI_OK;
if (num_matches == 1 && (ofs || !isglob))
break;
str += pos[0].rm_eo;
n -= pos[0].rm_eo;
regexec_flags |= REG_NOTBOL;
} while (n && pos[0].rm_eo>0);
return JSI_OK;
}
|
CWE-120
| null | 519,881 |
216932399022063955023752791608084008580
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static Jsi_OpCodes *code_push_top2() { JSI_NEW_CODES(0,OP_PUSHTOP2, 0); }
|
CWE-120
| null | 519,882 |
13439871813266346512934607455326104849
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static void insert_case2(Jsi_TreeEntry* n) {
if (node_color(n->parent) == _JSI_TREE_BLACK)
return;
insert_case3(n);
}
|
CWE-120
| null | 519,883 |
113298358491537974039710871287420537543
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
Jsi_Stack* Jsi_StackNew(void)
{
Jsi_Stack *stack = (Jsi_Stack*)Jsi_Calloc(1, sizeof(Jsi_Stack));
return stack;
}
|
CWE-120
| null | 519,884 |
165436706428688790002312348528879389243
| null | null |
other
|
jsish
|
430ea27accd4d4ffddc946c9402e7c9064835a18
| 0 |
static int jsi_DbQuery(Jsi_Db *jdb, Jsi_CDataDb *dbopts, const char *query)
{
int k, cnt, erc = -1;
Jsi_CDataDb statbinds[] = {{}, {}};
if (!dbopts) dbopts = statbinds;
OptionBind ob = {.binds = dbopts};
Jsi_StructSpec *specPtr, *specs;
Jsi_Interp *interp = jdb->interp;
if (!query) query="";
if (query[0]==';') {
if (!dbExecCmd(jdb, query+1, &erc)) {
Jsi_LogError("EXEC ERROR=\"%s\", SQL=\"%s\"", sqlite3_errmsg(jdb->db), query);
return erc;
}
return 0;
}
const char *cPtr = Jsi_Strstr(query, " %s");
if (!cPtr) cPtr = Jsi_Strstr(query, "\t%s");
if (!dbopts) {
Jsi_LogError("dbopts may not be null");
return -1;
}
if (!dbopts[0].data) {
Jsi_LogError("data may not be null");
return -1;
}
if (!dbopts[0].sf) {
Jsi_LogError("specs may not be null");
return -1;
}
for (k=0; dbopts[k].sf; k++) {
if (dbopts[k].arrSize>1 || k==0) {
int scnt = 0;
for (specPtr = dbopts[k].sf, scnt=0; specPtr->id>=JSI_OPTION_BOOL
&& specPtr->id < JSI_OPTION_END; specPtr++, scnt++) {
if (specPtr->flags&JSI_OPT_DB_IGNORE)
continue;
if (k==0) {
if (specPtr->flags&JSI_OPT_DB_ROWID) {
if (specPtr->id != JSI_OPTION_INT64) {
Jsi_LogError("rowid flag must be a wide field: %s", specPtr->name);
return -1;
}
ob.rowidPtr = specPtr;
}
if (specPtr->flags&JSI_OPT_DB_DIRTY) {
if (specPtr->id == JSI_OPTION_BOOL || specPtr->id == JSI_OPTION_INT) {
ob.dirtyPtr = specPtr;
} else {
Jsi_LogError("dirty flag must be a int/bool field: %s", specPtr->name);
return -1;
}
}
}
}
if (k==0)
ob.optLen = scnt;
assert(specPtr->id == JSI_OPTION_END);
}
if (!dbopts[k].prefix) break;
}
specs = dbopts[0].sf;
int structSize = specs[ob.optLen].size;
if (dbopts->memClear || dbopts->memFree) {
cnt = dbopts[0].arrSize;
void *rec = dbopts[0].data, *prec = rec;
void **recPtrPtr = NULL;
if (dbopts->isPtr2) {
recPtrPtr = (void**)rec; /* This is really a void***, but this gets recast below. */
rec = *recPtrPtr;
}
if (cnt<=0 && rec && dbopts->isPtr2) {
for (cnt=0; ((void**)rec)[cnt]!=NULL; cnt++);
}
for (k=0; k<cnt; k++) {
if (dbopts->isPtr2 || dbopts->isPtrs)
prec = ((void**)rec)[k];
else
prec = (char*)rec + (k * structSize);
if (!prec)
continue;
Jsi_OptionsFree(interp, (Jsi_OptionSpec*)specs, prec, 0);
if (dbopts->isPtr2 || dbopts->isPtrs) {
Jsi_Free(prec);
}
}
if (recPtrPtr) {
Jsi_Free(*recPtrPtr);
*recPtrPtr = NULL;
}
if (query == NULL || query[0] == 0)
return 0;
}
if (!Jsi_Strncasecmp(query, "SELECT", 6))
return dbOptSelect(jdb, query, &ob, dbopts);
DbEvalContext sEval = {};
int insert = 0, replace = 0, update = 0;
char nbuf[JSI_MAX_NUMBER_STRING], *bPtr;
#ifdef JSI_DB_DSTRING_SIZE
JSI_DSTRING_VAR(dStr, JSI_DB_DSTRING_SIZE);
#else
Jsi_DString sStr, *dStr = &sStr;
Jsi_DSInit(dStr);
#endif
if (dbopts->noCache)
sEval.nocache = 1;
if (dbEvalInit(interp, &sEval, jdb, NULL, dStr, 0, 0) != JSI_OK)
return -1;
int dataMax = dbopts[0].arrSize;
cnt = 0;
if (dataMax==0)
dataMax = 1;
char ch[2];
ch[0] = dbopts[0].prefix;
ch[1] = 0;
if (!ch[0])
ch[0] = ':';
if ((update=(Jsi_Strncasecmp(query, "UPDATE", 6)==0))) {
Jsi_DSAppendLen(dStr, query, cPtr?(cPtr-query):-1);
if (cPtr) {
Jsi_DSAppend(dStr, " ", NULL);
int cidx = 0;
int killf = (JSI_OPT_DB_IGNORE|JSI_OPT_READ_ONLY|JSI_OPT_INIT_ONLY);
for (specPtr = specs; specPtr->id != JSI_OPTION_END; specPtr++, cidx++) {
if (specPtr == ob.rowidPtr || specPtr == ob.dirtyPtr || (specPtr->flags&killf))
continue;
const char *fname = specPtr->name;
if (ch[0] == '?')
snprintf(bPtr=nbuf, sizeof(nbuf), "%d", cidx+1);
else
bPtr = (char*)specPtr->name;
Jsi_DSAppend(dStr, (cnt?",":""), "[", fname, "]=",
ch, bPtr, NULL);
cnt++;
}
Jsi_DSAppend(dStr, cPtr+3, NULL);
}
} else if ((insert=(Jsi_Strncasecmp(query, "INSERT", 6)==0))
|| (replace=(Jsi_Strncasecmp(query, "REPLACE", 7)==0))) {
Jsi_DSAppendLen(dStr, query, cPtr?(cPtr-query):-1);
if (cPtr) {
Jsi_DSAppend(dStr, " (", NULL);
int killf = JSI_OPT_DB_IGNORE;
if (replace)
killf |= (JSI_OPT_READ_ONLY|JSI_OPT_INIT_ONLY);
for (specPtr = specs; specPtr->id != JSI_OPTION_END; specPtr++) {
if (specPtr == ob.rowidPtr || specPtr == ob.dirtyPtr || specPtr->flags&killf)
continue;
const char *fname = specPtr->name;
Jsi_DSAppend(dStr, (cnt?",":""), "[", fname, "]", NULL);
cnt++;
}
Jsi_DSAppendLen(dStr,") VALUES(", -1);
cnt = 0;
int cidx = 0;
for (specPtr = specs; specPtr->id != JSI_OPTION_END; specPtr++, cidx++) {
if (specPtr == ob.rowidPtr || specPtr == ob.dirtyPtr
|| specPtr->flags&killf)
continue;
if (ch[0] == '?')
snprintf(bPtr=nbuf, sizeof(nbuf), "%d", cidx+1);
else
bPtr = (char*)specPtr->name;
Jsi_DSAppend(dStr, (cnt?",":""), ch, bPtr, NULL);
cnt++;
}
Jsi_DSAppend(dStr,")", cPtr+3, NULL);
}
} else if (!Jsi_Strncasecmp(query, "DELETE", 6)) {
Jsi_DSAppend(dStr, query, NULL);
} else {
Jsi_LogError("unrecognized query \"%s\": expected one of: SELECT, UPDATE, INSERT, REPLACE or DELETE", query);
return -1;
}
sEval.zSql = Jsi_DSValue(dStr);
if (jdb->echo && sEval.zSql)
Jsi_LogInfo("SQL-ECHO: %s\n", sEval.zSql);
int rc, bindMax = -1, dataIdx = 0;
cnt = 0;
int ismodify = (replace||insert||update);
int isnew = (replace||insert);
int didBegin = 0;
DbEvalContext *p = &sEval;
rc = dbPrepareStmt(p->jdb, p->zSql, &p->zSql, &p->pPreStmt);
if( rc!=JSI_OK ) return -1;
if (dataMax>1 && !dbopts->noBegin) {
didBegin = 1;
if (!dbExecCmd(jdb, JSI_DBQUERY_BEGIN_STR, &erc))
goto bail;
}
while (dataIdx<dataMax) {
if (ismodify && ob.dirtyPtr && (dbopts->dirtyOnly)) { /* Check to limit updates to dirty values only. */
void *rec = dbopts[0].data;
if (dbopts->isPtrs || dbopts->isPtr2)
rec = ((void**)rec)[dataIdx];
else
rec = (char*)rec + (dataIdx * structSize);
char *ptr = (char*)rec + ob.dirtyPtr->offset;
int isDirty = *(int*)ptr;
int bit = 0;
if (ob.dirtyPtr->id == JSI_OPTION_BOOL)
bit = (uintptr_t)ob.dirtyPtr->data;
if (!(isDirty&(1<<(bit)))) {
dataIdx++;
continue;
}
isDirty &= ~(1<<(bit));
*(int*)ptr = isDirty; /* Note that the dirty bit is cleared, even upon error.*/
}
rc = dbBindOptionStmt(jdb, p->pPreStmt->pStmt, &ob, dataIdx, bindMax, dbopts);
if( rc!=JSI_OK )
goto bail;
bindMax = 1;
rc = dbEvalStepSub(p, (dataIdx>=dataMax), &erc);
if (rc == JSI_ERROR)
goto bail;
cnt += sqlite3_changes(jdb->db);
if (rc != JSI_OK && rc != JSI_BREAK)
break;
if (ob.rowidPtr && isnew) {
void *rec = dbopts[0].data;
if (dbopts->isPtrs || dbopts->isPtr2)
rec = ((void**)rec)[dataIdx];
else
rec = (char*)rec + (dataIdx * structSize);
char *ptr = (char*)rec + ob.rowidPtr->offset;
*(Jsi_Wide*)ptr = sqlite3_last_insert_rowid(jdb->db);
}
dataIdx++;
}
if (didBegin && !dbExecCmd(jdb, JSI_DBQUERY_COMMIT_STR, &erc))
rc = JSI_ERROR;
dbEvalFinalize(&sEval);
if( rc==JSI_BREAK ) {
rc = JSI_OK;
}
return (rc==JSI_OK?cnt:erc);
bail:
dbEvalFinalize(&sEval);
if (didBegin)
dbExecCmd(jdb, JSI_DBQUERY_ROLLBACK_STR, NULL);
return erc;
}
|
CWE-120
| null | 519,885 |
88156223080492913239245303546201934345
| null | null |
other
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.